@stonyx/orm 0.3.2-beta.3 → 0.3.2-beta.300
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 +328 -22
- package/config/environment.js +8 -0
- package/dist/column-conversion.d.ts +34 -0
- package/dist/column-conversion.js +34 -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/index.d.ts +3 -0
- package/dist/index.js +5 -4
- package/dist/main.d.ts +12 -12
- package/dist/main.js +47 -43
- package/dist/manage-record.d.ts +1 -0
- package/dist/manage-record.js +66 -4
- package/dist/mysql/connection.d.ts +1 -0
- package/dist/mysql/mysql-db.d.ts +9 -0
- package/dist/mysql/mysql-db.js +48 -12
- package/dist/normalize-record-id.d.ts +67 -0
- package/dist/normalize-record-id.js +88 -0
- package/dist/orm-request.d.ts +17 -1
- package/dist/orm-request.js +78 -20
- package/dist/postgres/column-rules.d.ts +33 -0
- package/dist/postgres/column-rules.js +34 -0
- package/dist/postgres/connection.d.ts +1 -0
- package/dist/postgres/connection.js +8 -6
- package/dist/postgres/postgres-db.d.ts +13 -0
- package/dist/postgres/postgres-db.js +80 -27
- 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 +74 -4
- package/dist/types/orm-types.d.ts +11 -0
- package/package.json +20 -7
- package/src/column-conversion.ts +53 -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/index.ts +7 -4
- package/src/main.ts +55 -51
- package/src/manage-record.ts +72 -4
- package/src/mysql/connection.ts +1 -0
- package/src/mysql/mysql-db.ts +49 -14
- package/src/normalize-record-id.ts +88 -0
- package/src/orm-request.ts +110 -19
- package/src/postgres/column-rules.ts +37 -0
- package/src/postgres/connection.ts +10 -6
- package/src/postgres/postgres-db.ts +83 -29
- package/src/record.ts +8 -5
- package/src/relationships.ts +1 -1
- package/src/serializer.ts +39 -2
- package/src/store.ts +78 -4
- package/src/types/orm-types.ts +12 -0
- package/src/types/stonyx.d.ts +7 -1
|
@@ -8,6 +8,8 @@ import { createRecord } from '../manage-record.js';
|
|
|
8
8
|
import { confirm } from '@stonyx/utils/prompt';
|
|
9
9
|
import { readFile } from '@stonyx/utils/file';
|
|
10
10
|
import { getPluralName } from '../plural-registry.js';
|
|
11
|
+
import { convertRow } from '../column-conversion.js';
|
|
12
|
+
import { postgresJsonRule } from './column-rules.js';
|
|
11
13
|
import { isDbError } from '../utils.js';
|
|
12
14
|
import config from 'stonyx/config';
|
|
13
15
|
import log from 'stonyx/log';
|
|
@@ -19,6 +21,7 @@ interface PersistContext {
|
|
|
19
21
|
record?: OrmRecord;
|
|
20
22
|
recordId?: unknown;
|
|
21
23
|
oldState?: Record<string, unknown>;
|
|
24
|
+
rawData?: Record<string, unknown>;
|
|
22
25
|
}
|
|
23
26
|
|
|
24
27
|
interface PersistResponse {
|
|
@@ -60,6 +63,8 @@ interface PostgresDeps {
|
|
|
60
63
|
confirm: typeof confirm;
|
|
61
64
|
readFile: typeof readFile;
|
|
62
65
|
getPluralName: typeof getPluralName;
|
|
66
|
+
convertRow: typeof convertRow;
|
|
67
|
+
postgresJsonRule: typeof postgresJsonRule;
|
|
63
68
|
config: typeof config;
|
|
64
69
|
log: typeof log;
|
|
65
70
|
path: typeof path;
|
|
@@ -72,7 +77,8 @@ const defaultDeps: PostgresDeps = {
|
|
|
72
77
|
introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
|
|
73
78
|
loadLatestSnapshot, detectSchemaDrift,
|
|
74
79
|
buildInsert, buildUpdate, buildDelete, buildSelect, buildVectorSearch, buildHybridSearch,
|
|
75
|
-
createRecord, store, confirm, readFile, getPluralName, config, log, path
|
|
80
|
+
createRecord, store, confirm, readFile, getPluralName, config, log, path,
|
|
81
|
+
convertRow, postgresJsonRule
|
|
76
82
|
};
|
|
77
83
|
|
|
78
84
|
export default class PostgresDB {
|
|
@@ -89,6 +95,15 @@ export default class PostgresDB {
|
|
|
89
95
|
pool!: Pool | null;
|
|
90
96
|
pgConfig!: Record<string, unknown>;
|
|
91
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Promise-chain mutex for write serialization (#156).
|
|
100
|
+
* All persist() calls chain through this single queue so concurrent
|
|
101
|
+
* fire-and-forget writes never produce parallel transactions
|
|
102
|
+
* on FK-linked rows (which cause deadlocks).
|
|
103
|
+
* Reads are NOT affected — only persist() serializes.
|
|
104
|
+
*/
|
|
105
|
+
private _writeQueue: Promise<void> = Promise.resolve();
|
|
106
|
+
|
|
92
107
|
constructor(deps: Partial<PostgresDeps> = {}) {
|
|
93
108
|
const Ctor = this.constructor as typeof PostgresDB;
|
|
94
109
|
if (Ctor.instance) return Ctor.instance;
|
|
@@ -124,7 +139,15 @@ export default class PostgresDB {
|
|
|
124
139
|
if (pending.length > 0) {
|
|
125
140
|
this.deps.log.db?.(`${pending.length} pending migration(s) found.`);
|
|
126
141
|
|
|
127
|
-
|
|
142
|
+
let shouldApply: boolean;
|
|
143
|
+
if (this.pgConfig.autoMigrate === true) {
|
|
144
|
+
shouldApply = true;
|
|
145
|
+
} else if (this.pgConfig.autoMigrate === false) {
|
|
146
|
+
shouldApply = false;
|
|
147
|
+
this.deps.log.warn?.(`autoMigrate is false — skipping ${pending.length} pending migration(s).`);
|
|
148
|
+
} else {
|
|
149
|
+
shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
|
|
150
|
+
}
|
|
128
151
|
|
|
129
152
|
if (shouldApply) {
|
|
130
153
|
for (const filename of pending) {
|
|
@@ -145,9 +168,17 @@ export default class PostgresDB {
|
|
|
145
168
|
const modelCount = Object.keys(schemas).length;
|
|
146
169
|
|
|
147
170
|
if (modelCount > 0) {
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
171
|
+
let shouldGenerate: boolean;
|
|
172
|
+
if (this.pgConfig.autoMigrate === true) {
|
|
173
|
+
shouldGenerate = true;
|
|
174
|
+
} else if (this.pgConfig.autoMigrate === false) {
|
|
175
|
+
shouldGenerate = false;
|
|
176
|
+
this.deps.log.warn?.(`autoMigrate is false — skipping initial migration generation for ${modelCount} model(s).`);
|
|
177
|
+
} else {
|
|
178
|
+
shouldGenerate = await this.deps.confirm(
|
|
179
|
+
`No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`
|
|
180
|
+
);
|
|
181
|
+
}
|
|
151
182
|
|
|
152
183
|
if (shouldGenerate) {
|
|
153
184
|
const { generateMigration } = await import('./migration-generator.js');
|
|
@@ -467,17 +498,24 @@ export default class PostgresDB {
|
|
|
467
498
|
const Orm = (await import('@stonyx/orm')).default;
|
|
468
499
|
if ((Orm.instance as { isView?: (name: string) => boolean })?.isView?.(modelName)) return;
|
|
469
500
|
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
501
|
+
const work = async () => {
|
|
502
|
+
switch (operation) {
|
|
503
|
+
case 'create':
|
|
504
|
+
return this._persistCreate(modelName, context, response);
|
|
505
|
+
case 'update':
|
|
506
|
+
return this._persistUpdate(modelName, context, response);
|
|
507
|
+
case 'delete':
|
|
508
|
+
return this._persistDelete(modelName, context);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
|
|
512
|
+
// Chain through the write queue — .then(work, work) ensures the queue
|
|
513
|
+
// advances even when a previous persist rejects (#156).
|
|
514
|
+
this._writeQueue = this._writeQueue.then(work, work);
|
|
515
|
+
return this._writeQueue;
|
|
478
516
|
}
|
|
479
517
|
|
|
480
|
-
private async _persistCreate(modelName: string,
|
|
518
|
+
private async _persistCreate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
|
|
481
519
|
const schemas = this.deps.introspectModels();
|
|
482
520
|
const schema = schemas[modelName];
|
|
483
521
|
|
|
@@ -491,16 +529,21 @@ export default class PostgresDB {
|
|
|
491
529
|
|
|
492
530
|
if (!record) return;
|
|
493
531
|
|
|
494
|
-
const insertData = this._recordToRow(record, schema);
|
|
532
|
+
const insertData = this._recordToRow(record, schema, context.rawData);
|
|
495
533
|
|
|
496
|
-
// For auto-increment models, remove the pending ID
|
|
497
|
-
|
|
534
|
+
// For auto-increment models, remove the pending ID.
|
|
535
|
+
// Check context.rawData (not record.__data) because __pendingSqlId is not a model
|
|
536
|
+
// attribute and gets lost during serialization.
|
|
537
|
+
const isPendingId = context.rawData?.__pendingSqlId === true;
|
|
498
538
|
|
|
499
539
|
if (isPendingId) {
|
|
500
540
|
delete insertData.id;
|
|
501
541
|
}
|
|
502
542
|
|
|
503
|
-
|
|
543
|
+
// Convert the *complete* payload (attributes + id + FKs) in one place (#292).
|
|
544
|
+
const row = this.deps.convertRow(insertData, schema.columns, this.deps.postgresJsonRule);
|
|
545
|
+
|
|
546
|
+
const { sql, values } = this.deps.buildInsert(schema.table, row);
|
|
504
547
|
|
|
505
548
|
const result = await this.requirePool().query(sql, values);
|
|
506
549
|
|
|
@@ -549,7 +592,10 @@ export default class PostgresDB {
|
|
|
549
592
|
// Check FK changes too
|
|
550
593
|
for (const fkCol of Object.keys(schema.foreignKeys)) {
|
|
551
594
|
const relName = fkCol.replace(/_id$/, '');
|
|
552
|
-
const
|
|
595
|
+
const relValue = record.__relationships[relName];
|
|
596
|
+
const currentFkValue = (relValue && typeof relValue === 'object' && relValue !== null)
|
|
597
|
+
? (relValue as { id: unknown }).id ?? null
|
|
598
|
+
: relValue ?? record.__data[relName] ?? null;
|
|
553
599
|
const oldFkValue = oldState[relName] ?? null;
|
|
554
600
|
|
|
555
601
|
if (currentFkValue !== oldFkValue) {
|
|
@@ -562,7 +608,12 @@ export default class PostgresDB {
|
|
|
562
608
|
// PostgreSQL doesn't have ON UPDATE CURRENT_TIMESTAMP -- set updated_at manually
|
|
563
609
|
changedData.updated_at = new Date();
|
|
564
610
|
|
|
565
|
-
|
|
611
|
+
// Same conversion, same choke point as the create path (#292). Columns
|
|
612
|
+
// appended after the attribute loop (FKs, updated_at) are absent from
|
|
613
|
+
// schema.columns and pass through untouched.
|
|
614
|
+
const row = this.deps.convertRow(changedData, schema.columns, this.deps.postgresJsonRule);
|
|
615
|
+
|
|
616
|
+
const { sql, values } = this.deps.buildUpdate(schema.table, id, row);
|
|
566
617
|
await this.requirePool().query(sql, values);
|
|
567
618
|
}
|
|
568
619
|
|
|
@@ -579,7 +630,7 @@ export default class PostgresDB {
|
|
|
579
630
|
await this.requirePool().query(sql, values);
|
|
580
631
|
}
|
|
581
632
|
|
|
582
|
-
private _recordToRow(record: OrmRecord, schema: ModelSchema): Record<string, unknown> {
|
|
633
|
+
private _recordToRow(record: OrmRecord, schema: ModelSchema, rawData?: Record<string, unknown>): Record<string, unknown> {
|
|
583
634
|
const row: Record<string, unknown> = {};
|
|
584
635
|
const data = record.__data;
|
|
585
636
|
|
|
@@ -588,13 +639,11 @@ export default class PostgresDB {
|
|
|
588
639
|
row.id = data.id;
|
|
589
640
|
}
|
|
590
641
|
|
|
591
|
-
// Attribute columns
|
|
592
|
-
|
|
642
|
+
// Attribute columns. Type conversion is NOT applied here -- it is applied
|
|
643
|
+
// once to the finished payload by the caller, via convertRow (#292).
|
|
644
|
+
for (const col of Object.keys(schema.columns)) {
|
|
593
645
|
if (data[col] !== undefined) {
|
|
594
|
-
|
|
595
|
-
row[col] = pgType === 'JSONB' && typeof data[col] !== 'string'
|
|
596
|
-
? JSON.stringify(data[col])
|
|
597
|
-
: data[col];
|
|
646
|
+
row[col] = data[col];
|
|
598
647
|
}
|
|
599
648
|
}
|
|
600
649
|
|
|
@@ -603,11 +652,16 @@ export default class PostgresDB {
|
|
|
603
652
|
const relName = fkCol.replace(/_id$/, '');
|
|
604
653
|
const related = record.__relationships[relName];
|
|
605
654
|
|
|
606
|
-
if (related) {
|
|
655
|
+
if (related && typeof related === 'object' && related !== null) {
|
|
607
656
|
row[fkCol] = (related as { id: unknown }).id;
|
|
657
|
+
} else if (related != null) {
|
|
658
|
+
// Raw FK value (e.g., string ID stored directly in __relationships)
|
|
659
|
+
row[fkCol] = related;
|
|
608
660
|
} else if (data[relName] !== undefined) {
|
|
609
|
-
// Raw FK value (e.g., from create payload)
|
|
610
661
|
row[fkCol] = data[relName];
|
|
662
|
+
} else if (rawData?.[relName] !== undefined) {
|
|
663
|
+
// Fallback to original create payload for unresolved belongsTo FKs
|
|
664
|
+
row[fkCol] = rawData[relName];
|
|
611
665
|
}
|
|
612
666
|
}
|
|
613
667
|
|
package/src/record.ts
CHANGED
|
@@ -87,12 +87,15 @@ export default class Record {
|
|
|
87
87
|
|
|
88
88
|
for (const [key, childRecord] of Object.entries(this.__relationships)) {
|
|
89
89
|
if (Array.isArray(childRecord)) {
|
|
90
|
+
// Filter out cleaned records (those with no __model)
|
|
91
|
+
const live = childRecord.filter((r: Record) => r?.__model);
|
|
92
|
+
|
|
90
93
|
// Deduplicate by record ID — keep last occurrence (latest data wins)
|
|
91
94
|
const seen = new Set<unknown>();
|
|
92
95
|
const unique: Record[] = [];
|
|
93
96
|
|
|
94
|
-
for (let i =
|
|
95
|
-
const r =
|
|
97
|
+
for (let i = live.length - 1; i >= 0; i--) {
|
|
98
|
+
const r = live[i] as Record;
|
|
96
99
|
if (!seen.has(r.id)) {
|
|
97
100
|
seen.add(r.id);
|
|
98
101
|
unique.push(r);
|
|
@@ -102,7 +105,7 @@ export default class Record {
|
|
|
102
105
|
unique.reverse();
|
|
103
106
|
records[key] = unique.map((r: Record) => r.serialize());
|
|
104
107
|
} else {
|
|
105
|
-
records[key] = (childRecord as Record)?.serialize()
|
|
108
|
+
records[key] = (childRecord as Record)?.__model ? (childRecord as Record).serialize() : null;
|
|
106
109
|
}
|
|
107
110
|
}
|
|
108
111
|
|
|
@@ -136,8 +139,8 @@ export default class Record {
|
|
|
136
139
|
if (fields && !fields.has(key)) continue;
|
|
137
140
|
|
|
138
141
|
const relationshipData = Array.isArray(childRecord)
|
|
139
|
-
? childRecord.map((r: Record) => ({ type: r.__model.__name, id: r.id }))
|
|
140
|
-
: childRecord ? { type: (childRecord as Record).__model.__name, id: (childRecord as Record).id } : null;
|
|
142
|
+
? childRecord.filter((r: Record) => r?.__model).map((r: Record) => ({ type: r.__model.__name, id: r.id }))
|
|
143
|
+
: (childRecord && (childRecord as Record).__model) ? { type: (childRecord as Record).__model.__name, id: (childRecord as Record).id } : null;
|
|
141
144
|
|
|
142
145
|
// Dasherize the key for URL paths (e.g., accessLinks -> access-links)
|
|
143
146
|
const dasherizedKey = camelCaseToKebabCase(key);
|
package/src/relationships.ts
CHANGED
|
@@ -51,4 +51,4 @@ export function getPendingBelongsToRegistry(): PendingBelongsToMap {
|
|
|
51
51
|
return relationships.get('pendingBelongsTo') as PendingBelongsToMap;
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
export const TYPES: string[] = ['global', 'hasMany', 'belongsTo', 'pending'];
|
|
54
|
+
export const TYPES: string[] = ['global', 'hasMany', 'belongsTo', 'pending', 'pendingBelongsTo'];
|
package/src/serializer.ts
CHANGED
|
@@ -94,8 +94,45 @@ export default class Serializer {
|
|
|
94
94
|
const handlerOptions = { ...options, _relationshipKey: key };
|
|
95
95
|
const childRecord = handler(record, data, handlerOptions);
|
|
96
96
|
|
|
97
|
-
|
|
98
|
-
|
|
97
|
+
// hasMany relationships use a getter so format()/toJSON() always read
|
|
98
|
+
// the live registry array instead of a stale snapshot captured at
|
|
99
|
+
// serialization time. This is critical when child records are created
|
|
100
|
+
// in a later async frame — the belongsTo inverse wiring pushes into
|
|
101
|
+
// the shared registry array, and the getter ensures the parent sees it.
|
|
102
|
+
const isHasMany = (handler as { __relationshipType?: string }).__relationshipType === 'hasMany';
|
|
103
|
+
|
|
104
|
+
if (isHasMany) {
|
|
105
|
+
// `childRecord` IS the shared registry array — define a getter that
|
|
106
|
+
// always dereferences through the same array reference.
|
|
107
|
+
const registryArray = childRecord as unknown[];
|
|
108
|
+
Object.defineProperty(rec, key, {
|
|
109
|
+
enumerable: true,
|
|
110
|
+
configurable: true,
|
|
111
|
+
get: () => registryArray,
|
|
112
|
+
set(v: unknown) { relatedRecords[key] = v; }
|
|
113
|
+
});
|
|
114
|
+
Object.defineProperty(relatedRecords, key, {
|
|
115
|
+
enumerable: true,
|
|
116
|
+
configurable: true,
|
|
117
|
+
get: () => registryArray,
|
|
118
|
+
set(v: unknown) { Object.defineProperty(relatedRecords, key, { value: v, writable: true, enumerable: true, configurable: true }); }
|
|
119
|
+
});
|
|
120
|
+
} else {
|
|
121
|
+
rec[key] = childRecord;
|
|
122
|
+
relatedRecords[key] = childRecord;
|
|
123
|
+
|
|
124
|
+
// Preserve the raw FK value in __data when the belongsTo handler
|
|
125
|
+
// couldn't resolve the target (e.g., memory:false model not loaded).
|
|
126
|
+
// This allows adapters to read the FK from __data as a fallback
|
|
127
|
+
// when __relationships[key] is null. Only store when `data` is a
|
|
128
|
+
// truthy non-object — i.e., a raw FK string/number that the handler
|
|
129
|
+
// attempted but failed to resolve. When `data` is null/undefined
|
|
130
|
+
// (optional empty relationship) we intentionally skip to preserve
|
|
131
|
+
// the existing behavior of not populating __data for empty FKs.
|
|
132
|
+
if (childRecord === null && data && typeof data !== 'object') {
|
|
133
|
+
parsedData[key] = data;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
99
136
|
|
|
100
137
|
continue;
|
|
101
138
|
}
|
package/src/store.ts
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
|
|
|
5
5
|
interface UnloadOptions {
|
|
@@ -64,7 +64,7 @@ export default class Store {
|
|
|
64
64
|
get(key: string): Map<number | string, unknown> | undefined;
|
|
65
65
|
get(key: string, id: number | string): unknown;
|
|
66
66
|
get(key: string, id?: number | string): Map<number | string, unknown> | unknown | undefined {
|
|
67
|
-
if (
|
|
67
|
+
if (id === undefined) return this.data.get(key);
|
|
68
68
|
|
|
69
69
|
return this.data.get(key)?.get(id);
|
|
70
70
|
}
|
|
@@ -170,17 +170,68 @@ export default class Store {
|
|
|
170
170
|
this.data.set(key, value);
|
|
171
171
|
}
|
|
172
172
|
|
|
173
|
-
remove(key: string, id?: number | string): void {
|
|
173
|
+
remove(key: string, id?: number | string, options?: { _skipAutoPersist?: boolean }): void {
|
|
174
174
|
// Guard: read-only views cannot have records removed
|
|
175
175
|
if (Orm.instance?.isView?.(key)) {
|
|
176
176
|
throw new Error(`Cannot remove records from read-only view '${key}'`);
|
|
177
177
|
}
|
|
178
178
|
|
|
179
|
+
// Auto-persist delete to SQL (fire-and-forget) — skipped when the
|
|
180
|
+
// request path handles persist itself to avoid double-delete.
|
|
181
|
+
if (id && Orm.instance?.sqlDb && !options?._skipAutoPersist) {
|
|
182
|
+
Orm.instance.sqlDb.persist('delete', key, { recordId: id }, {}).catch((err: unknown) => {
|
|
183
|
+
Orm.instance.emitPersistError({
|
|
184
|
+
operation: 'delete',
|
|
185
|
+
modelName: key,
|
|
186
|
+
recordId: id,
|
|
187
|
+
error: err instanceof Error ? err : new Error(String(err)),
|
|
188
|
+
});
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
179
192
|
if (id) return this.unloadRecord(key, id);
|
|
180
193
|
|
|
181
194
|
this.unloadAllRecords(key);
|
|
182
195
|
}
|
|
183
196
|
|
|
197
|
+
/**
|
|
198
|
+
* Evict a record from the store with full relationship registry cleanup.
|
|
199
|
+
* The caller retains its reference to the returned record, which is the
|
|
200
|
+
* contract memory:false post-persist eviction relies on.
|
|
201
|
+
*
|
|
202
|
+
* @param registryId - The ID used when the record's relationships were
|
|
203
|
+
* registered. For SQL models with pending IDs, this is the original
|
|
204
|
+
* negative pending ID (before the adapter re-keyed to the real DB ID).
|
|
205
|
+
*/
|
|
206
|
+
evictRecord(modelName: string, id: unknown, registryId?: unknown): void {
|
|
207
|
+
const modelStore = this.data.get(modelName);
|
|
208
|
+
if (!modelStore) return;
|
|
209
|
+
|
|
210
|
+
if (typeof id !== 'string' && typeof id !== 'number') return;
|
|
211
|
+
const raw = modelStore.get(id);
|
|
212
|
+
if (!raw || !isStoreRecord(raw)) return;
|
|
213
|
+
|
|
214
|
+
const visited = new Set([`${modelName}:${id}`]);
|
|
215
|
+
|
|
216
|
+
// Remove from hasMany arrays and nullify belongsTo references using current ID
|
|
217
|
+
// (the adapter updates record.id, so value-based matches need the current ID)
|
|
218
|
+
this._removeFromHasManyArrays(modelName, id, visited);
|
|
219
|
+
this._nullifyBelongsToReferences(modelName, id, visited);
|
|
220
|
+
|
|
221
|
+
// Clean up relationship registry entries using the registry key
|
|
222
|
+
// (belongsTo/hasMany registries were keyed by the ID at registration time,
|
|
223
|
+
// which may differ from the current ID if SQL persist re-keyed the record)
|
|
224
|
+
const cleanupId = registryId ?? id;
|
|
225
|
+
this._cleanupRelationshipRegistries(modelName, cleanupId);
|
|
226
|
+
|
|
227
|
+
// If registryId differs from id, also clean with current id as safety net
|
|
228
|
+
if (registryId !== undefined && registryId !== id) {
|
|
229
|
+
this._cleanupRelationshipRegistries(modelName, id);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
modelStore.delete(id);
|
|
233
|
+
}
|
|
234
|
+
|
|
184
235
|
unloadRecord(model: string, id: unknown, options: UnloadOptions = {}): void {
|
|
185
236
|
const modelStore = this.data.get(model);
|
|
186
237
|
|
|
@@ -207,7 +258,6 @@ export default class Store {
|
|
|
207
258
|
this._removeFromHasManyArrays(modelName, recordId, visited);
|
|
208
259
|
this._nullifyBelongsToReferences(modelName, recordId, visited);
|
|
209
260
|
this._cleanupRelationshipRegistries(modelName, recordId);
|
|
210
|
-
recordToUnload.clean();
|
|
211
261
|
|
|
212
262
|
this.data.get(modelName)?.delete(recordId as string | number);
|
|
213
263
|
}
|
|
@@ -296,6 +346,30 @@ export default class Store {
|
|
|
296
346
|
|
|
297
347
|
const pendingMap = getPendingRegistry().get(modelName);
|
|
298
348
|
if (pendingMap) pendingMap.delete(recordId);
|
|
349
|
+
|
|
350
|
+
// Clean pendingBelongsTo entries in both directions
|
|
351
|
+
const pendingBelongsToMap = getPendingBelongsToRegistry();
|
|
352
|
+
if (pendingBelongsToMap) {
|
|
353
|
+
// Direction 1: evicted record was the TARGET others were waiting for
|
|
354
|
+
const targetEntries = pendingBelongsToMap.get(modelName);
|
|
355
|
+
if (targetEntries) targetEntries.delete(recordId);
|
|
356
|
+
|
|
357
|
+
// Direction 2: evicted record was the SOURCE with unresolved forward-references
|
|
358
|
+
for (const [, targetIdMap] of pendingBelongsToMap) {
|
|
359
|
+
for (const [targetId, entries] of targetIdMap) {
|
|
360
|
+
if (!Array.isArray(entries)) continue;
|
|
361
|
+
const filtered = entries.filter((e: unknown) => {
|
|
362
|
+
const entry = e as { sourceModelName?: string; relationshipId?: unknown };
|
|
363
|
+
return !(entry.sourceModelName === modelName && entry.relationshipId === recordId);
|
|
364
|
+
});
|
|
365
|
+
if (filtered.length === 0) {
|
|
366
|
+
targetIdMap.delete(targetId);
|
|
367
|
+
} else if (filtered.length < entries.length) {
|
|
368
|
+
targetIdMap.set(targetId, filtered);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
}
|
|
299
373
|
}
|
|
300
374
|
|
|
301
375
|
/**
|
package/src/types/orm-types.ts
CHANGED
|
@@ -18,6 +18,7 @@ export interface OrmMysqlConfig {
|
|
|
18
18
|
connectionLimit?: number;
|
|
19
19
|
migrationsDir?: string;
|
|
20
20
|
migrationsTable?: string;
|
|
21
|
+
autoMigrate?: boolean;
|
|
21
22
|
[key: string]: unknown;
|
|
22
23
|
}
|
|
23
24
|
|
|
@@ -30,6 +31,7 @@ export interface OrmPostgresConfig {
|
|
|
30
31
|
connectionLimit?: number;
|
|
31
32
|
migrationsDir?: string;
|
|
32
33
|
migrationsTable?: string;
|
|
34
|
+
autoMigrate?: boolean;
|
|
33
35
|
[key: string]: unknown;
|
|
34
36
|
}
|
|
35
37
|
|
|
@@ -48,6 +50,13 @@ export interface OrmRestServerConfig {
|
|
|
48
50
|
metaRoute: boolean;
|
|
49
51
|
}
|
|
50
52
|
|
|
53
|
+
export interface OrmDynamoDBConfig {
|
|
54
|
+
region?: string;
|
|
55
|
+
endpoint?: string;
|
|
56
|
+
tablePrefix?: string;
|
|
57
|
+
[key: string]: unknown;
|
|
58
|
+
}
|
|
59
|
+
|
|
51
60
|
export interface OrmSection {
|
|
52
61
|
db: OrmDbConfig;
|
|
53
62
|
paths: OrmPaths;
|
|
@@ -55,6 +64,9 @@ export interface OrmSection {
|
|
|
55
64
|
mysql?: OrmMysqlConfig;
|
|
56
65
|
postgres?: OrmPostgresConfig;
|
|
57
66
|
timescale?: OrmPostgresConfig;
|
|
67
|
+
dynamodb?: OrmDynamoDBConfig;
|
|
68
|
+
logColor?: string;
|
|
69
|
+
logMethod?: string;
|
|
58
70
|
[key: string]: unknown;
|
|
59
71
|
}
|
|
60
72
|
|
package/src/types/stonyx.d.ts
CHANGED
|
@@ -5,7 +5,13 @@ declare module 'stonyx/config' {
|
|
|
5
5
|
}
|
|
6
6
|
|
|
7
7
|
declare module 'stonyx/log' {
|
|
8
|
-
|
|
8
|
+
interface Log {
|
|
9
|
+
db(message: string): void;
|
|
10
|
+
error(message: string, ...args: unknown[]): void;
|
|
11
|
+
defineType(type: string, setting: string, options?: Record<string, unknown> | null): void;
|
|
12
|
+
[key: string]: ((...args: unknown[]) => void) | undefined;
|
|
13
|
+
}
|
|
14
|
+
const log: Log;
|
|
9
15
|
export default log;
|
|
10
16
|
}
|
|
11
17
|
|