@objectstack/driver-sql 4.0.4 → 4.1.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/src/sql-driver.ts DELETED
@@ -1,1388 +0,0 @@
1
- // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
2
-
3
- /**
4
- * SQL Driver for ObjectStack
5
- *
6
- * Implements the standard IDataDriver from @objectstack/spec via Knex.js.
7
- * Supports PostgreSQL, MySQL, SQLite, and other SQL databases.
8
- */
9
-
10
- import type { QueryAST, DriverOptions } from '@objectstack/spec/data';
11
- import type { IDataDriver } from '@objectstack/spec/contracts';
12
- import knex, { Knex } from 'knex';
13
- import { nanoid } from 'nanoid';
14
-
15
- /**
16
- * Default ID length for auto-generated IDs.
17
- */
18
- const DEFAULT_ID_LENGTH = 16;
19
-
20
- // ── Introspection Types ──────────────────────────────────────────────────────
21
-
22
- export interface IntrospectedColumn {
23
- name: string;
24
- type: string;
25
- nullable: boolean;
26
- defaultValue?: unknown;
27
- isPrimary?: boolean;
28
- isUnique?: boolean;
29
- maxLength?: number;
30
- }
31
-
32
- export interface IntrospectedForeignKey {
33
- columnName: string;
34
- referencedTable: string;
35
- referencedColumn: string;
36
- constraintName?: string;
37
- }
38
-
39
- export interface IntrospectedTable {
40
- name: string;
41
- columns: IntrospectedColumn[];
42
- foreignKeys: IntrospectedForeignKey[];
43
- primaryKeys: string[];
44
- }
45
-
46
- export interface IntrospectedSchema {
47
- tables: Record<string, IntrospectedTable>;
48
- }
49
-
50
- // ── Configuration Types ──────────────────────────────────────────────────────
51
-
52
- /**
53
- * SqlDriver configuration — passed directly to Knex.
54
- * See https://knexjs.org/guide/#configuration-options
55
- */
56
- export type SqlDriverConfig = Knex.Config;
57
-
58
- // ── SQL Driver ───────────────────────────────────────────────────────────────
59
-
60
- /**
61
- * SQL Driver for ObjectStack.
62
- *
63
- * Implements the IDataDriver contract via Knex.js for optimal SQL
64
- * generation against PostgreSQL, MySQL, SQLite and other SQL databases.
65
- */
66
- export class SqlDriver implements IDataDriver {
67
- // IDataDriver metadata
68
- public readonly name: string = 'com.objectstack.driver.sql';
69
- public readonly version: string = '1.0.0';
70
- public readonly supports = {
71
- // Basic CRUD Operations
72
- create: true,
73
- read: true,
74
- update: true,
75
- delete: true,
76
-
77
- // Bulk Operations
78
- bulkCreate: true,
79
- bulkUpdate: true,
80
- bulkDelete: true,
81
-
82
- // Transaction & Connection Management
83
- transactions: true,
84
- savepoints: false,
85
-
86
- // Query Operations
87
- queryFilters: true,
88
- queryAggregations: true,
89
- querySorting: true,
90
- queryPagination: true,
91
- queryWindowFunctions: true,
92
- querySubqueries: true,
93
- queryCTE: false,
94
- joins: true,
95
-
96
- // Advanced Features
97
- fullTextSearch: false,
98
- jsonQuery: false,
99
- geospatialQuery: false,
100
- streaming: false,
101
- jsonFields: true,
102
- arrayFields: true,
103
- vectorSearch: false,
104
-
105
- // Schema Management
106
- schemaSync: true,
107
- batchSchemaSync: false,
108
- migrations: false,
109
- indexes: false,
110
-
111
- // Performance & Optimization
112
- connectionPooling: true,
113
- preparedStatements: true,
114
- queryCache: false,
115
- };
116
-
117
- protected knex: Knex;
118
- protected config: Knex.Config;
119
- protected jsonFields: Record<string, string[]> = {};
120
- protected booleanFields: Record<string, string[]> = {};
121
- protected tablesWithTimestamps: Set<string> = new Set();
122
-
123
- /** Whether the underlying database is a SQLite variant (sqlite3 or better-sqlite3). */
124
- protected get isSqlite(): boolean {
125
- const c = (this.config as any).client;
126
- return c === 'sqlite3' || c === 'better-sqlite3';
127
- }
128
-
129
- /** Whether the underlying database is PostgreSQL. */
130
- protected get isPostgres(): boolean {
131
- const c = (this.config as any).client;
132
- return c === 'pg' || c === 'postgresql';
133
- }
134
-
135
- /** Whether the underlying database is MySQL. */
136
- protected get isMysql(): boolean {
137
- const c = (this.config as any).client;
138
- return c === 'mysql' || c === 'mysql2';
139
- }
140
-
141
- constructor(config: SqlDriverConfig) {
142
- this.config = config;
143
- this.knex = knex(config);
144
- }
145
-
146
- // ===================================
147
- // Lifecycle
148
- // ===================================
149
-
150
- async connect(): Promise<void> {
151
- // Ensure the database directory exists before any query can trigger
152
- // better-sqlite3 to open the file (e.g. loadMetaFromDb on startup).
153
- await this.ensureDatabaseExists();
154
- }
155
-
156
- async checkHealth(): Promise<boolean> {
157
- try {
158
- await this.knex.raw('SELECT 1');
159
- return true;
160
- } catch {
161
- return false;
162
- }
163
- }
164
-
165
- async disconnect(): Promise<void> {
166
- await this.knex.destroy();
167
- }
168
-
169
- // ===================================
170
- // CRUD — DriverInterface core
171
- // ===================================
172
-
173
- async find(object: string, query: QueryAST, options?: DriverOptions): Promise<any[]> {
174
- const builder = this.getBuilder(object, options);
175
-
176
- // SELECT
177
- if (query.fields) {
178
- builder.select((query.fields as string[]).map((f: string) => this.mapSortField(f)));
179
- } else {
180
- builder.select('*');
181
- }
182
-
183
- // WHERE
184
- if (query.where) {
185
- this.applyFilters(builder, query.where);
186
- }
187
-
188
- // ORDER BY
189
- if (query.orderBy && Array.isArray(query.orderBy)) {
190
- for (const item of query.orderBy) {
191
- if (item.field) {
192
- builder.orderBy(this.mapSortField(item.field), item.order || 'asc');
193
- }
194
- }
195
- }
196
-
197
- // PAGINATION
198
- if (query.offset !== undefined) builder.offset(query.offset);
199
- if (query.limit !== undefined) builder.limit(query.limit);
200
-
201
- let results: any[];
202
- try {
203
- results = await builder;
204
- } catch (error: any) {
205
- if (
206
- error.message &&
207
- (error.message.includes('no such column') ||
208
- (error.message.includes('column') && error.message.includes('does not exist')))
209
- ) {
210
- return [];
211
- }
212
- throw error;
213
- }
214
-
215
- if (!Array.isArray(results)) {
216
- return [];
217
- }
218
-
219
- if (this.isSqlite) {
220
- for (const row of results) {
221
- this.formatOutput(object, row);
222
- }
223
- }
224
- return results;
225
- }
226
-
227
- async findOne(object: string, query: QueryAST, options?: DriverOptions): Promise<any> {
228
- // When called with a string/number id fall back gracefully
229
- if (typeof query === 'string' || typeof query === 'number') {
230
- const res = await this.getBuilder(object, options).where('id', query).first();
231
- return this.formatOutput(object, res) || null;
232
- }
233
-
234
- if (query && typeof query === 'object') {
235
- const results = await this.find(object, { ...query, limit: 1 }, options);
236
- return results[0] || null;
237
- }
238
-
239
- return null;
240
- }
241
-
242
- /**
243
- * Stream records matching a structured query.
244
- * NOTE: Current implementation fetches all results then yields them.
245
- * TODO: Use Knex .stream() for true cursor-based streaming on large datasets.
246
- */
247
- async *findStream(object: string, query: QueryAST, options?: DriverOptions): AsyncGenerator<Record<string, any>> {
248
- const results = await this.find(object, query, options);
249
- for (const row of results) {
250
- yield row;
251
- }
252
- }
253
-
254
- async create(object: string, data: Record<string, any>, options?: DriverOptions): Promise<any> {
255
- const { _id, ...rest } = data;
256
- const toInsert = { ...rest };
257
-
258
- if (_id !== undefined && toInsert.id === undefined) {
259
- toInsert.id = _id;
260
- } else if (toInsert.id === undefined) {
261
- toInsert.id = nanoid(DEFAULT_ID_LENGTH);
262
- }
263
-
264
- const builder = this.getBuilder(object, options);
265
- const formatted = this.formatInput(object, toInsert);
266
-
267
- const result = await builder.insert(formatted).returning('*');
268
- return this.formatOutput(object, result[0]);
269
- }
270
-
271
- async update(object: string, id: string | number, data: Record<string, any>, options?: DriverOptions): Promise<any> {
272
- const builder = this.getBuilder(object, options);
273
- const formatted = this.formatInput(object, data);
274
-
275
- if (this.tablesWithTimestamps.has(object)) {
276
- if (this.isSqlite) {
277
- const now = new Date();
278
- formatted.updated_at = now.toISOString().replace('T', ' ').replace('Z', '');
279
- } else {
280
- formatted.updated_at = this.knex.fn.now();
281
- }
282
- }
283
-
284
- await builder.where('id', id).update(formatted);
285
-
286
- const updated = await this.getBuilder(object, options).where('id', id).first();
287
- return this.formatOutput(object, updated) || null;
288
- }
289
-
290
- async upsert(object: string, data: Record<string, any>, conflictKeys?: string[], options?: DriverOptions): Promise<Record<string, any>> {
291
- const { _id, ...rest } = data;
292
- const toUpsert = { ...rest };
293
-
294
- if (_id !== undefined && toUpsert.id === undefined) {
295
- toUpsert.id = _id;
296
- } else if (toUpsert.id === undefined) {
297
- toUpsert.id = nanoid(DEFAULT_ID_LENGTH);
298
- }
299
-
300
- const formatted = this.formatInput(object, toUpsert);
301
- const mergeKeys = conflictKeys && conflictKeys.length > 0 ? conflictKeys : ['id'];
302
-
303
- const builder = this.getBuilder(object, options);
304
- await builder.insert(formatted).onConflict(mergeKeys).merge();
305
-
306
- const result = await this.getBuilder(object, options).where('id', toUpsert.id).first();
307
- return this.formatOutput(object, result) || toUpsert;
308
- }
309
-
310
- async delete(object: string, id: string | number, options?: DriverOptions): Promise<boolean> {
311
- const builder = this.getBuilder(object, options);
312
- const count = await builder.where('id', id).delete();
313
- return count > 0;
314
- }
315
-
316
- // ===================================
317
- // Bulk & Batch Operations
318
- // ===================================
319
-
320
- async bulkCreate(object: string, data: any[], options?: DriverOptions): Promise<any> {
321
- const builder = this.getBuilder(object, options);
322
- return await builder.insert(data).returning('*');
323
- }
324
-
325
- /**
326
- * Batch-update multiple records by ID.
327
- * NOTE: Current implementation performs sequential updates for correctness.
328
- * TODO: Optimize with SQL CASE statements or batched transactions for performance.
329
- */
330
- async bulkUpdate(object: string, updates: Array<{ id: string | number; data: Record<string, any> }>, options?: DriverOptions): Promise<Record<string, any>[]> {
331
- const results: Record<string, any>[] = [];
332
- for (const { id, data } of updates) {
333
- const updated = await this.update(object, id, data, options);
334
- if (updated) results.push(updated);
335
- }
336
- return results;
337
- }
338
-
339
- async bulkDelete(object: string, ids: Array<string | number>, options?: DriverOptions): Promise<void> {
340
- const builder = this.getBuilder(object, options);
341
- await builder.whereIn('id', ids).delete();
342
- }
343
-
344
- async updateMany(object: string, query: QueryAST, data: any, options?: DriverOptions): Promise<number> {
345
- const builder = this.getBuilder(object, options);
346
- if (query.where) this.applyFilters(builder, query.where);
347
- const count = await builder.update(data);
348
- return count || 0;
349
- }
350
-
351
- async deleteMany(object: string, query: QueryAST, options?: DriverOptions): Promise<number> {
352
- const builder = this.getBuilder(object, options);
353
- if (query.where) this.applyFilters(builder, query.where);
354
- const count = await builder.delete();
355
- return count || 0;
356
- }
357
-
358
- async count(object: string, query?: QueryAST, options?: DriverOptions): Promise<number> {
359
- const builder = this.getBuilder(object, options);
360
-
361
- if (query?.where) {
362
- this.applyFilters(builder, query.where);
363
- }
364
-
365
- const result = await builder.count<{ count: number }[]>('* as count');
366
- if (result && result.length > 0) {
367
- const row: any = result[0];
368
- return Number(row.count ?? row['count(*)'] ?? 0);
369
- }
370
- return 0;
371
- }
372
-
373
- // ===================================
374
- // Raw Execution
375
- // ===================================
376
-
377
- async execute(command: any, params?: any[], options?: DriverOptions): Promise<any> {
378
- if (typeof command !== 'string') {
379
- return command;
380
- }
381
-
382
- const builder =
383
- options?.transaction
384
- ? this.knex.raw(command, params || []).transacting(options.transaction as Knex.Transaction)
385
- : this.knex.raw(command, params || []);
386
-
387
- return await builder;
388
- }
389
-
390
- // ===================================
391
- // Transactions
392
- // ===================================
393
-
394
- async beginTransaction(): Promise<Knex.Transaction> {
395
- return await this.knex.transaction();
396
- }
397
-
398
- /** IDataDriver standard */
399
- async commit(transaction: unknown): Promise<void> {
400
- await (transaction as Knex.Transaction).commit();
401
- }
402
-
403
- /** IDataDriver standard */
404
- async rollback(transaction: unknown): Promise<void> {
405
- await (transaction as Knex.Transaction).rollback();
406
- }
407
-
408
- /** @deprecated Use commit() instead */
409
- async commitTransaction(trx: Knex.Transaction): Promise<void> {
410
- await this.commit(trx);
411
- }
412
-
413
- /** @deprecated Use rollback() instead */
414
- async rollbackTransaction(trx: Knex.Transaction): Promise<void> {
415
- await this.rollback(trx);
416
- }
417
-
418
- // ===================================
419
- // Aggregation
420
- // ===================================
421
-
422
- async aggregate(object: string, query: any, options?: DriverOptions): Promise<any> {
423
- const builder = this.getBuilder(object, options);
424
-
425
- if (query.where) {
426
- this.applyFilters(builder, query.where);
427
- }
428
-
429
- if (query.groupBy) {
430
- builder.groupBy(query.groupBy);
431
- for (const field of query.groupBy) {
432
- builder.select(field);
433
- }
434
- }
435
-
436
- const aggregates = query.aggregations || query.aggregate;
437
- if (aggregates) {
438
- for (const agg of aggregates) {
439
- const funcName = agg.function || agg.func;
440
- const rawFunc = this.mapAggregateFunc(funcName);
441
- if (agg.alias) {
442
- builder.select(this.knex.raw(`${rawFunc}(??) as ??`, [agg.field, agg.alias]));
443
- } else {
444
- builder.select(this.knex.raw(`${rawFunc}(??)`, [agg.field]));
445
- }
446
- }
447
- }
448
-
449
- return await builder;
450
- }
451
-
452
- // ===================================
453
- // Distinct
454
- // ===================================
455
-
456
- async distinct(object: string, field: string, filters?: any, options?: DriverOptions): Promise<any[]> {
457
- const builder = this.getBuilder(object, options);
458
-
459
- if (filters) {
460
- this.applyFilters(builder, filters);
461
- }
462
-
463
- builder.distinct(field);
464
- const results = await builder;
465
- return results.map((row: any) => row[field]);
466
- }
467
-
468
- // ===================================
469
- // Window Functions
470
- // ===================================
471
-
472
- async findWithWindowFunctions(object: string, query: any, options?: DriverOptions): Promise<any[]> {
473
- const builder = this.getBuilder(object, options);
474
-
475
- builder.select('*');
476
-
477
- if (query.where) {
478
- this.applyFilters(builder, query.where);
479
- }
480
-
481
- if (query.windowFunctions && Array.isArray(query.windowFunctions)) {
482
- for (const wf of query.windowFunctions) {
483
- const windowFunc = this.buildWindowFunction(wf);
484
- builder.select(this.knex.raw(`${windowFunc} as ??`, [wf.alias]));
485
- }
486
- }
487
-
488
- if (query.orderBy && Array.isArray(query.orderBy)) {
489
- for (const sort of query.orderBy) {
490
- builder.orderBy(this.mapSortField(sort.field), sort.order || 'asc');
491
- }
492
- }
493
-
494
- if (query.limit) builder.limit(query.limit);
495
- if (query.offset) builder.offset(query.offset);
496
-
497
- return await builder;
498
- }
499
-
500
- // ===================================
501
- // Query Plan Analysis
502
- // ===================================
503
-
504
- /** IDataDriver standard: analyze query performance */
505
- async explain(object: string, query: any, options?: DriverOptions): Promise<any> {
506
- return this.analyzeQuery(object, query, options);
507
- }
508
-
509
- async analyzeQuery(object: string, query: any, options?: DriverOptions): Promise<any> {
510
- const builder = this.getBuilder(object, options);
511
-
512
- if (query.fields) {
513
- builder.select(query.fields);
514
- } else {
515
- builder.select('*');
516
- }
517
-
518
- if (query.where) {
519
- this.applyFilters(builder, query.where);
520
- }
521
-
522
- if (query.orderBy && Array.isArray(query.orderBy)) {
523
- for (const sort of query.orderBy) {
524
- builder.orderBy(this.mapSortField(sort.field), sort.order || 'asc');
525
- }
526
- }
527
-
528
- if (query.limit) builder.limit(query.limit);
529
- if (query.offset) builder.offset(query.offset);
530
-
531
- const sql = builder.toSQL();
532
- const client = (this.config as any).client;
533
- let explainResults: any;
534
-
535
- try {
536
- if (this.isPostgres) {
537
- explainResults = await this.knex.raw(`EXPLAIN (FORMAT JSON, ANALYZE) ${sql.sql}`, sql.bindings);
538
- } else if (this.isMysql) {
539
- explainResults = await this.knex.raw(`EXPLAIN FORMAT=JSON ${sql.sql}`, sql.bindings);
540
- } else if (this.isSqlite) {
541
- explainResults = await this.knex.raw(`EXPLAIN QUERY PLAN ${sql.sql}`, sql.bindings);
542
- } else {
543
- return {
544
- sql: sql.sql,
545
- bindings: sql.bindings,
546
- client,
547
- note: 'EXPLAIN not supported for this database client',
548
- };
549
- }
550
-
551
- return { sql: sql.sql, bindings: sql.bindings, client, plan: explainResults };
552
- } catch (error: any) {
553
- return {
554
- sql: sql.sql,
555
- bindings: sql.bindings,
556
- client,
557
- error: error.message,
558
- note: 'Failed to execute EXPLAIN.',
559
- };
560
- }
561
- }
562
-
563
- // ===================================
564
- // Schema Sync (syncSchema / init)
565
- // ===================================
566
-
567
- async syncSchema(object: string, schema: unknown, _options?: DriverOptions): Promise<void> {
568
- const objectDef = schema as { name: string; fields?: Record<string, any> };
569
- // Use the physical table name (`object`) for DDL operations. The caller
570
- // (e.g. syncRegisteredSchemas) passes the resolved tableName (e.g. 'sys_user')
571
- // while objectDef.name may contain the FQN (e.g. 'sys__user').
572
- await this.initObjects([{ ...objectDef, name: object }]);
573
- }
574
-
575
- async dropTable(object: string, _options?: DriverOptions): Promise<void> {
576
- await this.knex.schema.dropTableIfExists(object);
577
- }
578
-
579
- /**
580
- * Batch-initialise tables from an array of object definitions.
581
- */
582
- async initObjects(objects: Array<{ name: string; tableName?: string; fields?: Record<string, any> }>): Promise<void> {
583
- await this.ensureDatabaseExists();
584
-
585
- for (const obj of objects) {
586
- // Prefer explicit tableName (physical name) over obj.name (which may be a FQN).
587
- const tableName = obj.tableName || obj.name;
588
-
589
- const jsonCols: string[] = [];
590
- const booleanCols: string[] = [];
591
- if (obj.fields) {
592
- for (const [name, field] of Object.entries<any>(obj.fields)) {
593
- const type = field.type || 'string';
594
- if (this.isJsonField(type, field)) {
595
- jsonCols.push(name);
596
- }
597
- if (type === 'boolean') {
598
- booleanCols.push(name);
599
- }
600
- }
601
- }
602
- this.jsonFields[tableName] = jsonCols;
603
- this.booleanFields[tableName] = booleanCols;
604
-
605
- let exists = await this.knex.schema.hasTable(tableName);
606
-
607
- if (exists) {
608
- const columnInfo = await this.knex(tableName).columnInfo();
609
- const existingColumns = Object.keys(columnInfo);
610
-
611
- if (existingColumns.includes('_id') && !existingColumns.includes('id')) {
612
- await this.knex.schema.dropTable(tableName);
613
- exists = false;
614
- }
615
- }
616
-
617
- // Columns created unconditionally by initObjects — skip them when
618
- // iterating obj.fields to avoid duplicate-column errors (e.g. SQLite
619
- // rejects CREATE TABLE with two columns of the same name).
620
- const builtinColumns = new Set(['id', 'created_at', 'updated_at']);
621
-
622
- if (!exists) {
623
- await this.knex.schema.createTable(tableName, (table) => {
624
- table.string('id').primary();
625
- table.timestamp('created_at').defaultTo(this.knex.fn.now());
626
- table.timestamp('updated_at').defaultTo(this.knex.fn.now());
627
- if (obj.fields) {
628
- for (const [name, field] of Object.entries(obj.fields)) {
629
- if (builtinColumns.has(name)) continue;
630
- this.createColumn(table, name, field);
631
- }
632
- }
633
- });
634
- this.tablesWithTimestamps.add(tableName);
635
- } else {
636
- const columnInfo = await this.knex(tableName).columnInfo();
637
- const existingColumns = Object.keys(columnInfo);
638
-
639
- if (existingColumns.includes('updated_at')) {
640
- this.tablesWithTimestamps.add(tableName);
641
- }
642
-
643
- await this.knex.schema.alterTable(tableName, (table) => {
644
- if (obj.fields) {
645
- for (const [name, field] of Object.entries(obj.fields)) {
646
- if (!existingColumns.includes(name)) {
647
- this.createColumn(table, name, field);
648
- }
649
- }
650
- }
651
- });
652
- }
653
- }
654
- }
655
-
656
- // ===================================
657
- // Schema Introspection
658
- // ===================================
659
-
660
- async introspectSchema(): Promise<IntrospectedSchema> {
661
- const tables: Record<string, IntrospectedTable> = {};
662
- let tableNames: string[] = [];
663
-
664
- if (this.isPostgres) {
665
- const result = await this.knex.raw(`
666
- SELECT table_name
667
- FROM information_schema.tables
668
- WHERE table_schema = 'public'
669
- AND table_type = 'BASE TABLE'
670
- `);
671
- tableNames = result.rows.map((row: any) => row.table_name);
672
- } else if (this.isMysql) {
673
- const result = await this.knex.raw(`
674
- SELECT table_name
675
- FROM information_schema.tables
676
- WHERE table_schema = DATABASE()
677
- AND table_type = 'BASE TABLE'
678
- `);
679
- tableNames = result[0].map((row: any) => row.TABLE_NAME);
680
- } else if (this.isSqlite) {
681
- const result = await this.knex.raw(`
682
- SELECT name as table_name
683
- FROM sqlite_master
684
- WHERE type='table'
685
- AND name NOT LIKE 'sqlite_%'
686
- `);
687
- tableNames = result.map((row: any) => row.table_name);
688
- }
689
-
690
- for (const tableName of tableNames) {
691
- const columns = await this.introspectColumns(tableName);
692
- const foreignKeys = await this.introspectForeignKeys(tableName);
693
- const primaryKeys = await this.introspectPrimaryKeys(tableName);
694
- const uniqueConstraints = await this.introspectUniqueConstraints(tableName);
695
-
696
- for (const col of columns) {
697
- if (primaryKeys.includes(col.name)) col.isPrimary = true;
698
- if (uniqueConstraints.includes(col.name)) col.isUnique = true;
699
- }
700
-
701
- tables[tableName] = { name: tableName, columns, foreignKeys, primaryKeys };
702
- }
703
-
704
- return { tables };
705
- }
706
-
707
- // ===================================
708
- // Internal helpers
709
- // ===================================
710
-
711
- /** Expose the underlying Knex instance for advanced usage. */
712
- getKnex(): Knex {
713
- return this.knex;
714
- }
715
-
716
- protected getBuilder(object: string, options?: DriverOptions) {
717
- let builder = this.knex(object);
718
- if (options?.transaction) {
719
- builder = builder.transacting(options.transaction as Knex.Transaction);
720
- }
721
- return builder;
722
- }
723
-
724
- // ── Filter helpers ──────────────────────────────────────────────────────────
725
-
726
- protected applyFilters(builder: Knex.QueryBuilder, filters: any) {
727
- if (!filters) return;
728
-
729
- if (!Array.isArray(filters) && typeof filters === 'object') {
730
- const hasMongoOperators = Object.keys(filters).some(
731
- (k) =>
732
- k.startsWith('$') ||
733
- (typeof filters[k] === 'object' &&
734
- filters[k] !== null &&
735
- Object.keys(filters[k]).some((op) => op.startsWith('$'))),
736
- );
737
-
738
- if (hasMongoOperators) {
739
- this.applyFilterCondition(builder, filters);
740
- return;
741
- }
742
-
743
- for (const [key, value] of Object.entries(filters)) {
744
- if (['limit', 'offset', 'fields', 'orderBy'].includes(key)) continue;
745
- builder.where(key, value as any);
746
- }
747
- return;
748
- }
749
-
750
- if (!Array.isArray(filters) || filters.length === 0) return;
751
-
752
- let nextJoin: 'and' | 'or' = 'and';
753
-
754
- for (const item of filters) {
755
- if (typeof item === 'string') {
756
- if (item.toLowerCase() === 'or') nextJoin = 'or';
757
- else if (item.toLowerCase() === 'and') nextJoin = 'and';
758
- continue;
759
- }
760
-
761
- if (Array.isArray(item)) {
762
- const [fieldRaw, op, value] = item;
763
- const isCriterion = typeof fieldRaw === 'string' && typeof op === 'string';
764
-
765
- if (isCriterion) {
766
- const field = this.mapSortField(fieldRaw);
767
- const apply = (b: any) => {
768
- const method = nextJoin === 'or' ? 'orWhere' : 'where';
769
- const methodIn = nextJoin === 'or' ? 'orWhereIn' : 'whereIn';
770
- const methodNotIn = nextJoin === 'or' ? 'orWhereNotIn' : 'whereNotIn';
771
-
772
- if (op === 'contains') {
773
- b[method](field, 'like', `%${value}%`);
774
- return;
775
- }
776
-
777
- switch (op) {
778
- case '=':
779
- b[method](field, value);
780
- break;
781
- case '!=':
782
- b[method](field, '<>', value);
783
- break;
784
- case 'in':
785
- b[methodIn](field, value);
786
- break;
787
- case 'nin':
788
- b[methodNotIn](field, value);
789
- break;
790
- default:
791
- b[method](field, op, value);
792
- }
793
- };
794
- apply(builder);
795
- } else {
796
- const method = nextJoin === 'or' ? 'orWhere' : 'where';
797
- (builder as any)[method]((qb: any) => {
798
- this.applyFilters(qb, item);
799
- });
800
- }
801
-
802
- nextJoin = 'and';
803
- }
804
- }
805
- }
806
-
807
- protected applyFilterCondition(builder: Knex.QueryBuilder, condition: any, logicalOp: 'and' | 'or' = 'and') {
808
- if (!condition || typeof condition !== 'object') return;
809
-
810
- for (const [key, value] of Object.entries(condition)) {
811
- if (key === '$and' && Array.isArray(value)) {
812
- builder.where((qb) => {
813
- for (const sub of value) {
814
- qb.where((subQb) => {
815
- this.applyFilterCondition(subQb, sub, 'and');
816
- });
817
- }
818
- });
819
- } else if (key === '$or' && Array.isArray(value)) {
820
- const method = logicalOp === 'or' ? 'orWhere' : 'where';
821
- (builder as any)[method]((qb: any) => {
822
- for (const sub of value) {
823
- qb.orWhere((subQb: any) => {
824
- this.applyFilterCondition(subQb, sub, 'or');
825
- });
826
- }
827
- });
828
- } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
829
- const field = this.mapSortField(key);
830
- for (const [op, opValue] of Object.entries(value as Record<string, any>)) {
831
- const method = logicalOp === 'or' ? 'orWhere' : 'where';
832
- switch (op) {
833
- case '$eq':
834
- (builder as any)[method](field, opValue);
835
- break;
836
- case '$ne':
837
- (builder as any)[method](field, '<>', opValue);
838
- break;
839
- case '$gt':
840
- (builder as any)[method](field, '>', opValue);
841
- break;
842
- case '$gte':
843
- (builder as any)[method](field, '>=', opValue);
844
- break;
845
- case '$lt':
846
- (builder as any)[method](field, '<', opValue);
847
- break;
848
- case '$lte':
849
- (builder as any)[method](field, '<=', opValue);
850
- break;
851
- case '$in': {
852
- const mIn = logicalOp === 'or' ? 'orWhereIn' : 'whereIn';
853
- (builder as any)[mIn](field, opValue as any[]);
854
- break;
855
- }
856
- case '$nin': {
857
- const mNotIn = logicalOp === 'or' ? 'orWhereNotIn' : 'whereNotIn';
858
- (builder as any)[mNotIn](field, opValue as any[]);
859
- break;
860
- }
861
- case '$contains':
862
- (builder as any)[method](field, 'like', `%${opValue}%`);
863
- break;
864
- default:
865
- (builder as any)[method](field, opValue);
866
- }
867
- }
868
- } else {
869
- const field = this.mapSortField(key);
870
- const method = logicalOp === 'or' ? 'orWhere' : 'where';
871
- (builder as any)[method](field, value as any);
872
- }
873
- }
874
- }
875
-
876
- // ── Field mapping ───────────────────────────────────────────────────────────
877
-
878
- protected mapSortField(field: string): string {
879
- if (field === 'createdAt') return 'created_at';
880
- if (field === 'updatedAt') return 'updated_at';
881
- return field;
882
- }
883
-
884
- protected mapAggregateFunc(func: string): string {
885
- switch (func) {
886
- case 'count':
887
- return 'count';
888
- case 'sum':
889
- return 'sum';
890
- case 'avg':
891
- return 'avg';
892
- case 'min':
893
- return 'min';
894
- case 'max':
895
- return 'max';
896
- default:
897
- throw new Error(`Unsupported aggregate function: ${func}`);
898
- }
899
- }
900
-
901
- // ── Window function builder ─────────────────────────────────────────────────
902
-
903
- protected buildWindowFunction(spec: any): string {
904
- const func = spec.function.toUpperCase();
905
- let sql = `${func}()`;
906
-
907
- const overParts: string[] = [];
908
-
909
- if (spec.partitionBy && Array.isArray(spec.partitionBy) && spec.partitionBy.length > 0) {
910
- const partitionFields = spec.partitionBy.map((f: string) => this.mapSortField(f)).join(', ');
911
- overParts.push(`PARTITION BY ${partitionFields}`);
912
- }
913
-
914
- if (spec.orderBy && Array.isArray(spec.orderBy) && spec.orderBy.length > 0) {
915
- const orderFields = spec.orderBy
916
- .map((s: any) => {
917
- const field = this.mapSortField(s.field);
918
- const order = (s.order || 'asc').toUpperCase();
919
- return `${field} ${order}`;
920
- })
921
- .join(', ');
922
- overParts.push(`ORDER BY ${orderFields}`);
923
- }
924
-
925
- sql += overParts.length > 0 ? ` OVER (${overParts.join(' ')})` : ` OVER ()`;
926
- return sql;
927
- }
928
-
929
- // ── Column creation helper ──────────────────────────────────────────────────
930
-
931
- protected createColumn(table: Knex.CreateTableBuilder, name: string, field: any) {
932
- if (field.multiple) {
933
- table.json(name);
934
- return;
935
- }
936
-
937
- const type = field.type || 'string';
938
- let col: any;
939
- switch (type) {
940
- case 'string':
941
- case 'email':
942
- case 'url':
943
- case 'phone':
944
- case 'password':
945
- col = table.string(name);
946
- break;
947
- case 'text':
948
- case 'textarea':
949
- case 'html':
950
- case 'markdown':
951
- col = table.text(name);
952
- break;
953
- case 'integer':
954
- case 'int':
955
- col = table.integer(name);
956
- break;
957
- case 'float':
958
- case 'number':
959
- case 'currency':
960
- case 'percent':
961
- col = table.float(name);
962
- break;
963
- case 'boolean':
964
- col = table.boolean(name);
965
- break;
966
- case 'date':
967
- col = table.date(name);
968
- break;
969
- case 'datetime':
970
- col = table.timestamp(name);
971
- break;
972
- case 'time':
973
- col = table.time(name);
974
- break;
975
- case 'json':
976
- case 'object':
977
- case 'array':
978
- case 'image':
979
- case 'file':
980
- case 'avatar':
981
- case 'location':
982
- col = table.json(name);
983
- break;
984
- case 'lookup':
985
- col = table.string(name);
986
- if (field.reference_to) {
987
- table.foreign(name).references('id').inTable(field.reference_to);
988
- }
989
- break;
990
- case 'summary':
991
- col = table.float(name);
992
- break;
993
- case 'auto_number':
994
- col = table.string(name);
995
- break;
996
- case 'formula':
997
- return; // Virtual — no column
998
- default:
999
- col = table.string(name);
1000
- }
1001
-
1002
- if (col) {
1003
- if (field.unique) col.unique();
1004
- if (field.required) col.notNullable();
1005
- }
1006
- }
1007
-
1008
- // ── Database helpers ────────────────────────────────────────────────────────
1009
-
1010
- protected async ensureDatabaseExists() {
1011
- // SQLite auto-creates database files but NOT parent directories.
1012
- // Ensure the directory exists so better-sqlite3 can create the file.
1013
- if (this.isSqlite) {
1014
- const conn = (this.config as any).connection;
1015
- const filename = typeof conn === 'string' ? conn : conn?.filename;
1016
- if (filename && filename !== ':memory:' && !filename.startsWith(':')) {
1017
- const { dirname } = await import('node:path');
1018
- const { mkdir } = await import('node:fs/promises');
1019
- const dir = dirname(filename);
1020
- if (dir && dir !== '.') {
1021
- await mkdir(dir, { recursive: true });
1022
- }
1023
- }
1024
- return;
1025
- }
1026
-
1027
- // Only PostgreSQL and MySQL support programmatic database creation
1028
- if (!this.isPostgres && !this.isMysql) return;
1029
-
1030
- try {
1031
- await this.knex.raw('SELECT 1');
1032
- } catch (e: any) {
1033
- // PostgreSQL: '3D000' = database does not exist
1034
- // MySQL: 'ER_BAD_DB_ERROR' (errno 1049) = unknown database
1035
- if (
1036
- e.code === '3D000' ||
1037
- e.code === 'ER_BAD_DB_ERROR' ||
1038
- e.errno === 1049
1039
- ) {
1040
- await this.createDatabase();
1041
- } else {
1042
- throw e;
1043
- }
1044
- }
1045
- }
1046
-
1047
- protected async createDatabase() {
1048
- const config = this.config as any;
1049
- const connection = config.connection;
1050
- let dbName = '';
1051
- const adminConfig = { ...config };
1052
-
1053
- if (this.isPostgres) {
1054
- // PostgreSQL: connect to the 'postgres' maintenance database
1055
- if (typeof connection === 'string') {
1056
- const url = new URL(connection);
1057
- dbName = url.pathname.slice(1);
1058
- url.pathname = '/postgres';
1059
- adminConfig.connection = url.toString();
1060
- } else {
1061
- dbName = connection.database;
1062
- adminConfig.connection = { ...connection, database: 'postgres' };
1063
- }
1064
- } else if (this.isMysql) {
1065
- // MySQL: connect without specifying a database
1066
- if (typeof connection === 'string') {
1067
- const url = new URL(connection);
1068
- dbName = url.pathname.slice(1);
1069
- url.pathname = '/';
1070
- adminConfig.connection = url.toString();
1071
- } else {
1072
- dbName = connection.database;
1073
- const { database: _db, ...rest } = connection;
1074
- adminConfig.connection = rest;
1075
- }
1076
- } else {
1077
- return; // Unsupported dialect for auto-creation
1078
- }
1079
-
1080
- const adminKnex = knex(adminConfig);
1081
- try {
1082
- if (this.isPostgres) {
1083
- await adminKnex.raw(`CREATE DATABASE "${dbName}"`);
1084
- } else if (this.isMysql) {
1085
- await adminKnex.raw(`CREATE DATABASE IF NOT EXISTS \`${dbName}\``);
1086
- }
1087
- } finally {
1088
- await adminKnex.destroy();
1089
- }
1090
- }
1091
-
1092
- protected isJsonField(type: string, field: any): boolean {
1093
- return ['json', 'object', 'array', 'image', 'file', 'avatar', 'location'].includes(type) || field.multiple;
1094
- }
1095
-
1096
- // ── SQLite serialisation ────────────────────────────────────────────────────
1097
-
1098
- protected formatInput(object: string, data: any): any {
1099
- if (!this.isSqlite) return data;
1100
-
1101
- const fields = this.jsonFields[object];
1102
- if (!fields || fields.length === 0) return data;
1103
-
1104
- const copy = { ...data };
1105
- for (const field of fields) {
1106
- if (copy[field] !== undefined && typeof copy[field] === 'object' && copy[field] !== null) {
1107
- copy[field] = JSON.stringify(copy[field]);
1108
- }
1109
- }
1110
- return copy;
1111
- }
1112
-
1113
- protected formatOutput(object: string, data: any): any {
1114
- if (!data) return data;
1115
-
1116
- if (this.isSqlite) {
1117
- const jsonFields = this.jsonFields[object];
1118
- if (jsonFields && jsonFields.length > 0) {
1119
- for (const field of jsonFields) {
1120
- if (data[field] !== undefined && typeof data[field] === 'string') {
1121
- try {
1122
- data[field] = JSON.parse(data[field]);
1123
- } catch {
1124
- // keep as string
1125
- }
1126
- }
1127
- }
1128
- }
1129
-
1130
- const booleanFields = this.booleanFields[object];
1131
- if (booleanFields && booleanFields.length > 0) {
1132
- for (const field of booleanFields) {
1133
- if (data[field] !== undefined && data[field] !== null) {
1134
- data[field] = Boolean(data[field]);
1135
- }
1136
- }
1137
- }
1138
- }
1139
-
1140
- return data;
1141
- }
1142
-
1143
- // ── Introspection internals ─────────────────────────────────────────────────
1144
-
1145
- protected async introspectColumns(tableName: string): Promise<IntrospectedColumn[]> {
1146
- const columnInfo = await this.knex(tableName).columnInfo();
1147
- const columns: IntrospectedColumn[] = [];
1148
-
1149
- for (const [colName, info] of Object.entries<any>(columnInfo)) {
1150
- let type = 'string';
1151
- let maxLength: number | undefined;
1152
-
1153
- if (this.isSqlite) {
1154
- type = info.type?.toLowerCase() || 'string';
1155
- } else {
1156
- type = info.type || 'string';
1157
- }
1158
-
1159
- if (info.maxLength) {
1160
- maxLength = info.maxLength;
1161
- }
1162
-
1163
- columns.push({
1164
- name: colName,
1165
- type,
1166
- nullable: info.nullable !== false,
1167
- defaultValue: info.defaultValue,
1168
- isPrimary: false,
1169
- isUnique: false,
1170
- maxLength,
1171
- });
1172
- }
1173
-
1174
- return columns;
1175
- }
1176
-
1177
- protected async introspectForeignKeys(tableName: string): Promise<IntrospectedForeignKey[]> {
1178
- const foreignKeys: IntrospectedForeignKey[] = [];
1179
-
1180
- try {
1181
- if (this.isPostgres) {
1182
- const result = await this.knex.raw(
1183
- `
1184
- SELECT
1185
- kcu.column_name,
1186
- ccu.table_name AS referenced_table,
1187
- ccu.column_name AS referenced_column,
1188
- tc.constraint_name
1189
- FROM information_schema.table_constraints AS tc
1190
- JOIN information_schema.key_column_usage AS kcu
1191
- ON tc.constraint_name = kcu.constraint_name
1192
- AND tc.table_schema = kcu.table_schema
1193
- JOIN information_schema.constraint_column_usage AS ccu
1194
- ON ccu.constraint_name = tc.constraint_name
1195
- AND ccu.table_schema = tc.table_schema
1196
- WHERE tc.constraint_type = 'FOREIGN KEY'
1197
- AND tc.table_name = ?
1198
- `,
1199
- [tableName],
1200
- );
1201
-
1202
- for (const row of result.rows) {
1203
- foreignKeys.push({
1204
- columnName: row.column_name,
1205
- referencedTable: row.referenced_table,
1206
- referencedColumn: row.referenced_column,
1207
- constraintName: row.constraint_name,
1208
- });
1209
- }
1210
- } else if (this.isMysql) {
1211
- const result = await this.knex.raw(
1212
- `
1213
- SELECT
1214
- COLUMN_NAME as column_name,
1215
- REFERENCED_TABLE_NAME as referenced_table,
1216
- REFERENCED_COLUMN_NAME as referenced_column,
1217
- CONSTRAINT_NAME as constraint_name
1218
- FROM information_schema.KEY_COLUMN_USAGE
1219
- WHERE TABLE_SCHEMA = DATABASE()
1220
- AND TABLE_NAME = ?
1221
- AND REFERENCED_TABLE_NAME IS NOT NULL
1222
- `,
1223
- [tableName],
1224
- );
1225
-
1226
- for (const row of result[0]) {
1227
- foreignKeys.push({
1228
- columnName: row.column_name,
1229
- referencedTable: row.referenced_table,
1230
- referencedColumn: row.referenced_column,
1231
- constraintName: row.constraint_name,
1232
- });
1233
- }
1234
- } else if (this.isSqlite) {
1235
- const tableExistsResult = await this.knex.raw(
1236
- "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
1237
- [tableName],
1238
- );
1239
-
1240
- if (!Array.isArray(tableExistsResult) || tableExistsResult.length === 0) {
1241
- return foreignKeys;
1242
- }
1243
-
1244
- const safeTableName = tableName.replace(/[^a-zA-Z0-9_]/g, '');
1245
- const result = await this.knex.raw(`PRAGMA foreign_key_list(${safeTableName})`);
1246
-
1247
- for (const row of result) {
1248
- foreignKeys.push({
1249
- columnName: row.from,
1250
- referencedTable: row.table,
1251
- referencedColumn: row.to,
1252
- constraintName: `fk_${tableName}_${row.from}`,
1253
- });
1254
- }
1255
- }
1256
- } catch {
1257
- // silently ignore introspection errors
1258
- }
1259
-
1260
- return foreignKeys;
1261
- }
1262
-
1263
- protected async introspectPrimaryKeys(tableName: string): Promise<string[]> {
1264
- const primaryKeys: string[] = [];
1265
-
1266
- try {
1267
- if (this.isPostgres) {
1268
- const result = await this.knex.raw(
1269
- `
1270
- SELECT a.attname as column_name
1271
- FROM pg_index i
1272
- JOIN pg_attribute a ON a.attrelid = i.indrelid
1273
- AND a.attnum = ANY(i.indkey)
1274
- WHERE i.indrelid = ?::regclass
1275
- AND i.indisprimary
1276
- `,
1277
- [tableName],
1278
- );
1279
-
1280
- for (const row of result.rows) {
1281
- primaryKeys.push(row.column_name);
1282
- }
1283
- } else if (this.isMysql) {
1284
- const result = await this.knex.raw(
1285
- `
1286
- SELECT COLUMN_NAME as column_name
1287
- FROM information_schema.KEY_COLUMN_USAGE
1288
- WHERE TABLE_SCHEMA = DATABASE()
1289
- AND TABLE_NAME = ?
1290
- AND CONSTRAINT_NAME = 'PRIMARY'
1291
- `,
1292
- [tableName],
1293
- );
1294
-
1295
- for (const row of result[0]) {
1296
- primaryKeys.push(row.column_name);
1297
- }
1298
- } else if (this.isSqlite) {
1299
- const safeTableName = tableName.replace(/[^a-zA-Z0-9_]/g, '');
1300
-
1301
- const tablesResult = await this.knex.raw("SELECT name FROM sqlite_master WHERE type = 'table'");
1302
- const tableNames = Array.isArray(tablesResult) ? tablesResult.map((row: any) => row.name) : [];
1303
-
1304
- if (!tableNames.includes(safeTableName)) {
1305
- return primaryKeys;
1306
- }
1307
-
1308
- const result = await this.knex.raw(`PRAGMA table_info(${safeTableName})`);
1309
-
1310
- for (const row of result) {
1311
- if (row.pk === 1) {
1312
- primaryKeys.push(row.name);
1313
- }
1314
- }
1315
- }
1316
- } catch {
1317
- // silently ignore
1318
- }
1319
-
1320
- return primaryKeys;
1321
- }
1322
-
1323
- protected async introspectUniqueConstraints(tableName: string): Promise<string[]> {
1324
- const uniqueColumns: string[] = [];
1325
-
1326
- try {
1327
- if (this.isPostgres) {
1328
- const result = await this.knex.raw(
1329
- `
1330
- SELECT c.column_name
1331
- FROM information_schema.table_constraints tc
1332
- JOIN information_schema.constraint_column_usage AS ccu
1333
- ON tc.constraint_schema = ccu.constraint_schema
1334
- AND tc.constraint_name = ccu.constraint_name
1335
- WHERE tc.constraint_type = 'UNIQUE'
1336
- AND tc.table_name = ?
1337
- `,
1338
- [tableName],
1339
- );
1340
-
1341
- for (const row of result.rows) {
1342
- uniqueColumns.push(row.column_name);
1343
- }
1344
- } else if (this.isMysql) {
1345
- const result = await this.knex.raw(
1346
- `
1347
- SELECT COLUMN_NAME
1348
- FROM information_schema.TABLE_CONSTRAINTS tc
1349
- JOIN information_schema.KEY_COLUMN_USAGE kcu
1350
- USING (CONSTRAINT_NAME, TABLE_SCHEMA, TABLE_NAME)
1351
- WHERE CONSTRAINT_TYPE = 'UNIQUE'
1352
- AND TABLE_SCHEMA = DATABASE()
1353
- AND TABLE_NAME = ?
1354
- `,
1355
- [tableName],
1356
- );
1357
-
1358
- for (const row of result[0]) {
1359
- uniqueColumns.push(row.COLUMN_NAME);
1360
- }
1361
- } else if (this.isSqlite) {
1362
- const safeTableName = tableName.replace(/[^a-zA-Z0-9_]/g, '');
1363
-
1364
- const tablesResult = await this.knex.raw("SELECT name FROM sqlite_master WHERE type = 'table'");
1365
- const tableNames = Array.isArray(tablesResult) ? tablesResult.map((row: any) => row.name) : [];
1366
-
1367
- if (!tableNames.includes(safeTableName)) {
1368
- return uniqueColumns;
1369
- }
1370
-
1371
- const indexes = await this.knex.raw(`PRAGMA index_list(${safeTableName})`);
1372
-
1373
- for (const idx of indexes) {
1374
- if (idx.unique === 1) {
1375
- const info = await this.knex.raw(`PRAGMA index_info(${idx.name})`);
1376
- if (info.length === 1) {
1377
- uniqueColumns.push(info[0].name);
1378
- }
1379
- }
1380
- }
1381
- }
1382
- } catch {
1383
- // silently ignore
1384
- }
1385
-
1386
- return uniqueColumns;
1387
- }
1388
- }