@dockstat/sqlite-wrapper 1.1.2 → 1.2.0

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.
package/dist/index.d.ts DELETED
@@ -1,939 +0,0 @@
1
- // Generated by dts-bundle-generator v9.5.1
2
-
3
- import { Database, SQLQueryBindings } from 'bun:sqlite';
4
-
5
- /**
6
- * All SQLite data types including affinity types
7
- */
8
- export declare const SQLiteTypes: {
9
- readonly INTEGER: "INTEGER";
10
- readonly TEXT: "TEXT";
11
- readonly REAL: "REAL";
12
- readonly BLOB: "BLOB";
13
- readonly NUMERIC: "NUMERIC";
14
- readonly INT: "INT";
15
- readonly TINYINT: "TINYINT";
16
- readonly SMALLINT: "SMALLINT";
17
- readonly MEDIUMINT: "MEDIUMINT";
18
- readonly BIGINT: "BIGINT";
19
- readonly VARCHAR: "VARCHAR";
20
- readonly CHAR: "CHAR";
21
- readonly CHARACTER: "CHARACTER";
22
- readonly NCHAR: "NCHAR";
23
- readonly NVARCHAR: "NVARCHAR";
24
- readonly CLOB: "CLOB";
25
- readonly DOUBLE: "DOUBLE";
26
- readonly FLOAT: "FLOAT";
27
- readonly DECIMAL: "DECIMAL";
28
- readonly DATE: "DATE";
29
- readonly DATETIME: "DATETIME";
30
- readonly TIMESTAMP: "TIMESTAMP";
31
- readonly TIME: "TIME";
32
- readonly BOOLEAN: "BOOLEAN";
33
- readonly JSON: "JSON";
34
- };
35
- export type SQLiteType = (typeof SQLiteTypes)[keyof typeof SQLiteTypes];
36
- /**
37
- * SQLite built-in scalar functions
38
- */
39
- export declare const SQLiteFunctions: {
40
- readonly DATE: (expr: string) => string;
41
- readonly TIME: (expr: string) => string;
42
- readonly DATETIME: (expr: string) => string;
43
- readonly JULIANDAY: (expr: string) => string;
44
- readonly STRFTIME: (format: string, expr: string) => string;
45
- readonly LENGTH: (expr: string) => string;
46
- readonly LOWER: (expr: string) => string;
47
- readonly UPPER: (expr: string) => string;
48
- readonly TRIM: (expr: string, chars?: string) => string;
49
- readonly LTRIM: (expr: string, chars?: string) => string;
50
- readonly RTRIM: (expr: string, chars?: string) => string;
51
- readonly SUBSTR: (expr: string, start: number, length?: number) => string;
52
- readonly SUBSTRING: (expr: string, start: number, length?: number) => string;
53
- readonly REPLACE: (expr: string, old: string, replacement: string) => string;
54
- readonly PRINTF: (format: string, ...args: string[]) => string;
55
- readonly ABS: (expr: string) => string;
56
- readonly ROUND: (expr: string, digits?: number) => string;
57
- readonly RANDOM: () => string;
58
- readonly MIN: (...exprs: string[]) => string;
59
- readonly MAX: (...exprs: string[]) => string;
60
- readonly CAST: (expr: string, type: string) => string;
61
- readonly TYPEOF: (expr: string) => string;
62
- readonly COALESCE: (...exprs: string[]) => string;
63
- readonly IFNULL: (expr: string, replacement: string) => string;
64
- readonly NULLIF: (expr1: string, expr2: string) => string;
65
- readonly IIF: (condition: string, trueValue: string, falseValue: string) => string;
66
- readonly COUNT: (expr?: string) => string;
67
- readonly SUM: (expr: string) => string;
68
- readonly AVG: (expr: string) => string;
69
- readonly TOTAL: (expr: string) => string;
70
- readonly GROUP_CONCAT: (expr: string, separator?: string) => string;
71
- readonly JSON: (expr: string) => string;
72
- readonly JSON_EXTRACT: (json: string, path: string) => string;
73
- readonly JSON_TYPE: (json: string, path?: string) => string;
74
- readonly JSON_VALID: (expr: string) => string;
75
- readonly JSON_ARRAY: (...values: string[]) => string;
76
- readonly JSON_OBJECT: (...pairs: string[]) => string;
77
- };
78
- /**
79
- * SQLite keywords and special values
80
- */
81
- export declare const SQLiteKeywords: {
82
- readonly NULL: "NULL";
83
- readonly CURRENT_TIME: "CURRENT_TIME";
84
- readonly CURRENT_DATE: "CURRENT_DATE";
85
- readonly CURRENT_TIMESTAMP: "CURRENT_TIMESTAMP";
86
- readonly TRUE: "1";
87
- readonly FALSE: "0";
88
- readonly ROLLBACK: "ROLLBACK";
89
- readonly ABORT: "ABORT";
90
- readonly FAIL: "FAIL";
91
- readonly IGNORE: "IGNORE";
92
- readonly REPLACE: "REPLACE";
93
- };
94
- /**
95
- * Foreign key actions
96
- */
97
- export type ForeignKeyAction = "CASCADE" | "SET NULL" | "RESTRICT" | "NO ACTION" | "SET DEFAULT";
98
- /**
99
- * Column constraint options with comprehensive support
100
- */
101
- export interface ColumnConstraints {
102
- /** Column is PRIMARY KEY */
103
- primaryKey?: boolean;
104
- /** Column has AUTOINCREMENT (only valid with INTEGER PRIMARY KEY) */
105
- autoincrement?: boolean;
106
- /** Column is NOT NULL */
107
- notNull?: boolean;
108
- /** Column has UNIQUE constraint */
109
- unique?: boolean;
110
- /** Default value - can be literal value, function call, or keyword */
111
- default?: string | number | boolean | null | DefaultExpression;
112
- /** Custom check constraint */
113
- check?: string;
114
- /** Collation sequence */
115
- collate?: "BINARY" | "NOCASE" | "RTRIM" | string;
116
- /** References another table (foreign key) */
117
- references?: {
118
- table: string;
119
- column: string;
120
- onDelete?: ForeignKeyAction;
121
- onUpdate?: ForeignKeyAction;
122
- };
123
- /** Generated column expression (GENERATED ALWAYS AS) */
124
- generated?: {
125
- expression: string;
126
- stored?: boolean;
127
- };
128
- /** Column comment (stored as metadata, not in schema) */
129
- comment?: string;
130
- }
131
- /**
132
- * Type-safe default value expressions
133
- */
134
- export type DefaultExpression = {
135
- _type: "expression";
136
- expression: string;
137
- };
138
- /**
139
- * Helper to create default expressions
140
- */
141
- export declare const defaultExpr: (expression: string) => DefaultExpression;
142
- /**
143
- * Type-safe column definition
144
- */
145
- export interface ColumnDefinition extends ColumnConstraints {
146
- /** SQLite data type */
147
- type: SQLiteType;
148
- /** Optional type parameters (e.g., VARCHAR(255)) */
149
- length?: number;
150
- /** Precision for DECIMAL/NUMERIC types */
151
- precision?: number;
152
- /** Scale for DECIMAL/NUMERIC types */
153
- scale?: number;
154
- }
155
- /**
156
- * Type-safe table schema definition
157
- */
158
- export type TableSchema = Record<string, ColumnDefinition>;
159
- /**
160
- * Table constraint types
161
- */
162
- export interface TableConstraints {
163
- /** PRIMARY KEY constraint on multiple columns */
164
- primaryKey?: string[];
165
- /** UNIQUE constraints */
166
- unique?: string[] | string[][];
167
- /** CHECK constraints */
168
- check?: string[];
169
- /** FOREIGN KEY constraints */
170
- foreignKeys?: Array<{
171
- columns: string[];
172
- references: {
173
- table: string;
174
- columns: string[];
175
- onDelete?: ForeignKeyAction;
176
- onUpdate?: ForeignKeyAction;
177
- };
178
- }>;
179
- }
180
- /**
181
- * Enhanced table options
182
- */
183
- export interface TableOptions {
184
- /** Add IF NOT EXISTS clause */
185
- ifNotExists?: boolean;
186
- /** Create WITHOUT ROWID table */
187
- withoutRowId?: boolean;
188
- /** Table constraints */
189
- constraints?: TableConstraints;
190
- /** Temporary table */
191
- temporary?: boolean;
192
- /** Table comment */
193
- comment?: string;
194
- }
195
- /**
196
- * Comprehensive column helper functions with full type support
197
- */
198
- export declare const column: {
199
- /**
200
- * Create an INTEGER column with optional size specification
201
- */
202
- integer: (constraints?: ColumnConstraints & {
203
- size?: "TINYINT" | "SMALLINT" | "MEDIUMINT" | "BIGINT";
204
- }) => ColumnDefinition;
205
- /**
206
- * Create a TEXT column with optional length
207
- */
208
- text: (constraints?: ColumnConstraints & {
209
- length?: number;
210
- variant?: "VARCHAR" | "CHAR" | "CLOB" | "NCHAR" | "NVARCHAR";
211
- }) => ColumnDefinition;
212
- /**
213
- * Create a REAL column
214
- */
215
- real: (constraints?: ColumnConstraints & {
216
- variant?: "DOUBLE" | "FLOAT";
217
- }) => ColumnDefinition;
218
- /**
219
- * Create a BLOB column
220
- */
221
- blob: (constraints?: ColumnConstraints) => ColumnDefinition;
222
- /**
223
- * Create a NUMERIC/DECIMAL column with precision and scale
224
- */
225
- numeric: (constraints?: ColumnConstraints & {
226
- precision?: number;
227
- scale?: number;
228
- variant?: "DECIMAL";
229
- }) => ColumnDefinition;
230
- /**
231
- * Create a DATE column (stored as TEXT)
232
- */
233
- date: (constraints?: ColumnConstraints) => ColumnDefinition;
234
- /**
235
- * Create a DATETIME column (stored as TEXT)
236
- */
237
- datetime: (constraints?: ColumnConstraints) => ColumnDefinition;
238
- /**
239
- * Create a TIMESTAMP column (stored as INTEGER by default)
240
- */
241
- timestamp: (constraints?: ColumnConstraints & {
242
- asText?: boolean;
243
- }) => ColumnDefinition;
244
- /**
245
- * Create a TIME column (stored as TEXT)
246
- */
247
- time: (constraints?: ColumnConstraints) => ColumnDefinition;
248
- /**
249
- * Create a BOOLEAN column (stored as INTEGER)
250
- */
251
- boolean: (constraints?: ColumnConstraints) => ColumnDefinition;
252
- /**
253
- * Create a JSON column (stored as TEXT)
254
- */
255
- json: (constraints?: ColumnConstraints & {
256
- validateJson?: boolean;
257
- }) => ColumnDefinition;
258
- /**
259
- * Create a VARCHAR column with specified length
260
- */
261
- varchar: (length: number, constraints?: ColumnConstraints) => ColumnDefinition;
262
- /**
263
- * Create a CHAR column with specified length
264
- */
265
- char: (length: number, constraints?: ColumnConstraints) => ColumnDefinition;
266
- /**
267
- * Create an auto-incrementing primary key column
268
- */
269
- id: (constraints?: Omit<ColumnConstraints, "primaryKey" | "autoincrement" | "notNull">) => ColumnDefinition;
270
- /**
271
- * Create a UUID column (stored as TEXT)
272
- */
273
- uuid: (constraints?: ColumnConstraints & {
274
- generateDefault?: boolean;
275
- }) => ColumnDefinition;
276
- /**
277
- * Create a created_at timestamp column
278
- */
279
- createdAt: (constraints?: Omit<ColumnConstraints, "default" | "notNull"> & {
280
- asText?: boolean;
281
- }) => ColumnDefinition;
282
- /**
283
- * Create an updated_at timestamp column
284
- */
285
- updatedAt: (constraints?: Omit<ColumnConstraints, "default"> & {
286
- asText?: boolean;
287
- }) => ColumnDefinition;
288
- /**
289
- * Create a foreign key reference column
290
- */
291
- foreignKey: (refTable: string, refColumn?: string, constraints?: ColumnConstraints & {
292
- onDelete?: ForeignKeyAction;
293
- onUpdate?: ForeignKeyAction;
294
- type?: SQLiteType;
295
- }) => ColumnDefinition;
296
- /**
297
- * Create an enum column (with CHECK constraint)
298
- */
299
- enum: (values: string[], constraints?: ColumnConstraints) => ColumnDefinition;
300
- };
301
- /**
302
- * SQL function helpers for use in defaults and expressions
303
- */
304
- export declare const sql: {
305
- raw: (expression: string) => DefaultExpression;
306
- null: () => null;
307
- true: () => number;
308
- false: () => number;
309
- DATE: (expr: string) => string;
310
- TIME: (expr: string) => string;
311
- DATETIME: (expr: string) => string;
312
- JULIANDAY: (expr: string) => string;
313
- STRFTIME: (format: string, expr: string) => string;
314
- LENGTH: (expr: string) => string;
315
- LOWER: (expr: string) => string;
316
- UPPER: (expr: string) => string;
317
- TRIM: (expr: string, chars?: string) => string;
318
- LTRIM: (expr: string, chars?: string) => string;
319
- RTRIM: (expr: string, chars?: string) => string;
320
- SUBSTR: (expr: string, start: number, length?: number) => string;
321
- SUBSTRING: (expr: string, start: number, length?: number) => string;
322
- REPLACE: (expr: string, old: string, replacement: string) => string;
323
- PRINTF: (format: string, ...args: string[]) => string;
324
- ABS: (expr: string) => string;
325
- ROUND: (expr: string, digits?: number) => string;
326
- RANDOM: () => string;
327
- MIN: (...exprs: string[]) => string;
328
- MAX: (...exprs: string[]) => string;
329
- CAST: (expr: string, type: string) => string;
330
- TYPEOF: (expr: string) => string;
331
- COALESCE: (...exprs: string[]) => string;
332
- IFNULL: (expr: string, replacement: string) => string;
333
- NULLIF: (expr1: string, expr2: string) => string;
334
- IIF: (condition: string, trueValue: string, falseValue: string) => string;
335
- COUNT: (expr?: string) => string;
336
- SUM: (expr: string) => string;
337
- AVG: (expr: string) => string;
338
- TOTAL: (expr: string) => string;
339
- GROUP_CONCAT: (expr: string, separator?: string) => string;
340
- JSON: (expr: string) => string;
341
- JSON_EXTRACT: (json: string, path: string) => string;
342
- JSON_TYPE: (json: string, path?: string) => string;
343
- JSON_VALID: (expr: string) => string;
344
- JSON_ARRAY: (...values: string[]) => string;
345
- JSON_OBJECT: (...pairs: string[]) => string;
346
- now: () => DefaultExpression;
347
- currentTime: () => DefaultExpression;
348
- currentDate: () => DefaultExpression;
349
- currentTimestamp: () => DefaultExpression;
350
- unixTimestamp: () => DefaultExpression;
351
- };
352
- /**
353
- * Column names type for SELECT operations
354
- */
355
- export type ColumnNames<T> = [
356
- "*"
357
- ] | Array<keyof T>;
358
- /**
359
- * WHERE condition object type
360
- */
361
- export type WhereCondition<T> = Partial<T>;
362
- /**
363
- * Regex condition object type
364
- */
365
- export type RegexCondition<T> = Partial<Record<keyof T, RegExp | string>>;
366
- /**
367
- * Insert result interface
368
- */
369
- export interface InsertResult {
370
- insertId: number;
371
- changes: number;
372
- }
373
- /**
374
- * Update result interface
375
- */
376
- export interface UpdateResult {
377
- changes: number;
378
- }
379
- /**
380
- * Delete result interface
381
- */
382
- export interface DeleteResult {
383
- changes: number;
384
- }
385
- /**
386
- * Insert options interface
387
- */
388
- export interface InsertOptions {
389
- orIgnore?: boolean;
390
- orReplace?: boolean;
391
- orAbort?: boolean;
392
- orFail?: boolean;
393
- orRollback?: boolean;
394
- }
395
- /**
396
- * JSON column configuration
397
- */
398
- export interface JsonColumnConfig<T> {
399
- jsonColumns?: Array<keyof T>;
400
- }
401
- /**
402
- * Main QueryBuilder class that combines all functionality using composition.
403
- * This class provides a unified interface for SELECT, INSERT, UPDATE, and DELETE operations.
404
- *
405
- * Each operation type is implemented in a separate module for better maintainability:
406
- * - SELECT: column selection, ordering, limiting, result execution
407
- * - INSERT: single/bulk inserts with conflict resolution
408
- * - UPDATE: safe updates with mandatory WHERE conditions
409
- * - DELETE: safe deletes with mandatory WHERE conditions
410
- * - WHERE: shared conditional logic across all operations
411
- */
412
- export declare class QueryBuilder<T extends Record<string, unknown>> {
413
- private selectBuilder;
414
- private insertBuilder;
415
- private updateBuilder;
416
- private deleteBuilder;
417
- constructor(db: Database, tableName: string, jsonConfig?: JsonColumnConfig<T>);
418
- /**
419
- * Synchronize the state between all builders so WHERE conditions are shared.
420
- */
421
- private syncBuilderStates;
422
- /**
423
- * Add simple equality conditions to the WHERE clause.
424
- */
425
- where(conditions: WhereCondition<T>): this;
426
- /**
427
- * Add regex conditions (applied client-side).
428
- */
429
- whereRgx(conditions: RegexCondition<T>): this;
430
- /**
431
- * Add a raw SQL WHERE fragment with parameter binding.
432
- */
433
- whereExpr(expr: string, params?: SQLQueryBindings[]): this;
434
- /**
435
- * Alias for whereExpr.
436
- */
437
- whereRaw(expr: string, params?: SQLQueryBindings[]): this;
438
- /**
439
- * Add an IN clause with proper parameter binding.
440
- */
441
- whereIn(column: keyof T, values: SQLQueryBindings[]): this;
442
- /**
443
- * Add a NOT IN clause with proper parameter binding.
444
- */
445
- whereNotIn(column: keyof T, values: SQLQueryBindings[]): this;
446
- /**
447
- * Add a comparison operator condition.
448
- */
449
- whereOp(column: keyof T, op: string, value: SQLQueryBindings): this;
450
- /**
451
- * Add a BETWEEN condition.
452
- */
453
- whereBetween(column: keyof T, min: SQLQueryBindings, max: SQLQueryBindings): this;
454
- /**
455
- * Add a NOT BETWEEN condition.
456
- */
457
- whereNotBetween(column: keyof T, min: SQLQueryBindings, max: SQLQueryBindings): this;
458
- /**
459
- * Add an IS NULL condition.
460
- */
461
- whereNull(column: keyof T): this;
462
- /**
463
- * Add an IS NOT NULL condition.
464
- */
465
- whereNotNull(column: keyof T): this;
466
- /**
467
- * Specify which columns to select.
468
- */
469
- select(columns: ColumnNames<T>): this;
470
- /**
471
- * Add ORDER BY clause.
472
- */
473
- orderBy(column: keyof T): this;
474
- /**
475
- * Set order direction to descending.
476
- */
477
- desc(): this;
478
- /**
479
- * Set order direction to ascending.
480
- */
481
- asc(): this;
482
- /**
483
- * Add LIMIT clause.
484
- */
485
- limit(amount: number): this;
486
- /**
487
- * Add OFFSET clause.
488
- */
489
- offset(start: number): this;
490
- /**
491
- * Execute the query and return all matching rows.
492
- */
493
- all(): T[];
494
- /**
495
- * Execute the query and return the first matching row, or null.
496
- */
497
- get(): T | null;
498
- /**
499
- * Execute the query and return the first matching row, or null.
500
- */
501
- first(): T | null;
502
- /**
503
- * Execute a COUNT query and return the number of matching rows.
504
- */
505
- count(): number;
506
- /**
507
- * Check if any rows match the current conditions.
508
- */
509
- exists(): boolean;
510
- /**
511
- * Execute the query and return a single column value from the first row.
512
- */
513
- value<K extends keyof T>(column: K): T[K] | null;
514
- /**
515
- * Execute the query and return an array of values from a single column.
516
- */
517
- pluck<K extends keyof T>(column: K): T[K][];
518
- /**
519
- * Insert a single row or multiple rows into the table.
520
- */
521
- insert(data: Partial<T> | Partial<T>[], options?: InsertOptions): InsertResult;
522
- /**
523
- * Insert with OR IGNORE conflict resolution.
524
- */
525
- insertOrIgnore(data: Partial<T> | Partial<T>[]): InsertResult;
526
- /**
527
- * Insert with OR REPLACE conflict resolution.
528
- */
529
- insertOrReplace(data: Partial<T> | Partial<T>[]): InsertResult;
530
- /**
531
- * Insert with OR ABORT conflict resolution.
532
- */
533
- insertOrAbort(data: Partial<T> | Partial<T>[]): InsertResult;
534
- /**
535
- * Insert with OR FAIL conflict resolution.
536
- */
537
- insertOrFail(data: Partial<T> | Partial<T>[]): InsertResult;
538
- /**
539
- * Insert with OR ROLLBACK conflict resolution.
540
- */
541
- insertOrRollback(data: Partial<T> | Partial<T>[]): InsertResult;
542
- /**
543
- * Insert and get the inserted row back.
544
- */
545
- insertAndGet(data: Partial<T>, options?: InsertOptions): T | null;
546
- /**
547
- * Batch insert with transaction support.
548
- */
549
- insertBatch(rows: Partial<T>[], options?: InsertOptions): InsertResult;
550
- /**
551
- * Update rows matching the WHERE conditions.
552
- */
553
- update(data: Partial<T>): UpdateResult;
554
- /**
555
- * Update or insert (upsert) using INSERT OR REPLACE.
556
- */
557
- upsert(data: Partial<T>): UpdateResult;
558
- /**
559
- * Increment a numeric column by a specified amount.
560
- */
561
- increment(column: keyof T, amount?: number): UpdateResult;
562
- /**
563
- * Decrement a numeric column by a specified amount.
564
- */
565
- decrement(column: keyof T, amount?: number): UpdateResult;
566
- /**
567
- * Update and get the updated rows back.
568
- */
569
- updateAndGet(data: Partial<T>): T[];
570
- /**
571
- * Batch update multiple rows with different values.
572
- */
573
- updateBatch(updates: Array<{
574
- where: Partial<T>;
575
- data: Partial<T>;
576
- }>): UpdateResult;
577
- /**
578
- * Delete rows matching the WHERE conditions.
579
- */
580
- delete(): DeleteResult;
581
- /**
582
- * Delete and get the deleted rows back.
583
- */
584
- deleteAndGet(): T[];
585
- /**
586
- * Soft delete - mark rows as deleted instead of physically removing them.
587
- */
588
- softDelete(deletedColumn?: keyof T, deletedValue?: SQLQueryBindings): DeleteResult;
589
- /**
590
- * Restore soft deleted rows.
591
- */
592
- restore(deletedColumn?: keyof T): DeleteResult;
593
- /**
594
- * Batch delete multiple sets of rows.
595
- */
596
- deleteBatch(conditions: Array<Partial<T>>): DeleteResult;
597
- /**
598
- * Truncate the entire table (delete all rows).
599
- */
600
- truncate(): DeleteResult;
601
- /**
602
- * Delete rows older than a specified timestamp.
603
- */
604
- deleteOlderThan(timestampColumn: keyof T, olderThan: number): DeleteResult;
605
- /**
606
- * Delete duplicate rows based on specified columns.
607
- */
608
- deleteDuplicates(columns: Array<keyof T>): DeleteResult;
609
- }
610
- /**
611
- * TypedSQLite — comprehensive wrapper around bun:sqlite `Database`.
612
- *
613
- * This class provides full type safety for SQLite operations with support for:
614
- * - All SQLite data types and variations
615
- * - Built-in SQL functions
616
- * - Complex constraints and relationships
617
- * - Generated columns
618
- * - Table-level constraints
619
- * - JSON column support
620
- * - And much more...
621
- */
622
- export declare class DB {
623
- private db;
624
- /**
625
- * Open or create a SQLite database at `path`.
626
- *
627
- * @param path - Path to the SQLite file (e.g. "app.db"). Use ":memory:" for in-memory DB.
628
- * @param options - Optional database configuration
629
- */
630
- constructor(path: string, options?: {
631
- pragmas?: Array<[
632
- string,
633
- SQLQueryBindings
634
- ]>;
635
- loadExtensions?: string[];
636
- });
637
- /**
638
- * Get a typed QueryBuilder for a given table name.
639
- * (Documentation remains the same as before...)
640
- */
641
- table<T extends Record<string, unknown>>(tableName: string, jsonConfig?: JsonColumnConfig<T>): QueryBuilder<T>;
642
- /**
643
- * Close the underlying SQLite database handle.
644
- */
645
- close(): void;
646
- /**
647
- * Create a table with comprehensive type safety and feature support.
648
- *
649
- * Now supports all SQLite features:
650
- *
651
- * **Basic Usage:**
652
- * ```ts
653
- * import { column, sql } from "./db";
654
- *
655
- * db.createTable("users", {
656
- * id: column.id(), // Auto-incrementing primary key
657
- * email: column.varchar(255, { unique: true, notNull: true }),
658
- * name: column.text({ notNull: true }),
659
- * age: column.integer({ check: 'age >= 0 AND age <= 150' }),
660
- * balance: column.numeric({ precision: 10, scale: 2, default: 0 }),
661
- * is_active: column.boolean({ default: sql.true() }),
662
- * metadata: column.json({ validateJson: true }),
663
- * created_at: column.createdAt(),
664
- * updated_at: column.updatedAt(),
665
- * });
666
- * ```
667
- *
668
- * **Advanced Features:**
669
- * ```ts
670
- * db.createTable("orders", {
671
- * id: column.id(),
672
- * order_number: column.varchar(50, {
673
- * unique: true,
674
- * default: sql.raw("'ORD-' || strftime('%Y%m%d', 'now') || '-' || substr(hex(randomblob(4)), 1, 8)")
675
- * }),
676
- * customer_id: column.foreignKey('users', 'id', {
677
- * onDelete: 'CASCADE',
678
- * onUpdate: 'RESTRICT'
679
- * }),
680
- * status: column.enum(['pending', 'paid', 'shipped', 'delivered'], {
681
- * default: 'pending'
682
- * }),
683
- * total: column.numeric({ precision: 10, scale: 2, notNull: true }),
684
- * // Generated column
685
- * display_total: {
686
- * type: 'TEXT',
687
- * generated: {
688
- * expression: "printf('$%.2f', total)",
689
- * stored: false // VIRTUAL column
690
- * }
691
- * },
692
- * }, {
693
- * constraints: {
694
- * check: ['total >= 0'],
695
- * unique: [['customer_id', 'order_number']]
696
- * }
697
- * });
698
- * ```
699
- *
700
- * **Date/Time Columns:**
701
- * ```ts
702
- * db.createTable("events", {
703
- * id: column.id(),
704
- * name: column.text({ notNull: true }),
705
- * event_date: column.date({ notNull: true }),
706
- * start_time: column.time(),
707
- * created_at: column.timestamp({ default: sql.unixTimestamp() }),
708
- * expires_at: column.datetime({
709
- * default: sql.raw("datetime('now', '+1 year')")
710
- * }),
711
- * });
712
- * ```
713
- *
714
- * **JSON and Advanced Types:**
715
- * ```ts
716
- * db.createTable("products", {
717
- * id: column.uuid({ generateDefault: true }), // UUID primary key
718
- * name: column.text({ notNull: true }),
719
- * price: column.real({ check: 'price > 0' }),
720
- * specifications: column.json({ validateJson: true }),
721
- * tags: column.text(), // JSON array
722
- * image_data: column.blob(),
723
- * search_vector: {
724
- * type: 'TEXT',
725
- * generated: {
726
- * expression: "lower(name || ' ' || coalesce(json_extract(specifications, '$.description'), ''))",
727
- * stored: true // STORED for indexing
728
- * }
729
- * }
730
- * });
731
- * ```
732
- *
733
- * @param tableName - Table name to create.
734
- * @param columns - Column definitions (string, legacy object, or type-safe schema).
735
- * @param options - Table options including constraints and metadata.
736
- *
737
- * @throws {Error} If column definitions are invalid or constraints conflict.
738
- */
739
- createTable<_T extends Record<string, unknown>>(tableName: string, columns: string | Record<string, string> | TableSchema, options?: TableOptions): void;
740
- /**
741
- * Create an index on a table
742
- */
743
- createIndex(indexName: string, tableName: string, columns: string | string[], options?: {
744
- unique?: boolean;
745
- ifNotExists?: boolean;
746
- where?: string;
747
- partial?: string;
748
- }): void;
749
- /**
750
- * Drop a table
751
- */
752
- dropTable(tableName: string, options?: {
753
- ifExists?: boolean;
754
- }): void;
755
- /**
756
- * Drop an index
757
- */
758
- dropIndex(indexName: string, options?: {
759
- ifExists?: boolean;
760
- }): void;
761
- /**
762
- * Type guard to check if columns definition is a TableSchema
763
- */
764
- private isTableSchema;
765
- /**
766
- * Build SQL column definition from ColumnDefinition object
767
- */
768
- private buildColumnSQL;
769
- /**
770
- * Build table-level constraints
771
- */
772
- private buildTableConstraints;
773
- /**
774
- * Check if a string looks like a SQL function call
775
- */
776
- private isSQLFunction;
777
- /**
778
- * Store table comment as metadata (using a system table if needed)
779
- */
780
- private setTableComment;
781
- /**
782
- * Get table comment from metadata
783
- */
784
- getTableComment(tableName: string): string | null;
785
- /**
786
- * Execute a raw SQL statement
787
- */
788
- exec(sql: string): void;
789
- /**
790
- * Prepare a SQL statement for repeated execution
791
- */
792
- prepare(sql: string): import("bun:sqlite").Statement<unknown, SQLQueryBindings[] | [
793
- null
794
- ] | [
795
- string
796
- ] | [
797
- number
798
- ] | [
799
- bigint
800
- ] | [
801
- false
802
- ] | [
803
- true
804
- ] | [
805
- Uint8Array<ArrayBufferLike>
806
- ] | [
807
- Uint8ClampedArray<ArrayBufferLike>
808
- ] | [
809
- Uint16Array<ArrayBufferLike>
810
- ] | [
811
- Uint32Array<ArrayBufferLike>
812
- ] | [
813
- Int8Array<ArrayBufferLike>
814
- ] | [
815
- Int16Array<ArrayBufferLike>
816
- ] | [
817
- Int32Array<ArrayBufferLike>
818
- ] | [
819
- BigUint64Array<ArrayBufferLike>
820
- ] | [
821
- BigInt64Array<ArrayBufferLike>
822
- ] | [
823
- Float32Array<ArrayBufferLike>
824
- ] | [
825
- Float64Array<ArrayBufferLike>
826
- ] | [
827
- Record<string, string | number | bigint | boolean | NodeJS.TypedArray<ArrayBufferLike> | null>
828
- ]>;
829
- /**
830
- * Execute a transaction
831
- */
832
- transaction<T>(fn: () => T): T;
833
- /**
834
- * Begin a transaction manually
835
- */
836
- begin(mode?: "DEFERRED" | "IMMEDIATE" | "EXCLUSIVE"): void;
837
- /**
838
- * Commit a transaction
839
- */
840
- commit(): void;
841
- /**
842
- * Rollback a transaction
843
- */
844
- rollback(): void;
845
- /**
846
- * Create a savepoint
847
- */
848
- savepoint(name: string): void;
849
- /**
850
- * Release a savepoint
851
- */
852
- releaseSavepoint(name: string): void;
853
- /**
854
- * Rollback to a savepoint
855
- */
856
- rollbackToSavepoint(name: string): void;
857
- /**
858
- * Vacuum the database (reclaim space and optimize)
859
- */
860
- vacuum(): void;
861
- /**
862
- * Analyze the database (update statistics for query optimizer)
863
- */
864
- analyze(tableName?: string): void;
865
- /**
866
- * Check database integrity
867
- */
868
- integrityCheck(): Array<{
869
- integrity_check: string;
870
- }>;
871
- /**
872
- * Get database schema information
873
- */
874
- getSchema(): Array<{
875
- name: string;
876
- type: string;
877
- sql: string;
878
- }>;
879
- /**
880
- * Get table info (columns, types, constraints)
881
- */
882
- getTableInfo(tableName: string): Array<{
883
- cid: number;
884
- name: string;
885
- type: string;
886
- notnull: number;
887
- dflt_value: SQLQueryBindings;
888
- pk: number;
889
- }>;
890
- /**
891
- * Get foreign key information for a table
892
- */
893
- getForeignKeys(tableName: string): Array<{
894
- id: number;
895
- seq: number;
896
- table: string;
897
- from: string;
898
- to: string;
899
- on_update: string;
900
- on_delete: string;
901
- match: string;
902
- }>;
903
- /**
904
- * Get index information for a table
905
- */
906
- getIndexes(tableName: string): Array<{
907
- name: string;
908
- unique: number;
909
- origin: string;
910
- partial: number;
911
- }>;
912
- /**
913
- * Set or get a PRAGMA value.
914
- *
915
- * @param name - PRAGMA name (e.g., "foreign_keys", "journal_mode")
916
- * @param value - Value to set (omit to get current value)
917
- * @returns Current value when getting, undefined when setting
918
- */
919
- pragma(name: string, value?: SQLQueryBindings): SQLQueryBindings | undefined;
920
- /**
921
- * Load a SQLite extension.
922
- *
923
- * @param path - Absolute path to the compiled SQLite extension
924
- */
925
- loadExtension(path: string): void;
926
- /**
927
- * Get direct access to the underlying SQLite database instance.
928
- * Use this for advanced operations not covered by the wrapper.
929
- *
930
- * @returns The underlying Database instance
931
- */
932
- getDb(): Database;
933
- }
934
-
935
- export {
936
- DB as default,
937
- };
938
-
939
- export {};