@stonyx/orm 0.3.2-beta.16 → 0.3.2-beta.160

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.
Files changed (66) hide show
  1. package/README.md +1409 -11
  2. package/config/environment.js +99 -12
  3. package/dist/access-verdict.d.ts +85 -0
  4. package/dist/access-verdict.js +284 -0
  5. package/dist/commands.js +34 -0
  6. package/dist/dynamodb/connection.d.ts +31 -0
  7. package/dist/dynamodb/connection.js +28 -0
  8. package/dist/dynamodb/dynamodb-db.d.ts +142 -0
  9. package/dist/dynamodb/dynamodb-db.js +596 -0
  10. package/dist/dynamodb/operation-builder.d.ts +76 -0
  11. package/dist/dynamodb/operation-builder.js +116 -0
  12. package/dist/dynamodb/type-map.d.ts +31 -0
  13. package/dist/dynamodb/type-map.js +48 -0
  14. package/dist/hooks.d.ts +15 -1
  15. package/dist/index.d.ts +3 -0
  16. package/dist/index.js +8 -0
  17. package/dist/main.d.ts +116 -0
  18. package/dist/main.js +129 -0
  19. package/dist/manage-record.js +268 -12
  20. package/dist/mysql/connection.d.ts +1 -0
  21. package/dist/mysql/mysql-db.d.ts +8 -0
  22. package/dist/mysql/mysql-db.js +44 -10
  23. package/dist/orm-request.d.ts +274 -3
  24. package/dist/orm-request.js +1259 -65
  25. package/dist/postgres/connection.d.ts +1 -0
  26. package/dist/postgres/connection.js +8 -6
  27. package/dist/postgres/postgres-db.d.ts +8 -0
  28. package/dist/postgres/postgres-db.js +44 -10
  29. package/dist/record.d.ts +16 -0
  30. package/dist/record.js +154 -6
  31. package/dist/relationships.js +1 -1
  32. package/dist/serializer.js +38 -2
  33. package/dist/setup-rest-server.js +51 -5
  34. package/dist/standalone-db.js +17 -5
  35. package/dist/store.d.ts +13 -1
  36. package/dist/store.js +65 -6
  37. package/dist/types/orm-types.d.ts +260 -0
  38. package/dist/utils.d.ts +44 -0
  39. package/dist/utils.js +47 -0
  40. package/package.json +16 -7
  41. package/src/access-verdict.ts +312 -0
  42. package/src/commands.ts +43 -0
  43. package/src/dynamodb/connection.ts +50 -0
  44. package/src/dynamodb/dynamodb-db.ts +811 -0
  45. package/src/dynamodb/operation-builder.ts +202 -0
  46. package/src/dynamodb/type-map.ts +54 -0
  47. package/src/hooks.ts +15 -1
  48. package/src/index.ts +10 -0
  49. package/src/main.ts +133 -0
  50. package/src/manage-record.ts +294 -18
  51. package/src/mysql/connection.ts +1 -0
  52. package/src/mysql/mysql-db.ts +44 -12
  53. package/src/orm-request.ts +1281 -67
  54. package/src/postgres/connection.ts +10 -6
  55. package/src/postgres/postgres-db.ts +44 -12
  56. package/src/record.ts +182 -6
  57. package/src/relationships.ts +1 -1
  58. package/src/serializer.ts +39 -2
  59. package/src/setup-rest-server.ts +59 -6
  60. package/src/standalone-db.ts +17 -6
  61. package/src/store.ts +68 -6
  62. package/src/types/orm-types.ts +268 -1
  63. package/src/types/stonyx-rest-server.d.ts +14 -1
  64. package/src/types/stonyx.d.ts +7 -1
  65. package/src/utils.ts +50 -0
  66. package/config/environment.ts +0 -91
@@ -1,7 +1,7 @@
1
1
  import Orm, { store } from '@stonyx/orm';
2
2
  import OrmRecord from './record.js';
3
3
  import { getGlobalRegistry, getPendingRegistry, getPendingBelongsToRegistry, getBelongsToRegistry, getHasManyRegistry } from './relationships.js';
4
- import { isOrmRecord } from './utils.js';
4
+ import { isOrmRecord, maxNumericId, NO_FREE_ID_ERROR } from './utils.js';
5
5
  const defaultOptions = {
6
6
  isDbRecord: false,
7
7
  serialize: true,
@@ -52,13 +52,34 @@ export function createRecord(modelName, rawData = {}, userOptions = {}) {
52
52
  relationship.push(record);
53
53
  pendingHasMany.splice(0);
54
54
  }
55
+ // FK-based inverse hasMany wiring — when a child record is created with a
56
+ // foreign-key field (e.g. `owner: 'owner-1'` on an animal), find any parent
57
+ // whose hasMany registry targets this model and push the child into the
58
+ // parent's shared array. This covers edge cases where the child is created
59
+ // in a separate async frame without a belongsTo handler firing.
60
+ const hasManyReg = getHasManyRegistry();
61
+ if (hasManyReg) {
62
+ for (const [parentModelName, targetMap] of hasManyReg) {
63
+ const childArrayMap = targetMap.get(modelName);
64
+ if (!childArrayMap)
65
+ continue;
66
+ // Check if rawData contains a FK field matching the parent model name
67
+ const fkValue = rawData[parentModelName];
68
+ if (fkValue === undefined || fkValue === null)
69
+ continue;
70
+ const parentArray = childArrayMap.get(fkValue);
71
+ if (parentArray && !parentArray.includes(record)) {
72
+ parentArray.push(record);
73
+ }
74
+ }
75
+ }
55
76
  // Fulfill pending belongsTo relationships
56
77
  const pendingBelongsToQueue = getPendingBelongsToRegistry();
57
78
  const pendingBelongsToRaw = pendingBelongsToQueue.get(modelName)?.get(record.id);
58
79
  const pendingBelongsTo = Array.isArray(pendingBelongsToRaw) ? pendingBelongsToRaw : undefined;
59
80
  if (pendingBelongsTo) {
60
81
  const belongsToReg = getBelongsToRegistry();
61
- const hasManyReg = getHasManyRegistry();
82
+ const pendingHasManyReg = getHasManyRegistry();
62
83
  for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
63
84
  // Update the belongsTo relationship on the source record
64
85
  sourceRecord.__relationships[relationshipKey] = record;
@@ -72,7 +93,7 @@ export function createRecord(modelName, rawData = {}, userOptions = {}) {
72
93
  }
73
94
  }
74
95
  // Wire inverse hasMany if it exists
75
- const inverseHasMany = hasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
96
+ const inverseHasMany = pendingHasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
76
97
  if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
77
98
  inverseHasMany.push(sourceRecord);
78
99
  }
@@ -83,14 +104,24 @@ export function createRecord(modelName, rawData = {}, userOptions = {}) {
83
104
  // Auto-persist to SQL — skip for DB loads (isDbRecord) and relationship resolution (_relationshipKey)
84
105
  const shouldPersist = orm?.sqlDb && !options.isDbRecord && !userOptions._relationshipKey && !options._skipAutoPersist;
85
106
  if (shouldPersist) {
107
+ // Capture ID before persist — SQL adapters re-key pending IDs to real DB IDs,
108
+ // but relationship registries were keyed with this original ID
109
+ const registryId = record.id;
86
110
  const response = { data: { id: record.id } };
87
- orm.sqlDb.persist('create', modelName, { rawData }, response).catch((err) => {
111
+ orm.sqlDb.persist('create', modelName, { rawData }, response)
112
+ .catch((err) => {
88
113
  orm.emitPersistError({
89
114
  operation: 'create',
90
115
  modelName,
91
116
  recordId: record.id,
92
117
  error: err instanceof Error ? err : new Error(String(err)),
93
118
  });
119
+ })
120
+ .finally(() => {
121
+ // Evict non-memory records after persist to prevent unbounded heap growth (stonyx#81)
122
+ if (store._memoryResolver && !store._memoryResolver(modelName)) {
123
+ store.evictRecord(modelName, record.id, registryId);
124
+ }
94
125
  });
95
126
  }
96
127
  return record;
@@ -122,17 +153,58 @@ export function updateRecord(record, rawData, userOptions = {}) {
122
153
  }
123
154
  }
124
155
  /**
125
- * gets the next available id based on last record entry.
156
+ * gets the next available id, based on the HIGHEST id present.
126
157
  *
127
158
  * In MySQL mode with numeric IDs, assigns a temporary pending ID.
128
159
  * MySQL's AUTO_INCREMENT provides the real ID after INSERT.
160
+ *
161
+ * ---------------------------------------------------------------------------
162
+ * WAS: `Array.from(storeMap.values()).at(-1).id + 1` — the LAST INSERTED id,
163
+ * not the maximum (abofs/stonyx-orm#203). The store is a Map, so insertion
164
+ * order stops being ascending the moment a record is deleted and recreated, a
165
+ * db.json is written out of order, a directory-mode store is read back in file
166
+ * order, or a caller POSTs a high id and then a low one. After that, every
167
+ * server-assigned id is one that is ALREADY TAKEN — and `createRecord`'s
168
+ * last-entry-wins branch then overwrites that record IN PLACE and answers 200.
169
+ * No error, no 409, and the store's size does not change. That is the whole
170
+ * defect, and it is reachable from a create with NO id at all, which is the
171
+ * most ordinary write a consumer performs.
172
+ *
173
+ * Covered by test/unit/assign-record-id-test.ts. Note for anyone changing this
174
+ * function: before that file existed, the whole suite scored 951/0 both on the
175
+ * defect and on a naive `Math.max` fix that introduced a second one. A green
176
+ * suite is not evidence here; those assertions are.
177
+ * ---------------------------------------------------------------------------
129
178
  */
130
179
  function assignRecordId(modelName, rawData) {
131
- if (rawData.id)
180
+ // PRESENCE, not truthiness. `0` is a legal value for an `attr('number')` id,
181
+ // and `if (rawData.id) return` silently reassigned it, handing the caller back
182
+ // a different record than the one it named (#203).
183
+ //
184
+ // `''` is deliberately NOT honoured here and this is not an oversight: it is
185
+ // the one string that means "no id". `parseInt('')` is `NaN`, a record CAN be
186
+ // held under the key `NaN`, and orm-request.ts's body-id normalisation relies
187
+ // on `''` staying absent — otherwise `POST {"id":""}` answers 409 against a
188
+ // record it never named.
189
+ //
190
+ // WHAT WIDENING THIS TO `!== undefined` ACTUALLY DOES, measured rather than
191
+ // asserted: `{id: ''}` early-returns, `parseInt('')` NaNs it, and the record
192
+ // lands on the store's `NaN` slot and OVERWRITES whatever is there — #203's
193
+ // own defect class. It does NOT turn access-filter-enforcement-test.ts
194
+ // assertion 44 red; an earlier revision of this comment claimed it did, which
195
+ // converted an unknown into a false assurance. AC6's BOUNDARY assertions are
196
+ // what catch it, and they only do so because they seed the `NaN` slot first.
197
+ if (rawData.id || rawData.id === 0)
132
198
  return;
133
199
  // In SQL mode with numeric IDs, defer to database auto-increment.
134
200
  // Use unique negative integers — they survive the number transform (parseInt preserves negatives)
135
201
  // and avoid NaN store-key collisions that string pending IDs caused.
202
+ //
203
+ // This early return is ABOVE the max computation on purpose: a pending
204
+ // negative must never be a candidate for, or be perturbed by, the max path.
205
+ // Pinned directly (AC5.3) rather than by asserting the max is unaffected —
206
+ // that assertion could not have failed, because nothing negative ever reaches
207
+ // the code below.
136
208
  if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
137
209
  rawData.id = -(++pendingIdCounter);
138
210
  rawData.__pendingSqlId = true;
@@ -142,13 +214,197 @@ function assignRecordId(modelName, rawData) {
142
214
  if (!storeMap)
143
215
  throw new Error(`Cannot assign record ID: model "${modelName}" not found in store`);
144
216
  const modelStore = Array.from(storeMap.values()).filter(isOrmRecord);
145
- const lastRecord = modelStore.at(-1);
146
- rawData.id = lastRecord ? lastRecord.id + 1 : 1;
217
+ // ONE COPY of the max-numeric-id reduce, in src/utils.ts. There were three
218
+ // (here, StandaloneDB.create, and the #203 test helper) and `docs/
219
+ // improvements.md`'s WET Code category prescribes the extraction. What that
220
+ // helper must NOT be is `Math.max(...ids)`; the reason is measured and it is
221
+ // documented at the helper rather than duplicated here. Pinned by AC2.
222
+ const maxId = maxNumericId(modelStore);
223
+ // THE OCCUPANCY CHECK RUNS ON THE LANDING KEY, NOT ON THE RAW CANDIDATE, and
224
+ // the difference is a silent data loss rather than a nicety.
225
+ //
226
+ // `createRecord` looks the record up under `rawData.id` (:50) but WRITES it
227
+ // under `record.id` (:69) — the value after the model's declared id transform
228
+ // has run inside `serialize`. When the transform is not the identity those two
229
+ // differ, so a guard written as `storeMap.has(rawData.id)` checks a key the
230
+ // record will never occupy, misses an occupied slot and overwrites it —
231
+ // measured on an `uppercase`-id model: the guard checks `owner-1`, the record
232
+ // lands under `OWNER-1`, store size unchanged, no error. That is
233
+ // abofs/stonyx-orm#205's lookup-key/landing-key divergence reappearing inside
234
+ // #203's own fix, which is why AC4 exists and why `rawData.id` is set to the
235
+ // LANDING key below.
236
+ //
237
+ // THE SCOPE OF THAT CLAIM, stated rather than implied. Setting `rawData.id` to
238
+ // the landing key makes :50 and :69 agree for every IDEMPOTENT id transform —
239
+ // `number`, `float`, `string`, `passthrough`, `uppercase`, `trim`. It does NOT
240
+ // make them agree for `date` or `timestamp`: `transforms.date` returns a NEW
241
+ // object every call and a `Map` keys by identity, so `storeMap.has(landingKey)`
242
+ // is always `false` there and the occupancy check is vacuous. `dev` is broken
243
+ // for those types too — this is not a regression — but no comment here may
244
+ // claim a property it was not measured to have (#212 § AC5).
245
+ //
246
+ // Resolved ONCE, outside the walk: `getIdType` instantiates the model class,
247
+ // so resolving it per candidate would put a model construction on every
248
+ // iteration of a loop that exists to walk past occupied slots.
249
+ const toStoreKey = storeKeyDeriver(modelName);
250
+ // DOES THIS MODEL FILE ITS RECORDS UNDER STRING KEYS? Decided by RUNNING the
251
+ // model's own id transform once, not by matching a type NAME against a list:
252
+ // `Orm.instance.transforms` (main.ts:70) is a public, MUTABLE instance
253
+ // property, so any enumeration of "the string-ish types" written here would be
254
+ // wrong the moment a consumer registers one.
255
+ const stringKeyed = typeof toStoreKey(maxId + 1) === 'string';
256
+ // THE CANDIDATE FOR A STRING-KEYED MODEL IS NOT A BARE NUMBER, and this is
257
+ // abofs/stonyx-orm#209 — which is REOPENED — not aesthetics.
258
+ //
259
+ // `orm-request.ts`'s `coerceId` (:322) resolves a NUMERIC-LOOKING string to a
260
+ // NUMBER on every id-bearing surface, while a model declaring
261
+ // `id = attr('string')` files under the STRING key. So a server-assigned `'1'`
262
+ // produces a record that is created and then NOT ADDRESSABLE. Measured over
263
+ // the route, owner store `{'1': ...}`:
264
+ //
265
+ // GET /owners/1 -> 404 (the record exists)
266
+ // DELETE /owners/1 -> 404
267
+ // GET /owners/owner-1 -> 200
268
+ //
269
+ // and `_withHooks` (:1185) hands an after-`create` hook
270
+ // `context.record === undefined` for the same reason. `dev` assigned `'bob1'`,
271
+ // which is not numeric-looking, so `dev` has neither problem: a bare-number
272
+ // candidate would move #209 from "a caller supplied a numeric-looking id" onto
273
+ // the DEFAULT path for every server-assigned create on every string-id model.
274
+ // Prefixing with the model name keeps #209's population exactly as narrow as
275
+ // it already was, without touching the one shared coercion or the assertion
276
+ // that pins #209 open. Pinned by AC3.
277
+ const toCandidate = stringKeyed
278
+ ? (value) => `${modelName}-${value}`
279
+ : (value) => value;
280
+ // `maxId + 1` is the id AC1 pins: strictly greater than every numeric key
281
+ // present. IT IS NOT ALWAYS AVAILABLE, and that gap was a live denial of
282
+ // service. Float64 has no integer successor at or above 2^53, so
283
+ // `maxId + 1 === maxId` for every `maxId >= 9007199254740992` and `+ 1` inside
284
+ // the walk is a NO-OP there. One record filed under that key — which an
285
+ // unauthenticated `POST {"id":9007199254740992}` puts there, and which reaches
286
+ // even a filter-protected collection through has-many.ts:65 (#207), a channel
287
+ // GATE 0 does not cover — made the walk unable to advance, so it exhausted its
288
+ // budget and threw on EVERY subsequent server-assigned create, permanently,
289
+ // until that record was deleted. Measured over the route: 200, then 500 for
290
+ // every no-id create. `dev` answers 200.
291
+ //
292
+ // So a store holding one adversarial record must not disable its collection.
293
+ // When "above the max" is not a usable strategy the walk RESTARTS FROM 1: the
294
+ // store holds at most `size` keys, so one of `1 .. size + 1` is always free
295
+ // under an injective id transform. Pinned by AC7.
296
+ const start = maxId + 1;
297
+ let landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, start);
298
+ // THE RESTART, and it is the whole of the ceiling fix. Killing mutation:
299
+ // delete this block -> AC7 goes red (the route answers 409 instead of the
300
+ // created resource).
301
+ if (landingKey === NO_FREE_KEY && start !== 1) {
302
+ landingKey = firstFreeKey(storeMap, toStoreKey, toCandidate, 1);
303
+ }
304
+ if (landingKey === NO_FREE_KEY) {
305
+ // Reachable only with a NON-INJECTIVE id transform — see `firstFreeKey`.
306
+ // `createHandler` matches this message and answers 409 rather than letting it
307
+ // reach express's default handler, which serialises a stack trace with
308
+ // absolute install paths outside NODE_ENV=production (the hazard
309
+ // orm-request.ts:553-558 exists to name). Pinned by AC8.
310
+ throw new Error(`${NO_FREE_ID_ERROR} for model "${modelName}"`);
311
+ }
312
+ rawData.id = landingKey;
147
313
  }
148
- function isStringIdModel(modelName) {
149
- const modelClass = Orm.instance.getRecordClasses(modelName).modelClass;
314
+ // Returned instead of a key so that "no key" cannot be confused with a transform
315
+ // that legitimately produced `undefined` or `null`.
316
+ const NO_FREE_KEY = Symbol('no free store key');
317
+ /**
318
+ * The first store key at or above `start` that no record occupies, walking
319
+ * candidate ids upward, or `NO_FREE_KEY` if the walk cannot reach one.
320
+ */
321
+ function firstFreeKey(storeMap, toStoreKey, toCandidate, start) {
322
+ let candidate = start;
323
+ let landingKey = toStoreKey(toCandidate(candidate));
324
+ let attempts = 0;
325
+ while (storeMap.has(landingKey)) {
326
+ // THE BOUND IS EXACTLY TIGHT, not conservative: this walk tries
327
+ // `storeMap.size + 1` DISTINCT candidates against at most `storeMap.size`
328
+ // occupied keys, so under an injective `toStoreKey` it provably cannot fire.
329
+ // Under a non-injective one it provably terminates — and that is a reachable
330
+ // consumer state rather than a hypothesis: `transforms.boolean`
331
+ // (transforms.ts:4) collapses every candidate onto `true`/`false`, and
332
+ // `Orm.instance.transforms` (main.ts:70) is public and MUTABLE, so a consumer
333
+ // can register an arbitrary non-injective transform and name it as an id
334
+ // type. Without this, a no-id create spins forever inside a synchronous store
335
+ // walk and pins a worker, which is worse than either collision policy. Its
336
+ // EXISTENCE and its THRESHOLD are both pinned by AC8: deleting it makes AC8
337
+ // HANG rather than fail, and weakening it to fire on the first collision
338
+ // makes AC8.1 red.
339
+ if (++attempts > storeMap.size)
340
+ return NO_FREE_KEY;
341
+ // NOTE FOR ANYONE ADDING A SECOND EXIT HERE. A `candidate + 1 === candidate`
342
+ // float-saturation check was written, measured, and REMOVED: with the
343
+ // restart-from-1 above in place, deleting the saturation check leaves the
344
+ // whole suite green, because the budget reaches the same `NO_FREE_KEY` one
345
+ // pass later and the restart still answers. An unkillable guard in a change
346
+ // whose deliverable is falsifiable coverage is exactly what this story exists
347
+ // to stop shipping. `+ 1` being a no-op at 2^53 costs `size` extra `Map.has`
348
+ // calls on that one path and changes no outcome.
349
+ candidate += 1;
350
+ landingKey = toStoreKey(toCandidate(candidate));
351
+ }
352
+ return landingKey;
353
+ }
354
+ /**
355
+ * Returns the derivation that maps an id VALUE to the store KEY a record
356
+ * carrying it will actually be filed under — the model's declared id transform,
357
+ * the same one `serialize` runs at createRecord:68 before the `.set` at :69.
358
+ */
359
+ function storeKeyDeriver(modelName) {
360
+ const idType = getIdType(modelName);
361
+ const transform = idType ? Orm.instance?.transforms?.[idType] : undefined;
362
+ // SURVIVOR, RETAINED, with its reachability condition stated rather than left
363
+ // silent — `docs/project-structure.md` § "unkillable code reads as coverage and
364
+ // is not" is the standing rule and it applies outside orm-request.ts too.
365
+ //
366
+ // No mutation in this repo can kill this branch, and that is STRUCTURAL rather
367
+ // than an untested gap: `Model` declares `id = attr('number')` (model.ts:15) so
368
+ // every registered model has an id type; `ModelProperty` refuses a type with no
369
+ // registered transform (model-property.ts:4) so a declared type always
370
+ // resolves; and `getIdType` can therefore only return `undefined` when
371
+ // `getRecordClasses` yields no `modelClass` — in which case `createRecord`
372
+ // throws at :62 a few lines later regardless, so no record is ever filed
373
+ // through this branch.
374
+ //
375
+ // BECOMES REACHABLE if a model can be declared without an `id` property, if a
376
+ // store map can exist for a model with no registered class, or if
377
+ // `createRecord` stops constructing the model class. Kept rather than deleted
378
+ // because the alternative on that path is a `transform is not a function`
379
+ // TypeError, and because identity is exactly what `createRecord` would file
380
+ // under when no transform exists — the two agree, which is the property AC4 is
381
+ // about.
382
+ if (typeof transform !== 'function')
383
+ return value => value;
384
+ return value => {
385
+ try {
386
+ return transform(value);
387
+ }
388
+ catch {
389
+ // `uppercase` and `trim` (transforms.ts:11-12) call a string method on the
390
+ // value directly, so a NUMERIC candidate throws `value?.toUpperCase is not
391
+ // a function`. On `dev` they never saw one — `lastRecord.id + 1` on a
392
+ // string id is a string — so feeding them a number here would regress a
393
+ // legal, registered id type into an uncaught 500. The retry feeds the
394
+ // string form, which is the shape an id actually arrives in off a JSON body
395
+ // or a URL param. A transform that throws on BOTH shapes still propagates.
396
+ // Pinned by AC9.
397
+ return transform(String(value));
398
+ }
399
+ };
400
+ }
401
+ function getIdType(modelName) {
402
+ const modelClass = Orm.instance?.getRecordClasses(modelName).modelClass;
150
403
  if (!modelClass)
151
- return false;
404
+ return undefined;
152
405
  const model = new modelClass(modelName);
153
- return model.id?.type === 'string';
406
+ return model.id?.type;
407
+ }
408
+ function isStringIdModel(modelName) {
409
+ return getIdType(modelName) === 'string';
154
410
  }
@@ -8,6 +8,7 @@ interface MysqlConfig {
8
8
  connectionLimit?: number;
9
9
  migrationsTable?: string;
10
10
  migrationsDir?: string;
11
+ autoMigrate?: boolean;
11
12
  }
12
13
  export declare function getPool(mysqlConfig: MysqlConfig): Promise<Pool>;
13
14
  export declare function closePool(): Promise<void>;
@@ -61,6 +61,14 @@ export default class MysqlDB {
61
61
  deps: MysqlDBDeps;
62
62
  pool: Pool | null;
63
63
  mysqlConfig: MysqlConfig;
64
+ /**
65
+ * Promise-chain mutex for write serialization (#156).
66
+ * All persist() calls chain through this single queue so concurrent
67
+ * fire-and-forget writes never produce parallel InnoDB transactions
68
+ * on FK-linked rows (which cause deadlocks).
69
+ * Reads are NOT affected — only persist() serializes.
70
+ */
71
+ private _writeQueue;
64
72
  constructor(deps?: Partial<MysqlDBDeps>);
65
73
  private requirePool;
66
74
  init(): Promise<void>;
@@ -26,6 +26,14 @@ export default class MysqlDB {
26
26
  deps;
27
27
  pool;
28
28
  mysqlConfig;
29
+ /**
30
+ * Promise-chain mutex for write serialization (#156).
31
+ * All persist() calls chain through this single queue so concurrent
32
+ * fire-and-forget writes never produce parallel InnoDB transactions
33
+ * on FK-linked rows (which cause deadlocks).
34
+ * Reads are NOT affected — only persist() serializes.
35
+ */
36
+ _writeQueue = Promise.resolve();
29
37
  constructor(deps = {}) {
30
38
  if (MysqlDB.instance)
31
39
  return MysqlDB.instance;
@@ -57,7 +65,17 @@ export default class MysqlDB {
57
65
  const pending = files.filter(f => !applied.includes(f));
58
66
  if (pending.length > 0) {
59
67
  this.deps.log.db?.(`${pending.length} pending migration(s) found.`);
60
- const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
68
+ let shouldApply;
69
+ if (this.mysqlConfig.autoMigrate === true) {
70
+ shouldApply = true;
71
+ }
72
+ else if (this.mysqlConfig.autoMigrate === false) {
73
+ shouldApply = false;
74
+ this.deps.log.warn?.(`autoMigrate is false — skipping ${pending.length} pending migration(s).`);
75
+ }
76
+ else {
77
+ shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
78
+ }
61
79
  if (shouldApply) {
62
80
  for (const filename of pending) {
63
81
  const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename));
@@ -76,7 +94,17 @@ export default class MysqlDB {
76
94
  const schemas = this.deps.introspectModels();
77
95
  const modelCount = Object.keys(schemas).length;
78
96
  if (modelCount > 0) {
79
- const shouldGenerate = await this.deps.confirm(`No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`);
97
+ let shouldGenerate;
98
+ if (this.mysqlConfig.autoMigrate === true) {
99
+ shouldGenerate = true;
100
+ }
101
+ else if (this.mysqlConfig.autoMigrate === false) {
102
+ shouldGenerate = false;
103
+ this.deps.log.warn?.(`autoMigrate is false — skipping initial migration generation for ${modelCount} model(s).`);
104
+ }
105
+ else {
106
+ shouldGenerate = await this.deps.confirm(`No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`);
107
+ }
80
108
  if (shouldGenerate) {
81
109
  const { generateMigration } = await import('./migration-generator.js');
82
110
  const result = await generateMigration('initial_setup');
@@ -302,14 +330,20 @@ export default class MysqlDB {
302
330
  const Orm = (await import('@stonyx/orm')).default;
303
331
  if (Orm.instance?.isView?.(modelName))
304
332
  return;
305
- switch (operation) {
306
- case 'create':
307
- return this._persistCreate(modelName, context, response);
308
- case 'update':
309
- return this._persistUpdate(modelName, context, response);
310
- case 'delete':
311
- return this._persistDelete(modelName, context);
312
- }
333
+ const work = async () => {
334
+ switch (operation) {
335
+ case 'create':
336
+ return this._persistCreate(modelName, context, response);
337
+ case 'update':
338
+ return this._persistUpdate(modelName, context, response);
339
+ case 'delete':
340
+ return this._persistDelete(modelName, context);
341
+ }
342
+ };
343
+ // Chain through the write queue — .then(work, work) ensures the queue
344
+ // advances even when a previous persist rejects (#156).
345
+ this._writeQueue = this._writeQueue.then(work, work);
346
+ return this._writeQueue;
313
347
  }
314
348
  async _persistCreate(modelName, context, response) {
315
349
  const schemas = this.deps.introspectModels();