-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlite_helper.js
373 lines (333 loc) · 9.98 KB
/
sqlite_helper.js
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
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
* ===============================================================================================================
*/
/**
* Configuration database
* @type {Object}
*/
const config = {
databaseName: "YOUR_DATABASE_NAME.db", // set your database name
debug: true, // set false for production and set true for development
paths: {
documentsFolder: knownFolders.documents(), // don't change this part, this for get root directory file
assetsFolder: "assets/db", // location your sqlite file database
},
};
/**
* Path database
* @type {String}
*/
const dbPath = path.join(
config.paths.documentsFolder.path,
config.databaseName
);
/**
* Variable sqlite
* @type {Object}
*/
let sqlite = null;
/**
* Initialize database
* @async
* @function initializeDatabase
* @returns {Promise<Object>} sqlite
*/
async function initializeDatabase() {
if (sqlite) {
// If the database is already open, immediately return 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) {
// If the database is not in the document, copy it from assets.
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);
}
// copy the database file from assets to documents
await fileDb.copy(dbPath);
if (config.debug) {
console.log("Database copied to: ", dbPath);
}
}
// Open or create a connection to the database after ensuring the file exists.
sqlite = 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,
fields = "*",
conditionalQuery = null
) {
await initializeDatabase(); // Waiting for the database to be fully initialized
if (sqlite) {
let selectQuery;
if (conditionalQuery) {
selectQuery = `SELECT ${fields} FROM ${table} ${conditionalQuery}`;
} else {
selectQuery = `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 = null) {
await initializeDatabase(); // Waiting for the database to be fully initialized
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, data = []) {
await initializeDatabase(); // Waiting for the database to be fully initialized
if (sqlite) {
if (!data.length) {
console.log("No data to insert");
return;
}
let fields = data.map((item) => item.field).join(", ");
let holder = data.map(() => "?").join(", ");
let values = data.map((item) => item.value);
let 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, data = [], id, conditionalQuery) {
await initializeDatabase(); // Waiting for the database to be fully initialized
if (sqlite) {
if (!data.length) {
console.log("No data to update");
return;
}
let dataSet = data.map((item) => `${item.field} = ?`).join(", ");
let values = data.map((item) => item.value);
let 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, id, conditionalQuery) {
await initializeDatabase(); // Waiting for the database to be fully initialized
if (sqlite) {
let 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) {
await initializeDatabase(); // Waiting for the database to be fully initialized
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.");
}
}
}
/**
*
* @param {*} table - table name
* @param {*} ifExist - if exist (default: false)
* @returns - void
*/
export async function SQL__dropTable(table, ifExist = false) {
await initializeDatabase(); // Waiting for the database to be fully initialized
if (sqlite) {
let dropQuery = ifExist
? `DROP TABLE IF EXISTS ${table}`
: `DROP TABLE ${table}`;
try {
await sqlite.execute(dropQuery);
} catch (error) {
if (config.debug) {
console.log("SQL__dropTable error >> ", error);
}
}
} else {
if (config.debug) {
console.log("SQL__dropTable error >> Database not initialized.");
}
}
}
/**
*
* @param {*} query - raw query (default: null)
* @returns - data (array of objects)
*/
export async function SQL__query(query) {
await initializeDatabase(); // Waiting for the database to be fully initialized
if (sqlite) {
try {
const data = await sqlite.execute(query);
return data;
} catch (error) {
if (config.debug) {
console.log("SQL__query error >> ", error);
}
}
} else {
if (config.debug) {
console.log("SQL__query error >> Database not initialized.");
}
}
}