@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.
@@ -4,7 +4,7 @@ import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMi
4
4
  import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
5
5
  import type { ModelSchema, ViewSchema, SnapshotEntry } from './schema-introspector.js';
6
6
  import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
7
- import { buildInsert, buildUpdate, buildDelete, buildSelect } from './query-builder.js';
7
+ import { buildInsert, buildInsertMany, buildUpdate, buildDelete, buildSelect } from './query-builder.js';
8
8
  import { store } from '@stonyx/orm';
9
9
  import { createRecord } from '../manage-record.js';
10
10
  import { confirm } from '@stonyx/utils/prompt';
@@ -32,6 +32,43 @@ interface ExecuteResult {
32
32
  insertId?: number;
33
33
  }
34
34
 
35
+ interface QueuedWrite {
36
+ operation: string;
37
+ modelName: string;
38
+ context: PersistContext;
39
+ response: PersistResponse;
40
+ resolve: () => void;
41
+ reject: (error: unknown) => void;
42
+ }
43
+
44
+ interface PreparedCreate {
45
+ write: QueuedWrite;
46
+ modelName: string;
47
+ record: OrmRecord;
48
+ row: Record<string, unknown>;
49
+ isPendingId: boolean;
50
+ }
51
+
52
+ type ExitEmitter = Pick<NodeJS.Process, 'once' | 'removeListener'>;
53
+
54
+ const MYSQL_MAX_PLACEHOLDERS = 65535;
55
+ const DEFAULT_WRITE_BATCH_SIZE = 500;
56
+ const DEFAULT_WRITE_QUEUE_LIMIT = 10000;
57
+
58
+ export class WriteQueueFullError extends Error {
59
+ constructor(limit: number) {
60
+ super(`MysqlDB write queue is full (${limit} queued writes, writeQueueLimit); the write was rejected`);
61
+ this.name = 'WriteQueueFullError';
62
+ }
63
+ }
64
+
65
+ export class WriteQueueClosedError extends Error {
66
+ constructor() {
67
+ super('MysqlDB is shutting down; the write was rejected');
68
+ this.name = 'WriteQueueClosedError';
69
+ }
70
+ }
71
+
35
72
  interface OrmStore {
36
73
  get(key: string): Map<number | string, unknown> | undefined;
37
74
  get(key: string, id: number | string): unknown;
@@ -54,6 +91,7 @@ interface MysqlDBDeps {
54
91
  loadLatestSnapshot: typeof loadLatestSnapshot;
55
92
  detectSchemaDrift: typeof detectSchemaDrift;
56
93
  buildInsert: typeof buildInsert;
94
+ buildInsertMany: typeof buildInsertMany;
57
95
  buildUpdate: typeof buildUpdate;
58
96
  buildDelete: typeof buildDelete;
59
97
  buildSelect: typeof buildSelect;
@@ -65,6 +103,7 @@ interface MysqlDBDeps {
65
103
  config: typeof config;
66
104
  log: Record<string, ((...args: unknown[]) => void) | undefined>;
67
105
  path: typeof path;
106
+ process: ExitEmitter;
68
107
  }
69
108
 
70
109
  const defaultDeps: MysqlDBDeps = {
@@ -72,9 +111,9 @@ const defaultDeps: MysqlDBDeps = {
72
111
  getMigrationFiles, applyMigration, parseMigrationFile,
73
112
  introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
74
113
  loadLatestSnapshot, detectSchemaDrift,
75
- buildInsert, buildUpdate, buildDelete, buildSelect,
114
+ buildInsert, buildInsertMany, buildUpdate, buildDelete, buildSelect,
76
115
  createRecord, store: store as OrmStore, confirm, readFile, getPluralName,
77
- config, log, path
116
+ config, log, path, process
78
117
  };
79
118
 
80
119
  export default class MysqlDB {
@@ -84,14 +123,11 @@ export default class MysqlDB {
84
123
  pool!: Pool | null;
85
124
  mysqlConfig!: MysqlConfig;
86
125
 
87
- /**
88
- * Promise-chain mutex for write serialization (#156).
89
- * All persist() calls chain through this single queue so concurrent
90
- * fire-and-forget writes never produce parallel InnoDB transactions
91
- * on FK-linked rows (which cause deadlocks).
92
- * Reads are NOT affected — only persist() serializes.
93
- */
94
- private _writeQueue: Promise<void> = Promise.resolve();
126
+ private _queuedWrites: QueuedWrite[] = [];
127
+ private _inFlightWrites = new Set<QueuedWrite>();
128
+ private _drainingWrites: Promise<void> | null = null;
129
+ private _acceptingWrites = true;
130
+ private _exitReport: (() => void) | null = null;
95
131
 
96
132
  constructor(deps: Partial<MysqlDBDeps> = {}) {
97
133
  if (MysqlDB.instance) return MysqlDB.instance;
@@ -113,6 +149,20 @@ export default class MysqlDB {
113
149
  this.pool = await this.deps.getPool(this.mysqlConfig);
114
150
  await this.deps.ensureMigrationsTable(this.pool, this.mysqlConfig.migrationsTable);
115
151
  await this.loadMemoryRecords();
152
+ this._acceptingWrites = true;
153
+ this._registerExitReport();
154
+ }
155
+
156
+ get writeBatchSize(): number {
157
+ return Number(this.mysqlConfig?.writeBatchSize) || DEFAULT_WRITE_BATCH_SIZE;
158
+ }
159
+
160
+ get writeQueueLimit(): number {
161
+ return Number(this.mysqlConfig?.writeQueueLimit) || DEFAULT_WRITE_QUEUE_LIMIT;
162
+ }
163
+
164
+ get pendingWriteCount(): number {
165
+ return this._inFlightWrites.size + this._queuedWrites.length;
116
166
  }
117
167
 
118
168
  async startup(): Promise<void> {
@@ -200,10 +250,36 @@ export default class MysqlDB {
200
250
  }
201
251
 
202
252
  async shutdown(): Promise<void> {
253
+ this._acceptingWrites = false;
254
+ while (this._drainingWrites) await this._drainingWrites;
255
+ this._unregisterExitReport();
203
256
  await this.deps.closePool();
204
257
  this.pool = null;
205
258
  }
206
259
 
260
+ private _registerExitReport(): void {
261
+ if (this._exitReport) return;
262
+ this._exitReport = () => this._reportUnpersistedWrites();
263
+ this.deps.process.once('exit', this._exitReport);
264
+ }
265
+
266
+ private _unregisterExitReport(): void {
267
+ if (!this._exitReport) return;
268
+ this.deps.process.removeListener('exit', this._exitReport);
269
+ this._exitReport = null;
270
+ }
271
+
272
+ private _reportUnpersistedWrites(): void {
273
+ const lostWrites = [...this._inFlightWrites, ...this._queuedWrites];
274
+ if (lostWrites.length === 0) return;
275
+
276
+ const lostByModel = new Map<string, number>();
277
+ for (const { modelName } of lostWrites) lostByModel.set(modelName, (lostByModel.get(modelName) ?? 0) + 1);
278
+ const breakdown = [...lostByModel].map(([modelName, count]) => `${modelName}: ${count}`).join(', ');
279
+
280
+ this.deps.log.error?.(`[MysqlDB] Process exiting with ${lostWrites.length} queued write(s) not persisted; they are lost (${breakdown})`);
281
+ }
282
+
207
283
  async save(): Promise<void> {
208
284
  // No-op: MySQL persists data immediately via persist()
209
285
  }
@@ -419,76 +495,185 @@ export default class MysqlDB {
419
495
  }
420
496
 
421
497
  async persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
422
- // Views are read-only — no-op for all write operations
423
498
  const Orm = (await import('@stonyx/orm')).default;
424
499
  if ((Orm as unknown as { instance?: { isView?: (name: string) => boolean } }).instance?.isView?.(modelName)) return;
425
500
 
426
- const work = async () => {
427
- switch (operation) {
428
- case 'create':
429
- return this._persistCreate(modelName, context, response);
430
- case 'update':
431
- return this._persistUpdate(modelName, context, response);
432
- case 'delete':
433
- return this._persistDelete(modelName, context);
501
+ if (!this._acceptingWrites) throw new WriteQueueClosedError();
502
+ if (this._queuedWrites.length >= this.writeQueueLimit) throw new WriteQueueFullError(this.writeQueueLimit);
503
+
504
+ return new Promise<void>((resolve, reject) => {
505
+ const write: QueuedWrite = {
506
+ operation, modelName, context, response,
507
+ resolve: () => {
508
+ this._inFlightWrites.delete(write);
509
+ resolve();
510
+ },
511
+ reject: (error: unknown) => {
512
+ this._inFlightWrites.delete(write);
513
+ reject(error);
514
+ },
515
+ };
516
+ this._queuedWrites.push(write);
517
+ this._drainWritesInBackground();
518
+ });
519
+ }
520
+
521
+ private _drainWritesInBackground(): void {
522
+ if (this._drainingWrites) return;
523
+ this._drainingWrites = this._drainQueuedWrites().finally(() => {
524
+ this._drainingWrites = null;
525
+ });
526
+ }
527
+
528
+ private async _drainQueuedWrites(): Promise<void> {
529
+ while (this._queuedWrites.length > 0) {
530
+ const writes = this._takeNextWriteGroup();
531
+ writes.forEach(write => this._inFlightWrites.add(write));
532
+ try {
533
+ await this._executeWriteGroup(writes);
534
+ } catch (error) {
535
+ writes.filter(write => this._inFlightWrites.has(write)).forEach(write => write.reject(error));
434
536
  }
435
- };
537
+ }
538
+ }
539
+
540
+ private _takeNextWriteGroup(): QueuedWrite[] {
541
+ const [first] = this._queuedWrites;
542
+ let groupSize = 1;
543
+
544
+ if (first.operation === 'create') {
545
+ while (
546
+ groupSize < this.writeBatchSize
547
+ && groupSize < this._queuedWrites.length
548
+ && this._queuedWrites[groupSize].operation === 'create'
549
+ && this._queuedWrites[groupSize].modelName === first.modelName
550
+ ) groupSize++;
551
+ }
436
552
 
437
- // Chain through the write queue — .then(work, work) ensures the queue
438
- // advances even when a previous persist rejects (#156).
439
- this._writeQueue = this._writeQueue.then(work, work);
440
- return this._writeQueue;
553
+ return this._queuedWrites.splice(0, groupSize);
441
554
  }
442
555
 
443
- private async _persistCreate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
444
- const schemas = this.deps.introspectModels();
445
- const schema = schemas[modelName];
556
+ private async _executeWriteGroup(writes: QueuedWrite[]): Promise<void> {
557
+ const [first] = writes;
558
+ if (first.operation === 'create') return this._persistCreates(first.modelName, writes);
446
559
 
447
- if (!schema) return;
560
+ try {
561
+ if (first.operation === 'update') await this._persistUpdate(first.modelName, first.context, first.response);
562
+ if (first.operation === 'delete') await this._persistDelete(first.modelName, first.context);
563
+ first.resolve();
564
+ } catch (error) {
565
+ first.reject(error);
566
+ }
567
+ }
568
+
569
+ private async _persistCreates(modelName: string, writes: QueuedWrite[]): Promise<void> {
570
+ const schema = this.deps.introspectModels()[modelName];
571
+ const prepared: PreparedCreate[] = [];
572
+
573
+ for (const write of writes) {
574
+ try {
575
+ const create = schema ? this._prepareCreate(modelName, schema, write) : null;
576
+ if (create) prepared.push(create);
577
+ else write.resolve();
578
+ } catch (error) {
579
+ write.reject(error);
580
+ }
581
+ }
582
+
583
+ for (const chunk of this._chunkForSingleInsert(prepared)) {
584
+ await this._insertCreates(schema, chunk);
585
+ }
586
+ }
448
587
 
588
+ private _prepareCreate(modelName: string, schema: ModelSchema, write: QueuedWrite): PreparedCreate | null {
589
+ const { context, response } = write;
449
590
  const recordId = response?.data?.id;
450
591
  const record = recordId != null ? this.deps.store.get(modelName, (isNaN(recordId as number) ? recordId : parseInt(recordId as string)) as number | string) as OrmRecord | null : null;
451
592
 
452
- if (!record) return;
453
-
454
- const insertData = this._recordToRow(record, schema);
593
+ if (!record) return null;
455
594
 
456
- // For auto-increment models, remove the pending ID.
457
- // Check context.rawData (not record.__data) because __pendingSqlId is not a model
458
- // attribute and gets lost during serialization.
595
+ const row = this._recordToRow(record, schema);
459
596
  const isPendingId = context.rawData?.__pendingSqlId === true;
460
597
 
461
- if (isPendingId) {
462
- delete insertData.id;
463
- } else if (insertData.id !== undefined) {
464
- // Keep user-provided ID (string IDs or explicit numeric IDs)
598
+ if (isPendingId) delete row.id;
599
+
600
+ return { write, modelName, record, row, isPendingId };
601
+ }
602
+
603
+ private _chunkForSingleInsert(prepared: PreparedCreate[]): PreparedCreate[][] {
604
+ const chunks: PreparedCreate[][] = [];
605
+ let chunk: PreparedCreate[] = [];
606
+ let chunkColumns = new Set<string>();
607
+
608
+ for (const create of prepared) {
609
+ const columnsWithCreate = new Set([...chunkColumns, ...Object.keys(create.row)]);
610
+ const mixesIdSources = chunk.length > 0 && chunk[0].isPendingId !== create.isPendingId;
611
+ const exceedsPlaceholders = (chunk.length + 1) * columnsWithCreate.size > MYSQL_MAX_PLACEHOLDERS;
612
+
613
+ if (chunk.length > 0 && (mixesIdSources || exceedsPlaceholders)) {
614
+ chunks.push(chunk);
615
+ chunk = [];
616
+ chunkColumns = new Set(Object.keys(create.row));
617
+ } else {
618
+ chunkColumns = columnsWithCreate;
619
+ }
620
+
621
+ chunk.push(create);
465
622
  }
466
623
 
467
- const { sql, values } = this.deps.buildInsert(schema.table, insertData);
624
+ if (chunk.length > 0) chunks.push(chunk);
625
+ return chunks;
626
+ }
468
627
 
469
- const [result] = await this.requirePool().execute(sql, values) as [ExecuteResult, unknown];
628
+ private async _insertCreates(schema: ModelSchema, creates: PreparedCreate[]): Promise<void> {
629
+ if (creates.length === 1) return this._insertCreatesOneByOne(schema, creates);
470
630
 
471
- // Re-key the record in the store if MySQL generated the ID
472
- if (isPendingId && result.insertId) {
473
- const pendingId = record.id;
474
- const realId = result.insertId;
475
- const modelStore = this.deps.store.get(modelName);
476
- if (!modelStore) throw new Error(`Model "${modelName}" not found in store during ID re-key`);
631
+ let firstInsertId: number | undefined;
477
632
 
478
- modelStore.delete(pendingId as number | string);
479
- record.__data.id = realId;
480
- record.id = realId;
481
- modelStore.set(realId as number | string, record);
633
+ try {
634
+ const { sql, values } = this.deps.buildInsertMany(schema.table, creates.map(({ row }) => row));
635
+ const [result] = await this.requirePool().execute(sql, values) as [ExecuteResult, unknown];
636
+ firstInsertId = result.insertId;
637
+ } catch {
638
+ return this._insertCreatesOneByOne(schema, creates);
639
+ }
482
640
 
483
- // Update the response data with the real ID
484
- if (response?.data) {
485
- response.data.id = realId;
486
- }
641
+ creates.forEach((create, index) => {
642
+ if (firstInsertId) this._adoptGeneratedId(create, firstInsertId + index);
643
+ create.write.resolve();
644
+ });
645
+ }
487
646
 
488
- delete record.__data.__pendingSqlId;
647
+ private async _insertCreatesOneByOne(schema: ModelSchema, creates: PreparedCreate[]): Promise<void> {
648
+ for (const create of creates) {
649
+ try {
650
+ const { sql, values } = this.deps.buildInsert(schema.table, create.row);
651
+ const [result] = await this.requirePool().execute(sql, values) as [ExecuteResult, unknown];
652
+ if (result.insertId) this._adoptGeneratedId(create, result.insertId);
653
+ create.write.resolve();
654
+ } catch (error) {
655
+ create.write.reject(error);
656
+ }
489
657
  }
490
658
  }
491
659
 
660
+ private _adoptGeneratedId({ modelName, record, isPendingId, write }: PreparedCreate, realId: number): void {
661
+ if (!isPendingId) return;
662
+
663
+ const pendingId = record.id;
664
+ const modelStore = this.deps.store.get(modelName);
665
+ if (!modelStore) throw new Error(`Model "${modelName}" not found in store during ID re-key`);
666
+
667
+ modelStore.delete(pendingId as number | string);
668
+ record.__data.id = realId;
669
+ record.id = realId;
670
+ modelStore.set(realId, record);
671
+
672
+ if (write.response?.data) write.response.data.id = realId;
673
+
674
+ delete record.__data.__pendingSqlId;
675
+ }
676
+
492
677
  private async _persistUpdate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
493
678
  const schemas = this.deps.introspectModels();
494
679
  const schema = schemas[modelName];
@@ -27,6 +27,27 @@ export function buildInsert(table: string, data: Record<string, unknown>): Query
27
27
  return { sql, values };
28
28
  }
29
29
 
30
+ export function buildInsertMany(table: string, rows: Record<string, unknown>[]): QueryResult {
31
+ validateIdentifier(table, 'table name');
32
+
33
+ const columns = [...new Set(rows.flatMap(row => Object.keys(row)))];
34
+ columns.forEach(column => validateIdentifier(column, 'column name'));
35
+
36
+ const values: unknown[] = [];
37
+ const tuples = rows.map(row => {
38
+ const cells = columns.map(column => {
39
+ if (!Object.hasOwn(row, column)) return 'DEFAULT';
40
+ values.push(row[column]);
41
+ return '?';
42
+ });
43
+ return `(${cells.join(', ')})`;
44
+ });
45
+
46
+ const sql = `INSERT INTO \`${table}\` (${columns.map(column => `\`${column}\``).join(', ')}) VALUES ${tuples.join(', ')}`;
47
+
48
+ return { sql, values };
49
+ }
50
+
30
51
  export function buildUpdate(table: string, id: unknown, data: Record<string, unknown>): QueryResult {
31
52
  validateIdentifier(table, 'table name');
32
53
 
@@ -21,7 +21,7 @@ export async function getPool(pgConfig: PgConfig, extensions: string[] = ['vecto
21
21
 
22
22
  const { default: pg } = await import('pg');
23
23
 
24
- const { host, port, user, password, database, connectionLimit, migrationsDir, migrationsTable, autoMigrate, ...poolOpts } = pgConfig;
24
+ const { host, port, user, password, database, connectionLimit, migrationsDir, migrationsTable, autoMigrate, writeBatchSize, writeQueueLimit, ...poolOpts } = pgConfig;
25
25
 
26
26
  pool = new pg.Pool({
27
27
  host,