@stonyx/orm 0.3.2-beta.326 → 0.3.2-beta.328

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.
@@ -2,7 +2,7 @@ import { getPool, closePool } from './connection.js';
2
2
  import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
3
3
  import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
4
4
  import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
5
- import { buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch } from './query-builder.js';
5
+ import { buildInsert, buildInsertMany, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch } from './query-builder.js';
6
6
  import { store } from '@stonyx/orm';
7
7
  import { createRecord } from '../manage-record.js';
8
8
  import { confirm } from '@stonyx/utils/prompt';
@@ -28,6 +28,43 @@ interface PersistResponse {
28
28
  data?: { id: unknown };
29
29
  }
30
30
 
31
+ interface QueuedWrite {
32
+ operation: string;
33
+ modelName: string;
34
+ context: PersistContext;
35
+ response: PersistResponse;
36
+ resolve: () => void;
37
+ reject: (error: unknown) => void;
38
+ }
39
+
40
+ interface PreparedCreate {
41
+ write: QueuedWrite;
42
+ modelName: string;
43
+ record: OrmRecord;
44
+ row: Record<string, unknown>;
45
+ isPendingId: boolean;
46
+ }
47
+
48
+ type ExitEmitter = Pick<NodeJS.Process, 'once' | 'removeListener'>;
49
+
50
+ const POSTGRES_MAX_BIND_PARAMETERS = 65535;
51
+ const DEFAULT_WRITE_BATCH_SIZE = 500;
52
+ const DEFAULT_WRITE_QUEUE_LIMIT = 10000;
53
+
54
+ export class WriteQueueFullError extends Error {
55
+ constructor(limit: number) {
56
+ super(`PostgresDB write queue is full (${limit} queued writes, writeQueueLimit); the write was rejected`);
57
+ this.name = 'WriteQueueFullError';
58
+ }
59
+ }
60
+
61
+ export class WriteQueueClosedError extends Error {
62
+ constructor() {
63
+ super('PostgresDB is shutting down; the write was rejected');
64
+ this.name = 'WriteQueueClosedError';
65
+ }
66
+ }
67
+
31
68
  interface SearchResult {
32
69
  record: OrmRecord;
33
70
  distance: number;
@@ -53,6 +90,7 @@ interface PostgresDeps {
53
90
  loadLatestSnapshot: typeof loadLatestSnapshot;
54
91
  detectSchemaDrift: typeof detectSchemaDrift;
55
92
  buildInsert: typeof buildInsert;
93
+ buildInsertMany: typeof buildInsertMany;
56
94
  buildUpdate: typeof buildUpdate;
57
95
  buildDelete: typeof buildDelete;
58
96
  buildSelect: typeof buildSelect;
@@ -68,6 +106,7 @@ interface PostgresDeps {
68
106
  config: typeof config;
69
107
  log: typeof log;
70
108
  path: typeof path;
109
+ process: ExitEmitter;
71
110
  [key: string]: unknown;
72
111
  }
73
112
 
@@ -76,8 +115,8 @@ const defaultDeps: PostgresDeps = {
76
115
  getMigrationFiles, applyMigration, parseMigrationFile,
77
116
  introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
78
117
  loadLatestSnapshot, detectSchemaDrift,
79
- buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch,
80
- createRecord, store, confirm, readFile, getPluralName, config, log, path,
118
+ buildInsert, buildInsertMany, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch,
119
+ createRecord, store, confirm, readFile, getPluralName, config, log, path, process,
81
120
  convertRow, postgresJsonRule
82
121
  };
83
122
 
@@ -95,14 +134,11 @@ export default class PostgresDB {
95
134
  pool!: Pool | null;
96
135
  pgConfig!: Record<string, unknown>;
97
136
 
98
- /**
99
- * Promise-chain mutex for write serialization (#156).
100
- * All persist() calls chain through this single queue so concurrent
101
- * fire-and-forget writes never produce parallel transactions
102
- * on FK-linked rows (which cause deadlocks).
103
- * Reads are NOT affected — only persist() serializes.
104
- */
105
- private _writeQueue: Promise<void> = Promise.resolve();
137
+ private _queuedWrites: QueuedWrite[] = [];
138
+ private _inFlightWrites = new Set<QueuedWrite>();
139
+ private _drainingWrites: Promise<void> | null = null;
140
+ private _acceptingWrites = true;
141
+ private _exitReport: (() => void) | null = null;
106
142
 
107
143
  constructor(deps: Partial<PostgresDeps> = {}) {
108
144
  const Ctor = this.constructor as typeof PostgresDB;
@@ -126,6 +162,20 @@ export default class PostgresDB {
126
162
  );
127
163
  await this.deps.ensureMigrationsTable(this.pool, this.pgConfig.migrationsTable as string | undefined);
128
164
  await this.loadMemoryRecords();
165
+ this._acceptingWrites = true;
166
+ this._registerExitReport();
167
+ }
168
+
169
+ get writeBatchSize(): number {
170
+ return Number(this.pgConfig?.writeBatchSize) || DEFAULT_WRITE_BATCH_SIZE;
171
+ }
172
+
173
+ get writeQueueLimit(): number {
174
+ return Number(this.pgConfig?.writeQueueLimit) || DEFAULT_WRITE_QUEUE_LIMIT;
175
+ }
176
+
177
+ get pendingWriteCount(): number {
178
+ return this._inFlightWrites.size + this._queuedWrites.length;
129
179
  }
130
180
 
131
181
  async startup(): Promise<void> {
@@ -211,10 +261,36 @@ export default class PostgresDB {
211
261
  }
212
262
 
213
263
  async shutdown(): Promise<void> {
264
+ this._acceptingWrites = false;
265
+ while (this._drainingWrites) await this._drainingWrites;
266
+ this._unregisterExitReport();
214
267
  await this.deps.closePool();
215
268
  this.pool = null;
216
269
  }
217
270
 
271
+ private _registerExitReport(): void {
272
+ if (this._exitReport) return;
273
+ this._exitReport = () => this._reportUnpersistedWrites();
274
+ this.deps.process.once('exit', this._exitReport);
275
+ }
276
+
277
+ private _unregisterExitReport(): void {
278
+ if (!this._exitReport) return;
279
+ this.deps.process.removeListener('exit', this._exitReport);
280
+ this._exitReport = null;
281
+ }
282
+
283
+ private _reportUnpersistedWrites(): void {
284
+ const lostWrites = [...this._inFlightWrites, ...this._queuedWrites];
285
+ if (lostWrites.length === 0) return;
286
+
287
+ const lostByModel = new Map<string, number>();
288
+ for (const { modelName } of lostWrites) lostByModel.set(modelName, (lostByModel.get(modelName) ?? 0) + 1);
289
+ const breakdown = [...lostByModel].map(([modelName, count]) => `${modelName}: ${count}`).join(', ');
290
+
291
+ this.deps.log.error?.(`[PostgresDB] Process exiting with ${lostWrites.length} queued write(s) not persisted; they are lost (${breakdown})`);
292
+ }
293
+
218
294
  async save(): Promise<void> {
219
295
  // No-op: PostgreSQL persists data immediately via persist()
220
296
  }
@@ -494,77 +570,185 @@ export default class PostgresDB {
494
570
  }
495
571
 
496
572
  async persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
497
- // Views are read-only -- no-op for all write operations
498
573
  const Orm = (await import('@stonyx/orm')).default;
499
574
  if ((Orm.instance as { isView?: (name: string) => boolean })?.isView?.(modelName)) return;
500
575
 
501
- const work = async () => {
502
- switch (operation) {
503
- case 'create':
504
- return this._persistCreate(modelName, context, response);
505
- case 'update':
506
- return this._persistUpdate(modelName, context, response);
507
- case 'delete':
508
- return this._persistDelete(modelName, context);
576
+ if (!this._acceptingWrites) throw new WriteQueueClosedError();
577
+ if (this._queuedWrites.length >= this.writeQueueLimit) throw new WriteQueueFullError(this.writeQueueLimit);
578
+
579
+ return new Promise<void>((resolve, reject) => {
580
+ const write: QueuedWrite = {
581
+ operation, modelName, context, response,
582
+ resolve: () => {
583
+ this._inFlightWrites.delete(write);
584
+ resolve();
585
+ },
586
+ reject: (error: unknown) => {
587
+ this._inFlightWrites.delete(write);
588
+ reject(error);
589
+ },
590
+ };
591
+ this._queuedWrites.push(write);
592
+ this._drainWritesInBackground();
593
+ });
594
+ }
595
+
596
+ private _drainWritesInBackground(): void {
597
+ if (this._drainingWrites) return;
598
+ this._drainingWrites = this._drainQueuedWrites().finally(() => {
599
+ this._drainingWrites = null;
600
+ });
601
+ }
602
+
603
+ private async _drainQueuedWrites(): Promise<void> {
604
+ while (this._queuedWrites.length > 0) {
605
+ const writes = this._takeNextWriteGroup();
606
+ writes.forEach(write => this._inFlightWrites.add(write));
607
+ try {
608
+ await this._executeWriteGroup(writes);
609
+ } catch (error) {
610
+ writes.filter(write => this._inFlightWrites.has(write)).forEach(write => write.reject(error));
509
611
  }
510
- };
612
+ }
613
+ }
511
614
 
512
- // Chain through the write queue — .then(work, work) ensures the queue
513
- // advances even when a previous persist rejects (#156).
514
- this._writeQueue = this._writeQueue.then(work, work);
515
- return this._writeQueue;
615
+ private _takeNextWriteGroup(): QueuedWrite[] {
616
+ const [first] = this._queuedWrites;
617
+ let groupSize = 1;
618
+
619
+ if (first.operation === 'create') {
620
+ while (
621
+ groupSize < this.writeBatchSize
622
+ && groupSize < this._queuedWrites.length
623
+ && this._queuedWrites[groupSize].operation === 'create'
624
+ && this._queuedWrites[groupSize].modelName === first.modelName
625
+ ) groupSize++;
626
+ }
627
+
628
+ return this._queuedWrites.splice(0, groupSize);
516
629
  }
517
630
 
518
- private async _persistCreate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
519
- const schemas = this.deps.introspectModels();
520
- const schema = schemas[modelName];
631
+ private async _executeWriteGroup(writes: QueuedWrite[]): Promise<void> {
632
+ const [first] = writes;
633
+ if (first.operation === 'create') return this._persistCreates(first.modelName, writes);
521
634
 
522
- if (!schema) return;
635
+ try {
636
+ if (first.operation === 'update') await this._persistUpdate(first.modelName, first.context, first.response);
637
+ if (first.operation === 'delete') await this._persistDelete(first.modelName, first.context);
638
+ first.resolve();
639
+ } catch (error) {
640
+ first.reject(error);
641
+ }
642
+ }
523
643
 
644
+ private async _persistCreates(modelName: string, writes: QueuedWrite[]): Promise<void> {
645
+ const schema = this.deps.introspectModels()[modelName];
646
+ const prepared: PreparedCreate[] = [];
647
+
648
+ for (const write of writes) {
649
+ try {
650
+ const create = schema ? this._prepareCreate(modelName, schema, write) : null;
651
+ if (create) prepared.push(create);
652
+ else write.resolve();
653
+ } catch (error) {
654
+ write.reject(error);
655
+ }
656
+ }
657
+
658
+ for (const chunk of this._chunkWithinBindParameterLimit(prepared)) {
659
+ await this._insertCreates(schema, chunk);
660
+ }
661
+ }
662
+
663
+ private _prepareCreate(modelName: string, schema: ModelSchema, write: QueuedWrite): PreparedCreate | null {
664
+ const { context, response } = write;
524
665
  const recordId = response?.data?.id;
525
666
  const storeRef = this.deps.store as unknown as {
526
667
  get(name: string, id: unknown): OrmRecord | null;
527
668
  };
528
669
  const record = recordId != null ? storeRef.get(modelName, isNaN(recordId as number) ? recordId : parseInt(recordId as string)) : null;
529
670
 
530
- if (!record) return;
671
+ if (!record) return null;
531
672
 
532
673
  const insertData = this._recordToRow(record, schema, context.rawData);
533
-
534
- // For auto-increment models, remove the pending ID.
535
- // Check context.rawData (not record.__data) because __pendingSqlId is not a model
536
- // attribute and gets lost during serialization.
537
674
  const isPendingId = context.rawData?.__pendingSqlId === true;
538
675
 
539
- if (isPendingId) {
540
- delete insertData.id;
541
- }
676
+ if (isPendingId) delete insertData.id;
542
677
 
543
- // Convert the *complete* payload (attributes + id + FKs) in one place (#292).
544
678
  const row = this.deps.convertRow(insertData, schema.columns, this.deps.postgresJsonRule);
545
679
 
546
- const { sql, values } = this.deps.buildInsert(schema.table, row);
547
-
548
- const result = await this.requirePool().query(sql, values);
680
+ return { write, modelName, record, row, isPendingId };
681
+ }
549
682
 
550
- // Re-key the record in the store if PostgreSQL generated the ID (via RETURNING)
551
- if (isPendingId && result.rows.length > 0) {
552
- const pendingId = record.id;
553
- const realId = result.rows[0].id as string | number;
554
- const modelStore = (this.deps.store as unknown as { get(name: string): Map<unknown, unknown> }).get(modelName);
683
+ private _chunkWithinBindParameterLimit(prepared: PreparedCreate[]): PreparedCreate[][] {
684
+ const chunks: PreparedCreate[][] = [];
685
+ let chunk: PreparedCreate[] = [];
686
+ let chunkColumns = new Set<string>();
555
687
 
556
- modelStore.delete(pendingId);
557
- record.__data.id = realId;
558
- record.id = realId;
559
- modelStore.set(realId, record);
688
+ for (const create of prepared) {
689
+ const columnsWithCreate = new Set([...chunkColumns, ...Object.keys(create.row)]);
560
690
 
561
- // Update the response data with the real ID
562
- if (response?.data) {
563
- response.data.id = realId;
691
+ if (chunk.length > 0 && (chunk.length + 1) * columnsWithCreate.size > POSTGRES_MAX_BIND_PARAMETERS) {
692
+ chunks.push(chunk);
693
+ chunk = [];
694
+ chunkColumns = new Set(Object.keys(create.row));
695
+ } else {
696
+ chunkColumns = columnsWithCreate;
564
697
  }
565
698
 
566
- delete record.__data.__pendingSqlId;
699
+ chunk.push(create);
567
700
  }
701
+
702
+ if (chunk.length > 0) chunks.push(chunk);
703
+ return chunks;
704
+ }
705
+
706
+ private async _insertCreates(schema: ModelSchema, creates: PreparedCreate[]): Promise<void> {
707
+ if (creates.length === 1) return this._insertCreatesOneByOne(schema, creates);
708
+
709
+ let result: { rows: Record<string, unknown>[] };
710
+
711
+ try {
712
+ const { sql, values } = this.deps.buildInsertMany(schema.table, creates.map(({ row }) => row));
713
+ result = await this.requirePool().query(sql, values);
714
+ } catch {
715
+ return this._insertCreatesOneByOne(schema, creates);
716
+ }
717
+
718
+ creates.forEach((create, index) => {
719
+ this._adoptGeneratedId(create, result.rows[index]);
720
+ create.write.resolve();
721
+ });
722
+ }
723
+
724
+ private async _insertCreatesOneByOne(schema: ModelSchema, creates: PreparedCreate[]): Promise<void> {
725
+ for (const create of creates) {
726
+ try {
727
+ const { sql, values } = this.deps.buildInsert(schema.table, create.row);
728
+ const result = await this.requirePool().query(sql, values);
729
+ this._adoptGeneratedId(create, result.rows[0]);
730
+ create.write.resolve();
731
+ } catch (error) {
732
+ create.write.reject(error);
733
+ }
734
+ }
735
+ }
736
+
737
+ private _adoptGeneratedId({ modelName, record, isPendingId, write }: PreparedCreate, returnedRow: Record<string, unknown> | undefined): void {
738
+ if (!isPendingId || !returnedRow) return;
739
+
740
+ const pendingId = record.id;
741
+ const realId = returnedRow.id as string | number;
742
+ const modelStore = (this.deps.store as unknown as { get(name: string): Map<unknown, unknown> }).get(modelName);
743
+
744
+ modelStore.delete(pendingId);
745
+ record.__data.id = realId;
746
+ record.id = realId;
747
+ modelStore.set(realId, record);
748
+
749
+ if (write.response?.data) write.response.data.id = realId;
750
+
751
+ delete record.__data.__pendingSqlId;
568
752
  }
569
753
 
570
754
  private async _persistUpdate(modelName: string, context: PersistContext, _response: PersistResponse): Promise<void> {
@@ -37,6 +37,27 @@ export function buildInsert(table: string, data: Record<string, unknown>): Query
37
37
  return { sql, values };
38
38
  }
39
39
 
40
+ export function buildInsertMany(table: string, rows: Record<string, unknown>[]): QueryResult {
41
+ validateIdentifier(table, 'table name');
42
+
43
+ const columns = [...new Set(rows.flatMap(row => Object.keys(row)))];
44
+ columns.forEach(column => validateIdentifier(column, 'column name'));
45
+
46
+ const values: unknown[] = [];
47
+ const tuples = rows.map(row => {
48
+ const cells = columns.map(column => {
49
+ if (!Object.hasOwn(row, column)) return 'DEFAULT';
50
+ values.push(row[column]);
51
+ return `$${values.length}`;
52
+ });
53
+ return `(${cells.join(', ')})`;
54
+ });
55
+
56
+ const sql = `INSERT INTO "${table}" (${columns.map(column => `"${column}"`).join(', ')}) VALUES ${tuples.join(', ')} RETURNING "id"`;
57
+
58
+ return { sql, values };
59
+ }
60
+
40
61
  export function buildUpdate(table: string, id: unknown, data: Record<string, unknown>): QueryResult {
41
62
  validateIdentifier(table, 'table name');
42
63
 
@@ -1,5 +1,4 @@
1
- // Re-export all base PostgreSQL query builders
2
- export { validateIdentifier, buildInsert, buildUpdate, buildDelete, buildSelect } from '../postgres/query-builder.js';
1
+ export { validateIdentifier, buildInsert, buildInsertMany, buildUpdate, buildDelete, buildSelect } from '../postgres/query-builder.js';
3
2
 
4
3
  import { validateIdentifier } from '../postgres/query-builder.js';
5
4