-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsql-driver.ts
More file actions
2600 lines (2339 loc) · 99.1 KB
/
Copy pathsql-driver.ts
File metadata and controls
2600 lines (2339 loc) · 99.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 { parseAutonumberFormat, renderAutonumber, missingFieldValues, type AutonumberToken } 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__';
/**
* Field types whose value is an array or object and must be stored as a JSON
* column (and JSON-(de)serialized at the driver boundary). SINGLE SOURCE for
* both the DDL column-type switch and `isJsonField` so the two can't drift —
* the drift between them is exactly what let array-valued fields (multiselect/
* checkboxes/tags/repeater/vector) reach the SQLite binder un-serialized and
* crash with "SQLite3 can only bind numbers, strings, bigints, buffers, and
* null" (#field-zoo). `image`/`file`/`avatar`/`video`/`audio` hold structured
* upload metadata; `composite`/`address`/`location`/`record` are objects; the
* rest are arrays.
*/
const JSON_COLUMN_TYPES = new Set<string>([
'json', 'object', 'array', 'record',
'image', 'file', 'avatar', 'video', 'audio',
'location', 'address', 'composite',
'multiselect', 'checkboxes', 'tags', 'repeater', 'vector',
]);
/**
* Field types whose value is a numeric scalar. SINGLE SOURCE for the DDL
* column-type switch (these map to INTEGER/REAL columns) and the read-side
* coercion registry (`numericFields`).
*
* The read coercion exists so the fix is robust on SQLite even when the column
* predates it: a `rating`/`slider`/`progress` column created before #2025 has
* TEXT affinity and returns '4' not 4, and SQLite never alters a column's type
* in-place (the reconciler only ADDS columns). Coercing numeric-looking strings
* back to numbers on read transparently repairs those legacy rows — mirroring
* how `dateFields` repairs legacy timestamp-typed `Field.date` rows — so the
* type fidelity no longer depends on column affinity alone. `toggle`/`record`
* already self-heal this way via `booleanFields`/`jsonFields`; this closes the
* gap for the numeric scalars.
*/
const NUMERIC_SCALAR_TYPES = new Set<string>([
'integer', 'int',
'float', 'number', 'currency', 'percent', 'summary',
'rating', 'slider', 'progress',
]);
// ── 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 numericFields: 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; tokens: AutonumberToken[]; tenantField: string | null }>
> = {};
/** Whether the sequences table has been ensured this process. */
protected sequencesTableReady = false;
/**
* Whether `_objectstack_sequences` is the current `key_hash`-keyed shape.
* Set on a fresh create or a successful in-place migration. If a legacy table
* could NOT be migrated, this stays false: fixed-prefix sequences (empty
* scope) keep working via the legacy `(object, tenant_id, field)` key, while a
* per-scope write raises an actionable error rather than corrupting counters.
*/
protected sequencesHasKeyHash = 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();
// SQLite space hygiene (ADR-0057). With the default `auto_vacuum=NONE`,
// freed pages are never returned to the OS — a database that briefly grew
// (e.g. high-frequency telemetry before retention sweeps run) stays at its
// high-water mark forever. INCREMENTAL lets a later `PRAGMA incremental_vacuum`
// (run by the lifecycle Reaper, or manually) reclaim that space without a
// full blocking VACUUM. NOTE: auto_vacuum only changes layout on a *fresh*
// database or after a one-time full VACUUM, so this benefits new dev DBs;
// existing files need a single `VACUUM` to adopt it. Harmless / no-op on
// :memory: and on already-incremental databases.
if (this.isSqlite) {
try {
await this.knex.raw('PRAGMA auto_vacuum = INCREMENTAL');
} catch (e) {
this.logger.warn('Failed to set PRAGMA auto_vacuum=INCREMENTAL', e);
}
}
}
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`).
*
* The row key is `key_hash` — a SHA-256 of `(object, tenant_id, field, scope)`
* where `scope` is the rendered autonumber prefix (date/field tokens before
* the `{0000}` slot), so a new day/group/parent starts a fresh counter. A
* single 64-char hashed primary key (rather than the four raw columns, which
* blow past MySQL's 3072-byte index limit under utf8mb4 and bound how long a
* `{field}` scope may be) keys every dialect uniformly and lets `scope` be a
* generous non-indexed column. Fixed-prefix formats use the empty scope and
* keep their single global counter (backward compatible).
*/
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.createSequencesTable(SEQUENCES_TABLE);
this.sequencesHasKeyHash = true;
} 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;
// A racing creator may have used an older schema. Migrate in place.
await this.ensureSequencesKeyHashShape();
}
} else {
// Pre-existing table may predate the `key_hash`/`scope` shape. Migrate.
await this.ensureSequencesKeyHashShape();
}
this.sequencesTableReady = true;
})();
try {
await this.sequencesTableEnsurePromise;
} finally {
this.sequencesTableEnsurePromise = null;
}
}
/** SHA-256 of the composite counter key — the table's single-column PK. */
protected sequenceKeyHash(object: string, tenantId: string, field: string, scope: string): string {
return createHash('sha256')
.update(`${object}\u001f${tenantId}\u001f${field}\u001f${scope}`)
.digest('hex');
}
/** Create the current `key_hash`-keyed sequences table shape. */
protected async createSequencesTable(table: string): Promise<void> {
await this.knex.schema.createTable(table, (t) => {
t.string('key_hash', 64).notNullable().primary();
t.string('object').notNullable();
t.string('tenant_id').notNullable();
t.string('field').notNullable();
// Non-indexed, so it is free of the PK length limit — a long `{plan_no}`
// composite scope fits. 1024 is far above any realistic rendered prefix.
t.string('scope', 1024).notNullable().defaultTo('');
t.bigInteger('last_value').notNullable().defaultTo(0);
t.timestamp('updated_at').defaultTo(this.knex.fn.now());
});
}
/**
* Migrate a pre-existing `_objectstack_sequences` table to the current
* `key_hash`-keyed shape. Handles both the original 3-column table (no
* `scope`) and an interim 4-column `(object, tenant_id, field, scope)` table:
* every legacy row is read, its `key_hash` computed in app code (no portable
* SQL hash exists), and re-inserted into a freshly built table that then
* replaces the original. Idempotent — a no-op once `key_hash` is present.
*
* If the rebuild fails, `sequencesHasKeyHash` stays false: fixed-prefix
* sequences keep working via the legacy key and per-scope writes error
* actionably (see getNextSequenceValue), rather than corrupting data.
*/
protected async ensureSequencesKeyHashShape(): Promise<void> {
if (await this.knex.schema.hasColumn(SEQUENCES_TABLE, 'key_hash')) {
this.sequencesHasKeyHash = true;
return;
}
const hasScope = await this.knex.schema.hasColumn(SEQUENCES_TABLE, 'scope');
const TMP = `${SEQUENCES_TABLE}__rebuild`;
try {
const rows: any[] = await this.knex(SEQUENCES_TABLE).select('*');
await this.knex.schema.dropTableIfExists(TMP);
await this.createSequencesTable(TMP);
const migrated = rows.map((r) => {
const scope = hasScope && r.scope != null ? String(r.scope) : '';
return {
key_hash: this.sequenceKeyHash(String(r.object), String(r.tenant_id), String(r.field), scope),
object: r.object,
tenant_id: r.tenant_id,
field: r.field,
scope,
last_value: r.last_value ?? 0,
updated_at: r.updated_at ?? this.knex.fn.now(),
};
});
if (migrated.length > 0) await this.knex(TMP).insert(migrated);
await this.knex.schema.dropTable(SEQUENCES_TABLE);
await this.knex.schema.renameTable(TMP, SEQUENCES_TABLE);
this.sequencesHasKeyHash = true;
} catch (err) {
// Leave the original table intact; fall back to legacy keying for
// fixed-prefix sequences and refuse per-scope writes until migrated.
this.sequencesHasKeyHash = false;
await this.knex.schema.dropTableIfExists(TMP).catch(() => {});
this.logger.warn(
`[autonumber] Failed to migrate ${SEQUENCES_TABLE} to the key_hash shape. ` +
`Fixed-prefix autonumbers keep working; date/{field}/per-parent formats will ` +
`error until the table is migrated.`,
{ error: String(err) },
);
}
}
/**
* 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,
scope = '',
): Promise<number> {
await this.ensureSequencesTable();
const resolvedTenantId = tenantField && tenantId ? String(tenantId) : GLOBAL_TENANT;
if (scope !== '' && !this.sequencesHasKeyHash) {
// The legacy sequences table could not be migrated to the key_hash shape,
// so it cannot represent per-scope counters. Fail with a clear, actionable
// message instead of corrupting the single legacy counter.
throw new Error(
`Cannot generate a per-scope autonumber for "${object}.${field}": the ` +
`${SEQUENCES_TABLE} table is still the legacy shape. ` +
`Migrate it to the key_hash shape before using date/{field}/per-parent formats.`,
);
}
// `scope` (rendered date/field prefix, boundary-delimited) gives each
// period/group its own counter; '' keeps the single global counter for
// fixed-prefix formats. `prefix` is the full rendered prefix used to
// bootstrap from existing data. The row is keyed by a hash of the composite;
// on an un-migrated legacy table only fixed-prefix (scope '') reaches here,
// so fall back to the original `(object, tenant_id, field)` key for it.
const key = this.sequencesHasKeyHash
? { key_hash: this.sequenceKeyHash(tableName, resolvedTenantId, field, scope) }
: { object: tableName, tenant_id: resolvedTenantId, field };
const insertRow = this.sequencesHasKeyHash
? { ...key, object: tableName, tenant_id: resolvedTenantId, field, scope }
: { ...key };
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({ ...insertRow, 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 the caller left empty, render the format and
* reserve the next counter value. The counter is scoped to the rendered
* prefix (date tokens like `{YYYYMMDD}` in the request's business timezone,
* plus `{field}` interpolation from the row), so it resets per period/group;
* the full rendered prefix bootstraps the counter from existing data, and the
* tenant scopes it for isolation.
*/
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;
const timezone = (options as any)?.timezone as string | undefined;
const now = new Date();
for (const cfg of cfgs) {
if (row[cfg.name] !== undefined && row[cfg.name] !== null && row[cfg.name] !== '') continue;
// A `{field}` token with no value would render to an empty prefix and
// silently merge this record into the wrong counter scope, so refuse to
// generate rather than emit a wrong record number (the referenced field
// must be populated before the autonumber — see field.zod docs).
const missing = missingFieldValues(cfg.tokens, row);
if (missing.length > 0) {
throw new Error(
`Cannot generate autonumber "${object}.${cfg.name}" (format "${cfg.format}"): ` +
`referenced field(s) [${missing.join(', ')}] are empty on the record. ` +
`Fields interpolated into an autonumber format must be set before the record is created.`,
);
}
// 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;
// Resolve the scope/prefix for this row (counter-value-independent),
// reserve the next value under that scope, then render the final string.
const probe = renderAutonumber({ tokens: cfg.tokens, seq: 0, record: row, now, timezone });
const next = await this.getNextSequenceValue(
object,
tableName,
cfg.name,
probe.prefix,
cfg.tenantField,
tenantId,
parentTrx,
probe.scope,
);
row[cfg.name] = renderAutonumber({ tokens: cfg.tokens, seq: next, record: row, now, timezone }).value;
}
}
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
// ===================================