@stonyx/orm 0.3.2-alpha.11 → 0.3.2-alpha.111
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 +174 -6
- package/dist/dynamodb/connection.d.ts +7 -4
- package/dist/dynamodb/connection.js +4 -4
- package/dist/dynamodb/dynamodb-db.d.ts +11 -0
- package/dist/dynamodb/dynamodb-db.js +54 -14
- package/dist/dynamodb/operation-builder.js +20 -13
- package/dist/main.js +19 -1
- package/dist/manage-record.js +34 -3
- 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 +1 -0
- package/dist/orm-request.js +31 -13
- 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.js +7 -5
- package/dist/relationships.js +1 -1
- package/dist/serializer.js +38 -2
- package/dist/store.d.ts +13 -1
- package/dist/store.js +65 -6
- package/dist/types/orm-types.d.ts +3 -0
- package/package.json +11 -7
- package/src/dynamodb/connection.ts +9 -8
- package/src/dynamodb/dynamodb-db.ts +56 -13
- package/src/dynamodb/operation-builder.ts +29 -15
- package/src/main.ts +19 -1
- package/src/manage-record.ts +41 -9
- package/src/mysql/connection.ts +1 -0
- package/src/mysql/mysql-db.ts +44 -12
- package/src/orm-request.ts +38 -12
- package/src/postgres/connection.ts +10 -6
- package/src/postgres/postgres-db.ts +44 -12
- package/src/record.ts +8 -5
- package/src/relationships.ts +1 -1
- package/src/serializer.ts +39 -2
- package/src/store.ts +68 -6
- package/src/types/orm-types.ts +3 -0
package/dist/mysql/mysql-db.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
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();
|
package/dist/orm-request.d.ts
CHANGED
package/dist/orm-request.js
CHANGED
|
@@ -42,11 +42,28 @@ function getModelRelationships(modelName) {
|
|
|
42
42
|
}
|
|
43
43
|
return relationships;
|
|
44
44
|
}
|
|
45
|
-
|
|
46
|
-
|
|
45
|
+
/**
|
|
46
|
+
* Build the absolute base URL that every advertised link hangs off — origin
|
|
47
|
+
* plus the prefix the ORM's routes are actually mounted at.
|
|
48
|
+
*
|
|
49
|
+
* The prefix is derived from the *request*, not from
|
|
50
|
+
* `config.orm.restServer.route`. Express sets `request.baseUrl` to the real
|
|
51
|
+
* mountpath registered by `RestServer.mountRoute`, which for this module is
|
|
52
|
+
* always `<prefix>/<pluralizedModel>` (see setup-rest-server.ts). Stripping the
|
|
53
|
+
* trailing model segment therefore yields the prefix by construction, and the
|
|
54
|
+
* link builder cannot drift from the mount registrar the way a second,
|
|
55
|
+
* independent normalisation of `route` would.
|
|
56
|
+
*
|
|
57
|
+
* When `request.baseUrl` is absent or does not end in the model segment the
|
|
58
|
+
* prefix is empty, which reproduces the previous origin-only behaviour.
|
|
59
|
+
*/
|
|
60
|
+
function getBaseUrl(request, pluralizedModel) {
|
|
47
61
|
const protocol = request.protocol || 'http';
|
|
48
62
|
const host = request.get('host');
|
|
49
|
-
|
|
63
|
+
const modelSegment = `/${pluralizedModel}`;
|
|
64
|
+
const mountPath = request.baseUrl ?? '';
|
|
65
|
+
const prefix = mountPath.endsWith(modelSegment) ? mountPath.slice(0, -modelSegment.length) : '';
|
|
66
|
+
return `${protocol}://${host}${prefix}`;
|
|
50
67
|
}
|
|
51
68
|
function getId(params) {
|
|
52
69
|
const id = params.id;
|
|
@@ -209,7 +226,7 @@ export default class OrmRequest extends Request {
|
|
|
209
226
|
recordsToReturn = recordsToReturn.filter(accessFilter);
|
|
210
227
|
if (queryFilterPredicate)
|
|
211
228
|
recordsToReturn = recordsToReturn.filter(queryFilterPredicate);
|
|
212
|
-
const baseUrl = getBaseUrl(request);
|
|
229
|
+
const baseUrl = getBaseUrl(request, pluralizedModel);
|
|
213
230
|
const data = recordsToReturn.map(record => record.toJSON?.({ fields: modelFields, baseUrl }));
|
|
214
231
|
return buildResponse(data, request.query?.include, recordsToReturn, {
|
|
215
232
|
links: { self: `${baseUrl}/${pluralizedModel}` },
|
|
@@ -222,7 +239,7 @@ export default class OrmRequest extends Request {
|
|
|
222
239
|
return 404;
|
|
223
240
|
const fieldsMap = parseFields(request.query);
|
|
224
241
|
const modelFields = fieldsMap.get(pluralizedModel) || fieldsMap.get(model);
|
|
225
|
-
const baseUrl = getBaseUrl(request);
|
|
242
|
+
const baseUrl = getBaseUrl(request, pluralizedModel);
|
|
226
243
|
return buildResponse(record.toJSON?.({ fields: modelFields, baseUrl }), request.query?.include, record, {
|
|
227
244
|
links: { self: `${baseUrl}/${pluralizedModel}/${request.params.id}` },
|
|
228
245
|
baseUrl
|
|
@@ -289,7 +306,7 @@ export default class OrmRequest extends Request {
|
|
|
289
306
|
return { data: record.toJSON?.() };
|
|
290
307
|
};
|
|
291
308
|
const deleteHandler = ({ params }) => {
|
|
292
|
-
store.remove(model, getId(params));
|
|
309
|
+
store.remove(model, getId(params), { _skipAutoPersist: true });
|
|
293
310
|
return 204;
|
|
294
311
|
};
|
|
295
312
|
// Wrap handlers with hooks
|
|
@@ -348,9 +365,13 @@ export default class OrmRequest extends Request {
|
|
|
348
365
|
}
|
|
349
366
|
// Execute main handler
|
|
350
367
|
const response = await handler(request, state);
|
|
351
|
-
//
|
|
368
|
+
// Set context.record for update BEFORE persist so SQL drivers can read it
|
|
369
|
+
if (operation === 'update' && response?.data) {
|
|
370
|
+
context.record = store.get(this.model, getId(request.params));
|
|
371
|
+
}
|
|
372
|
+
// Persist to SQL database for all write operations (create/update/delete)
|
|
352
373
|
const sqlDb = Orm.instance.sqlDb;
|
|
353
|
-
if (sqlDb && (operation
|
|
374
|
+
if (sqlDb && WRITE_OPERATIONS.has(operation)) {
|
|
354
375
|
await sqlDb.persist(operation, this.model, context, response);
|
|
355
376
|
}
|
|
356
377
|
// Add response and relevant records to context
|
|
@@ -367,9 +388,6 @@ export default class OrmRequest extends Request {
|
|
|
367
388
|
const recordId = isNaN(responseData.id) ? responseData.id : parseInt(responseData.id);
|
|
368
389
|
context.record = store.get(this.model, recordId);
|
|
369
390
|
}
|
|
370
|
-
else if (operation === 'update' && response?.data) {
|
|
371
|
-
context.record = store.get(this.model, getId(request.params));
|
|
372
|
-
}
|
|
373
391
|
else if (operation === 'delete') {
|
|
374
392
|
// For delete, the record may no longer exist, but we have oldState
|
|
375
393
|
context.recordId = getId(request.params);
|
|
@@ -396,7 +414,7 @@ export default class OrmRequest extends Request {
|
|
|
396
414
|
if (!record)
|
|
397
415
|
return 404;
|
|
398
416
|
const relatedData = record.__relationships[relationshipName];
|
|
399
|
-
const baseUrl = getBaseUrl(request);
|
|
417
|
+
const baseUrl = getBaseUrl(request, pluralizedModel);
|
|
400
418
|
let data;
|
|
401
419
|
if (info.isArray) {
|
|
402
420
|
// hasMany - return array
|
|
@@ -418,7 +436,7 @@ export default class OrmRequest extends Request {
|
|
|
418
436
|
if (!record)
|
|
419
437
|
return 404;
|
|
420
438
|
const relatedData = record.__relationships[relationshipName];
|
|
421
|
-
const baseUrl = getBaseUrl(request);
|
|
439
|
+
const baseUrl = getBaseUrl(request, pluralizedModel);
|
|
422
440
|
let data;
|
|
423
441
|
if (info.isArray) {
|
|
424
442
|
// hasMany - return array of linkage objects
|
|
@@ -7,15 +7,17 @@ export async function getPool(pgConfig, extensions = ['vector']) {
|
|
|
7
7
|
if (pool)
|
|
8
8
|
return pool;
|
|
9
9
|
const { default: pg } = await import('pg');
|
|
10
|
+
const { host, port, user, password, database, connectionLimit, migrationsDir, migrationsTable, autoMigrate, ...poolOpts } = pgConfig;
|
|
10
11
|
pool = new pg.Pool({
|
|
11
|
-
host
|
|
12
|
-
port
|
|
13
|
-
user
|
|
14
|
-
password
|
|
15
|
-
database
|
|
16
|
-
max:
|
|
12
|
+
host,
|
|
13
|
+
port,
|
|
14
|
+
user,
|
|
15
|
+
password,
|
|
16
|
+
database,
|
|
17
|
+
max: connectionLimit,
|
|
17
18
|
idleTimeoutMillis: 30000,
|
|
18
19
|
connectionTimeoutMillis: 10000,
|
|
20
|
+
...poolOpts,
|
|
19
21
|
});
|
|
20
22
|
// Enable requested PostgreSQL extensions
|
|
21
23
|
for (const ext of extensions) {
|
|
@@ -72,6 +72,14 @@ export default class PostgresDB {
|
|
|
72
72
|
deps: PostgresDeps;
|
|
73
73
|
pool: Pool | null;
|
|
74
74
|
pgConfig: Record<string, unknown>;
|
|
75
|
+
/**
|
|
76
|
+
* Promise-chain mutex for write serialization (#156).
|
|
77
|
+
* All persist() calls chain through this single queue so concurrent
|
|
78
|
+
* fire-and-forget writes never produce parallel transactions
|
|
79
|
+
* on FK-linked rows (which cause deadlocks).
|
|
80
|
+
* Reads are NOT affected — only persist() serializes.
|
|
81
|
+
*/
|
|
82
|
+
private _writeQueue;
|
|
75
83
|
constructor(deps?: Partial<PostgresDeps>);
|
|
76
84
|
protected requirePool(): Pool;
|
|
77
85
|
init(): Promise<void>;
|
|
@@ -30,6 +30,14 @@ export default class PostgresDB {
|
|
|
30
30
|
deps;
|
|
31
31
|
pool;
|
|
32
32
|
pgConfig;
|
|
33
|
+
/**
|
|
34
|
+
* Promise-chain mutex for write serialization (#156).
|
|
35
|
+
* All persist() calls chain through this single queue so concurrent
|
|
36
|
+
* fire-and-forget writes never produce parallel transactions
|
|
37
|
+
* on FK-linked rows (which cause deadlocks).
|
|
38
|
+
* Reads are NOT affected — only persist() serializes.
|
|
39
|
+
*/
|
|
40
|
+
_writeQueue = Promise.resolve();
|
|
33
41
|
constructor(deps = {}) {
|
|
34
42
|
const Ctor = this.constructor;
|
|
35
43
|
if (Ctor.instance)
|
|
@@ -57,7 +65,17 @@ export default class PostgresDB {
|
|
|
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
|
-
|
|
68
|
+
let shouldApply;
|
|
69
|
+
if (this.pgConfig.autoMigrate === true) {
|
|
70
|
+
shouldApply = true;
|
|
71
|
+
}
|
|
72
|
+
else if (this.pgConfig.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 PostgresDB {
|
|
|
76
94
|
const schemas = this.deps.introspectModels();
|
|
77
95
|
const modelCount = Object.keys(schemas).length;
|
|
78
96
|
if (modelCount > 0) {
|
|
79
|
-
|
|
97
|
+
let shouldGenerate;
|
|
98
|
+
if (this.pgConfig.autoMigrate === true) {
|
|
99
|
+
shouldGenerate = true;
|
|
100
|
+
}
|
|
101
|
+
else if (this.pgConfig.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');
|
|
@@ -356,14 +384,20 @@ export default class PostgresDB {
|
|
|
356
384
|
const Orm = (await import('@stonyx/orm')).default;
|
|
357
385
|
if (Orm.instance?.isView?.(modelName))
|
|
358
386
|
return;
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
387
|
+
const work = async () => {
|
|
388
|
+
switch (operation) {
|
|
389
|
+
case 'create':
|
|
390
|
+
return this._persistCreate(modelName, context, response);
|
|
391
|
+
case 'update':
|
|
392
|
+
return this._persistUpdate(modelName, context, response);
|
|
393
|
+
case 'delete':
|
|
394
|
+
return this._persistDelete(modelName, context);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
// Chain through the write queue — .then(work, work) ensures the queue
|
|
398
|
+
// advances even when a previous persist rejects (#156).
|
|
399
|
+
this._writeQueue = this._writeQueue.then(work, work);
|
|
400
|
+
return this._writeQueue;
|
|
367
401
|
}
|
|
368
402
|
async _persistCreate(modelName, context, response) {
|
|
369
403
|
const schemas = this.deps.introspectModels();
|
package/dist/record.js
CHANGED
|
@@ -40,11 +40,13 @@ export default class Record {
|
|
|
40
40
|
const records = {};
|
|
41
41
|
for (const [key, childRecord] of Object.entries(this.__relationships)) {
|
|
42
42
|
if (Array.isArray(childRecord)) {
|
|
43
|
+
// Filter out cleaned records (those with no __model)
|
|
44
|
+
const live = childRecord.filter((r) => r?.__model);
|
|
43
45
|
// Deduplicate by record ID — keep last occurrence (latest data wins)
|
|
44
46
|
const seen = new Set();
|
|
45
47
|
const unique = [];
|
|
46
|
-
for (let i =
|
|
47
|
-
const r =
|
|
48
|
+
for (let i = live.length - 1; i >= 0; i--) {
|
|
49
|
+
const r = live[i];
|
|
48
50
|
if (!seen.has(r.id)) {
|
|
49
51
|
seen.add(r.id);
|
|
50
52
|
unique.push(r);
|
|
@@ -54,7 +56,7 @@ export default class Record {
|
|
|
54
56
|
records[key] = unique.map((r) => r.serialize());
|
|
55
57
|
}
|
|
56
58
|
else {
|
|
57
|
-
records[key] = childRecord?.serialize()
|
|
59
|
+
records[key] = childRecord?.__model ? childRecord.serialize() : null;
|
|
58
60
|
}
|
|
59
61
|
}
|
|
60
62
|
return { ...data, ...records };
|
|
@@ -86,8 +88,8 @@ export default class Record {
|
|
|
86
88
|
if (fields && !fields.has(key))
|
|
87
89
|
continue;
|
|
88
90
|
const relationshipData = Array.isArray(childRecord)
|
|
89
|
-
? childRecord.map((r) => ({ type: r.__model.__name, id: r.id }))
|
|
90
|
-
: childRecord ? { type: childRecord.__model.__name, id: childRecord.id } : null;
|
|
91
|
+
? childRecord.filter((r) => r?.__model).map((r) => ({ type: r.__model.__name, id: r.id }))
|
|
92
|
+
: (childRecord && childRecord.__model) ? { type: childRecord.__model.__name, id: childRecord.id } : null;
|
|
91
93
|
// Dasherize the key for URL paths (e.g., accessLinks -> access-links)
|
|
92
94
|
const dasherizedKey = camelCaseToKebabCase(key);
|
|
93
95
|
relationships[dasherizedKey] = { data: relationshipData };
|
package/dist/relationships.js
CHANGED
|
@@ -38,4 +38,4 @@ export function getPendingRegistry() {
|
|
|
38
38
|
export function getPendingBelongsToRegistry() {
|
|
39
39
|
return relationships.get('pendingBelongsTo');
|
|
40
40
|
}
|
|
41
|
-
export const TYPES = ['global', 'hasMany', 'belongsTo', 'pending'];
|
|
41
|
+
export const TYPES = ['global', 'hasMany', 'belongsTo', 'pending', 'pendingBelongsTo'];
|
package/dist/serializer.js
CHANGED
|
@@ -79,8 +79,44 @@ export default class Serializer {
|
|
|
79
79
|
// Pass relationship key name to handler for pending fulfillment
|
|
80
80
|
const handlerOptions = { ...options, _relationshipKey: key };
|
|
81
81
|
const childRecord = handler(record, data, handlerOptions);
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
// hasMany relationships use a getter so format()/toJSON() always read
|
|
83
|
+
// the live registry array instead of a stale snapshot captured at
|
|
84
|
+
// serialization time. This is critical when child records are created
|
|
85
|
+
// in a later async frame — the belongsTo inverse wiring pushes into
|
|
86
|
+
// the shared registry array, and the getter ensures the parent sees it.
|
|
87
|
+
const isHasMany = handler.__relationshipType === 'hasMany';
|
|
88
|
+
if (isHasMany) {
|
|
89
|
+
// `childRecord` IS the shared registry array — define a getter that
|
|
90
|
+
// always dereferences through the same array reference.
|
|
91
|
+
const registryArray = childRecord;
|
|
92
|
+
Object.defineProperty(rec, key, {
|
|
93
|
+
enumerable: true,
|
|
94
|
+
configurable: true,
|
|
95
|
+
get: () => registryArray,
|
|
96
|
+
set(v) { relatedRecords[key] = v; }
|
|
97
|
+
});
|
|
98
|
+
Object.defineProperty(relatedRecords, key, {
|
|
99
|
+
enumerable: true,
|
|
100
|
+
configurable: true,
|
|
101
|
+
get: () => registryArray,
|
|
102
|
+
set(v) { Object.defineProperty(relatedRecords, key, { value: v, writable: true, enumerable: true, configurable: true }); }
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
rec[key] = childRecord;
|
|
107
|
+
relatedRecords[key] = childRecord;
|
|
108
|
+
// Preserve the raw FK value in __data when the belongsTo handler
|
|
109
|
+
// couldn't resolve the target (e.g., memory:false model not loaded).
|
|
110
|
+
// This allows adapters to read the FK from __data as a fallback
|
|
111
|
+
// when __relationships[key] is null. Only store when `data` is a
|
|
112
|
+
// truthy non-object — i.e., a raw FK string/number that the handler
|
|
113
|
+
// attempted but failed to resolve. When `data` is null/undefined
|
|
114
|
+
// (optional empty relationship) we intentionally skip to preserve
|
|
115
|
+
// the existing behavior of not populating __data for empty FKs.
|
|
116
|
+
if (childRecord === null && data && typeof data !== 'object') {
|
|
117
|
+
parsedData[key] = data;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
84
120
|
continue;
|
|
85
121
|
}
|
|
86
122
|
// Aggregate property handling — use the rawData value, not the aggregate descriptor
|
package/dist/store.d.ts
CHANGED
|
@@ -45,7 +45,19 @@ export default class Store {
|
|
|
45
45
|
*/
|
|
46
46
|
private _isMemoryModel;
|
|
47
47
|
set(key: string, value: Map<number | string, unknown>): void;
|
|
48
|
-
remove(key: string, id?: number | string
|
|
48
|
+
remove(key: string, id?: number | string, options?: {
|
|
49
|
+
_skipAutoPersist?: boolean;
|
|
50
|
+
}): void;
|
|
51
|
+
/**
|
|
52
|
+
* Evict a record from the store with full relationship registry cleanup.
|
|
53
|
+
* The caller retains its reference to the returned record, which is the
|
|
54
|
+
* contract memory:false post-persist eviction relies on.
|
|
55
|
+
*
|
|
56
|
+
* @param registryId - The ID used when the record's relationships were
|
|
57
|
+
* registered. For SQL models with pending IDs, this is the original
|
|
58
|
+
* negative pending ID (before the adapter re-keyed to the real DB ID).
|
|
59
|
+
*/
|
|
60
|
+
evictRecord(modelName: string, id: unknown, registryId?: unknown): void;
|
|
49
61
|
unloadRecord(model: string, id: unknown, options?: UnloadOptions): void;
|
|
50
62
|
unloadAllRecords(model: string, options?: UnloadOptions): void;
|
|
51
63
|
private _removeFromHasManyArrays;
|
package/dist/store.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import Orm, { relationships } from '@stonyx/orm';
|
|
2
|
-
import { TYPES, getHasManyRegistry, getBelongsToRegistry, getPendingRegistry } from './relationships.js';
|
|
2
|
+
import { TYPES, getHasManyRegistry, getBelongsToRegistry, getPendingRegistry, getPendingBelongsToRegistry } from './relationships.js';
|
|
3
3
|
import ViewResolver from './view-resolver.js';
|
|
4
4
|
function isStoreRecord(value) {
|
|
5
5
|
return typeof value === 'object' && value !== null && '__data' in value;
|
|
@@ -22,7 +22,7 @@ export default class Store {
|
|
|
22
22
|
this.data = new Map();
|
|
23
23
|
}
|
|
24
24
|
get(key, id) {
|
|
25
|
-
if (
|
|
25
|
+
if (id === undefined)
|
|
26
26
|
return this.data.get(key);
|
|
27
27
|
return this.data.get(key)?.get(id);
|
|
28
28
|
}
|
|
@@ -107,13 +107,14 @@ export default class Store {
|
|
|
107
107
|
set(key, value) {
|
|
108
108
|
this.data.set(key, value);
|
|
109
109
|
}
|
|
110
|
-
remove(key, id) {
|
|
110
|
+
remove(key, id, options) {
|
|
111
111
|
// Guard: read-only views cannot have records removed
|
|
112
112
|
if (Orm.instance?.isView?.(key)) {
|
|
113
113
|
throw new Error(`Cannot remove records from read-only view '${key}'`);
|
|
114
114
|
}
|
|
115
|
-
// Auto-persist delete to SQL
|
|
116
|
-
|
|
115
|
+
// Auto-persist delete to SQL (fire-and-forget) — skipped when the
|
|
116
|
+
// request path handles persist itself to avoid double-delete.
|
|
117
|
+
if (id && Orm.instance?.sqlDb && !options?._skipAutoPersist) {
|
|
117
118
|
Orm.instance.sqlDb.persist('delete', key, { recordId: id }, {}).catch((err) => {
|
|
118
119
|
Orm.instance.emitPersistError({
|
|
119
120
|
operation: 'delete',
|
|
@@ -127,6 +128,40 @@ export default class Store {
|
|
|
127
128
|
return this.unloadRecord(key, id);
|
|
128
129
|
this.unloadAllRecords(key);
|
|
129
130
|
}
|
|
131
|
+
/**
|
|
132
|
+
* Evict a record from the store with full relationship registry cleanup.
|
|
133
|
+
* The caller retains its reference to the returned record, which is the
|
|
134
|
+
* contract memory:false post-persist eviction relies on.
|
|
135
|
+
*
|
|
136
|
+
* @param registryId - The ID used when the record's relationships were
|
|
137
|
+
* registered. For SQL models with pending IDs, this is the original
|
|
138
|
+
* negative pending ID (before the adapter re-keyed to the real DB ID).
|
|
139
|
+
*/
|
|
140
|
+
evictRecord(modelName, id, registryId) {
|
|
141
|
+
const modelStore = this.data.get(modelName);
|
|
142
|
+
if (!modelStore)
|
|
143
|
+
return;
|
|
144
|
+
if (typeof id !== 'string' && typeof id !== 'number')
|
|
145
|
+
return;
|
|
146
|
+
const raw = modelStore.get(id);
|
|
147
|
+
if (!raw || !isStoreRecord(raw))
|
|
148
|
+
return;
|
|
149
|
+
const visited = new Set([`${modelName}:${id}`]);
|
|
150
|
+
// Remove from hasMany arrays and nullify belongsTo references using current ID
|
|
151
|
+
// (the adapter updates record.id, so value-based matches need the current ID)
|
|
152
|
+
this._removeFromHasManyArrays(modelName, id, visited);
|
|
153
|
+
this._nullifyBelongsToReferences(modelName, id, visited);
|
|
154
|
+
// Clean up relationship registry entries using the registry key
|
|
155
|
+
// (belongsTo/hasMany registries were keyed by the ID at registration time,
|
|
156
|
+
// which may differ from the current ID if SQL persist re-keyed the record)
|
|
157
|
+
const cleanupId = registryId ?? id;
|
|
158
|
+
this._cleanupRelationshipRegistries(modelName, cleanupId);
|
|
159
|
+
// If registryId differs from id, also clean with current id as safety net
|
|
160
|
+
if (registryId !== undefined && registryId !== id) {
|
|
161
|
+
this._cleanupRelationshipRegistries(modelName, id);
|
|
162
|
+
}
|
|
163
|
+
modelStore.delete(id);
|
|
164
|
+
}
|
|
130
165
|
unloadRecord(model, id, options = {}) {
|
|
131
166
|
const modelStore = this.data.get(model);
|
|
132
167
|
if (!modelStore) {
|
|
@@ -149,7 +184,6 @@ export default class Store {
|
|
|
149
184
|
this._removeFromHasManyArrays(modelName, recordId, visited);
|
|
150
185
|
this._nullifyBelongsToReferences(modelName, recordId, visited);
|
|
151
186
|
this._cleanupRelationshipRegistries(modelName, recordId);
|
|
152
|
-
recordToUnload.clean();
|
|
153
187
|
this.data.get(modelName)?.delete(recordId);
|
|
154
188
|
}
|
|
155
189
|
}
|
|
@@ -230,6 +264,31 @@ export default class Store {
|
|
|
230
264
|
const pendingMap = getPendingRegistry().get(modelName);
|
|
231
265
|
if (pendingMap)
|
|
232
266
|
pendingMap.delete(recordId);
|
|
267
|
+
// Clean pendingBelongsTo entries in both directions
|
|
268
|
+
const pendingBelongsToMap = getPendingBelongsToRegistry();
|
|
269
|
+
if (pendingBelongsToMap) {
|
|
270
|
+
// Direction 1: evicted record was the TARGET others were waiting for
|
|
271
|
+
const targetEntries = pendingBelongsToMap.get(modelName);
|
|
272
|
+
if (targetEntries)
|
|
273
|
+
targetEntries.delete(recordId);
|
|
274
|
+
// Direction 2: evicted record was the SOURCE with unresolved forward-references
|
|
275
|
+
for (const [, targetIdMap] of pendingBelongsToMap) {
|
|
276
|
+
for (const [targetId, entries] of targetIdMap) {
|
|
277
|
+
if (!Array.isArray(entries))
|
|
278
|
+
continue;
|
|
279
|
+
const filtered = entries.filter((e) => {
|
|
280
|
+
const entry = e;
|
|
281
|
+
return !(entry.sourceModelName === modelName && entry.relationshipId === recordId);
|
|
282
|
+
});
|
|
283
|
+
if (filtered.length === 0) {
|
|
284
|
+
targetIdMap.delete(targetId);
|
|
285
|
+
}
|
|
286
|
+
else if (filtered.length < entries.length) {
|
|
287
|
+
targetIdMap.set(targetId, filtered);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
233
292
|
}
|
|
234
293
|
/**
|
|
235
294
|
* Extracts hasMany and non-bidirectional belongsTo children from a record
|
|
@@ -16,6 +16,7 @@ export interface OrmMysqlConfig {
|
|
|
16
16
|
connectionLimit?: number;
|
|
17
17
|
migrationsDir?: string;
|
|
18
18
|
migrationsTable?: string;
|
|
19
|
+
autoMigrate?: boolean;
|
|
19
20
|
[key: string]: unknown;
|
|
20
21
|
}
|
|
21
22
|
export interface OrmPostgresConfig {
|
|
@@ -27,6 +28,7 @@ export interface OrmPostgresConfig {
|
|
|
27
28
|
connectionLimit?: number;
|
|
28
29
|
migrationsDir?: string;
|
|
29
30
|
migrationsTable?: string;
|
|
31
|
+
autoMigrate?: boolean;
|
|
30
32
|
[key: string]: unknown;
|
|
31
33
|
}
|
|
32
34
|
export interface OrmPaths {
|
|
@@ -45,6 +47,7 @@ export interface OrmRestServerConfig {
|
|
|
45
47
|
export interface OrmDynamoDBConfig {
|
|
46
48
|
region?: string;
|
|
47
49
|
endpoint?: string;
|
|
50
|
+
tablePrefix?: string;
|
|
48
51
|
[key: string]: unknown;
|
|
49
52
|
}
|
|
50
53
|
export interface OrmSection {
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"stonyx-async",
|
|
5
5
|
"stonyx-module"
|
|
6
6
|
],
|
|
7
|
-
"version": "0.3.2-alpha.
|
|
7
|
+
"version": "0.3.2-alpha.111",
|
|
8
8
|
"description": "",
|
|
9
9
|
"main": "dist/index.js",
|
|
10
10
|
"type": "module",
|
|
@@ -61,9 +61,10 @@
|
|
|
61
61
|
},
|
|
62
62
|
"homepage": "https://github.com/abofs/stonyx-orm#readme",
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"@stonyx/cron": "0.2.1-beta.
|
|
65
|
-
"@stonyx/events": "0.1.1-beta.
|
|
66
|
-
"stonyx": "0.2.3-beta.
|
|
64
|
+
"@stonyx/cron": "0.2.1-beta.122",
|
|
65
|
+
"@stonyx/events": "0.1.1-beta.64",
|
|
66
|
+
"@stonyx/utils": "0.2.3-beta.27",
|
|
67
|
+
"stonyx": "0.2.3-beta.94"
|
|
67
68
|
},
|
|
68
69
|
"peerDependencies": {
|
|
69
70
|
"@aws-sdk/client-dynamodb": "^3.0.0",
|
|
@@ -90,8 +91,7 @@
|
|
|
90
91
|
}
|
|
91
92
|
},
|
|
92
93
|
"devDependencies": {
|
|
93
|
-
"@stonyx/rest-server": "0.2.1-beta.
|
|
94
|
-
"@stonyx/utils": "0.2.3-beta.24",
|
|
94
|
+
"@stonyx/rest-server": "0.2.1-beta.123",
|
|
95
95
|
"@types/node": "^25.6.0",
|
|
96
96
|
"mysql2": "^3.20.0",
|
|
97
97
|
"pg": "^8.20.0",
|
|
@@ -103,6 +103,10 @@
|
|
|
103
103
|
"scripts": {
|
|
104
104
|
"build": "tsc",
|
|
105
105
|
"build:test": "tsc -p tsconfig.test.json",
|
|
106
|
-
"test": "pnpm build && NODE_ENV=test node --import tsx/esm --import ./test/setup.ts node_modules/qunit/bin/qunit.js 'test/**/*-test.ts'"
|
|
106
|
+
"test": "pnpm build && NODE_ENV=test node --import tsx/esm --import ./test/setup.ts node_modules/qunit/bin/qunit.js 'test/**/*-test.ts' && ORM_TEST_ROUTE=/ pnpm test:mounted && ORM_TEST_ROUTE=/api pnpm test:mounted && ORM_TEST_ROUTE=api pnpm test:mounted && ORM_TEST_ROUTE=/api/v1 pnpm test:mounted && ORM_TEST_ROUTE=/api/ pnpm test:mounted && pnpm test:readme && pnpm test:reference",
|
|
107
|
+
"test:mounted": "node --import tsx/esm --import ./test/integration/mounted-route/setup.ts node_modules/qunit/bin/qunit.js 'test/integration/mounted-route/links-mounted.ts' 'test/zz-exit-test.ts'",
|
|
108
|
+
"test:readme": "pnpm build && node --import tsx/esm --import ./test/integration/readme-access/setup.ts node_modules/qunit/bin/qunit.js 'test/integration/readme-access/readme-sample.ts' 'test/zz-exit-test.ts'",
|
|
109
|
+
"test:reference": "pnpm build && node --import tsx/esm --import ./test/integration/reference-access/setup.ts node_modules/qunit/bin/qunit.js 'test/integration/reference-access/reference-sample.ts' 'test/zz-exit-test.ts'",
|
|
110
|
+
"test:dynamodb": "pnpm build && node --import tsx/esm --import ./test/integration/dynamodb/setup.ts node_modules/qunit/bin/qunit.js 'test/integration/dynamodb/**/*-test.ts'"
|
|
107
111
|
}
|
|
108
112
|
}
|