-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQL3.js
More file actions
497 lines (443 loc) · 16.1 KB
/
SQL3.js
File metadata and controls
497 lines (443 loc) · 16.1 KB
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/**
* Copyright (c) 2025
* @Version : 1.0.0
* @Author : https://salarizadi.ir
* @description A promise-based wrapper for SQLite3 that provides a fluent interface
* for database operations with chainable where clauses and transaction support.
*/
const sqlite3 = require('sqlite3').verbose();
/**
* SQL3 - An enhanced SQLite3 wrapper class providing promise-based database operations
* with support for query building, transactions, and batch processing.
*/
class SQL3 {
/**
* Creates a new SQL3 instance
* @param {string} databaseFile - Path to the SQLite database file
*/
constructor (databaseFile) {
this.db = new sqlite3.Database(databaseFile);
// Internal state for WHERE clause building
this._clearWhereConditions();
// Stores the last executed query for debugging and logging
this.lastQuery = {
sql : null,
type: null,
params: null,
};
this.isTransactionActive = false;
}
/**
* Stores the details of the last executed query
* @private
* @param {string} sql - The SQL query string
* @param {Array|Object} params - Query parameters
* @param {string} type - Query type (run/all/get)
*/
_storeLastQuery (sql, type, params) {
this.lastQuery = { sql, type, params: Array.isArray(params) ? [...params] : params };
}
/**
* Retrieves the last executed query details
* @returns {Object} Object containing the last query's SQL, type, and parameters
*/
getLastQuery = () => this.lastQuery
/**
* Executes a write operation (INSERT, UPDATE, DELETE)
* @private
* @param {string} sql - SQL query to execute
* @param {Array} params - Query parameters
* @returns {Promise<Object>} Object containing lastID and number of changes
*/
_run (sql, params = []) {
this._storeLastQuery(sql, 'run', params);
return new Promise((resolve, reject) => {
this.db.run(sql, params, function(err) {
if (err) reject(new Error(`SQL run error: ${err.message}`));
else resolve({ lastID: this.lastID, changes: this.changes });
});
});
}
/**
* Executes a query returning multiple rows
* @private
* @param {string} sql - SQL query to execute
* @param {Array} params - Query parameters
* @returns {Promise<Array>} Array of result rows
*/
_all (sql, params = []) {
this._storeLastQuery(sql, 'all', params);
return new Promise((resolve, reject) => {
this.db.all(sql, params, (err, rows) => {
if (err) reject(new Error(`SQL all error: ${err.message}`));
else resolve(rows || []);
});
});
}
/**
* Executes a query returning a single row
* @private
* @param {string} sql - SQL query to execute
* @param {Array} params - Query parameters
* @returns {Promise<Object|null>} Single result row or null
*/
_get (sql, params = []) {
this._storeLastQuery(sql, 'get', params);
return new Promise((resolve, reject) => {
this.db.get(sql, params, (err, row) => {
if (err) reject(new Error(`SQL get error: ${err.message}`));
else resolve(row || null);
});
});
}
/**
* Iterates over each row in the query result using generator pattern
* @param {string} sql - SQL query to execute
* @param {Array} params - Query parameters
* @returns {AsyncGenerator<Object>} Async generator yielding each row
*/
async* each (sql, params = []) {
return new Promise((resolve, reject) => {
const rows = [];
this.db.each(
sql,
params,
(err, row) => {
if (err) {
reject(err);
return;
}
rows.push(row);
},
(err, count) => {
if (err) {
reject(err);
return;
}
resolve(rows);
}
);
}).then(function* (rows) {
for (const row of rows) {
yield row;
}
});
}
/**
* Generic query executor supporting multiple query types
* @param {string} sql - SQL query to execute
* @param {Array} params - Query parameters
* @param {string} method - Query type (all/get/run/each)
* @returns {Promise} Query results based on type
*/
async query (sql, params = [], method = 'all') {
return new Promise((resolve, reject) => {
const callback = (err, result) => {
if (err) {
reject(err);
return;
}
resolve(result);
};
switch (method) {
case 'all':
this.db.all(sql, params, callback);
break;
case 'get':
this.db.get(sql, params, callback);
break;
case 'run':
this.db.run(sql, params, callback);
break;
case 'each':
resolve(this.each(sql, params));
break;
default:
reject(new Error(`Unknown method: ${method}`));
}
});
}
/**
* Checks if a table exists in the database
* @param {string} table - Table name to check
* @returns {Promise<boolean>} True if table exists, false otherwise
*/
async tableExists (table) {
const result = await this._get(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
[table]
);
return !!result;
}
/**
* Creates a new table if it doesn't exist
* @param {string} table - Table name
* @param {Object} columns - Column definitions {columnName: columnType}
* @returns {Promise} Result of table creation
*/
async createTable (table, columns) {
if (!columns || typeof columns !== 'object') {
throw new Error('Invalid columns definition');
}
const columnDefs = Object.entries(columns).map(([name, type]) => `${name} ${type}`);
return this._run(`CREATE TABLE IF NOT EXISTS ${table} (${columnDefs.join(', ')})`);
}
/**
* Drops a table if it exists
* @param {string} table - Table name to drop
* @returns {Promise} Result of drop operation
*/
async dropTable (table) {
return this._run(`DROP TABLE IF EXISTS ${table}`);
}
/**
* Adds a WHERE condition to the query chain
* @param {string} column - Column name
* @param {*} value - Value to compare against
* @param {string} operator - Logical operator (AND/OR)
* @param {string} comparison - Comparison operator (=, >, <, etc.)
* @returns {SQL3} This instance for chaining
*/
where (column, value, operator = 'AND', comparison = '=') {
this.whereClauses.push(`${column} ${comparison} ?`);
this.whereParams.push(value);
this.whereOperators.push(operator);
return this;
}
/**
* Clears all WHERE conditions
* @private
*/
_clearWhereConditions () {
this.whereClauses = [];
this.whereParams = [];
this.whereOperators = [];
}
/**
* Builds the WHERE clause from stored conditions
* @private
* @returns {Object} WHERE clause and parameters
*/
_buildWhereClause () {
if (this.whereClauses.length === 0) return { whereClause: '', params: [] };
const whereClause = this.whereClauses.reduce((acc, clause, index) => {
if (index === 0) return ` WHERE ${clause}`;
return `${acc} ${this.whereOperators[index]} ${clause}`;
}, '');
return { whereClause, params: [...this.whereParams] };
}
/**
* Retrieves all matching rows from a table
* @param {string} table - Table name
* @param {string|Array} columns - Columns to select
* @returns {Promise<Array>} Matching rows
*/
async get (table, columns = '*') {
let columnStr = columns;
if (Array.isArray(columns))
columnStr = columns.join(', ');
const { whereClause, params } = this._buildWhereClause();
const query = `SELECT ${columnStr} FROM ${table}${whereClause}`;
this._clearWhereConditions();
return await this._all(query, params);
}
/**
* Retrieves a single row from a table
* @param {string} table - Table name
* @param {string} columns - Columns to select
* @returns {Promise<Object|null>} First matching row or null
*/
async getOne (table, columns = '*') {
const { whereClause, params } = this._buildWhereClause();
const query = `SELECT ${columns} FROM ${table}${whereClause} LIMIT 1`;
const result = await this._get(query, params);
this._clearWhereConditions();
if (!result) return null;
if (columns !== '*' && !columns.includes(',')) {
return result[columns];
}
return result;
}
/**
* Counts rows in a table
* @param {string} table - Table name
* @param {string} column - Column to count
* @returns {Promise<number>} Number of matching rows
*/
async count (table, column = '*') {
const { whereClause, params } = this._buildWhereClause();
const query = `SELECT COUNT(${column}) as count FROM ${table}${whereClause}`;
const result = await this._get(query, params);
this._clearWhereConditions();
return result?.count || 0;
}
/**
* Inserts a new row into a table
* @param {string} table - Table name
* @param {Object} data - Data to insert {column: value}
* @returns {Promise<Object>} Result with success status and lastID
*/
async insert (table, data) {
if (!data || typeof data !== 'object') {
throw new Error('Invalid data for insert');
}
const columns = Object.keys(data);
const values = Object.values(data);
const placeholders = new Array(values.length).fill('?').join(', ');
const query = `INSERT INTO ${table} (${columns.join(', ')}) VALUES (${placeholders})`;
try {
const result = await this._run(query, values);
return { success: true, lastID: result.lastID };
} catch (error) {
return { success: false, error: error.message };
}
}
/**
* Updates rows in a table
* @param {string} table - Table name
* @param {Object} data - Data to update {column: value}
* @returns {Promise<Object>} Result of update operation
*/
async update (table, data) {
if (!data || typeof data !== 'object') {
throw new Error('Invalid data for update');
}
const columns = Object.keys(data);
const setClauses = columns.map(col => `${col} = ?`);
const values = Object.values(data);
const { whereClause, params } = this._buildWhereClause();
const query = `UPDATE ${table} SET ${setClauses.join(', ')}${whereClause}`;
const result = await this._run(query, [...values, ...params]);
this._clearWhereConditions();
return result;
}
/**
* Deletes rows from a table
* @param {string} table - Table name
* @returns {Promise<Object>} Result of delete operation
*/
async delete (table) {
const { whereClause, params } = this._buildWhereClause();
const query = `DELETE FROM ${table}${whereClause}`;
const result = await this._run(query, params);
this._clearWhereConditions();
return result;
}
/**
* Implements pagination for table queries
* @param {string} table - Table name
* @param {number} page - Page number
* @param {number} perPage - Items per page
* @param {string} columns - Columns to select
* @returns {Promise<Object>} Paginated results with metadata
*/
async paginate (table, page = 1, perPage = 10, columns = '*') {
const offset = (page - 1) * perPage;
const totalCount = await this.count(table);
const { whereClause, params } = this._buildWhereClause();
const query = `SELECT ${columns} FROM ${table}${whereClause} LIMIT ${perPage} OFFSET ${offset}`;
const data = await this._all(query, params);
this._clearWhereConditions();
return {
data,
pagination: {
total: totalCount,
per_page: perPage,
current_page: page,
total_pages: Math.ceil(totalCount / perPage),
has_more: page < Math.ceil(totalCount / perPage)
}
};
}
/**
* Processes table data in batches
* @param {string} table - Table name
* @param {number} batchSize - Number of records per batch
* @param {Function} callback - Function to process each batch
* @param {string} columns - Columns to select
* @returns {Promise<void>}
*/
async batchSize (table, batchSize, callback, columns = '*') {
let offset = 0;
while (true) {
const { whereClause, params } = this._buildWhereClause();
const query = `SELECT ${columns} FROM ${table}${whereClause} LIMIT ${batchSize} OFFSET ${offset}`;
const batch = await this._all(query, params);
if (batch.length === 0) break;
await callback(batch);
offset += batchSize;
}
this._clearWhereConditions();
}
/**
* Begins a new SQLite transaction
* @throws {Error} If a transaction is already active
* @returns {Promise<void>}
*/
async beginTransaction () {
if (this.isTransactionActive)
throw new Error('Transaction already active');
await this._run('BEGIN TRANSACTION');
this.isTransactionActive = true;
}
/**
* Commits the current active transaction
* @throws {Error} If no transaction is active
* @returns {Promise<void>}
*/
async commit () {
if (!this.isTransactionActive)
throw new Error('No active transaction to commit');
await this._run('COMMIT');
this.isTransactionActive = false;
}
/**
* Rolls back the current active transaction
* If no transaction is active, silently returns
* @returns {Promise<void>}
*/
async rollback () {
if (!this.isTransactionActive) return;
await this._run('ROLLBACK');
this.isTransactionActive = false;
}
/**
* Performs VACUUM operation on the database to optimize storage and performance
* Can be used with or without additional options
* @param {string} into - Name of the new database file (for VACUUM INTO)
* @returns {Promise<boolean>}
*/
async vacuum (into) {
// Check if there's an active transaction since VACUUM can't run inside a transaction
if (this.isTransactionActive)
throw new Error('Cannot VACUUM within a transaction');
try {
// If INTO option is provided, use VACUUM INTO syntax
if (into) {
// VACUUM INTO allows creating a new database file with the vacuumed contents
await this._run(`VACUUM INTO '${into}'`);
} else {
// Regular VACUUM operation
await this._run('VACUUM');
}
} catch (error) {
throw new Error(`VACUUM operation failed: ${error.message}`);
}
}
/**
* Closes the database connection
* @returns {Promise<void>}
*/
close () {
return new Promise((resolve, reject) => {
this.db.close(err => {
if (err) reject(new Error(`Failed to close database: ${err.message}`)); else {
this._clearWhereConditions();
this.isTransactionActive = false;
resolve();
}
});
});
}
}
module.exports = SQL3;