-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite_helper.ts
394 lines (351 loc) · 9.95 KB
/
sqlite_helper.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
import { knownFolders, path, File } from "@nativescript/core";
import { openOrCreate } from "@nativescript-community/sqlite";
/*
* @Name : SQLite Helper {N}
* @Version : 2.0
* @Repo : https://github.com/dyazincahya/sqlite-helper-nativescript
* @Author : Kang Cahya (github.com/dyazincahya)
* @Blog : https://www.kang-cahya.com
* ===============================================================================================================
* @References : https://github.com/nativescript-community/sqlite
* https://www.tutorialspoint.com/sqlite/index.htm
* ===============================================================================================================
*/
interface Config {
databaseName: string;
debug: boolean;
paths: {
documentsFolder: any;
assetsFolder: string;
};
}
interface DataField {
field: string;
value: any;
}
/**
* Configuration database
* @type {Object}
*/
const config: Config = {
databaseName: "YOUR_DATABASE_NAME.db",
debug: true,
paths: {
documentsFolder: knownFolders.documents(),
assetsFolder: "assets/db",
},
};
/**
* Path database
* @type {String}
*/
const dbPath: string = path.join(
config.paths.documentsFolder.path,
config.databaseName
);
/**
* Variable sqlite
* @type {Object}
*/
let sqlite: any = null;
/**
* Initialize database
* @async
* @function initializeDatabase
* @returns {Promise<Object>} sqlite
*/
async function initializeDatabase(): Promise<any> {
if (sqlite) {
return sqlite;
}
if (!config.databaseName || config.databaseName === "YOUR_DATABASE_NAME.db") {
console.log("Database name is not defined or empty.");
return null;
}
try {
const isFileDbExists = File.exists(dbPath);
if (!isFileDbExists) {
const assetsPath = knownFolders
.currentApp()
.getFolder(config.paths.assetsFolder).path;
const pathDbAssets = path.join(assetsPath, config.databaseName);
const fileDb = File.fromPath(pathDbAssets);
if (config.debug) {
console.log("Database not found. Copying from assets...");
console.log("Assets path:", pathDbAssets);
console.log("Database path:", dbPath);
console.log("File exists:", fileDb.exists);
console.log("File path:", fileDb.path);
console.log("File size:", fileDb.size);
console.log("File extension:", fileDb.extension);
}
await fileDb.copy(dbPath);
if (config.debug) {
console.log("Database copied to:", dbPath);
}
}
sqlite = await openOrCreate(dbPath);
if (config.debug) {
console.log("Database opened at:", dbPath);
}
return sqlite;
} catch (error) {
if (config.debug) {
console.error("Error initializing database:", error);
}
}
}
/*
* MAIN FUNCTION of SQLITE-HELPER
* --------------------------------
* - SQL__select
* - SQL__selectRaw
* - SQL__insert
* - SQL__update
* - SQL__delete
* - SQL__truncate
* - SQL__dropTable
* - SQL__query
* --------------------------------
* Example:
SQL__select("table_name", "field1, field2", "WHERE id = 1")
SQL__selectRaw("SELECT * FROM table_name WHERE id = 1")
SQL__insert("table_name", [{field: "field1", value: "value1"}, {field: "field2", value: "value2"}])
SQL__update("table_name", [{field: "field1", value: "new_value1"}, {field: "field2", value: "new_value2"}], 1, "WHERE id = 1")
SQL__delete("table_name", 1, "WHERE id = 1")
SQL__truncate("table_name")
SQL__dropTable("table_name")
SQL__query("SELECT * FROM table_name")
--------------------------------
* --------------------------------
* --------------------------------
* --------------------------------
*/
/**
*
* @param {*} table - table name
* @param {*} fields - fields name (default: "*")
* @param {*} conditionalQuery - conditional query (default: null)
* @returns - data (array of objects)
*/
export async function SQL__select(
table: string,
fields: string = "*",
conditionalQuery: string | null = null
): Promise<any[] | undefined> {
await initializeDatabase();
if (sqlite) {
const selectQuery = conditionalQuery
? `SELECT ${fields} FROM ${table} ${conditionalQuery}`
: `SELECT ${fields} FROM ${table}`;
try {
const data = await sqlite.select(selectQuery);
return data;
} catch (error) {
if (config.debug) {
console.log("SQL__select error >>", error);
}
}
} else {
if (config.debug) {
console.log("SQL__select error >> Database not initialized.");
}
}
}
/**
*
* @param {*} query - raw query (default: null)
* @returns - data (array of objects)
*/
export async function SQL__selectRaw(query: string | null): Promise<any[] | undefined> {
await initializeDatabase();
if (sqlite) {
if (!query) {
console.log("No query");
return;
}
try {
const data = await sqlite.select(query);
return data;
} catch (error) {
if (config.debug) {
console.log("SQL__selectRaw error >>", error);
}
}
} else {
if (config.debug) {
console.log("SQL__selectRaw error >> Database not initialized.");
}
}
}
/**
*
* @param {*} table - table name
* @param {*} data - data (array of objects)
* @returns - void
*/
export async function SQL__insert(table: string, data: DataField[] = []): Promise<void> {
await initializeDatabase();
if (sqlite) {
if (!data.length) {
console.log("No data to insert");
return;
}
const fields = data.map((item) => item.field).join(", ");
const holder = data.map(() => "?").join(", ");
const values = data.map((item) => item.value);
const insertQuery = `INSERT INTO ${table} (${fields}) VALUES (${holder})`;
try {
await sqlite.execute(insertQuery, values);
} catch (error) {
if (config.debug) {
console.log("SQL__insert error >>", error);
}
}
} else {
if (config.debug) {
console.log("SQL__insert error >> Database not initialized.");
}
}
}
/**
*
* @param {*} table - table name
* @param {*} data - data (array of objects)
* @param {*} id - id (default: null) - if null, use conditionalQuery
* @param {*} conditionalQuery - conditional query (default: null) - if null, use id
* @returns - void
*/
export async function SQL__update(
table: string,
data: DataField[] = [],
id?: number,
conditionalQuery?: string
): Promise<void> {
await initializeDatabase();
if (sqlite) {
if (!data.length) {
console.log("No data to update");
return;
}
const dataSet = data.map((item) => `${item.field} = ?`).join(", ");
const values = data.map((item) => item.value);
const updateQuery = id
? `UPDATE ${table} SET ${dataSet} WHERE id=${id}`
: `UPDATE ${table} SET ${dataSet} ${conditionalQuery || ""}`;
try {
await sqlite.execute(updateQuery, values);
} catch (error) {
if (config.debug) {
console.log("SQL__update error >>", error);
}
}
} else {
if (config.debug) {
console.log("SQL__update error >> Database not initialized.");
}
}
}
/**
*
* @param {*} table - table name
* @param {*} id - id (default: null) - if null, use conditionalQuery
* @param {*} conditionalQuery - conditional query (default: null) - if null, use id
* @returns - void
*/
export async function SQL__delete(
table: string,
id?: number,
conditionalQuery?: string
): Promise<void> {
await initializeDatabase();
if (sqlite) {
const deleteQuery = id
? `DELETE FROM ${table} WHERE id=${id}`
: `DELETE FROM ${table} ${conditionalQuery || ""}`;
try {
await sqlite.execute(deleteQuery);
} catch (error) {
if (config.debug) {
console.log("SQL__delete error >>", error);
}
}
} else {
if (config.debug) {
console.log("SQL__delete error >> Database not initialized.");
}
}
}
/**
*
* @param {*} table - table name
* @returns - void
*/
export async function SQL__truncate(table: string): Promise<void> {
await initializeDatabase();
if (sqlite) {
try {
await sqlite.execute(`DELETE FROM ${table}`);
await sqlite.execute("VACUUM");
} catch (error) {
if (config.debug) {
console.log("SQL__truncate error >>", error);
}
}
} else {
if (config.debug) {
console.log("SQL__truncate error >> Database not initialized.");
}
}
}
/**
* Drops a table from the database.
*
* @param table - Name of the table to drop.
* @param ifExist - Whether to include "IF EXISTS" in the query (default: false).
* @returns - A promise that resolves to void.
*/
export async function SQL__dropTable(table: string, ifExist: boolean = false): Promise<void> {
await initializeDatabase(); // Wait for the database to be fully initialized
if (sqlite) {
const dropQuery = ifExist
? `DROP TABLE IF EXISTS ${table}`
: `DROP TABLE ${table}`;
try {
await sqlite.execute(dropQuery);
} catch (error) {
if (config.debug) {
console.error("SQL__dropTable error >>", error);
}
}
} else {
if (config.debug) {
console.error("SQL__dropTable error >> Database not initialized.");
}
}
}
/**
* Executes a raw SQL query and returns the data.
*
* @param query - Raw SQL query string (default: null).
* @returns - A promise that resolves to an array of objects.
*/
export async function SQL__query(query: string): Promise<any[]> {
await initializeDatabase(); // Wait for the database to be fully initialized
if (sqlite) {
try {
const data = await sqlite.execute(query);
return data || [];
} catch (error) {
if (config.debug) {
console.error("SQL__query error >>", error);
}
return [];
}
} else {
if (config.debug) {
console.error("SQL__query error >> Database not initialized.");
}
return [];
}
}