-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathsql-driver.ts
More file actions
2325 lines (2072 loc) · 84.1 KB
/
Copy pathsql-driver.ts
File metadata and controls
2325 lines (2072 loc) · 84.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
/**
* SQL Driver for ObjectStack
*
* Implements the standard IDataDriver from @objectstack/spec via Knex.js.
* Supports PostgreSQL, MySQL, SQLite, and other SQL databases.
*/
import type { QueryAST, DriverOptions, SchemaMode } from '@objectstack/spec/data';
import type { IDataDriver } from '@objectstack/spec/contracts';
import { StorageNameMapping } from '@objectstack/spec/system';
import { ExternalSchemaModeViolationError } from '@objectstack/spec/shared';
import knex, { Knex } from 'knex';
import { nanoid } from 'nanoid';
import { createHash } from 'node:crypto';
/**
* Default ID length for auto-generated IDs.
*/
const DEFAULT_ID_LENGTH = 16;
/**
* Internal table that persists per-(object, tenant, field) auto-number
* counters so sequences are monotonic, tenant-isolated, and resilient to
* concurrent writers. Lazily created on first autonumber-bearing insert.
*/
const SEQUENCES_TABLE = '_objectstack_sequences';
/**
* Sentinel tenant_id used when an object has no tenant field (org-less
* objects like Setup-side singletons). Keeps the (object, tenant, field)
* primary key non-null.
*/
const GLOBAL_TENANT = '__global__';
// ── Introspection Types ──────────────────────────────────────────────────────
export interface IntrospectedColumn {
name: string;
type: string;
nullable: boolean;
defaultValue?: unknown;
isPrimary?: boolean;
isUnique?: boolean;
maxLength?: number;
}
export interface IntrospectedForeignKey {
columnName: string;
referencedTable: string;
referencedColumn: string;
constraintName?: string;
}
export interface IntrospectedTable {
name: string;
columns: IntrospectedColumn[];
foreignKeys: IntrospectedForeignKey[];
primaryKeys: string[];
}
export interface IntrospectedSchema {
tables: Record<string, IntrospectedTable>;
}
// ── Configuration Types ──────────────────────────────────────────────────────
/**
* SqlDriver configuration — passed directly to Knex.
* See https://knexjs.org/guide/#configuration-options
*
* `schemaMode` (ADR-0015) is an ObjectStack-level concern, not a Knex
* option: it is stripped before constructing the Knex instance and gates
* all schema-mutating DDL. Defaults to `'managed'` when omitted, preserving
* legacy behaviour.
*/
export type SqlDriverConfig = Knex.Config & { schemaMode?: SchemaMode };
// ── SQL Driver ───────────────────────────────────────────────────────────────
/**
* SQL Driver for ObjectStack.
*
* Implements the IDataDriver contract via Knex.js for optimal SQL
* generation against PostgreSQL, MySQL, SQLite and other SQL databases.
*/
export class SqlDriver implements IDataDriver {
// IDataDriver metadata
public readonly name: string = 'com.objectstack.driver.sql';
public readonly version: string = '1.0.0';
public get supports() {
return {
// Basic CRUD Operations
create: true,
read: true,
update: true,
delete: true,
// Bulk Operations
bulkCreate: true,
bulkUpdate: true,
bulkDelete: true,
// Transaction & Connection Management
transactions: true,
savepoints: false,
// Query Operations
queryFilters: true,
queryAggregations: true,
/**
* Per-granularity native date bucket support. Granularities marked
* `false` (or absent) fall back to in-memory `bucketDateValue()` via
* `engine.findData` — see `buildDateBucketExpr()` for the SQL emitted.
*/
queryDateGranularity: this.dateGranularityCapabilities,
querySorting: true,
queryPagination: true,
queryWindowFunctions: true,
querySubqueries: true,
queryCTE: false,
joins: true,
// Advanced Features
fullTextSearch: false,
jsonQuery: false,
geospatialQuery: false,
streaming: false,
jsonFields: true,
arrayFields: true,
vectorSearch: false,
// Persistent, atomic autonumber sequences via `_objectstack_sequences`
// (see fillAutoNumberFields / getNextSequenceValue). The engine defers
// autonumber generation to this driver — it is the single source of truth.
autonumber: true,
// Schema Management
schemaSync: true,
batchSchemaSync: false,
migrations: false,
// Object-level declared `indexes` (incl. multi-column UNIQUE) are
// materialized during `initObjects` — see `syncDeclaredIndexes`.
indexes: true,
// Performance & Optimization
connectionPooling: true,
preparedStatements: true,
queryCache: false,
};
}
protected knex: Knex;
protected config: Knex.Config;
protected jsonFields: Record<string, string[]> = {};
protected booleanFields: Record<string, string[]> = {};
protected dateFields: Record<string, Set<string>> = {};
protected datetimeFields: Record<string, Set<string>> = {};
protected tablesWithTimestamps: Set<string> = new Set();
/**
* Autonumber field configs per table, captured during initObjects.
*
* Each entry records:
* - `prefix` + `padWidth`: how to render the next value (`CTR-0007`)
* - `tenantField`: the column to scope the sequence by (defaults to
* `organization_id` if the object has that field, otherwise null →
* sequence is shared globally for that field)
*
* Numbering is backed by the `_objectstack_sequences` row keyed by
* `(object, tenant_id, field)`, not by scanning the data table on each
* insert. The sequence row is bootstrapped from the existing MAX on
* first use so legacy data is respected.
*/
protected autoNumberFields: Record<
string,
Array<{ name: string; format: string; prefix: string; padWidth: number; tenantField: string | null }>
> = {};
/** Whether the sequences table has been ensured this process. */
protected sequencesTableReady = false;
/** In-flight ensure promise; deduplicates concurrent first calls. */
protected sequencesTableEnsurePromise: Promise<void> | null = null;
/**
* Per-table tenant-isolation column. Populated during `initObjects` by
* detecting an `organization_id` field. When set and the caller passes
* `DriverOptions.tenantId`, the driver automatically:
*
* - scopes reads/updates/deletes/aggregates to that tenant
* - injects `organization_id` on inserts that omit it
*
* If `tenantId` is absent (admin / seed / system path) no scope is
* applied — preserves backward compatibility for tools that legitimately
* need cross-tenant access. Tenant enforcement is therefore opt-in by
* the caller, not by the driver.
*/
protected tenantFieldByTable: Record<string, string | null> = {};
/** Throttle table for missing-tenantId warnings ({object}:{op}). */
protected tenantAuditWarned: Set<string> = new Set();
/**
* Optional logger sink for security-audit warnings. Tests inject a spy;
* production callers wire in their preferred logger. Defaults to
* `console.warn` so warnings surface even without setup.
*/
protected logger: { warn: (msg: string, meta?: any) => void } = {
warn: (msg, meta) => console.warn(msg, meta ?? ''),
};
/** Whether the underlying database is a SQLite variant (sqlite3 or better-sqlite3). */
protected get isSqlite(): boolean {
const c = (this.config as any).client;
return c === 'sqlite3' || c === 'better-sqlite3';
}
/** Whether the underlying database is PostgreSQL. */
protected get isPostgres(): boolean {
const c = (this.config as any).client;
return c === 'pg' || c === 'postgresql';
}
/** Whether the underlying database is MySQL. */
protected get isMysql(): boolean {
const c = (this.config as any).client;
return c === 'mysql' || c === 'mysql2';
}
/**
* Per-granularity native SQL bucket support, computed from dialect.
*
* Must match `bucketDateValue()` in @objectstack/objectql exactly:
* year → 'YYYY'
* month → 'YYYY-MM'
* day → 'YYYY-MM-DD'
* quarter → 'YYYY-Q[1-4]'
* week → 'YYYY-W[01-53]' (ISO-8601)
*
* Granularities not listed (or set to false) fall back to in-memory bucketing
* via engine.findData → applyInMemoryAggregation.
*/
protected get dateGranularityCapabilities(): Record<string, boolean> {
if (this.isPostgres) {
return { day: true, month: true, quarter: true, year: true, week: true };
}
if (this.isMysql) {
return { day: true, month: true, quarter: true, year: true, week: true };
}
if (this.isSqlite) {
// SQLite's strftime gained ISO week (%V) in 3.46 (2024-05-23); play it safe
// and bucket week in-memory. Day/month/year/quarter are universally available.
return { day: true, month: true, quarter: true, year: true, week: false };
}
return {};
}
/**
* Build SQL fragment + bindings for a date bucket expression.
* Returns `null` when the current dialect does not support the requested
* granularity — callers must fall back to in-memory bucketing.
*
* Exposed as `{sql, bindings}` (not `Knex.Raw`) so callers can both
* `groupByRaw()` and embed the same expression inside a `select() as alias`
* with correctly forwarded identifier bindings.
*/
protected buildDateBucketExpr(
field: string,
granularity: 'day' | 'week' | 'month' | 'quarter' | 'year',
): { sql: string; bindings: any[] } | null {
if (!this.dateGranularityCapabilities[granularity]) return null;
if (this.isPostgres) {
switch (granularity) {
case 'year': return { sql: `to_char((??)::timestamptz AT TIME ZONE 'UTC', 'YYYY')`, bindings: [field] };
case 'month': return { sql: `to_char((??)::timestamptz AT TIME ZONE 'UTC', 'YYYY-MM')`, bindings: [field] };
case 'day': return { sql: `to_char((??)::timestamptz AT TIME ZONE 'UTC', 'YYYY-MM-DD')`, bindings: [field] };
case 'quarter': return { sql: `to_char((??)::timestamptz AT TIME ZONE 'UTC', 'YYYY"-Q"Q')`, bindings: [field] };
case 'week': return { sql: `to_char((??)::timestamptz AT TIME ZONE 'UTC', 'IYYY"-W"IW')`, bindings: [field] };
}
}
if (this.isMysql) {
switch (granularity) {
case 'year': return { sql: `date_format(convert_tz(??, @@session.time_zone, '+00:00'), '%Y')`, bindings: [field] };
case 'month': return { sql: `date_format(convert_tz(??, @@session.time_zone, '+00:00'), '%Y-%m')`, bindings: [field] };
case 'day': return { sql: `date_format(convert_tz(??, @@session.time_zone, '+00:00'), '%Y-%m-%d')`, bindings: [field] };
case 'quarter': return { sql: `concat(date_format(convert_tz(??, @@session.time_zone, '+00:00'), '%Y'), '-Q', quarter(convert_tz(??, @@session.time_zone, '+00:00')))`, bindings: [field, field] };
case 'week': return { sql: `date_format(convert_tz(??, @@session.time_zone, '+00:00'), '%x-W%v')`, bindings: [field] };
}
}
if (this.isSqlite) {
switch (granularity) {
case 'year': return { sql: `strftime('%Y', ??)`, bindings: [field] };
case 'month': return { sql: `strftime('%Y-%m', ??)`, bindings: [field] };
case 'day': return { sql: `strftime('%Y-%m-%d', ??)`, bindings: [field] };
case 'quarter': return { sql: `(strftime('%Y', ??) || '-Q' || ((cast(strftime('%m', ??) as integer) - 1) / 3 + 1))`, bindings: [field, field] };
case 'week': return null; // see capabilities note
}
}
return null;
}
/**
* Schema ownership mode (ADR-0015). When not `'managed'`, all
* schema-mutating DDL is rejected by {@link assertSchemaMutable}. The
* runtime injects this from `Datasource.schemaMode`; defaults to
* `'managed'` so existing callers are unaffected.
*/
protected readonly schemaMode: SchemaMode;
constructor(config: SqlDriverConfig) {
// `schemaMode` is an ObjectStack concern, not a Knex option — strip it
// before handing the config to Knex.
const { schemaMode, ...knexConfig } = config;
this.schemaMode = schemaMode ?? 'managed';
this.config = knexConfig;
this.knex = knex(knexConfig);
}
/**
* DDL gate (ADR-0015 §5.1). Single choke-point asserting that
* schema-mutating DDL is only performed on a `managed` datasource.
* Federated datasources (`external` / `validate-only`) are guests in a
* database ObjectStack does not own and must never run DDL against.
*/
protected assertSchemaMutable(operation: string): void {
if (this.schemaMode !== 'managed') {
throw new ExternalSchemaModeViolationError(
`DDL operation '${operation}' is forbidden: datasource schemaMode='${this.schemaMode}'. ` +
`ObjectStack never mutates the schema of an external database.`,
);
}
}
// ===================================
// Lifecycle
// ===================================
async connect(): Promise<void> {
// Ensure the database directory exists before any query can trigger
// better-sqlite3 to open the file (e.g. loadMetaFromDb on startup).
await this.ensureDatabaseExists();
}
async checkHealth(): Promise<boolean> {
try {
await this.knex.raw('SELECT 1');
return true;
} catch {
return false;
}
}
async disconnect(): Promise<void> {
await this.knex.destroy();
}
// ===================================
// CRUD — DriverInterface core
// ===================================
async find(object: string, query: QueryAST, options?: DriverOptions): Promise<any[]> {
// Build everything EXCEPT the SELECT list, so the unknown-column retry
// below can rebuild without re-deriving where/order/pagination.
const buildBase = () => {
const b = this.getBuilder(object, options);
this.applyTenantScope(b, object, options);
// WHERE
if (query.where) {
this.applyFilters(b, query.where);
}
// ORDER BY
if (query.orderBy && Array.isArray(query.orderBy)) {
for (const item of query.orderBy) {
if (item.field) {
b.orderBy(this.mapSortField(item.field), item.order || 'asc');
}
}
}
// PAGINATION
if (query.offset !== undefined) b.offset(query.offset);
if (query.limit !== undefined) b.limit(query.limit);
return b;
};
const builder = buildBase();
// SELECT
if (query.fields) {
builder.select((query.fields as string[]).map((f: string) => this.mapSortField(f)));
} else {
builder.select('*');
}
let results: any[];
try {
results = await builder;
} catch (error: any) {
const isUnknownColumn =
error.message &&
(error.message.includes('no such column') ||
(error.message.includes('column') && error.message.includes('does not exist')));
if (isUnknownColumn) {
// A `$select` projection naming a column the table lacks (e.g. a
// generic list view auto-requesting `status`/`due_date`/`image` on an
// object without them) makes the WHOLE query fail. Swallowing that
// into an empty result — the old behavior — reads to the UI as "no
// records exist" even though rows are there: a silent data-loss
// footgun. When the failure came from the projection, retry once
// selecting all columns so the real rows still come back; the unknown
// field is simply absent from each row (it never existed). The
// engine's unknown-field filter is the first line of defense, but it
// only fires when the object's schema is populated in the registry —
// this driver backstop holds even when it isn't (notably the cloud
// multi-tenant runtime, where the projection otherwise zeroes the list).
if (query.fields) {
try {
results = await buildBase().select('*');
} catch {
return [];
}
} else {
return [];
}
} else {
throw error;
}
}
if (!Array.isArray(results)) {
return [];
}
// formatOutput is dialect-agnostic for `Field.date` (ADR-0053 Phase 1);
// its json/boolean deserialisation stays SQLite-gated internally. Run it
// for every dialect so reads match `findOne` and date columns come back
// as `YYYY-MM-DD`.
for (const row of results) {
this.formatOutput(object, row);
}
return results;
}
async findOne(object: string, query: QueryAST, options?: DriverOptions): Promise<any> {
// When called with a string/number id fall back gracefully
if (typeof query === 'string' || typeof query === 'number') {
const builder = this.getBuilder(object, options).where('id', query);
this.applyTenantScope(builder, object, options);
const res = await builder.first();
return this.formatOutput(object, res) || null;
}
if (query && typeof query === 'object') {
const results = await this.find(object, { ...query, limit: 1 }, options);
return results[0] || null;
}
return null;
}
/**
* Stream records matching a structured query.
* NOTE: Current implementation fetches all results then yields them.
* TODO: Use Knex .stream() for true cursor-based streaming on large datasets.
*/
async *findStream(object: string, query: QueryAST, options?: DriverOptions): AsyncGenerator<Record<string, any>> {
const results = await this.find(object, query, options);
for (const row of results) {
yield row;
}
}
async create(object: string, data: Record<string, any>, options?: DriverOptions): Promise<any> {
const { _id, ...rest } = data;
const toInsert = { ...rest };
if (_id !== undefined && toInsert.id === undefined) {
toInsert.id = _id;
} else if (toInsert.id === undefined) {
toInsert.id = nanoid(DEFAULT_ID_LENGTH);
}
this.auditMissingTenant(object, 'create', options);
this.injectTenantOnInsert(object, toInsert, options);
await this.fillAutoNumberFields(object, toInsert, options);
const builder = this.getBuilder(object, options);
const formatted = this.formatInput(object, toInsert);
const result = await builder.insert(formatted).returning('*');
return this.formatOutput(object, result[0]);
}
/**
* Ensure the sequence-counter table exists. Idempotent and cheap after
* the first call (cached via `sequencesTableReady`).
*/
protected async ensureSequencesTable(): Promise<void> {
if (this.sequencesTableReady) return;
if (this.sequencesTableEnsurePromise) {
await this.sequencesTableEnsurePromise;
return;
}
this.sequencesTableEnsurePromise = (async () => {
const exists = await this.knex.schema.hasTable(SEQUENCES_TABLE);
if (!exists) {
try {
await this.knex.schema.createTable(SEQUENCES_TABLE, (t) => {
t.string('object').notNullable();
t.string('tenant_id').notNullable();
t.string('field').notNullable();
t.bigInteger('last_value').notNullable().defaultTo(0);
t.timestamp('updated_at').defaultTo(this.knex.fn.now());
t.primary(['object', 'tenant_id', 'field']);
});
} catch (err: any) {
// Race or cross-process create — re-check existence; ignore
// "already exists" errors from any dialect.
const stillMissing = !(await this.knex.schema.hasTable(SEQUENCES_TABLE));
if (stillMissing) throw err;
}
}
this.sequencesTableReady = true;
})();
try {
await this.sequencesTableEnsurePromise;
} finally {
this.sequencesTableEnsurePromise = null;
}
}
/**
* Bootstrap helper: scan the data table for the highest numeric suffix
* matching `prefix` (optionally scoped to a tenant). Used the first time
* a sequence row is created so legacy/seeded data continues monotonically.
*/
protected async scanMaxNumericTail(
queryRunner: Knex | Knex.Transaction,
tableName: string,
field: string,
prefix: string,
tenantField: string | null,
tenantId: string | null,
): Promise<number> {
const escapedPrefix = prefix.replace(/([\\%_])/g, '\\$1');
let builder = queryRunner(tableName).select(field).where(field, 'like', `${escapedPrefix}%`).whereNotNull(field);
if (tenantField && tenantId !== null) {
builder = builder.where(tenantField, tenantId);
}
const rows = await builder;
let maxN = 0;
for (const r of rows as any[]) {
const v: string = (r as any)[field];
if (typeof v !== 'string') continue;
const tail = v.slice(prefix.length);
const n = parseInt(tail.replace(/[^0-9]/g, ''), 10);
if (Number.isFinite(n) && n > maxN) maxN = n;
}
return maxN;
}
/**
* Atomically reserve and return the next sequence value for
* `(object, tenantId, field)`. Bootstraps from the data-table MAX on
* first call so existing seeded records continue monotonically.
*
* Concurrency:
* - SQLite: a write transaction (`BEGIN IMMEDIATE` via knex) serializes
* all writers; safe in-process. Cross-process SQLite is out of scope.
* - Postgres/MySQL: `SELECT … FOR UPDATE` row lock ensures only one
* transaction reads-modifies-writes at a time. A PK-violation race on
* first insert is retried as an UPDATE.
*
* Gaps are tolerated by design — a rolled-back insert "burns" a number,
* matching standard sequence semantics.
*/
protected async getNextSequenceValue(
object: string,
tableName: string,
field: string,
prefix: string,
tenantField: string | null,
tenantId: string | null,
parentTrx?: Knex.Transaction,
): Promise<number> {
await this.ensureSequencesTable();
const resolvedTenantId = tenantField && tenantId ? String(tenantId) : GLOBAL_TENANT;
const key = { object: tableName, tenant_id: resolvedTenantId, field };
const runner: Knex | Knex.Transaction = parentTrx ?? this.knex;
return runner.transaction(async (trx) => {
// Lock the row (no-op on SQLite, real lock on Postgres/MySQL).
let existing: any;
try {
existing = await trx(SEQUENCES_TABLE).where(key).forUpdate().first();
} catch {
// Some dialects/versions reject .forUpdate() on a missing row in
// weird ways; fall back to plain SELECT then rely on transaction
// isolation. Postgres/MySQL behave normally here.
existing = await trx(SEQUENCES_TABLE).where(key).first();
}
if (!existing) {
const seedMax = await this.scanMaxNumericTail(
trx,
tableName,
field,
prefix,
tenantField,
resolvedTenantId === GLOBAL_TENANT ? null : resolvedTenantId,
);
const initial = seedMax + 1;
try {
await trx(SEQUENCES_TABLE).insert({ ...key, last_value: initial });
return initial;
} catch (err) {
// Another writer raced us to the first INSERT. Fall through to
// the UPDATE path with the now-present row.
existing = await trx(SEQUENCES_TABLE).where(key).forUpdate().first();
if (!existing) throw err;
}
}
const next = Number(existing.last_value) + 1;
await trx(SEQUENCES_TABLE).where(key).update({ last_value: next, updated_at: this.knex.fn.now() });
return next;
});
}
/**
* For each `auto_number` field on the object that the caller did not
* provide a value for, reserve the next sequence value scoped to the
* record's tenant (or globally if the object has no tenant field) and
* render `prefix + zero-padded(value)`.
*/
protected async fillAutoNumberFields(
object: string,
row: Record<string, any>,
options?: DriverOptions,
): Promise<void> {
const tableName = StorageNameMapping.resolveTableName({ name: object } as any);
const cfgs = this.autoNumberFields[tableName] || this.autoNumberFields[object];
if (!cfgs || cfgs.length === 0) return;
const parentTrx = options?.transaction as Knex.Transaction | undefined;
for (const cfg of cfgs) {
if (row[cfg.name] !== undefined && row[cfg.name] !== null && row[cfg.name] !== '') continue;
// Resolve tenant for this row: explicit field on the record wins,
// then driver options, else null → global sequence.
const rowTenant = cfg.tenantField ? row[cfg.tenantField] : undefined;
const optTenant = (options as any)?.tenantId;
const tenantId = rowTenant != null && rowTenant !== ''
? String(rowTenant)
: optTenant != null && optTenant !== ''
? String(optTenant)
: null;
const next = await this.getNextSequenceValue(
object,
tableName,
cfg.name,
cfg.prefix,
cfg.tenantField,
tenantId,
parentTrx,
);
row[cfg.name] = `${cfg.prefix}${String(next).padStart(cfg.padWidth, '0')}`;
}
}
async update(object: string, id: string | number, data: Record<string, any>, options?: DriverOptions): Promise<any> {
this.auditMissingTenant(object, 'update', options);
const builder = this.getBuilder(object, options).where('id', id);
this.applyTenantScope(builder, object, options);
const formatted = this.formatInput(object, data);
if (this.tablesWithTimestamps.has(object)) {
if (this.isSqlite) {
const now = new Date();
formatted.updated_at = now.toISOString().replace('T', ' ').replace('Z', '');
} else {
formatted.updated_at = this.knex.fn.now();
}
}
await builder.update(formatted);
const readback = this.getBuilder(object, options).where('id', id);
this.applyTenantScope(readback, object, options);
const updated = await readback.first();
return this.formatOutput(object, updated) || null;
}
async upsert(object: string, data: Record<string, any>, conflictKeys?: string[], options?: DriverOptions): Promise<Record<string, any>> {
const { _id, ...rest } = data;
const toUpsert = { ...rest };
if (_id !== undefined && toUpsert.id === undefined) {
toUpsert.id = _id;
} else if (toUpsert.id === undefined) {
toUpsert.id = nanoid(DEFAULT_ID_LENGTH);
}
this.auditMissingTenant(object, 'upsert', options);
this.injectTenantOnInsert(object, toUpsert, options);
await this.fillAutoNumberFields(object, toUpsert, options);
const formatted = this.formatInput(object, toUpsert);
const mergeKeys = conflictKeys && conflictKeys.length > 0 ? conflictKeys : ['id'];
const builder = this.getBuilder(object, options);
await builder.insert(formatted).onConflict(mergeKeys).merge();
const readback = this.getBuilder(object, options).where('id', toUpsert.id);
this.applyTenantScope(readback, object, options);
const result = await readback.first();
return this.formatOutput(object, result) || toUpsert;
}
async delete(object: string, id: string | number, options?: DriverOptions): Promise<boolean> {
this.auditMissingTenant(object, 'delete', options);
const builder = this.getBuilder(object, options).where('id', id);
this.applyTenantScope(builder, object, options);
const count = await builder.delete();
return count > 0;
}
// ===================================
// Bulk & Batch Operations
// ===================================
async bulkCreate(object: string, data: any[], options?: DriverOptions): Promise<any> {
this.auditMissingTenant(object, 'bulkCreate', options);
for (const row of data) {
if (row && typeof row === 'object') {
this.injectTenantOnInsert(object, row, options);
// Reserve a persistent sequence value for each row's autonumber
// field(s) — the engine no longer pre-fills these (see #1603).
await this.fillAutoNumberFields(object, row, options);
}
}
const builder = this.getBuilder(object, options);
return await builder.insert(data).returning('*');
}
/**
* Batch-update multiple records by ID.
* NOTE: Current implementation performs sequential updates for correctness.
* TODO: Optimize with SQL CASE statements or batched transactions for performance.
*/
async bulkUpdate(object: string, updates: Array<{ id: string | number; data: Record<string, any> }>, options?: DriverOptions): Promise<Record<string, any>[]> {
const results: Record<string, any>[] = [];
for (const { id, data } of updates) {
const updated = await this.update(object, id, data, options);
if (updated) results.push(updated);
}
return results;
}
async bulkDelete(object: string, ids: Array<string | number>, options?: DriverOptions): Promise<void> {
this.auditMissingTenant(object, 'bulkDelete', options);
const builder = this.getBuilder(object, options).whereIn('id', ids);
this.applyTenantScope(builder, object, options);
await builder.delete();
}
async updateMany(object: string, query: QueryAST, data: any, options?: DriverOptions): Promise<number> {
this.auditMissingTenant(object, 'updateMany', options);
const builder = this.getBuilder(object, options);
this.applyTenantScope(builder, object, options);
if (query.where) this.applyFilters(builder, query.where);
const count = await builder.update(data);
return count || 0;
}
async deleteMany(object: string, query: QueryAST, options?: DriverOptions): Promise<number> {
this.auditMissingTenant(object, 'deleteMany', options);
const builder = this.getBuilder(object, options);
this.applyTenantScope(builder, object, options);
if (query.where) this.applyFilters(builder, query.where);
const count = await builder.delete();
return count || 0;
}
async count(object: string, query?: QueryAST, options?: DriverOptions): Promise<number> {
const builder = this.getBuilder(object, options);
this.applyTenantScope(builder, object, options);
if (query?.where) {
this.applyFilters(builder, query.where);
}
const result = await builder.count<{ count: number }[]>('* as count');
if (result && result.length > 0) {
const row: any = result[0];
return Number(row.count ?? row['count(*)'] ?? 0);
}
return 0;
}
// ===================================
// Raw Execution
// ===================================
/**
* Run a raw SQL string or knex builder through the underlying knex
* connection.
*
* ⚠️ **Tenant isolation bypass.** Unlike `find`/`update`/`delete` etc.,
* raw `execute()` does NOT inject the `organization_id` predicate. The
* caller is responsible for either:
* - inlining the tenant filter into the SQL (`WHERE organization_id = ?`),
* - or restricting `execute()` to genuinely global queries
* (schema introspection, sys_* tables that opt out of tenancy).
*
* Prefer the typed CRUD APIs whenever the operation can be expressed
* through them — they handle tenancy, soft-delete, and audit warnings
* automatically. See `README.md > Tenant Isolation` for the full bypass
* matrix.
*/
async execute(command: any, params?: any[], options?: DriverOptions): Promise<any> {
if (typeof command !== 'string') {
return command;
}
const builder =
options?.transaction
? this.knex.raw(command, params || []).transacting(options.transaction as Knex.Transaction)
: this.knex.raw(command, params || []);
return await builder;
}
// ===================================
// Transactions
// ===================================
async beginTransaction(): Promise<Knex.Transaction> {
return await this.knex.transaction();
}
/** IDataDriver standard */
async commit(transaction: unknown): Promise<void> {
await (transaction as Knex.Transaction).commit();
}
/** IDataDriver standard */
async rollback(transaction: unknown): Promise<void> {
await (transaction as Knex.Transaction).rollback();
}
/** @deprecated Use commit() instead */
async commitTransaction(trx: Knex.Transaction): Promise<void> {
await this.commit(trx);
}
/** @deprecated Use rollback() instead */
async rollbackTransaction(trx: Knex.Transaction): Promise<void> {
await this.rollback(trx);
}
// ===================================
// Aggregation
// ===================================
async aggregate(object: string, query: any, options?: DriverOptions): Promise<any> {
const builder = this.getBuilder(object, options);
this.applyTenantScope(builder, object, options);
if (query.where) {
this.applyFilters(builder, query.where);
}
if (query.groupBy) {
// groupBy items may be plain strings ('region') or structured objects
// ({ field: 'closed_at', dateGranularity: 'quarter' }). For structured
// items we emit a dialect-specific bucket expression aliased as the
// field name so the resulting row keys match in-memory bucketDateValue.
for (const g of query.groupBy as Array<string | { field: string; dateGranularity?: string }>) {
if (typeof g === 'string') {
builder.groupBy(g);
builder.select(g);
} else if (g && typeof g === 'object' && g.field) {
if (g.dateGranularity) {
const bucket = this.buildDateBucketExpr(g.field, g.dateGranularity as any);
if (!bucket) {
throw new Error(
`SqlDriver: dateGranularity '${g.dateGranularity}' not supported on dialect ` +
`'${(this.config as any).client}'. Engine must fall back to in-memory bucketing.`,
);
}
builder.groupByRaw(bucket.sql, bucket.bindings);
builder.select(this.knex.raw(`${bucket.sql} as ??`, [...bucket.bindings, g.field]));
} else {
builder.groupBy(g.field);
builder.select(g.field);
}
}
}
}
const aggregates = query.aggregations || query.aggregate;
if (aggregates) {
for (const agg of aggregates) {
const funcName = agg.function || agg.func;
const rawFunc = this.mapAggregateFunc(funcName);
// Spec: `field` is optional for COUNT (means COUNT(*)).
const fieldExpr = agg.field ?? '*';
if (agg.alias) {
if (fieldExpr === '*') {
builder.select(this.knex.raw(`${rawFunc}(*) as ??`, [agg.alias]));
} else {
builder.select(this.knex.raw(`${rawFunc}(??) as ??`, [fieldExpr, agg.alias]));
}
} else {
if (fieldExpr === '*') {
builder.select(this.knex.raw(`${rawFunc}(*)`));
} else {
builder.select(this.knex.raw(`${rawFunc}(??)`, [fieldExpr]));
}
}
}
}
return await builder;
}
// ===================================
// Distinct
// ===================================
async distinct(object: string, field: string, filters?: any, options?: DriverOptions): Promise<any[]> {
const builder = this.getBuilder(object, options);
if (filters) {
this.applyFilters(builder, filters);
}
builder.distinct(field);
const results = await builder;
return results.map((row: any) => row[field]);
}
// ===================================
// Window Functions
// ===================================
async findWithWindowFunctions(object: string, query: any, options?: DriverOptions): Promise<any[]> {
const builder = this.getBuilder(object, options);
builder.select('*');
if (query.where) {
this.applyFilters(builder, query.where);
}
if (query.windowFunctions && Array.isArray(query.windowFunctions)) {
for (const wf of query.windowFunctions) {
const windowFunc = this.buildWindowFunction(wf);
builder.select(this.knex.raw(`${windowFunc} as ??`, [wf.alias]));
}
}
if (query.orderBy && Array.isArray(query.orderBy)) {
for (const sort of query.orderBy) {
builder.orderBy(this.mapSortField(sort.field), sort.order || 'asc');
}
}
if (query.limit) builder.limit(query.limit);
if (query.offset) builder.offset(query.offset);
return await builder;
}
// ===================================
// Query Plan Analysis
// ===================================
/** IDataDriver standard: analyze query performance */
async explain(object: string, query: any, options?: DriverOptions): Promise<any> {
return this.analyzeQuery(object, query, options);
}
async analyzeQuery(object: string, query: any, options?: DriverOptions): Promise<any> {
const builder = this.getBuilder(object, options);
if (query.fields) {
builder.select(query.fields);
} else {
builder.select('*');
}
if (query.where) {
this.applyFilters(builder, query.where);