@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,116 @@
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
+ * PutItem — optionally with a condition expression.
13
+ *
14
+ * Pass conditionExpression = 'attribute_not_exists(id)' to enforce uniqueness.
15
+ */
16
+ export function buildPutItem(tableName, item, conditionExpression) {
17
+ const params = { TableName: tableName, Item: item };
18
+ if (conditionExpression)
19
+ params.ConditionExpression = conditionExpression;
20
+ return params;
21
+ }
22
+ /**
23
+ * GetItem by primary key.
24
+ */
25
+ export function buildGetItem(tableName, key) {
26
+ return { TableName: tableName, Key: key };
27
+ }
28
+ /**
29
+ * UpdateItem with a SET expression built from the `updates` object.
30
+ * Only the supplied attributes are updated (diff-based call site).
31
+ */
32
+ export function buildUpdateItem(tableName, key, updates) {
33
+ const names = {};
34
+ const values = {};
35
+ const setClauses = [];
36
+ for (const [attr, val] of Object.entries(updates)) {
37
+ const nameAlias = `#${attr}`;
38
+ const valAlias = `:${attr}`;
39
+ names[nameAlias] = attr;
40
+ values[valAlias] = val;
41
+ setClauses.push(`${nameAlias} = ${valAlias}`);
42
+ }
43
+ return {
44
+ TableName: tableName,
45
+ Key: key,
46
+ UpdateExpression: `SET ${setClauses.join(', ')}`,
47
+ ExpressionAttributeNames: names,
48
+ ExpressionAttributeValues: values,
49
+ ReturnValues: 'NONE',
50
+ };
51
+ }
52
+ /**
53
+ * DeleteItem by primary key.
54
+ */
55
+ export function buildDeleteItem(tableName, key) {
56
+ return { TableName: tableName, Key: key };
57
+ }
58
+ /**
59
+ * ScanCommand params.
60
+ * If conditions are supplied they are rendered as a FilterExpression using AND.
61
+ */
62
+ export function buildScan(tableName, conditions, exclusiveStartKey) {
63
+ const params = { TableName: tableName };
64
+ if (exclusiveStartKey)
65
+ params.ExclusiveStartKey = exclusiveStartKey;
66
+ if (conditions && Object.keys(conditions).length > 0) {
67
+ const validEntries = Object.entries(conditions).filter(([, val]) => val !== undefined && val !== null);
68
+ if (validEntries.length > 0) {
69
+ const names = {};
70
+ const values = {};
71
+ const clauses = [];
72
+ for (const [attr, val] of validEntries) {
73
+ const nameAlias = `#${attr}`;
74
+ const valAlias = `:${attr}`;
75
+ names[nameAlias] = attr;
76
+ values[valAlias] = val;
77
+ clauses.push(`${nameAlias} = ${valAlias}`);
78
+ }
79
+ params.FilterExpression = clauses.join(' AND ');
80
+ params.ExpressionAttributeNames = names;
81
+ params.ExpressionAttributeValues = values;
82
+ }
83
+ }
84
+ return params;
85
+ }
86
+ /**
87
+ * QueryCommand params for a GSI.
88
+ * keyConditions must be in the form { attrName: value } and will be rendered
89
+ * as equality expressions joined by AND.
90
+ */
91
+ export function buildQuery(tableName, indexName, keyConditions, exclusiveStartKey) {
92
+ const validEntries = Object.entries(keyConditions).filter(([, val]) => val !== undefined && val !== null);
93
+ if (validEntries.length === 0) {
94
+ throw new Error('buildQuery: all keyCondition values are undefined/null');
95
+ }
96
+ const names = {};
97
+ const values = {};
98
+ const clauses = [];
99
+ for (const [attr, val] of validEntries) {
100
+ const nameAlias = `#${attr}`;
101
+ const valAlias = `:${attr}`;
102
+ names[nameAlias] = attr;
103
+ values[valAlias] = val;
104
+ clauses.push(`${nameAlias} = ${valAlias}`);
105
+ }
106
+ const params = {
107
+ TableName: tableName,
108
+ IndexName: indexName,
109
+ KeyConditionExpression: clauses.join(' AND '),
110
+ ExpressionAttributeNames: names,
111
+ ExpressionAttributeValues: values,
112
+ };
113
+ if (exclusiveStartKey)
114
+ params.ExclusiveStartKey = exclusiveStartKey;
115
+ return params;
116
+ }
@@ -0,0 +1,31 @@
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
+ export type DynamoScalarType = 'S' | 'N' | 'BOOL';
8
+ /**
9
+ * DynamoDB attribute-type string for a given ORM attr type.
10
+ * - string → S
11
+ * - number / float → N (stored as Number; DocumentClient handles it)
12
+ * - boolean → BOOL
13
+ * - date → S (ISO-8601 string — enables range queries)
14
+ * - timestamp → N (milliseconds since epoch)
15
+ * - passthrough/trim/etc → S (safe default)
16
+ *
17
+ * For key schema declarations only `S` and `N` are valid; BOOL
18
+ * is legal for attributes but never for a PK/SK.
19
+ */
20
+ declare const typeMap: Record<string, DynamoScalarType>;
21
+ /**
22
+ * Returns the DynamoDB attribute type for a given ORM type string.
23
+ * Defaults to 'S' for any unknown/custom type.
24
+ */
25
+ export declare function getDynamoType(attrType: string): DynamoScalarType;
26
+ /**
27
+ * Returns the DynamoDB key type ('S' | 'N') for use in KeySchema.
28
+ * BOOL cannot be a key attribute; anything that maps to BOOL falls back to 'S'.
29
+ */
30
+ export declare function getDynamoKeyType(attrType: string): 'S' | 'N';
31
+ export default typeMap;
@@ -0,0 +1,48 @@
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
+ * DynamoDB attribute-type string for a given ORM attr type.
9
+ * - string → S
10
+ * - number / float → N (stored as Number; DocumentClient handles it)
11
+ * - boolean → BOOL
12
+ * - date → S (ISO-8601 string — enables range queries)
13
+ * - timestamp → N (milliseconds since epoch)
14
+ * - passthrough/trim/etc → S (safe default)
15
+ *
16
+ * For key schema declarations only `S` and `N` are valid; BOOL
17
+ * is legal for attributes but never for a PK/SK.
18
+ */
19
+ const typeMap = {
20
+ string: 'S',
21
+ number: 'N',
22
+ float: 'N',
23
+ boolean: 'BOOL',
24
+ date: 'S',
25
+ timestamp: 'N',
26
+ passthrough: 'S',
27
+ trim: 'S',
28
+ uppercase: 'S',
29
+ ceil: 'N',
30
+ floor: 'N',
31
+ round: 'N',
32
+ };
33
+ /**
34
+ * Returns the DynamoDB attribute type for a given ORM type string.
35
+ * Defaults to 'S' for any unknown/custom type.
36
+ */
37
+ export function getDynamoType(attrType) {
38
+ return typeMap[attrType] ?? 'S';
39
+ }
40
+ /**
41
+ * Returns the DynamoDB key type ('S' | 'N') for use in KeySchema.
42
+ * BOOL cannot be a key attribute; anything that maps to BOOL falls back to 'S'.
43
+ */
44
+ export function getDynamoKeyType(attrType) {
45
+ const t = getDynamoType(attrType);
46
+ return t === 'N' ? 'N' : 'S';
47
+ }
48
+ export default typeMap;
package/dist/index.d.ts CHANGED
@@ -8,7 +8,10 @@ import { createRecord, updateRecord } from './manage-record.js';
8
8
  import { count, avg, sum, min, max } from './aggregates.js';
9
9
  export { default } from './main.js';
10
10
  export { store, relationships } from './main.js';
11
+ export type { PersistErrorDetail } from './main.js';
11
12
  export { Model, View, Serializer };
12
13
  export { attr, belongsTo, hasMany, createRecord, updateRecord };
13
14
  export { count, avg, sum, min, max };
15
+ export { default as normalizeRecordId } from './normalize-record-id.js';
16
+ export type { OrmRequest$ as OrmAccessRequest } from './orm-request.js';
14
17
  export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js';
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ export { store, relationships } from './main.js';
26
26
  export { Model, View, Serializer }; // base classes
27
27
  export { attr, belongsTo, hasMany, createRecord, updateRecord }; // helpers
28
28
  export { count, avg, sum, min, max }; // aggregate helpers
29
+ export { default as normalizeRecordId } from './normalize-record-id.js'; // canonical URL-id -> record-id resolution (#270)
29
30
  export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js'; // middleware hooks
30
31
  // Store API:
31
32
  // store.get(model, id) -- sync, memory-only
@@ -33,7 +34,7 @@ export { beforeHook, afterHook, clearHook, clearAllHooks } from './hooks.js'; //
33
34
  // store.findAll(model) -- async, all records
34
35
  // store.query(model, conditions) -- async, always hits SQL
35
36
  //
36
- // Programmatic CRUD (memory + SQL persistence):
37
- // Orm.create(model, data) -- async, createRecord + sqlDb.persist
38
- // Orm.update(model, id, data) -- async, updateRecord + sqlDb.persist
39
- // Orm.remove(model, id) -- async, sqlDb.persist + store.remove
37
+ // Data-layer auto-persist (memory + SQL persistence):
38
+ // createRecord(model, data) -- sync, auto-persists to SQL (fire-and-forget)
39
+ // updateRecord(record, data) -- sync, auto-persists to SQL (fire-and-forget)
40
+ // store.remove(model, id) -- sync, auto-persists delete to SQL (fire-and-forget)
package/dist/main.d.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  import Store from './store.js';
2
- import type { OrmRecord } from './types/orm-types.js';
3
2
  interface OrmOptions {
4
3
  dbType?: string;
5
4
  }
@@ -16,6 +15,12 @@ export interface OrmDB {
16
15
  save(): Promise<void>;
17
16
  init(): Promise<void>;
18
17
  }
18
+ export interface PersistErrorDetail {
19
+ operation: 'create' | 'update' | 'delete';
20
+ modelName: string;
21
+ recordId: unknown;
22
+ error: Error;
23
+ }
19
24
  export default class Orm {
20
25
  static initialized: boolean;
21
26
  static relationships: Map<string, Map<string, unknown>>;
@@ -30,6 +35,7 @@ export default class Orm {
30
35
  options: OrmOptions;
31
36
  sqlDb?: SqlDb;
32
37
  db?: OrmDB | SqlDb;
38
+ private _persistErrorHandler;
33
39
  constructor(options?: OrmOptions);
34
40
  init(): Promise<void>;
35
41
  startup(): Promise<void>;
@@ -41,20 +47,14 @@ export default class Orm {
41
47
  };
42
48
  isView(modelName: string): boolean;
43
49
  /**
44
- * Programmatic create — writes to memory AND persists to SQL database.
45
- * Use instead of createRecord() when records must be persisted to PostgreSQL/TimescaleDB.
46
- */
47
- static create(modelName: string, data?: Record<string, unknown>): Promise<OrmRecord>;
48
- /**
49
- * Programmatic update — updates in memory AND persists to SQL database.
50
- * Captures old state for diff-based UPDATE queries.
50
+ * Register a callback to be invoked when a fire-and-forget SQL persist fails.
51
+ * Without a handler, persist errors are logged via log.error (backwards-compatible).
51
52
  */
52
- static update(modelName: string, id: string | number, data: Record<string, unknown>): Promise<OrmRecord>;
53
+ onPersistError(handler: ((detail: PersistErrorDetail) => void) | null): void;
53
54
  /**
54
- * Programmatic delete — removes from SQL database AND memory store.
55
- * SQL delete runs first to ensure consistency on failure.
55
+ * Emit a persist error to the registered handler, or fall back to log.error.
56
56
  */
57
- static remove(modelName: string, id: string | number): Promise<void>;
57
+ emitPersistError(detail: PersistErrorDetail): void;
58
58
  warn(message: string): void;
59
59
  }
60
60
  export declare const store: Store;
package/dist/main.js CHANGED
@@ -19,12 +19,10 @@ import log from 'stonyx/log';
19
19
  import { forEachFileImport } from '@stonyx/utils/file';
20
20
  import { kebabCaseToPascalCase, pluralize } from '@stonyx/utils/string';
21
21
  import { registerPluralName } from './plural-registry.js';
22
- import setupRestServer from './setup-rest-server.js';
23
22
  import baseTransforms from './transforms.js';
24
23
  import Store from './store.js';
25
24
  import Serializer from './serializer.js';
26
25
  import { setup } from '@stonyx/events';
27
- import { isOrmRecord } from './utils.js';
28
26
  const defaultOptions = {
29
27
  dbType: 'json'
30
28
  };
@@ -42,6 +40,7 @@ export default class Orm {
42
40
  options;
43
41
  sqlDb;
44
42
  db;
43
+ _persistErrorHandler = null;
45
44
  constructor(options = {}) {
46
45
  if (Orm.instance)
47
46
  return Orm.instance;
@@ -54,6 +53,10 @@ export default class Orm {
54
53
  Orm.instance = this;
55
54
  }
56
55
  async init() {
56
+ // Self-register so log.db works even when @stonyx/orm is in the
57
+ // consumer's `dependencies` (stonyx loader only merges devDependencies).
58
+ const { logColor = 'white', logMethod = 'db' } = config.orm;
59
+ log.defineType(logMethod, logColor);
57
60
  const { paths, restServer } = config.orm;
58
61
  const promises = ['Model', 'Serializer', 'Transform'].map(type => {
59
62
  const lowerCaseType = type.toLowerCase();
@@ -115,12 +118,37 @@ export default class Orm {
115
118
  this.db = this.sqlDb;
116
119
  promises.push(this.sqlDb.init());
117
120
  }
121
+ else if (config.orm.dynamodb) {
122
+ const { default: DynamoDBDB } = await import('./dynamodb/dynamodb-db.js');
123
+ this.sqlDb = new DynamoDBDB();
124
+ this.db = this.sqlDb;
125
+ promises.push(this.sqlDb.init());
126
+ }
118
127
  else if (this.options.dbType !== 'none') {
119
128
  const db = new DB();
120
129
  this.db = db;
121
130
  promises.push(db.init());
122
131
  }
123
132
  if (restServer.enabled === 'true') {
133
+ // MUST stay dynamic. setup-rest-server.js names the optional
134
+ // '@stonyx/rest-server' peer in its own static graph — directly, and
135
+ // through orm-request.ts / meta-request.ts, which import `Request` at
136
+ // module scope because they extend it (correctly: an `extends` base
137
+ // class cannot be awaited). Node links a module's entire static graph
138
+ // before evaluating any of it, so a static import here puts that
139
+ // specifier on the entry graph and `import('@stonyx/orm')` throws
140
+ // ERR_MODULE_NOT_FOUND for an ORM-only consumer that never installed the
141
+ // optional peer.
142
+ //
143
+ // NOT the same reason the SQL/DynamoDB drivers above are lazy: those
144
+ // modules carry no static peer specifier that survives to `dist/`
145
+ // (postgres-db.ts:15 and mysql-db.ts:17 are `import type`, erased by
146
+ // tsc), so the `await import()` there is not what isolates pg / mysql2 /
147
+ // @aws-sdk — that happens one layer down, in src/*/connection.ts (and
148
+ // src/dynamodb/dynamodb-db.ts).
149
+ // setup-rest-server.js is the only dist module whose laziness is
150
+ // load-bearing for peer resolution. (#280)
151
+ const { default: setupRestServer } = await import('./setup-rest-server.js');
124
152
  promises.push(setupRestServer(restServer.route, paths.access, restServer.metaRoute));
125
153
  }
126
154
  // Wire up memory resolver so store.find() can check model memory flags
@@ -170,53 +198,29 @@ export default class Orm {
170
198
  return !!this.views[`${modelClassPrefix}View`];
171
199
  }
172
200
  /**
173
- * Programmatic create — writes to memory AND persists to SQL database.
174
- * Use instead of createRecord() when records must be persisted to PostgreSQL/TimescaleDB.
201
+ * Register a callback to be invoked when a fire-and-forget SQL persist fails.
202
+ * Without a handler, persist errors are logged via log.error (backwards-compatible).
175
203
  */
176
- static async create(modelName, data = {}) {
177
- if (!Orm.initialized)
178
- throw new Error('ORM is not ready');
179
- const { createRecord } = await import('./manage-record.js');
180
- const record = createRecord(modelName, data, { serialize: false });
181
- if (Orm.instance.sqlDb) {
182
- const response = { data: { id: record.id } };
183
- await Orm.instance.sqlDb.persist('create', modelName, {}, response);
184
- }
185
- return record;
204
+ onPersistError(handler) {
205
+ this._persistErrorHandler = handler;
186
206
  }
187
207
  /**
188
- * Programmatic update — updates in memory AND persists to SQL database.
189
- * Captures old state for diff-based UPDATE queries.
208
+ * Emit a persist error to the registered handler, or fall back to log.error.
190
209
  */
191
- static async update(modelName, id, data) {
192
- if (!Orm.initialized)
193
- throw new Error('ORM is not ready');
194
- const record = Orm.store.get(modelName, id);
195
- if (!record || !isOrmRecord(record))
196
- throw new Error(`Record ${modelName}:${id} not found`);
197
- const oldState = JSON.parse(JSON.stringify(record.__data));
198
- // Apply attribute updates directly, matching the REST handler pattern
199
- for (const [key, value] of Object.entries(data)) {
200
- if (key === 'id')
201
- continue;
202
- record[key] = value;
203
- }
204
- if (Orm.instance.sqlDb) {
205
- await Orm.instance.sqlDb.persist('update', modelName, { record, oldState }, {});
210
+ emitPersistError(detail) {
211
+ const fallbackLog = () => log.error?.(`[ORM] Failed to persist ${detail.operation} for ${detail.modelName}:${String(detail.recordId)}: ${detail.error.message}`);
212
+ if (this._persistErrorHandler) {
213
+ try {
214
+ this._persistErrorHandler(detail);
215
+ }
216
+ catch (handlerError) {
217
+ fallbackLog();
218
+ log.error?.(`[ORM] onPersistError handler threw: ${handlerError instanceof Error ? handlerError.message : String(handlerError)}`);
219
+ }
206
220
  }
207
- return record;
208
- }
209
- /**
210
- * Programmatic delete — removes from SQL database AND memory store.
211
- * SQL delete runs first to ensure consistency on failure.
212
- */
213
- static async remove(modelName, id) {
214
- if (!Orm.initialized)
215
- throw new Error('ORM is not ready');
216
- if (Orm.instance.sqlDb) {
217
- await Orm.instance.sqlDb.persist('delete', modelName, { recordId: id }, {});
221
+ else {
222
+ fallbackLog();
218
223
  }
219
- Orm.store.remove(modelName, id);
220
224
  }
221
225
  // Queue warnings to avoid the same error from being logged in the same iteration
222
226
  warn(message) {
@@ -4,6 +4,7 @@ interface CreateRecordOptions {
4
4
  serialize?: boolean;
5
5
  transform?: boolean;
6
6
  update?: boolean;
7
+ _skipAutoPersist?: boolean;
7
8
  [key: string]: unknown;
8
9
  }
9
10
  export declare function createRecord(modelName: string, rawData?: {
@@ -7,6 +7,7 @@ const defaultOptions = {
7
7
  serialize: true,
8
8
  transform: true
9
9
  };
10
+ let pendingIdCounter = 0;
10
11
  export function createRecord(modelName, rawData = {}, userOptions = {}) {
11
12
  const orm = Orm.instance;
12
13
  const { initialized } = Orm;
@@ -51,13 +52,34 @@ export function createRecord(modelName, rawData = {}, userOptions = {}) {
51
52
  relationship.push(record);
52
53
  pendingHasMany.splice(0);
53
54
  }
55
+ // FK-based inverse hasMany wiring — when a child record is created with a
56
+ // foreign-key field (e.g. `owner: 'owner-1'` on an animal), find any parent
57
+ // whose hasMany registry targets this model and push the child into the
58
+ // parent's shared array. This covers edge cases where the child is created
59
+ // in a separate async frame without a belongsTo handler firing.
60
+ const hasManyReg = getHasManyRegistry();
61
+ if (hasManyReg) {
62
+ for (const [parentModelName, targetMap] of hasManyReg) {
63
+ const childArrayMap = targetMap.get(modelName);
64
+ if (!childArrayMap)
65
+ continue;
66
+ // Check if rawData contains a FK field matching the parent model name
67
+ const fkValue = rawData[parentModelName];
68
+ if (fkValue === undefined || fkValue === null)
69
+ continue;
70
+ const parentArray = childArrayMap.get(fkValue);
71
+ if (parentArray && !parentArray.includes(record)) {
72
+ parentArray.push(record);
73
+ }
74
+ }
75
+ }
54
76
  // Fulfill pending belongsTo relationships
55
77
  const pendingBelongsToQueue = getPendingBelongsToRegistry();
56
78
  const pendingBelongsToRaw = pendingBelongsToQueue.get(modelName)?.get(record.id);
57
79
  const pendingBelongsTo = Array.isArray(pendingBelongsToRaw) ? pendingBelongsToRaw : undefined;
58
80
  if (pendingBelongsTo) {
59
81
  const belongsToReg = getBelongsToRegistry();
60
- const hasManyReg = getHasManyRegistry();
82
+ const pendingHasManyReg = getHasManyRegistry();
61
83
  for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
62
84
  // Update the belongsTo relationship on the source record
63
85
  sourceRecord.__relationships[relationshipKey] = record;
@@ -71,7 +93,7 @@ export function createRecord(modelName, rawData = {}, userOptions = {}) {
71
93
  }
72
94
  }
73
95
  // Wire inverse hasMany if it exists
74
- const inverseHasMany = hasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
96
+ const inverseHasMany = pendingHasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
75
97
  if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
76
98
  inverseHasMany.push(sourceRecord);
77
99
  }
@@ -79,6 +101,29 @@ export function createRecord(modelName, rawData = {}, userOptions = {}) {
79
101
  // Clear the pending queue
80
102
  pendingBelongsTo.length = 0;
81
103
  }
104
+ // Auto-persist to SQL — skip for DB loads (isDbRecord) and relationship resolution (_relationshipKey)
105
+ const shouldPersist = orm?.sqlDb && !options.isDbRecord && !userOptions._relationshipKey && !options._skipAutoPersist;
106
+ if (shouldPersist) {
107
+ // Capture ID before persist — SQL adapters re-key pending IDs to real DB IDs,
108
+ // but relationship registries were keyed with this original ID
109
+ const registryId = record.id;
110
+ const response = { data: { id: record.id } };
111
+ orm.sqlDb.persist('create', modelName, { rawData }, response)
112
+ .catch((err) => {
113
+ orm.emitPersistError({
114
+ operation: 'create',
115
+ modelName,
116
+ recordId: record.id,
117
+ error: err instanceof Error ? err : new Error(String(err)),
118
+ });
119
+ })
120
+ .finally(() => {
121
+ // Evict non-memory records after persist to prevent unbounded heap growth (stonyx#81)
122
+ if (store._memoryResolver && !store._memoryResolver(modelName)) {
123
+ store.evictRecord(modelName, record.id, registryId);
124
+ }
125
+ });
126
+ }
82
127
  return record;
83
128
  }
84
129
  export function updateRecord(record, rawData, userOptions = {}) {
@@ -90,7 +135,22 @@ export function updateRecord(record, rawData, userOptions = {}) {
90
135
  throw new Error(`Cannot update records for read-only view '${modelName}'`);
91
136
  }
92
137
  const options = { ...defaultOptions, ...userOptions, update: true };
138
+ // Capture old state before update for SQL diff
139
+ const oldState = record.__data ? JSON.parse(JSON.stringify(record.__data)) : {};
93
140
  record.serialize(rawData, options);
141
+ // Auto-persist to SQL — skip for DB loads (isDbRecord) and relationship resolution (_relationshipKey)
142
+ const orm = Orm.instance;
143
+ const shouldPersist = orm?.sqlDb && !options.isDbRecord && !userOptions._relationshipKey && !options._skipAutoPersist;
144
+ if (shouldPersist && modelName) {
145
+ orm.sqlDb.persist('update', modelName, { record, oldState }, {}).catch((err) => {
146
+ orm.emitPersistError({
147
+ operation: 'update',
148
+ modelName,
149
+ recordId: record.id,
150
+ error: err instanceof Error ? err : new Error(String(err)),
151
+ });
152
+ });
153
+ }
94
154
  }
95
155
  /**
96
156
  * gets the next available id based on last record entry.
@@ -101,9 +161,11 @@ export function updateRecord(record, rawData, userOptions = {}) {
101
161
  function assignRecordId(modelName, rawData) {
102
162
  if (rawData.id)
103
163
  return;
104
- // In SQL mode with numeric IDs, defer to database auto-increment
164
+ // In SQL mode with numeric IDs, defer to database auto-increment.
165
+ // Use unique negative integers — they survive the number transform (parseInt preserves negatives)
166
+ // and avoid NaN store-key collisions that string pending IDs caused.
105
167
  if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
106
- rawData.id = `__pending_${Date.now()}_${Math.random()}`;
168
+ rawData.id = -(++pendingIdCounter);
107
169
  rawData.__pendingSqlId = true;
108
170
  return;
109
171
  }
@@ -8,6 +8,7 @@ interface MysqlConfig {
8
8
  connectionLimit?: number;
9
9
  migrationsTable?: string;
10
10
  migrationsDir?: string;
11
+ autoMigrate?: boolean;
11
12
  }
12
13
  export declare function getPool(mysqlConfig: MysqlConfig): Promise<Pool>;
13
14
  export declare function closePool(): Promise<void>;
@@ -16,6 +16,7 @@ interface PersistContext {
16
16
  record?: OrmRecord;
17
17
  recordId?: unknown;
18
18
  oldState?: Record<string, unknown>;
19
+ rawData?: Record<string, unknown>;
19
20
  }
20
21
  interface PersistResponse {
21
22
  data?: {
@@ -60,6 +61,14 @@ export default class MysqlDB {
60
61
  deps: MysqlDBDeps;
61
62
  pool: Pool | null;
62
63
  mysqlConfig: MysqlConfig;
64
+ /**
65
+ * Promise-chain mutex for write serialization (#156).
66
+ * All persist() calls chain through this single queue so concurrent
67
+ * fire-and-forget writes never produce parallel InnoDB transactions
68
+ * on FK-linked rows (which cause deadlocks).
69
+ * Reads are NOT affected — only persist() serializes.
70
+ */
71
+ private _writeQueue;
63
72
  constructor(deps?: Partial<MysqlDBDeps>);
64
73
  private requirePool;
65
74
  init(): Promise<void>;