@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.
Files changed (61) hide show
  1. package/README.md +328 -22
  2. package/config/environment.js +8 -0
  3. package/dist/column-conversion.d.ts +34 -0
  4. package/dist/column-conversion.js +34 -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/index.d.ts +3 -0
  15. package/dist/index.js +5 -4
  16. package/dist/main.d.ts +12 -12
  17. package/dist/main.js +47 -43
  18. package/dist/manage-record.d.ts +1 -0
  19. package/dist/manage-record.js +66 -4
  20. package/dist/mysql/connection.d.ts +1 -0
  21. package/dist/mysql/mysql-db.d.ts +9 -0
  22. package/dist/mysql/mysql-db.js +48 -12
  23. package/dist/normalize-record-id.d.ts +67 -0
  24. package/dist/normalize-record-id.js +88 -0
  25. package/dist/orm-request.d.ts +17 -1
  26. package/dist/orm-request.js +78 -20
  27. package/dist/postgres/column-rules.d.ts +33 -0
  28. package/dist/postgres/column-rules.js +34 -0
  29. package/dist/postgres/connection.d.ts +1 -0
  30. package/dist/postgres/connection.js +8 -6
  31. package/dist/postgres/postgres-db.d.ts +13 -0
  32. package/dist/postgres/postgres-db.js +80 -27
  33. package/dist/record.js +7 -5
  34. package/dist/relationships.js +1 -1
  35. package/dist/serializer.js +38 -2
  36. package/dist/store.d.ts +13 -1
  37. package/dist/store.js +74 -4
  38. package/dist/types/orm-types.d.ts +11 -0
  39. package/package.json +20 -7
  40. package/src/column-conversion.ts +53 -0
  41. package/src/commands.ts +43 -0
  42. package/src/dynamodb/connection.ts +50 -0
  43. package/src/dynamodb/dynamodb-db.ts +811 -0
  44. package/src/dynamodb/operation-builder.ts +202 -0
  45. package/src/dynamodb/type-map.ts +54 -0
  46. package/src/index.ts +7 -4
  47. package/src/main.ts +55 -51
  48. package/src/manage-record.ts +72 -4
  49. package/src/mysql/connection.ts +1 -0
  50. package/src/mysql/mysql-db.ts +49 -14
  51. package/src/normalize-record-id.ts +88 -0
  52. package/src/orm-request.ts +110 -19
  53. package/src/postgres/column-rules.ts +37 -0
  54. package/src/postgres/connection.ts +10 -6
  55. package/src/postgres/postgres-db.ts +83 -29
  56. package/src/record.ts +8 -5
  57. package/src/relationships.ts +1 -1
  58. package/src/serializer.ts +39 -2
  59. package/src/store.ts +78 -4
  60. package/src/types/orm-types.ts +12 -0
  61. package/src/types/stonyx.d.ts +7 -1
@@ -0,0 +1,202 @@
1
+ /**
2
+ * DynamoDB operation parameter builders.
3
+ *
4
+ * Each function returns a plain-object "params" bag that can be passed
5
+ * directly to the corresponding DocumentClient command
6
+ * (PutCommand, GetCommand, UpdateCommand, DeleteCommand, ScanCommand, QueryCommand).
7
+ *
8
+ * All functions are pure — no SDK imports here; the caller wraps params
9
+ * in the appropriate Command class.
10
+ */
11
+
12
+ export interface PutItemParams {
13
+ TableName: string;
14
+ Item: Record<string, unknown>;
15
+ ConditionExpression?: string;
16
+ }
17
+
18
+ export interface GetItemParams {
19
+ TableName: string;
20
+ Key: Record<string, unknown>;
21
+ }
22
+
23
+ export interface UpdateItemParams {
24
+ TableName: string;
25
+ Key: Record<string, unknown>;
26
+ UpdateExpression: string;
27
+ ExpressionAttributeNames: Record<string, string>;
28
+ ExpressionAttributeValues: Record<string, unknown>;
29
+ ReturnValues: string;
30
+ }
31
+
32
+ export interface DeleteItemParams {
33
+ TableName: string;
34
+ Key: Record<string, unknown>;
35
+ }
36
+
37
+ export interface ScanParams {
38
+ TableName: string;
39
+ FilterExpression?: string;
40
+ ExpressionAttributeNames?: Record<string, string>;
41
+ ExpressionAttributeValues?: Record<string, unknown>;
42
+ ExclusiveStartKey?: Record<string, unknown>;
43
+ }
44
+
45
+ export interface QueryParams {
46
+ TableName: string;
47
+ IndexName: string;
48
+ KeyConditionExpression: string;
49
+ ExpressionAttributeNames: Record<string, string>;
50
+ ExpressionAttributeValues: Record<string, unknown>;
51
+ ExclusiveStartKey?: Record<string, unknown>;
52
+ }
53
+
54
+ /**
55
+ * PutItem — optionally with a condition expression.
56
+ *
57
+ * Pass conditionExpression = 'attribute_not_exists(id)' to enforce uniqueness.
58
+ */
59
+ export function buildPutItem(
60
+ tableName: string,
61
+ item: Record<string, unknown>,
62
+ conditionExpression?: string,
63
+ ): PutItemParams {
64
+ const params: PutItemParams = { TableName: tableName, Item: item };
65
+ if (conditionExpression) params.ConditionExpression = conditionExpression;
66
+ return params;
67
+ }
68
+
69
+ /**
70
+ * GetItem by primary key.
71
+ */
72
+ export function buildGetItem(
73
+ tableName: string,
74
+ key: Record<string, unknown>,
75
+ ): GetItemParams {
76
+ return { TableName: tableName, Key: key };
77
+ }
78
+
79
+ /**
80
+ * UpdateItem with a SET expression built from the `updates` object.
81
+ * Only the supplied attributes are updated (diff-based call site).
82
+ */
83
+ export function buildUpdateItem(
84
+ tableName: string,
85
+ key: Record<string, unknown>,
86
+ updates: Record<string, unknown>,
87
+ ): UpdateItemParams {
88
+ const names: Record<string, string> = {};
89
+ const values: Record<string, unknown> = {};
90
+ const setClauses: string[] = [];
91
+
92
+ for (const [attr, val] of Object.entries(updates)) {
93
+ const nameAlias = `#${attr}`;
94
+ const valAlias = `:${attr}`;
95
+ names[nameAlias] = attr;
96
+ values[valAlias] = val;
97
+ setClauses.push(`${nameAlias} = ${valAlias}`);
98
+ }
99
+
100
+ return {
101
+ TableName: tableName,
102
+ Key: key,
103
+ UpdateExpression: `SET ${setClauses.join(', ')}`,
104
+ ExpressionAttributeNames: names,
105
+ ExpressionAttributeValues: values,
106
+ ReturnValues: 'NONE',
107
+ };
108
+ }
109
+
110
+ /**
111
+ * DeleteItem by primary key.
112
+ */
113
+ export function buildDeleteItem(
114
+ tableName: string,
115
+ key: Record<string, unknown>,
116
+ ): DeleteItemParams {
117
+ return { TableName: tableName, Key: key };
118
+ }
119
+
120
+ /**
121
+ * ScanCommand params.
122
+ * If conditions are supplied they are rendered as a FilterExpression using AND.
123
+ */
124
+ export function buildScan(
125
+ tableName: string,
126
+ conditions?: Record<string, unknown>,
127
+ exclusiveStartKey?: Record<string, unknown>,
128
+ ): ScanParams {
129
+ const params: ScanParams = { TableName: tableName };
130
+
131
+ if (exclusiveStartKey) params.ExclusiveStartKey = exclusiveStartKey;
132
+
133
+ if (conditions && Object.keys(conditions).length > 0) {
134
+ const validEntries = Object.entries(conditions).filter(
135
+ ([, val]) => val !== undefined && val !== null,
136
+ );
137
+
138
+ if (validEntries.length > 0) {
139
+ const names: Record<string, string> = {};
140
+ const values: Record<string, unknown> = {};
141
+ const clauses: string[] = [];
142
+
143
+ for (const [attr, val] of validEntries) {
144
+ const nameAlias = `#${attr}`;
145
+ const valAlias = `:${attr}`;
146
+ names[nameAlias] = attr;
147
+ values[valAlias] = val;
148
+ clauses.push(`${nameAlias} = ${valAlias}`);
149
+ }
150
+
151
+ params.FilterExpression = clauses.join(' AND ');
152
+ params.ExpressionAttributeNames = names;
153
+ params.ExpressionAttributeValues = values;
154
+ }
155
+ }
156
+
157
+ return params;
158
+ }
159
+
160
+ /**
161
+ * QueryCommand params for a GSI.
162
+ * keyConditions must be in the form { attrName: value } and will be rendered
163
+ * as equality expressions joined by AND.
164
+ */
165
+ export function buildQuery(
166
+ tableName: string,
167
+ indexName: string,
168
+ keyConditions: Record<string, unknown>,
169
+ exclusiveStartKey?: Record<string, unknown>,
170
+ ): QueryParams {
171
+ const validEntries = Object.entries(keyConditions).filter(
172
+ ([, val]) => val !== undefined && val !== null,
173
+ );
174
+
175
+ if (validEntries.length === 0) {
176
+ throw new Error('buildQuery: all keyCondition values are undefined/null');
177
+ }
178
+
179
+ const names: Record<string, string> = {};
180
+ const values: Record<string, unknown> = {};
181
+ const clauses: string[] = [];
182
+
183
+ for (const [attr, val] of validEntries) {
184
+ const nameAlias = `#${attr}`;
185
+ const valAlias = `:${attr}`;
186
+ names[nameAlias] = attr;
187
+ values[valAlias] = val;
188
+ clauses.push(`${nameAlias} = ${valAlias}`);
189
+ }
190
+
191
+ const params: QueryParams = {
192
+ TableName: tableName,
193
+ IndexName: indexName,
194
+ KeyConditionExpression: clauses.join(' AND '),
195
+ ExpressionAttributeNames: names,
196
+ ExpressionAttributeValues: values,
197
+ };
198
+
199
+ if (exclusiveStartKey) params.ExclusiveStartKey = exclusiveStartKey;
200
+
201
+ return params;
202
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Maps ORM attribute types to DynamoDB scalar attribute types.
3
+ * DynamoDB DocumentClient auto-marshalls JS objects, so most values
4
+ * are sent as their native JS types. This map is used by the
5
+ * schema-introspector and startup provisioner for table/GSI creation.
6
+ */
7
+
8
+ export type DynamoScalarType = 'S' | 'N' | 'BOOL';
9
+
10
+ /**
11
+ * DynamoDB attribute-type string for a given ORM attr type.
12
+ * - string → S
13
+ * - number / float → N (stored as Number; DocumentClient handles it)
14
+ * - boolean → BOOL
15
+ * - date → S (ISO-8601 string — enables range queries)
16
+ * - timestamp → N (milliseconds since epoch)
17
+ * - passthrough/trim/etc → S (safe default)
18
+ *
19
+ * For key schema declarations only `S` and `N` are valid; BOOL
20
+ * is legal for attributes but never for a PK/SK.
21
+ */
22
+ const typeMap: Record<string, DynamoScalarType> = {
23
+ string: 'S',
24
+ number: 'N',
25
+ float: 'N',
26
+ boolean: 'BOOL',
27
+ date: 'S',
28
+ timestamp: 'N',
29
+ passthrough: 'S',
30
+ trim: 'S',
31
+ uppercase: 'S',
32
+ ceil: 'N',
33
+ floor: 'N',
34
+ round: 'N',
35
+ };
36
+
37
+ /**
38
+ * Returns the DynamoDB attribute type for a given ORM type string.
39
+ * Defaults to 'S' for any unknown/custom type.
40
+ */
41
+ export function getDynamoType(attrType: string): DynamoScalarType {
42
+ return typeMap[attrType] ?? 'S';
43
+ }
44
+
45
+ /**
46
+ * Returns the DynamoDB key type ('S' | 'N') for use in KeySchema.
47
+ * BOOL cannot be a key attribute; anything that maps to BOOL falls back to 'S'.
48
+ */
49
+ export function getDynamoKeyType(attrType: string): 'S' | 'N' {
50
+ const t = getDynamoType(attrType);
51
+ return t === 'N' ? 'N' : 'S';
52
+ }
53
+
54
+ export default typeMap;
package/src/index.ts CHANGED
@@ -26,9 +26,12 @@ import { count, avg, sum, min, max } from './aggregates.js';
26
26
 
27
27
  export { default } from './main.js';
28
28
  export { store, relationships } from './main.js';
29
+ export type { PersistErrorDetail } from './main.js';
29
30
  export { Model, View, Serializer }; // base classes
30
31
  export { attr, belongsTo, hasMany, createRecord, updateRecord }; // helpers
31
32
  export { count, avg, sum, min, max }; // aggregate helpers
33
+ export { default as normalizeRecordId } from './normalize-record-id.js'; // canonical URL-id -> record-id resolution (#270)
34
+ export type { OrmRequest$ as OrmAccessRequest } from './orm-request.js'; // the request access() is handed, incl. recordId (#270)
32
35
  export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js'; // middleware hooks
33
36
 
34
37
  // Store API:
@@ -37,7 +40,7 @@ export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js'; //
37
40
  // store.findAll(model) -- async, all records
38
41
  // store.query(model, conditions) -- async, always hits SQL
39
42
  //
40
- // Programmatic CRUD (memory + SQL persistence):
41
- // Orm.create(model, data) -- async, createRecord + sqlDb.persist
42
- // Orm.update(model, id, data) -- async, updateRecord + sqlDb.persist
43
- // Orm.remove(model, id) -- async, sqlDb.persist + store.remove
43
+ // Data-layer auto-persist (memory + SQL persistence):
44
+ // createRecord(model, data) -- sync, auto-persists to SQL (fire-and-forget)
45
+ // updateRecord(record, data) -- sync, auto-persists to SQL (fire-and-forget)
46
+ // store.remove(model, id) -- sync, auto-persists delete to SQL (fire-and-forget)
package/src/main.ts CHANGED
@@ -20,13 +20,10 @@ import log from 'stonyx/log';
20
20
  import { forEachFileImport } from '@stonyx/utils/file';
21
21
  import { kebabCaseToPascalCase, pluralize } from '@stonyx/utils/string';
22
22
  import { registerPluralName } from './plural-registry.js';
23
- import setupRestServer from './setup-rest-server.js';
24
23
  import baseTransforms from './transforms.js';
25
24
  import Store from './store.js';
26
25
  import Serializer from './serializer.js';
27
26
  import { setup } from '@stonyx/events';
28
- import type { OrmRecord } from './types/orm-types.js';
29
- import { isOrmRecord } from './utils.js';
30
27
 
31
28
  interface OrmOptions {
32
29
  dbType?: string;
@@ -51,6 +48,13 @@ const defaultOptions: OrmOptions = {
51
48
  dbType: 'json'
52
49
  }
53
50
 
51
+ export interface PersistErrorDetail {
52
+ operation: 'create' | 'update' | 'delete';
53
+ modelName: string;
54
+ recordId: unknown;
55
+ error: Error;
56
+ }
57
+
54
58
  export default class Orm {
55
59
  static initialized: boolean = false;
56
60
  static relationships: Map<string, Map<string, unknown>> = new Map();
@@ -67,6 +71,8 @@ export default class Orm {
67
71
  sqlDb?: SqlDb;
68
72
  db?: OrmDB | SqlDb;
69
73
 
74
+ private _persistErrorHandler: ((detail: PersistErrorDetail) => void) | null = null;
75
+
70
76
  constructor(options: OrmOptions = {}) {
71
77
  if (Orm.instance) return Orm.instance;
72
78
 
@@ -83,6 +89,11 @@ export default class Orm {
83
89
  }
84
90
 
85
91
  async init(): Promise<void> {
92
+ // Self-register so log.db works even when @stonyx/orm is in the
93
+ // consumer's `dependencies` (stonyx loader only merges devDependencies).
94
+ const { logColor = 'white', logMethod = 'db' } = config.orm;
95
+ log.defineType(logMethod, logColor);
96
+
86
97
  const { paths, restServer } = config.orm;
87
98
 
88
99
  const promises: Promise<unknown>[] = ['Model', 'Serializer', 'Transform'].map(type => {
@@ -152,6 +163,11 @@ export default class Orm {
152
163
  this.sqlDb = new MysqlDB() as SqlDb;
153
164
  this.db = this.sqlDb;
154
165
  promises.push(this.sqlDb.init());
166
+ } else if (config.orm.dynamodb) {
167
+ const { default: DynamoDBDB } = await import('./dynamodb/dynamodb-db.js');
168
+ this.sqlDb = new DynamoDBDB() as SqlDb;
169
+ this.db = this.sqlDb;
170
+ promises.push(this.sqlDb.init());
155
171
  } else if (this.options.dbType !== 'none') {
156
172
  const db = new DB();
157
173
  this.db = db;
@@ -160,6 +176,25 @@ export default class Orm {
160
176
  }
161
177
 
162
178
  if (restServer.enabled === 'true') {
179
+ // MUST stay dynamic. setup-rest-server.js names the optional
180
+ // '@stonyx/rest-server' peer in its own static graph — directly, and
181
+ // through orm-request.ts / meta-request.ts, which import `Request` at
182
+ // module scope because they extend it (correctly: an `extends` base
183
+ // class cannot be awaited). Node links a module's entire static graph
184
+ // before evaluating any of it, so a static import here puts that
185
+ // specifier on the entry graph and `import('@stonyx/orm')` throws
186
+ // ERR_MODULE_NOT_FOUND for an ORM-only consumer that never installed the
187
+ // optional peer.
188
+ //
189
+ // NOT the same reason the SQL/DynamoDB drivers above are lazy: those
190
+ // modules carry no static peer specifier that survives to `dist/`
191
+ // (postgres-db.ts:15 and mysql-db.ts:17 are `import type`, erased by
192
+ // tsc), so the `await import()` there is not what isolates pg / mysql2 /
193
+ // @aws-sdk — that happens one layer down, in src/*/connection.ts (and
194
+ // src/dynamodb/dynamodb-db.ts).
195
+ // setup-rest-server.js is the only dist module whose laziness is
196
+ // load-bearing for peer resolution. (#280)
197
+ const { default: setupRestServer } = await import('./setup-rest-server.js');
163
198
  promises.push(setupRestServer(restServer.route, paths.access, restServer.metaRoute));
164
199
  }
165
200
 
@@ -217,60 +252,29 @@ export default class Orm {
217
252
  }
218
253
 
219
254
  /**
220
- * Programmatic create — writes to memory AND persists to SQL database.
221
- * Use instead of createRecord() when records must be persisted to PostgreSQL/TimescaleDB.
222
- */
223
- static async create(modelName: string, data: Record<string, unknown> = {}): Promise<OrmRecord> {
224
- if (!Orm.initialized) throw new Error('ORM is not ready');
225
-
226
- const { createRecord } = await import('./manage-record.js');
227
- const record = createRecord(modelName, data, { serialize: false }) as unknown as OrmRecord;
228
-
229
- if (Orm.instance.sqlDb) {
230
- const response: { data: { id: unknown } } = { data: { id: record.id } };
231
- await Orm.instance.sqlDb.persist('create', modelName, {}, response);
232
- }
233
-
234
- return record;
235
- }
236
-
237
- /**
238
- * Programmatic update — updates in memory AND persists to SQL database.
239
- * Captures old state for diff-based UPDATE queries.
255
+ * Register a callback to be invoked when a fire-and-forget SQL persist fails.
256
+ * Without a handler, persist errors are logged via log.error (backwards-compatible).
240
257
  */
241
- static async update(modelName: string, id: string | number, data: Record<string, unknown>): Promise<OrmRecord> {
242
- if (!Orm.initialized) throw new Error('ORM is not ready');
243
-
244
- const record = Orm.store.get(modelName, id);
245
- if (!record || !isOrmRecord(record)) throw new Error(`Record ${modelName}:${id} not found`);
246
-
247
- const oldState = JSON.parse(JSON.stringify(record.__data));
248
-
249
- // Apply attribute updates directly, matching the REST handler pattern
250
- for (const [key, value] of Object.entries(data)) {
251
- if (key === 'id') continue;
252
- record[key] = value;
253
- }
254
-
255
- if (Orm.instance.sqlDb) {
256
- await Orm.instance.sqlDb.persist('update', modelName, { record, oldState }, {});
257
- }
258
-
259
- return record;
258
+ onPersistError(handler: ((detail: PersistErrorDetail) => void) | null): void {
259
+ this._persistErrorHandler = handler;
260
260
  }
261
261
 
262
262
  /**
263
- * Programmatic delete — removes from SQL database AND memory store.
264
- * SQL delete runs first to ensure consistency on failure.
263
+ * Emit a persist error to the registered handler, or fall back to log.error.
265
264
  */
266
- static async remove(modelName: string, id: string | number): Promise<void> {
267
- if (!Orm.initialized) throw new Error('ORM is not ready');
268
-
269
- if (Orm.instance.sqlDb) {
270
- await Orm.instance.sqlDb.persist('delete', modelName, { recordId: id }, {});
265
+ emitPersistError(detail: PersistErrorDetail): void {
266
+ const fallbackLog = () => log.error?.(`[ORM] Failed to persist ${detail.operation} for ${detail.modelName}:${String(detail.recordId)}: ${detail.error.message}`);
267
+
268
+ if (this._persistErrorHandler) {
269
+ try {
270
+ this._persistErrorHandler(detail);
271
+ } catch (handlerError) {
272
+ fallbackLog();
273
+ log.error?.(`[ORM] onPersistError handler threw: ${handlerError instanceof Error ? handlerError.message : String(handlerError)}`);
274
+ }
275
+ } else {
276
+ fallbackLog();
271
277
  }
272
-
273
- Orm.store.remove(modelName, id);
274
278
  }
275
279
 
276
280
  // Queue warnings to avoid the same error from being logged in the same iteration
@@ -9,6 +9,7 @@ interface CreateRecordOptions {
9
9
  serialize?: boolean;
10
10
  transform?: boolean;
11
11
  update?: boolean;
12
+ _skipAutoPersist?: boolean;
12
13
  [key: string]: unknown;
13
14
  }
14
15
 
@@ -25,6 +26,8 @@ const defaultOptions: CreateRecordOptions = {
25
26
  transform: true
26
27
  };
27
28
 
29
+ let pendingIdCounter = 0;
30
+
28
31
  export function createRecord(modelName: string, rawData: { [key: string]: unknown } = {}, userOptions: CreateRecordOptions = {}): OrmRecord {
29
32
  const orm = Orm.instance;
30
33
  const { initialized } = Orm;
@@ -76,6 +79,28 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
76
79
  pendingHasMany.splice(0);
77
80
  }
78
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
+
79
104
  // Fulfill pending belongsTo relationships
80
105
  const pendingBelongsToQueue = getPendingBelongsToRegistry();
81
106
  const pendingBelongsToRaw = pendingBelongsToQueue.get(modelName)?.get(record.id);
@@ -83,7 +108,7 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
83
108
 
84
109
  if (pendingBelongsTo) {
85
110
  const belongsToReg = getBelongsToRegistry();
86
- const hasManyReg = getHasManyRegistry();
111
+ const pendingHasManyReg = getHasManyRegistry();
87
112
 
88
113
  for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
89
114
  // Update the belongsTo relationship on the source record
@@ -100,7 +125,7 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
100
125
  }
101
126
 
102
127
  // Wire inverse hasMany if it exists
103
- const inverseHasMany = hasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
128
+ const inverseHasMany = pendingHasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
104
129
 
105
130
  if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
106
131
  inverseHasMany.push(sourceRecord);
@@ -111,6 +136,30 @@ export function createRecord(modelName: string, rawData: { [key: string]: unknow
111
136
  pendingBelongsTo.length = 0;
112
137
  }
113
138
 
139
+ // Auto-persist to SQL — skip for DB loads (isDbRecord) and relationship resolution (_relationshipKey)
140
+ const shouldPersist = orm?.sqlDb && !options.isDbRecord && !userOptions._relationshipKey && !options._skipAutoPersist;
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;
145
+ const response = { data: { id: record.id } };
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
+ }
160
+ });
161
+ }
162
+
114
163
  return record;
115
164
  }
116
165
 
@@ -125,7 +174,24 @@ export function updateRecord(record: OrmRecord, rawData: unknown, userOptions: C
125
174
 
126
175
  const options = { ...defaultOptions, ...userOptions, update: true };
127
176
 
177
+ // Capture old state before update for SQL diff
178
+ const oldState = record.__data ? JSON.parse(JSON.stringify(record.__data)) : {};
179
+
128
180
  record.serialize(rawData, options);
181
+
182
+ // Auto-persist to SQL — skip for DB loads (isDbRecord) and relationship resolution (_relationshipKey)
183
+ const orm = Orm.instance;
184
+ const shouldPersist = orm?.sqlDb && !options.isDbRecord && !userOptions._relationshipKey && !options._skipAutoPersist;
185
+ if (shouldPersist && modelName) {
186
+ orm!.sqlDb!.persist('update', modelName, { record, oldState }, {}).catch((err: unknown) => {
187
+ orm!.emitPersistError({
188
+ operation: 'update',
189
+ modelName,
190
+ recordId: record.id,
191
+ error: err instanceof Error ? err : new Error(String(err)),
192
+ });
193
+ });
194
+ }
129
195
  }
130
196
 
131
197
  /**
@@ -137,9 +203,11 @@ export function updateRecord(record: OrmRecord, rawData: unknown, userOptions: C
137
203
  function assignRecordId(modelName: string, rawData: { [key: string]: unknown }): void {
138
204
  if (rawData.id) return;
139
205
 
140
- // In SQL mode with numeric IDs, defer to database auto-increment
206
+ // In SQL mode with numeric IDs, defer to database auto-increment.
207
+ // Use unique negative integers — they survive the number transform (parseInt preserves negatives)
208
+ // and avoid NaN store-key collisions that string pending IDs caused.
141
209
  if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
142
- rawData.id = `__pending_${Date.now()}_${Math.random()}`;
210
+ rawData.id = -(++pendingIdCounter);
143
211
  rawData.__pendingSqlId = true;
144
212
  return;
145
213
  }
@@ -9,6 +9,7 @@ interface MysqlConfig {
9
9
  connectionLimit?: number;
10
10
  migrationsTable?: string;
11
11
  migrationsDir?: string;
12
+ autoMigrate?: boolean;
12
13
  }
13
14
 
14
15
  let pool: Pool | null = null;