@dockstat/sqlite-wrapper 1.2.2 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,431 @@
1
+ import type { Database, SQLQueryBindings } from "bun:sqlite";
2
+ import type {
3
+ ColumnNames,
4
+ WhereCondition,
5
+ RegexCondition,
6
+ InsertResult,
7
+ UpdateResult,
8
+ DeleteResult,
9
+ InsertOptions,
10
+ JsonColumnConfig,
11
+ QueryBuilderState,
12
+ } from "../types";
13
+ import { SelectQueryBuilder } from "./select";
14
+ import { InsertQueryBuilder } from "./insert";
15
+ import { UpdateQueryBuilder } from "./update";
16
+ import { DeleteQueryBuilder } from "./delete";
17
+
18
+ /**
19
+ * Main QueryBuilder class that combines all functionality using composition.
20
+ * This class provides a unified interface for SELECT, INSERT, UPDATE, and DELETE operations.
21
+ *
22
+ * Each operation type is implemented in a separate module for better maintainability:
23
+ * - SELECT: column selection, ordering, limiting, result execution
24
+ * - INSERT: single/bulk inserts with conflict resolution
25
+ * - UPDATE: safe updates with mandatory WHERE conditions
26
+ * - DELETE: safe deletes with mandatory WHERE conditions
27
+ * - WHERE: shared conditional logic across all operations
28
+ */
29
+ export class QueryBuilder<T extends Record<string, unknown>> {
30
+ private selectBuilder: SelectQueryBuilder<T>;
31
+ private insertBuilder: InsertQueryBuilder<T>;
32
+ private updateBuilder: UpdateQueryBuilder<T>;
33
+ private deleteBuilder: DeleteQueryBuilder<T>;
34
+
35
+ constructor(
36
+ db: Database,
37
+ tableName: string,
38
+ jsonConfig?: JsonColumnConfig<T>,
39
+ ) {
40
+ // Create instances of each specialized builder
41
+ this.selectBuilder = new SelectQueryBuilder<T>(db, tableName, jsonConfig);
42
+ this.insertBuilder = new InsertQueryBuilder<T>(db, tableName, jsonConfig);
43
+ this.updateBuilder = new UpdateQueryBuilder<T>(db, tableName, jsonConfig);
44
+ this.deleteBuilder = new DeleteQueryBuilder<T>(db, tableName, jsonConfig);
45
+
46
+ // Ensure all builders share the same state for WHERE conditions
47
+ this.syncBuilderStates();
48
+ }
49
+
50
+ /**
51
+ * Synchronize the state between all builders so WHERE conditions are shared.
52
+ */
53
+ private syncBuilderStates(): void {
54
+ const masterState = (
55
+ this.selectBuilder as unknown as { state: QueryBuilderState<T> }
56
+ ).state;
57
+ (this.insertBuilder as unknown as { state: QueryBuilderState<T> }).state =
58
+ masterState;
59
+ (this.updateBuilder as unknown as { state: QueryBuilderState<T> }).state =
60
+ masterState;
61
+ (this.deleteBuilder as unknown as { state: QueryBuilderState<T> }).state =
62
+ masterState;
63
+ }
64
+
65
+ // ===== WHERE METHODS (delegated to selectBuilder) =====
66
+
67
+ /**
68
+ * Add simple equality conditions to the WHERE clause.
69
+ */
70
+ where(conditions: WhereCondition<T>): this {
71
+ this.selectBuilder.where(conditions);
72
+ return this;
73
+ }
74
+
75
+ /**
76
+ * Add regex conditions (applied client-side).
77
+ */
78
+ whereRgx(conditions: RegexCondition<T>): this {
79
+ this.selectBuilder.whereRgx(conditions);
80
+ return this;
81
+ }
82
+
83
+ /**
84
+ * Add a raw SQL WHERE fragment with parameter binding.
85
+ */
86
+ whereExpr(expr: string, params: SQLQueryBindings[] = []): this {
87
+ this.selectBuilder.whereExpr(expr, params);
88
+ return this;
89
+ }
90
+
91
+ /**
92
+ * Alias for whereExpr.
93
+ */
94
+ whereRaw(expr: string, params: SQLQueryBindings[] = []): this {
95
+ this.selectBuilder.whereRaw(expr, params);
96
+ return this;
97
+ }
98
+
99
+ /**
100
+ * Add an IN clause with proper parameter binding.
101
+ */
102
+ whereIn(column: keyof T, values: SQLQueryBindings[]): this {
103
+ this.selectBuilder.whereIn(column, values);
104
+ return this;
105
+ }
106
+
107
+ /**
108
+ * Add a NOT IN clause with proper parameter binding.
109
+ */
110
+ whereNotIn(column: keyof T, values: SQLQueryBindings[]): this {
111
+ this.selectBuilder.whereNotIn(column, values);
112
+ return this;
113
+ }
114
+
115
+ /**
116
+ * Add a comparison operator condition.
117
+ */
118
+ whereOp(column: keyof T, op: string, value: SQLQueryBindings): this {
119
+ this.selectBuilder.whereOp(column, op, value);
120
+ return this;
121
+ }
122
+
123
+ /**
124
+ * Add a BETWEEN condition.
125
+ */
126
+ whereBetween(
127
+ column: keyof T,
128
+ min: SQLQueryBindings,
129
+ max: SQLQueryBindings,
130
+ ): this {
131
+ this.selectBuilder.whereBetween(column, min, max);
132
+ return this;
133
+ }
134
+
135
+ /**
136
+ * Add a NOT BETWEEN condition.
137
+ */
138
+ whereNotBetween(
139
+ column: keyof T,
140
+ min: SQLQueryBindings,
141
+ max: SQLQueryBindings,
142
+ ): this {
143
+ this.selectBuilder.whereNotBetween(column, min, max);
144
+ return this;
145
+ }
146
+
147
+ /**
148
+ * Add an IS NULL condition.
149
+ */
150
+ whereNull(column: keyof T): this {
151
+ this.selectBuilder.whereNull(column);
152
+ return this;
153
+ }
154
+
155
+ /**
156
+ * Add an IS NOT NULL condition.
157
+ */
158
+ whereNotNull(column: keyof T): this {
159
+ this.selectBuilder.whereNotNull(column);
160
+ return this;
161
+ }
162
+
163
+ // ===== SELECT METHODS (delegated to selectBuilder) =====
164
+
165
+ /**
166
+ * Specify which columns to select.
167
+ */
168
+ select(columns: ColumnNames<T>): this {
169
+ this.selectBuilder.select(columns);
170
+ return this;
171
+ }
172
+
173
+ /**
174
+ * Add ORDER BY clause.
175
+ */
176
+ orderBy(column: keyof T): this {
177
+ this.selectBuilder.orderBy(column);
178
+ return this;
179
+ }
180
+
181
+ /**
182
+ * Set order direction to descending.
183
+ */
184
+ desc(): this {
185
+ this.selectBuilder.desc();
186
+ return this;
187
+ }
188
+
189
+ /**
190
+ * Set order direction to ascending.
191
+ */
192
+ asc(): this {
193
+ this.selectBuilder.asc();
194
+ return this;
195
+ }
196
+
197
+ /**
198
+ * Add LIMIT clause.
199
+ */
200
+ limit(amount: number): this {
201
+ this.selectBuilder.limit(amount);
202
+ return this;
203
+ }
204
+
205
+ /**
206
+ * Add OFFSET clause.
207
+ */
208
+ offset(start: number): this {
209
+ this.selectBuilder.offset(start);
210
+ return this;
211
+ }
212
+
213
+ // ===== SELECT EXECUTION METHODS (delegated to selectBuilder) =====
214
+
215
+ /**
216
+ * Execute the query and return all matching rows.
217
+ */
218
+ all(): T[] {
219
+ return this.selectBuilder.all();
220
+ }
221
+
222
+ /**
223
+ * Execute the query and return the first matching row, or null.
224
+ */
225
+ get(): T | null {
226
+ return this.selectBuilder.get();
227
+ }
228
+
229
+ /**
230
+ * Execute the query and return the first matching row, or null.
231
+ */
232
+ first(): T | null {
233
+ return this.selectBuilder.first();
234
+ }
235
+
236
+ /**
237
+ * Execute a COUNT query and return the number of matching rows.
238
+ */
239
+ count(): number {
240
+ return this.selectBuilder.count();
241
+ }
242
+
243
+ /**
244
+ * Check if any rows match the current conditions.
245
+ */
246
+ exists(): boolean {
247
+ return this.selectBuilder.exists();
248
+ }
249
+
250
+ /**
251
+ * Execute the query and return a single column value from the first row.
252
+ */
253
+ value<K extends keyof T>(column: K): T[K] | null {
254
+ return this.selectBuilder.value(column);
255
+ }
256
+
257
+ /**
258
+ * Execute the query and return an array of values from a single column.
259
+ */
260
+ pluck<K extends keyof T>(column: K): T[K][] {
261
+ return this.selectBuilder.pluck(column);
262
+ }
263
+
264
+ // ===== INSERT METHODS (delegated to insertBuilder) =====
265
+
266
+ /**
267
+ * Insert a single row or multiple rows into the table.
268
+ */
269
+ insert(
270
+ data: Partial<T> | Partial<T>[],
271
+ options?: InsertOptions,
272
+ ): InsertResult {
273
+ return this.insertBuilder.insert(data, options);
274
+ }
275
+
276
+ /**
277
+ * Insert with OR IGNORE conflict resolution.
278
+ */
279
+ insertOrIgnore(data: Partial<T> | Partial<T>[]): InsertResult {
280
+ return this.insertBuilder.insertOrIgnore(data);
281
+ }
282
+
283
+ /**
284
+ * Insert with OR REPLACE conflict resolution.
285
+ */
286
+ insertOrReplace(data: Partial<T> | Partial<T>[]): InsertResult {
287
+ return this.insertBuilder.insertOrReplace(data);
288
+ }
289
+
290
+ /**
291
+ * Insert with OR ABORT conflict resolution.
292
+ */
293
+ insertOrAbort(data: Partial<T> | Partial<T>[]): InsertResult {
294
+ return this.insertBuilder.insertOrAbort(data);
295
+ }
296
+
297
+ /**
298
+ * Insert with OR FAIL conflict resolution.
299
+ */
300
+ insertOrFail(data: Partial<T> | Partial<T>[]): InsertResult {
301
+ return this.insertBuilder.insertOrFail(data);
302
+ }
303
+
304
+ /**
305
+ * Insert with OR ROLLBACK conflict resolution.
306
+ */
307
+ insertOrRollback(data: Partial<T> | Partial<T>[]): InsertResult {
308
+ return this.insertBuilder.insertOrRollback(data);
309
+ }
310
+
311
+ /**
312
+ * Insert and get the inserted row back.
313
+ */
314
+ insertAndGet(data: Partial<T>, options?: InsertOptions): T | null {
315
+ return this.insertBuilder.insertAndGet(data, options);
316
+ }
317
+
318
+ /**
319
+ * Batch insert with transaction support.
320
+ */
321
+ insertBatch(rows: Partial<T>[], options?: InsertOptions): InsertResult {
322
+ return this.insertBuilder.insertBatch(rows, options);
323
+ }
324
+
325
+ // ===== UPDATE METHODS (delegated to updateBuilder) =====
326
+
327
+ /**
328
+ * Update rows matching the WHERE conditions.
329
+ */
330
+ update(data: Partial<T>): UpdateResult {
331
+ return this.updateBuilder.update(data);
332
+ }
333
+
334
+ /**
335
+ * Update or insert (upsert) using INSERT OR REPLACE.
336
+ */
337
+ upsert(data: Partial<T>): UpdateResult {
338
+ return this.updateBuilder.upsert(data);
339
+ }
340
+
341
+ /**
342
+ * Increment a numeric column by a specified amount.
343
+ */
344
+ increment(column: keyof T, amount = 1): UpdateResult {
345
+ return this.updateBuilder.increment(column, amount);
346
+ }
347
+
348
+ /**
349
+ * Decrement a numeric column by a specified amount.
350
+ */
351
+ decrement(column: keyof T, amount = 1): UpdateResult {
352
+ return this.updateBuilder.decrement(column, amount);
353
+ }
354
+
355
+ /**
356
+ * Update and get the updated rows back.
357
+ */
358
+ updateAndGet(data: Partial<T>): T[] {
359
+ return this.updateBuilder.updateAndGet(data);
360
+ }
361
+
362
+ /**
363
+ * Batch update multiple rows with different values.
364
+ */
365
+ updateBatch(
366
+ updates: Array<{ where: Partial<T>; data: Partial<T> }>,
367
+ ): UpdateResult {
368
+ return this.updateBuilder.updateBatch(updates);
369
+ }
370
+
371
+ // ===== DELETE METHODS (delegated to deleteBuilder) =====
372
+
373
+ /**
374
+ * Delete rows matching the WHERE conditions.
375
+ */
376
+ delete(): DeleteResult {
377
+ return this.deleteBuilder.delete();
378
+ }
379
+
380
+ /**
381
+ * Delete and get the deleted rows back.
382
+ */
383
+ deleteAndGet(): T[] {
384
+ return this.deleteBuilder.deleteAndGet();
385
+ }
386
+
387
+ /**
388
+ * Soft delete - mark rows as deleted instead of physically removing them.
389
+ */
390
+ softDelete(
391
+ deletedColumn: keyof T = "deleted_at" as keyof T,
392
+ deletedValue: SQLQueryBindings = Math.floor(Date.now() / 1000),
393
+ ): DeleteResult {
394
+ return this.deleteBuilder.softDelete(deletedColumn, deletedValue);
395
+ }
396
+
397
+ /**
398
+ * Restore soft deleted rows.
399
+ */
400
+ restore(deletedColumn: keyof T = "deleted_at" as keyof T): DeleteResult {
401
+ return this.deleteBuilder.restore(deletedColumn);
402
+ }
403
+
404
+ /**
405
+ * Batch delete multiple sets of rows.
406
+ */
407
+ deleteBatch(conditions: Array<Partial<T>>): DeleteResult {
408
+ return this.deleteBuilder.deleteBatch(conditions);
409
+ }
410
+
411
+ /**
412
+ * Truncate the entire table (delete all rows).
413
+ */
414
+ truncate(): DeleteResult {
415
+ return this.deleteBuilder.truncate();
416
+ }
417
+
418
+ /**
419
+ * Delete rows older than a specified timestamp.
420
+ */
421
+ deleteOlderThan(timestampColumn: keyof T, olderThan: number): DeleteResult {
422
+ return this.deleteBuilder.deleteOlderThan(timestampColumn, olderThan);
423
+ }
424
+
425
+ /**
426
+ * Delete duplicate rows based on specified columns.
427
+ */
428
+ deleteDuplicates(columns: Array<keyof T>): DeleteResult {
429
+ return this.deleteBuilder.deleteDuplicates(columns);
430
+ }
431
+ }
@@ -0,0 +1,243 @@
1
+ import type { SQLQueryBindings } from "bun:sqlite";
2
+ import type { InsertResult, InsertOptions } from "../types";
3
+ import { WhereQueryBuilder } from "./where";
4
+
5
+ /**
6
+ * Mixin class that adds INSERT functionality to the QueryBuilder.
7
+ * Handles single and bulk insert operations with conflict resolution.
8
+ */
9
+ export class InsertQueryBuilder<
10
+ T extends Record<string, unknown>,
11
+ > extends WhereQueryBuilder<T> {
12
+ /**
13
+ * Insert a single row or multiple rows into the table.
14
+ *
15
+ * @param data - Single object or array of objects to insert
16
+ * @param options - Insert options (OR IGNORE, OR REPLACE, etc.)
17
+ * @returns Insert result with insertId and changes count
18
+ */
19
+ insert(
20
+ data: Partial<T> | Partial<T>[],
21
+ options?: InsertOptions,
22
+ ): InsertResult {
23
+ const rows = Array.isArray(data) ? data : [data];
24
+
25
+ // Transform rows to handle JSON serialization
26
+ const transformedRows = rows.map((row) => this.transformRowToDb(row));
27
+
28
+ if (transformedRows.length === 0) {
29
+ throw new Error("insert: data cannot be empty");
30
+ }
31
+
32
+ // Get all unique columns from all rows
33
+ const allColumns = new Set<string>();
34
+ for (const row of transformedRows) {
35
+ for (const col of Object.keys(row)) {
36
+ allColumns.add(col);
37
+ }
38
+ }
39
+
40
+ const columns = Array.from(allColumns);
41
+ if (columns.length === 0) {
42
+ throw new Error("insert: no columns to insert");
43
+ }
44
+
45
+ // Build INSERT statement with conflict resolution
46
+ let insertType = "INSERT";
47
+ if (options?.orIgnore) insertType = "INSERT OR IGNORE";
48
+ else if (options?.orReplace) insertType = "INSERT OR REPLACE";
49
+ else if (options?.orAbort) insertType = "INSERT OR ABORT";
50
+ else if (options?.orFail) insertType = "INSERT OR FAIL";
51
+ else if (options?.orRollback) insertType = "INSERT OR ROLLBACK";
52
+
53
+ const quotedColumns = columns
54
+ .map((col) => this.quoteIdentifier(col))
55
+ .join(", ");
56
+ const placeholders = columns.map(() => "?").join(", ");
57
+
58
+ const query = `${insertType} INTO ${this.quoteIdentifier(this.getTableName())} (${quotedColumns}) VALUES (${placeholders})`;
59
+ const stmt = this.getDb().prepare(query);
60
+
61
+ let totalChanges = 0;
62
+ let lastInsertId = 0;
63
+
64
+ // Execute for each row
65
+ for (const row of transformedRows) {
66
+ const values = columns.map(
67
+ (col) => row[col as keyof typeof row] ?? null,
68
+ ) as SQLQueryBindings[];
69
+ const result = stmt.run(...values);
70
+ totalChanges += result.changes;
71
+ if (result.lastInsertRowid) {
72
+ lastInsertId = Number(result.lastInsertRowid);
73
+ }
74
+ }
75
+
76
+ const result = {
77
+ insertId: lastInsertId,
78
+ changes: totalChanges,
79
+ };
80
+ this.reset();
81
+ return result;
82
+ }
83
+
84
+ /**
85
+ * Insert with OR IGNORE conflict resolution.
86
+ * Convenience method equivalent to insert(data, { orIgnore: true })
87
+ *
88
+ * @param data - Single object or array of objects to insert
89
+ * @returns Insert result with insertId and changes count
90
+ */
91
+ insertOrIgnore(data: Partial<T> | Partial<T>[]): InsertResult {
92
+ return this.insert(data, { orIgnore: true });
93
+ }
94
+
95
+ /**
96
+ * Insert with OR REPLACE conflict resolution.
97
+ * Convenience method equivalent to insert(data, { orReplace: true })
98
+ *
99
+ * @param data - Single object or array of objects to insert
100
+ * @returns Insert result with insertId and changes count
101
+ */
102
+ insertOrReplace(data: Partial<T> | Partial<T>[]): InsertResult {
103
+ return this.insert(data, { orReplace: true });
104
+ }
105
+
106
+ /**
107
+ * Insert with OR ABORT conflict resolution.
108
+ * This is the default behavior but provided for explicit usage.
109
+ *
110
+ * @param data - Single object or array of objects to insert
111
+ * @returns Insert result with insertId and changes count
112
+ */
113
+ insertOrAbort(data: Partial<T> | Partial<T>[]): InsertResult {
114
+ return this.insert(data, { orAbort: true });
115
+ }
116
+
117
+ /**
118
+ * Insert with OR FAIL conflict resolution.
119
+ *
120
+ * @param data - Single object or array of objects to insert
121
+ * @returns Insert result with insertId and changes count
122
+ */
123
+ insertOrFail(data: Partial<T> | Partial<T>[]): InsertResult {
124
+ return this.insert(data, { orFail: true });
125
+ }
126
+
127
+ /**
128
+ * Insert with OR ROLLBACK conflict resolution.
129
+ *
130
+ * @param data - Single object or array of objects to insert
131
+ * @returns Insert result with insertId and changes count
132
+ */
133
+ insertOrRollback(data: Partial<T> | Partial<T>[]): InsertResult {
134
+ return this.insert(data, { orRollback: true });
135
+ }
136
+
137
+ /**
138
+ * Insert and get the inserted row back.
139
+ * This is useful when you want to see the row with auto-generated fields.
140
+ *
141
+ * @param data - Single object to insert (bulk not supported for this method)
142
+ * @param options - Insert options
143
+ * @returns The inserted row with all fields, or null if insertion failed
144
+ */
145
+ insertAndGet(data: Partial<T>, options?: InsertOptions): T | null {
146
+ const result = this.insert(data, options);
147
+
148
+ if (result.changes === 0) {
149
+ return null;
150
+ }
151
+
152
+ // If we have an insertId, try to fetch the inserted row
153
+ if (result.insertId > 0) {
154
+ try {
155
+ const row = this.getDb()
156
+ .prepare(
157
+ `SELECT * FROM ${this.quoteIdentifier(this.getTableName())} WHERE rowid = ?`,
158
+ )
159
+ .get(result.insertId) as T | null;
160
+ return row ? this.transformRowFromDb(row) : null;
161
+ } catch {
162
+ // If fetching by rowid fails, return null
163
+ return null;
164
+ }
165
+ }
166
+
167
+ return null;
168
+ }
169
+
170
+ /**
171
+ * Batch insert with transaction support.
172
+ * This method wraps multiple inserts in a transaction for better performance
173
+ * and atomicity when inserting large amounts of data.
174
+ *
175
+ * @param rows - Array of objects to insert
176
+ * @param options - Insert options
177
+ * @returns Insert result with total changes
178
+ */
179
+ insertBatch(rows: Partial<T>[], options?: InsertOptions): InsertResult {
180
+ if (!Array.isArray(rows) || rows.length === 0) {
181
+ throw new Error("insertBatch: rows must be a non-empty array");
182
+ }
183
+
184
+ const db = this.getDb();
185
+
186
+ // Use a transaction for batch operations
187
+ const transaction = db.transaction((rowsToInsert: Partial<T>[]) => {
188
+ let totalChanges = 0;
189
+ let lastInsertId = 0;
190
+
191
+ // Transform rows to handle JSON serialization
192
+ const transformedRows = rowsToInsert.map((row) =>
193
+ this.transformRowToDb(row),
194
+ );
195
+
196
+ // Get all unique columns from all rows
197
+ const allColumns = new Set<string>();
198
+ for (const row of transformedRows) {
199
+ for (const col of Object.keys(row)) {
200
+ allColumns.add(col);
201
+ }
202
+ }
203
+
204
+ const columns = Array.from(allColumns);
205
+ if (columns.length === 0) {
206
+ throw new Error("insertBatch: no columns to insert");
207
+ }
208
+
209
+ // Build INSERT statement with conflict resolution
210
+ let insertType = "INSERT";
211
+ if (options?.orIgnore) insertType = "INSERT OR IGNORE";
212
+ else if (options?.orReplace) insertType = "INSERT OR REPLACE";
213
+ else if (options?.orAbort) insertType = "INSERT OR ABORT";
214
+ else if (options?.orFail) insertType = "INSERT OR FAIL";
215
+ else if (options?.orRollback) insertType = "INSERT OR ROLLBACK";
216
+
217
+ const quotedColumns = columns
218
+ .map((col) => this.quoteIdentifier(col))
219
+ .join(", ");
220
+ const placeholders = columns.map(() => "?").join(", ");
221
+
222
+ const query = `${insertType} INTO ${this.quoteIdentifier(this.getTableName())} (${quotedColumns}) VALUES (${placeholders})`;
223
+ const stmt = db.prepare(query);
224
+
225
+ for (const row of transformedRows) {
226
+ const values = columns.map(
227
+ (col) => row[col as keyof typeof row] ?? null,
228
+ ) as SQLQueryBindings[];
229
+ const result = stmt.run(...values);
230
+ totalChanges += result.changes;
231
+ if (result.lastInsertRowid) {
232
+ lastInsertId = Number(result.lastInsertRowid);
233
+ }
234
+ }
235
+
236
+ return { insertId: lastInsertId, changes: totalChanges };
237
+ });
238
+
239
+ const result = transaction(rows);
240
+ this.reset();
241
+ return result;
242
+ }
243
+ }