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