@stonyx/orm 0.2.1-beta.83 → 0.2.1-beta.84

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 (149) hide show
  1. package/dist/aggregates.d.ts +21 -0
  2. package/dist/aggregates.js +90 -0
  3. package/dist/attr.d.ts +2 -0
  4. package/dist/attr.js +22 -0
  5. package/dist/belongs-to.d.ts +11 -0
  6. package/dist/belongs-to.js +58 -0
  7. package/dist/cli.d.ts +22 -0
  8. package/dist/cli.js +148 -0
  9. package/dist/commands.d.ts +7 -0
  10. package/dist/commands.js +146 -0
  11. package/dist/db.d.ts +21 -0
  12. package/dist/db.js +174 -0
  13. package/dist/exports/db.d.ts +7 -0
  14. package/{src → dist}/exports/db.js +2 -4
  15. package/dist/has-many.d.ts +11 -0
  16. package/dist/has-many.js +57 -0
  17. package/dist/hooks.d.ts +47 -0
  18. package/dist/hooks.js +106 -0
  19. package/dist/index.d.ts +14 -0
  20. package/dist/index.js +34 -0
  21. package/dist/main.d.ts +46 -0
  22. package/dist/main.js +178 -0
  23. package/dist/manage-record.d.ts +13 -0
  24. package/dist/manage-record.js +113 -0
  25. package/dist/meta-request.d.ts +6 -0
  26. package/dist/meta-request.js +52 -0
  27. package/dist/migrate.d.ts +2 -0
  28. package/dist/migrate.js +57 -0
  29. package/dist/model-property.d.ts +9 -0
  30. package/dist/model-property.js +29 -0
  31. package/dist/model.d.ts +15 -0
  32. package/dist/model.js +18 -0
  33. package/dist/mysql/connection.d.ts +14 -0
  34. package/dist/mysql/connection.js +24 -0
  35. package/dist/mysql/migration-generator.d.ts +45 -0
  36. package/dist/mysql/migration-generator.js +245 -0
  37. package/dist/mysql/migration-runner.d.ts +12 -0
  38. package/dist/mysql/migration-runner.js +83 -0
  39. package/dist/mysql/mysql-db.d.ts +100 -0
  40. package/dist/mysql/mysql-db.js +411 -0
  41. package/dist/mysql/query-builder.d.ts +10 -0
  42. package/dist/mysql/query-builder.js +44 -0
  43. package/dist/mysql/schema-introspector.d.ts +19 -0
  44. package/dist/mysql/schema-introspector.js +286 -0
  45. package/dist/mysql/type-map.d.ts +21 -0
  46. package/dist/mysql/type-map.js +36 -0
  47. package/dist/orm-request.d.ts +38 -0
  48. package/dist/orm-request.js +453 -0
  49. package/dist/plural-registry.d.ts +4 -0
  50. package/{src → dist}/plural-registry.js +3 -6
  51. package/dist/postgres/connection.d.ts +15 -0
  52. package/dist/postgres/connection.js +30 -0
  53. package/dist/postgres/migration-generator.d.ts +45 -0
  54. package/dist/postgres/migration-generator.js +257 -0
  55. package/dist/postgres/migration-runner.d.ts +10 -0
  56. package/dist/postgres/migration-runner.js +82 -0
  57. package/dist/postgres/postgres-db.d.ts +119 -0
  58. package/dist/postgres/postgres-db.js +473 -0
  59. package/dist/postgres/query-builder.d.ts +27 -0
  60. package/dist/postgres/query-builder.js +98 -0
  61. package/dist/postgres/schema-introspector.d.ts +29 -0
  62. package/dist/postgres/schema-introspector.js +309 -0
  63. package/dist/postgres/type-map.d.ts +23 -0
  64. package/dist/postgres/type-map.js +53 -0
  65. package/dist/record.d.ts +75 -0
  66. package/dist/record.js +115 -0
  67. package/dist/relationships.d.ts +10 -0
  68. package/dist/relationships.js +35 -0
  69. package/dist/serializer.d.ts +17 -0
  70. package/dist/serializer.js +130 -0
  71. package/dist/setup-rest-server.d.ts +1 -0
  72. package/dist/setup-rest-server.js +54 -0
  73. package/dist/standalone-db.d.ts +58 -0
  74. package/dist/standalone-db.js +142 -0
  75. package/dist/store.d.ts +62 -0
  76. package/dist/store.js +271 -0
  77. package/dist/timescale/query-builder.d.ts +41 -0
  78. package/dist/timescale/query-builder.js +87 -0
  79. package/dist/timescale/timescale-db.d.ts +44 -0
  80. package/dist/timescale/timescale-db.js +81 -0
  81. package/dist/transforms.d.ts +2 -0
  82. package/dist/transforms.js +17 -0
  83. package/dist/types/orm-types.d.ts +142 -0
  84. package/dist/types/orm-types.js +1 -0
  85. package/dist/utils.d.ts +5 -0
  86. package/dist/utils.js +13 -0
  87. package/dist/view-resolver.d.ts +8 -0
  88. package/dist/view-resolver.js +165 -0
  89. package/dist/view.d.ts +11 -0
  90. package/dist/view.js +18 -0
  91. package/package.json +34 -11
  92. package/src/{aggregates.js → aggregates.ts} +27 -13
  93. package/src/{attr.js → attr.ts} +2 -2
  94. package/src/{belongs-to.js → belongs-to.ts} +36 -17
  95. package/src/{cli.js → cli.ts} +17 -11
  96. package/src/{commands.js → commands.ts} +179 -170
  97. package/src/{db.js → db.ts} +35 -26
  98. package/src/exports/db.ts +7 -0
  99. package/src/has-many.ts +91 -0
  100. package/src/{hooks.js → hooks.ts} +23 -27
  101. package/src/{index.js → index.ts} +4 -4
  102. package/src/{main.js → main.ts} +59 -34
  103. package/src/{manage-record.js → manage-record.ts} +41 -22
  104. package/src/{meta-request.js → meta-request.ts} +17 -14
  105. package/src/{migrate.js → migrate.ts} +9 -9
  106. package/src/{model-property.js → model-property.ts} +12 -6
  107. package/src/{model.js → model.ts} +5 -4
  108. package/src/mysql/{connection.js → connection.ts} +43 -28
  109. package/src/mysql/{migration-generator.js → migration-generator.ts} +332 -286
  110. package/src/mysql/{migration-runner.js → migration-runner.ts} +116 -110
  111. package/src/mysql/{mysql-db.js → mysql-db.ts} +533 -473
  112. package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
  113. package/src/mysql/{schema-introspector.js → schema-introspector.ts} +355 -325
  114. package/src/mysql/{type-map.js → type-map.ts} +42 -37
  115. package/src/{orm-request.js → orm-request.ts} +165 -95
  116. package/src/plural-registry.ts +12 -0
  117. package/src/postgres/{connection.js → connection.ts} +14 -5
  118. package/src/postgres/{migration-generator.js → migration-generator.ts} +82 -38
  119. package/src/postgres/{migration-runner.js → migration-runner.ts} +11 -10
  120. package/src/postgres/{postgres-db.js → postgres-db.ts} +195 -114
  121. package/src/postgres/{query-builder.js → query-builder.ts} +27 -28
  122. package/src/postgres/{schema-introspector.js → schema-introspector.ts} +87 -58
  123. package/src/postgres/{type-map.js → type-map.ts} +10 -6
  124. package/src/{record.js → record.ts} +73 -34
  125. package/src/relationships.ts +48 -0
  126. package/src/{serializer.js → serializer.ts} +44 -36
  127. package/src/{setup-rest-server.js → setup-rest-server.ts} +18 -13
  128. package/src/{standalone-db.js → standalone-db.ts} +33 -24
  129. package/src/{store.js → store.ts} +90 -68
  130. package/src/timescale/{query-builder.js → query-builder.ts} +33 -38
  131. package/src/timescale/timescale-db.ts +107 -0
  132. package/src/transforms.ts +20 -0
  133. package/src/types/mysql2.d.ts +30 -0
  134. package/src/types/orm-types.ts +146 -0
  135. package/src/types/pg.d.ts +28 -0
  136. package/src/types/stonyx-cron.d.ts +5 -0
  137. package/src/types/stonyx-events.d.ts +4 -0
  138. package/src/types/stonyx-rest-server.d.ts +11 -0
  139. package/src/types/stonyx-utils.d.ts +33 -0
  140. package/src/types/stonyx.d.ts +21 -0
  141. package/src/utils.ts +16 -0
  142. package/src/{view-resolver.js → view-resolver.ts} +53 -28
  143. package/src/view.ts +22 -0
  144. package/src/has-many.js +0 -68
  145. package/src/relationships.js +0 -43
  146. package/src/timescale/timescale-db.js +0 -111
  147. package/src/transforms.js +0 -20
  148. package/src/utils.js +0 -12
  149. package/src/view.js +0 -21
@@ -1,473 +1,533 @@
1
- import { getPool, closePool } from './connection.js';
2
- import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
3
- import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
4
- import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
5
- import { buildInsert, buildUpdate, buildDelete, buildSelect } from './query-builder.js';
6
- import { createRecord, store } from '@stonyx/orm';
7
- import { confirm } from '@stonyx/utils/prompt';
8
- import { readFile } from '@stonyx/utils/file';
9
- import { getPluralName } from '../plural-registry.js';
10
- import config from 'stonyx/config';
11
- import log from 'stonyx/log';
12
- import path from 'path';
13
-
14
- const defaultDeps = {
15
- getPool, closePool, ensureMigrationsTable, getAppliedMigrations,
16
- getMigrationFiles, applyMigration, parseMigrationFile,
17
- introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
18
- loadLatestSnapshot, detectSchemaDrift,
19
- buildInsert, buildUpdate, buildDelete, buildSelect,
20
- createRecord, store, confirm, readFile, getPluralName, config, log, path
21
- };
22
-
23
- export default class MysqlDB {
24
- constructor(deps = {}) {
25
- if (MysqlDB.instance) return MysqlDB.instance;
26
- MysqlDB.instance = this;
27
-
28
- this.deps = { ...defaultDeps, ...deps };
29
- this.pool = null;
30
- this.mysqlConfig = this.deps.config.orm.mysql;
31
- }
32
-
33
- async init() {
34
- this.pool = await this.deps.getPool(this.mysqlConfig);
35
- await this.deps.ensureMigrationsTable(this.pool, this.mysqlConfig.migrationsTable);
36
- await this.loadMemoryRecords();
37
- }
38
-
39
- async startup() {
40
- const migrationsPath = this.deps.path.resolve(this.deps.config.rootPath, this.mysqlConfig.migrationsDir);
41
-
42
- // Check for pending migrations
43
- const applied = await this.deps.getAppliedMigrations(this.pool, this.mysqlConfig.migrationsTable);
44
- const files = await this.deps.getMigrationFiles(migrationsPath);
45
- const pending = files.filter(f => !applied.includes(f));
46
-
47
- if (pending.length > 0) {
48
- this.deps.log.db(`${pending.length} pending migration(s) found.`);
49
-
50
- const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
51
-
52
- if (shouldApply) {
53
- for (const filename of pending) {
54
- const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename));
55
- const { up } = this.deps.parseMigrationFile(content);
56
-
57
- await this.deps.applyMigration(this.pool, filename, up, this.mysqlConfig.migrationsTable);
58
- this.deps.log.db(`Applied migration: ${filename}`);
59
- }
60
-
61
- // Reload records after applying migrations
62
- await this.loadMemoryRecords();
63
- } else {
64
- this.deps.log.warn('Skipping pending migrations. Schema may be outdated.');
65
- }
66
- } else if (files.length === 0) {
67
- const schemas = this.deps.introspectModels();
68
- const modelCount = Object.keys(schemas).length;
69
-
70
- if (modelCount > 0) {
71
- const shouldGenerate = await this.deps.confirm(
72
- `No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`
73
- );
74
-
75
- if (shouldGenerate) {
76
- const { generateMigration } = await import('./migration-generator.js');
77
- const result = await generateMigration('initial_setup');
78
-
79
- if (result) {
80
- const { up } = this.deps.parseMigrationFile(result.content);
81
- await this.deps.applyMigration(this.pool, result.filename, up, this.mysqlConfig.migrationsTable);
82
- this.deps.log.db(`Applied migration: ${result.filename}`);
83
- await this.loadMemoryRecords();
84
- }
85
- } else {
86
- this.deps.log.warn('Skipping initial migration. Tables may not exist.');
87
- }
88
- }
89
- }
90
-
91
- // Check for schema drift
92
- const schemas = this.deps.introspectModels();
93
- const snapshot = await this.deps.loadLatestSnapshot(this.deps.path.resolve(this.deps.config.rootPath, this.mysqlConfig.migrationsDir));
94
-
95
- if (Object.keys(snapshot).length > 0) {
96
- const drift = this.deps.detectSchemaDrift(schemas, snapshot);
97
-
98
- if (drift.hasChanges) {
99
- this.deps.log.warn('Schema drift detected: models have changed since the last migration.');
100
- this.deps.log.warn('Run `stonyx db:generate-migration` to create a new migration.');
101
- }
102
- }
103
- }
104
-
105
- async shutdown() {
106
- await this.deps.closePool();
107
- this.pool = null;
108
- }
109
-
110
- async save() {
111
- // No-op: MySQL persists data immediately via persist()
112
- }
113
-
114
- /**
115
- * Loads only models with memory: true into the in-memory store on startup.
116
- * Models with memory: false are skipped — accessed on-demand via find()/findAll().
117
- */
118
- async loadMemoryRecords() {
119
- const schemas = this.deps.introspectModels();
120
- const order = this.deps.getTopologicalOrder(schemas);
121
- const Orm = (await import('@stonyx/orm')).default;
122
-
123
- for (const modelName of order) {
124
- // Check the model's memory flag — skip non-memory models
125
- const { modelClass } = Orm.instance.getRecordClasses(modelName);
126
- if (modelClass?.memory === false) {
127
- this.deps.log.db(`Skipping memory load for '${modelName}' (memory: false)`);
128
- continue;
129
- }
130
-
131
- const schema = schemas[modelName];
132
- const { sql, values } = this.deps.buildSelect(schema.table);
133
-
134
- try {
135
- const [rows] = await this.pool.execute(sql, values);
136
-
137
- for (const row of rows) {
138
- const rawData = this._rowToRawData(row, schema);
139
- this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
140
- }
141
- } catch (error) {
142
- // Table may not exist yet (pre-migration) — skip gracefully
143
- if (error.code === 'ER_NO_SUCH_TABLE') {
144
- this.deps.log.db(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
145
- continue;
146
- }
147
-
148
- throw error;
149
- }
150
- }
151
-
152
- // Load views with memory: true
153
- const viewSchemas = this.deps.introspectViews();
154
-
155
- for (const [viewName, viewSchema] of Object.entries(viewSchemas)) {
156
- const { modelClass: viewClass } = Orm.instance.getRecordClasses(viewName);
157
- if (viewClass?.memory !== true) {
158
- this.deps.log.db(`Skipping memory load for view '${viewName}' (memory: false)`);
159
- continue;
160
- }
161
-
162
- const schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
163
- const { sql, values } = this.deps.buildSelect(schema.table);
164
-
165
- try {
166
- const [rows] = await this.pool.execute(sql, values);
167
-
168
- for (const row of rows) {
169
- const rawData = this._rowToRawData(row, schema);
170
- this.deps.createRecord(viewName, rawData, { isDbRecord: true, serialize: false, transform: false });
171
- }
172
- } catch (error) {
173
- if (error.code === 'ER_NO_SUCH_TABLE') {
174
- this.deps.log.db(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
175
- continue;
176
- }
177
- throw error;
178
- }
179
- }
180
- }
181
-
182
- /**
183
- * @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
184
- */
185
- async loadAllRecords() {
186
- return this.loadMemoryRecords();
187
- }
188
-
189
- /**
190
- * Find a single record by ID from MySQL.
191
- * Does NOT cache the result in the store for memory: false models.
192
- * @param {string} modelName
193
- * @param {string|number} id
194
- * @returns {Promise<Record|undefined>}
195
- */
196
- async findRecord(modelName, id) {
197
- const schemas = this.deps.introspectModels();
198
- let schema = schemas[modelName];
199
-
200
- // Check views if not found in models
201
- if (!schema) {
202
- const viewSchemas = this.deps.introspectViews();
203
- const viewSchema = viewSchemas[modelName];
204
- if (viewSchema) {
205
- schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
206
- }
207
- }
208
-
209
- if (!schema) return undefined;
210
-
211
- const { sql, values } = this.deps.buildSelect(schema.table, { id });
212
-
213
- try {
214
- const [rows] = await this.pool.execute(sql, values);
215
-
216
- if (rows.length === 0) return undefined;
217
-
218
- const rawData = this._rowToRawData(rows[0], schema);
219
- const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
220
-
221
- // Don't let memory:false records accumulate in the store
222
- // The caller keeps the reference; the store doesn't retain it
223
- this._evictIfNotMemory(modelName, record);
224
-
225
- return record;
226
- } catch (error) {
227
- if (error.code === 'ER_NO_SUCH_TABLE') return undefined;
228
- throw error;
229
- }
230
- }
231
-
232
- /**
233
- * Find all records of a model from MySQL, with optional conditions.
234
- * @param {string} modelName
235
- * @param {Object} [conditions] - Optional WHERE conditions (key-value pairs)
236
- * @returns {Promise<Record[]>}
237
- */
238
- async findAll(modelName, conditions) {
239
- const schemas = this.deps.introspectModels();
240
- let schema = schemas[modelName];
241
-
242
- // Check views if not found in models
243
- if (!schema) {
244
- const viewSchemas = this.deps.introspectViews();
245
- const viewSchema = viewSchemas[modelName];
246
- if (viewSchema) {
247
- schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
248
- }
249
- }
250
-
251
- if (!schema) return [];
252
-
253
- const { sql, values } = this.deps.buildSelect(schema.table, conditions);
254
-
255
- try {
256
- const [rows] = await this.pool.execute(sql, values);
257
-
258
- const records = rows.map(row => {
259
- const rawData = this._rowToRawData(row, schema);
260
- return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
261
- });
262
-
263
- // Don't let memory:false records accumulate in the store
264
- for (const record of records) {
265
- this._evictIfNotMemory(modelName, record);
266
- }
267
-
268
- return records;
269
- } catch (error) {
270
- if (error.code === 'ER_NO_SUCH_TABLE') return [];
271
- throw error;
272
- }
273
- }
274
-
275
- /**
276
- * Remove a record from the in-memory store if its model has memory: false.
277
- * The record object itself survives — the caller retains the reference.
278
- * This prevents on-demand queries from leaking records into the store.
279
- * @private
280
- */
281
- _evictIfNotMemory(modelName, record) {
282
- const store = this.deps.store;
283
-
284
- // Use the memory resolver if available (set by Orm.init)
285
- if (store._memoryResolver && !store._memoryResolver(modelName)) {
286
- const modelStore = store.get?.(modelName) ?? store.data?.get(modelName);
287
- if (modelStore) modelStore.delete(record.id);
288
- }
289
- }
290
-
291
- _rowToRawData(row, schema) {
292
- const rawData = { ...row };
293
-
294
- for (const [col, mysqlType] of Object.entries(schema.columns)) {
295
- if (rawData[col] == null) continue;
296
-
297
- // Convert boolean columns from MySQL TINYINT(1) 0/1 to false/true
298
- if (mysqlType === 'TINYINT(1)') {
299
- rawData[col] = !!rawData[col];
300
- }
301
-
302
- // Parse JSON columns back to JS values (custom transforms stored as JSON)
303
- if (mysqlType === 'JSON' && typeof rawData[col] === 'string') {
304
- try { rawData[col] = JSON.parse(rawData[col]); } catch { /* keep raw string */ }
305
- }
306
- }
307
-
308
- // Map FK columns back to relationship keys
309
- // e.g., owner_id → owner (the belongsTo handler expects the id value under the relationship key name)
310
- for (const [fkCol, fkDef] of Object.entries(schema.foreignKeys)) {
311
- const relName = fkCol.replace(/_id$/, '');
312
-
313
- if (rawData[fkCol] !== undefined) {
314
- rawData[relName] = rawData[fkCol];
315
- delete rawData[fkCol];
316
- }
317
- }
318
-
319
- // Remove timestamp columns managed by MySQL
320
- delete rawData.created_at;
321
- delete rawData.updated_at;
322
-
323
- return rawData;
324
- }
325
-
326
- async persist(operation, modelName, context, response) {
327
- // Views are read-only — no-op for all write operations
328
- const Orm = (await import('@stonyx/orm')).default;
329
- if (Orm.instance?.isView?.(modelName)) return;
330
-
331
- switch (operation) {
332
- case 'create':
333
- return this._persistCreate(modelName, context, response);
334
- case 'update':
335
- return this._persistUpdate(modelName, context, response);
336
- case 'delete':
337
- return this._persistDelete(modelName, context);
338
- }
339
- }
340
-
341
- async _persistCreate(modelName, context, response) {
342
- const schemas = this.deps.introspectModels();
343
- const schema = schemas[modelName];
344
-
345
- if (!schema) return;
346
-
347
- const recordId = response?.data?.id;
348
- const record = recordId != null ? this.deps.store.get(modelName, isNaN(recordId) ? recordId : parseInt(recordId)) : null;
349
-
350
- if (!record) return;
351
-
352
- const insertData = this._recordToRow(record, schema);
353
-
354
- // For auto-increment models, remove the pending ID
355
- const isPendingId = record.__data.__pendingSqlId;
356
-
357
- if (isPendingId) {
358
- delete insertData.id;
359
- } else if (insertData.id !== undefined) {
360
- // Keep user-provided ID (string IDs or explicit numeric IDs)
361
- }
362
-
363
- const { sql, values } = this.deps.buildInsert(schema.table, insertData);
364
-
365
- const [result] = await this.pool.execute(sql, values);
366
-
367
- // Re-key the record in the store if MySQL generated the ID
368
- if (isPendingId && result.insertId) {
369
- const pendingId = record.id;
370
- const realId = result.insertId;
371
- const modelStore = this.deps.store.get(modelName);
372
-
373
- modelStore.delete(pendingId);
374
- record.__data.id = realId;
375
- record.id = realId;
376
- modelStore.set(realId, record);
377
-
378
- // Update the response data with the real ID
379
- if (response?.data) {
380
- response.data.id = realId;
381
- }
382
-
383
- delete record.__data.__pendingSqlId;
384
- }
385
- }
386
-
387
- async _persistUpdate(modelName, context, response) {
388
- const schemas = this.deps.introspectModels();
389
- const schema = schemas[modelName];
390
-
391
- if (!schema) return;
392
-
393
- const record = context.record;
394
- if (!record) return;
395
-
396
- const id = record.id;
397
- const oldState = context.oldState || {};
398
- const currentData = record.__data;
399
-
400
- // Build a diff of changed columns
401
- const changedData = {};
402
-
403
- for (const [col] of Object.entries(schema.columns)) {
404
- if (currentData[col] !== oldState[col]) {
405
- changedData[col] = currentData[col] ?? null;
406
- }
407
- }
408
-
409
- // Check FK changes too
410
- for (const fkCol of Object.keys(schema.foreignKeys)) {
411
- const relName = fkCol.replace(/_id$/, '');
412
- const currentFkValue = record.__relationships[relName]?.id ?? null;
413
- const oldFkValue = oldState[relName] ?? null;
414
-
415
- if (currentFkValue !== oldFkValue) {
416
- changedData[fkCol] = currentFkValue;
417
- }
418
- }
419
-
420
- if (Object.keys(changedData).length === 0) return;
421
-
422
- const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
423
- await this.pool.execute(sql, values);
424
- }
425
-
426
- async _persistDelete(modelName, context) {
427
- const schemas = this.deps.introspectModels();
428
- const schema = schemas[modelName];
429
-
430
- if (!schema) return;
431
-
432
- const id = context.recordId;
433
- if (id == null) return;
434
-
435
- const { sql, values } = this.deps.buildDelete(schema.table, id);
436
- await this.pool.execute(sql, values);
437
- }
438
-
439
- _recordToRow(record, schema) {
440
- const row = {};
441
- const data = record.__data;
442
-
443
- // ID
444
- if (data.id !== undefined) {
445
- row.id = data.id;
446
- }
447
-
448
- // Attribute columns
449
- for (const [col, mysqlType] of Object.entries(schema.columns)) {
450
- if (data[col] !== undefined) {
451
- // JSON columns: stringify non-string values for MySQL JSON storage
452
- row[col] = mysqlType === 'JSON' && typeof data[col] !== 'string'
453
- ? JSON.stringify(data[col])
454
- : data[col];
455
- }
456
- }
457
-
458
- // FK columns from relationships
459
- for (const fkCol of Object.keys(schema.foreignKeys)) {
460
- const relName = fkCol.replace(/_id$/, '');
461
- const related = record.__relationships[relName];
462
-
463
- if (related) {
464
- row[fkCol] = related.id;
465
- } else if (data[relName] !== undefined) {
466
- // Raw FK value (e.g., from create payload)
467
- row[fkCol] = data[relName];
468
- }
469
- }
470
-
471
- return row;
472
- }
473
- }
1
+ import { getPool, closePool } from './connection.js';
2
+ import type { MysqlConfig } from './connection.js';
3
+ import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
4
+ import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
5
+ import type { ModelSchema, ViewSchema, SnapshotEntry } from './schema-introspector.js';
6
+ import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
7
+ import { buildInsert, buildUpdate, buildDelete, buildSelect } from './query-builder.js';
8
+ import { store } from '@stonyx/orm';
9
+ import { createRecord } from '../manage-record.js';
10
+ import { confirm } from '@stonyx/utils/prompt';
11
+ import { readFile } from '@stonyx/utils/file';
12
+ import { getPluralName } from '../plural-registry.js';
13
+ import { isDbError } from '../utils.js';
14
+ import config from 'stonyx/config';
15
+ import log from 'stonyx/log';
16
+ import path from 'path';
17
+ import type { Pool } from 'mysql2/promise';
18
+ import type { OrmRecord } from '../types/orm-types.js';
19
+
20
+ interface PersistContext {
21
+ record?: OrmRecord;
22
+ recordId?: unknown;
23
+ oldState?: Record<string, unknown>;
24
+ }
25
+
26
+ interface PersistResponse {
27
+ data?: { id?: unknown };
28
+ }
29
+
30
+ interface ExecuteResult {
31
+ insertId?: number;
32
+ }
33
+
34
+ interface OrmStore {
35
+ get(key: string): Map<number | string, unknown> | undefined;
36
+ get(key: string, id: number | string): unknown;
37
+ _memoryResolver?: (modelName: string) => boolean;
38
+ data?: Map<string, Map<number | string, unknown>>;
39
+ }
40
+
41
+ interface MysqlDBDeps {
42
+ getPool: typeof getPool;
43
+ closePool: typeof closePool;
44
+ ensureMigrationsTable: typeof ensureMigrationsTable;
45
+ getAppliedMigrations: typeof getAppliedMigrations;
46
+ getMigrationFiles: typeof getMigrationFiles;
47
+ applyMigration: typeof applyMigration;
48
+ parseMigrationFile: typeof parseMigrationFile;
49
+ introspectModels: typeof introspectModels;
50
+ introspectViews: typeof introspectViews;
51
+ getTopologicalOrder: typeof getTopologicalOrder;
52
+ schemasToSnapshot: typeof schemasToSnapshot;
53
+ loadLatestSnapshot: typeof loadLatestSnapshot;
54
+ detectSchemaDrift: typeof detectSchemaDrift;
55
+ buildInsert: typeof buildInsert;
56
+ buildUpdate: typeof buildUpdate;
57
+ buildDelete: typeof buildDelete;
58
+ buildSelect: typeof buildSelect;
59
+ createRecord: typeof createRecord;
60
+ store: OrmStore;
61
+ confirm: typeof confirm;
62
+ readFile: typeof readFile;
63
+ getPluralName: typeof getPluralName;
64
+ config: typeof config;
65
+ log: Record<string, ((...args: unknown[]) => void) | undefined>;
66
+ path: typeof path;
67
+ }
68
+
69
+ const defaultDeps: MysqlDBDeps = {
70
+ getPool, closePool, ensureMigrationsTable, getAppliedMigrations,
71
+ getMigrationFiles, applyMigration, parseMigrationFile,
72
+ introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot,
73
+ loadLatestSnapshot, detectSchemaDrift,
74
+ buildInsert, buildUpdate, buildDelete, buildSelect,
75
+ createRecord, store: store as unknown as OrmStore, confirm, readFile, getPluralName,
76
+ config, log, path
77
+ };
78
+
79
+ export default class MysqlDB {
80
+ static instance: MysqlDB | undefined;
81
+
82
+ deps!: MysqlDBDeps;
83
+ pool!: Pool | null;
84
+ mysqlConfig!: MysqlConfig;
85
+
86
+ constructor(deps: Partial<MysqlDBDeps> = {}) {
87
+ if (MysqlDB.instance) return MysqlDB.instance;
88
+ MysqlDB.instance = this;
89
+
90
+ this.deps = { ...defaultDeps, ...deps } as MysqlDBDeps;
91
+ this.pool = null;
92
+ this.mysqlConfig = this.deps.config.orm.mysql!;
93
+ }
94
+
95
+ private requirePool(): Pool {
96
+ if (!this.pool) throw new Error('MysqlDB pool not initialized — call init() first');
97
+ return this.pool;
98
+ }
99
+
100
+ async init(): Promise<void> {
101
+ this.pool = await this.deps.getPool(this.mysqlConfig);
102
+ await this.deps.ensureMigrationsTable(this.pool, this.mysqlConfig.migrationsTable);
103
+ await this.loadMemoryRecords();
104
+ }
105
+
106
+ async startup(): Promise<void> {
107
+ const migrationsPath = this.deps.path.resolve(this.deps.config.rootPath, this.mysqlConfig.migrationsDir!);
108
+
109
+ // Check for pending migrations
110
+ const applied = await this.deps.getAppliedMigrations(this.requirePool(), this.mysqlConfig.migrationsTable);
111
+ const files = await this.deps.getMigrationFiles(migrationsPath);
112
+ const pending = files.filter(f => !applied.includes(f));
113
+
114
+ if (pending.length > 0) {
115
+ this.deps.log.db!(`${pending.length} pending migration(s) found.`);
116
+
117
+ const shouldApply = await this.deps.confirm(`${pending.length} pending migration(s) found. Apply now?`);
118
+
119
+ if (shouldApply) {
120
+ for (const filename of pending) {
121
+ const content = await this.deps.readFile(this.deps.path.join(migrationsPath, filename)) as string;
122
+ const { up } = this.deps.parseMigrationFile(content);
123
+
124
+ await this.deps.applyMigration(this.requirePool(), filename, up, this.mysqlConfig.migrationsTable);
125
+ this.deps.log.db!(`Applied migration: ${filename}`);
126
+ }
127
+
128
+ // Reload records after applying migrations
129
+ await this.loadMemoryRecords();
130
+ } else {
131
+ this.deps.log.warn!('Skipping pending migrations. Schema may be outdated.');
132
+ }
133
+ } else if (files.length === 0) {
134
+ const schemas = this.deps.introspectModels();
135
+ const modelCount = Object.keys(schemas).length;
136
+
137
+ if (modelCount > 0) {
138
+ const shouldGenerate = await this.deps.confirm(
139
+ `No migrations found but ${modelCount} model(s) detected. Generate and apply initial migration?`
140
+ );
141
+
142
+ if (shouldGenerate) {
143
+ const { generateMigration } = await import('./migration-generator.js');
144
+ const result = await generateMigration('initial_setup');
145
+
146
+ if (result) {
147
+ const { up } = this.deps.parseMigrationFile(result.content);
148
+ await this.deps.applyMigration(this.requirePool(), result.filename, up, this.mysqlConfig.migrationsTable);
149
+ this.deps.log.db!(`Applied migration: ${result.filename}`);
150
+ await this.loadMemoryRecords();
151
+ }
152
+ } else {
153
+ this.deps.log.warn!('Skipping initial migration. Tables may not exist.');
154
+ }
155
+ }
156
+ }
157
+
158
+ // Check for schema drift
159
+ const schemas = this.deps.introspectModels();
160
+ const snapshot = await this.deps.loadLatestSnapshot(this.deps.path.resolve(this.deps.config.rootPath, this.mysqlConfig.migrationsDir!)) as Record<string, SnapshotEntry>;
161
+
162
+ if (Object.keys(snapshot).length > 0) {
163
+ const drift = this.deps.detectSchemaDrift(schemas, snapshot);
164
+
165
+ if (drift.hasChanges) {
166
+ this.deps.log.warn!('Schema drift detected: models have changed since the last migration.');
167
+ this.deps.log.warn!('Run `stonyx db:generate-migration` to create a new migration.');
168
+ }
169
+ }
170
+ }
171
+
172
+ async shutdown(): Promise<void> {
173
+ await this.deps.closePool();
174
+ this.pool = null;
175
+ }
176
+
177
+ async save(): Promise<void> {
178
+ // No-op: MySQL persists data immediately via persist()
179
+ }
180
+
181
+ /**
182
+ * Loads only models with memory: true into the in-memory store on startup.
183
+ * Models with memory: false are skipped accessed on-demand via find()/findAll().
184
+ */
185
+ async loadMemoryRecords(): Promise<void> {
186
+ const schemas = this.deps.introspectModels();
187
+ const order = this.deps.getTopologicalOrder(schemas);
188
+ const Orm = (await import('@stonyx/orm')).default;
189
+
190
+ for (const modelName of order) {
191
+ // Check the model's memory flag skip non-memory models
192
+ const { modelClass } = Orm.instance.getRecordClasses(modelName) as { modelClass?: { memory?: boolean } };
193
+ if (modelClass?.memory === false) {
194
+ this.deps.log.db!(`Skipping memory load for '${modelName}' (memory: false)`);
195
+ continue;
196
+ }
197
+
198
+ const schema = schemas[modelName];
199
+ const { sql, values } = this.deps.buildSelect(schema.table);
200
+
201
+ try {
202
+ const [rows] = await this.requirePool().execute(sql, values) as [Record<string, unknown>[], unknown];
203
+
204
+ for (const row of rows) {
205
+ const rawData = this._rowToRawData(row, schema);
206
+ this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
207
+ }
208
+ } catch (error) {
209
+ // Table may not exist yet (pre-migration) skip gracefully
210
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') {
211
+ this.deps.log.db!(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
212
+ continue;
213
+ }
214
+
215
+ throw error;
216
+ }
217
+ }
218
+
219
+ // Load views with memory: true
220
+ const viewSchemas = this.deps.introspectViews();
221
+
222
+ for (const [viewName, viewSchema] of Object.entries(viewSchemas)) {
223
+ const { modelClass: viewClass } = Orm.instance.getRecordClasses(viewName) as { modelClass?: { memory?: boolean } };
224
+ if (viewClass?.memory !== true) {
225
+ this.deps.log.db!(`Skipping memory load for view '${viewName}' (memory: false)`);
226
+ continue;
227
+ }
228
+
229
+ const schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
230
+ const { sql, values } = this.deps.buildSelect(schema.table);
231
+
232
+ try {
233
+ const [rows] = await this.requirePool().execute(sql, values) as [Record<string, unknown>[], unknown];
234
+
235
+ for (const row of rows) {
236
+ const rawData = this._rowToRawData(row, schema);
237
+ this.deps.createRecord(viewName, rawData, { isDbRecord: true, serialize: false, transform: false });
238
+ }
239
+ } catch (error) {
240
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') {
241
+ this.deps.log.db!(`View '${viewSchema.viewName}' does not exist yet. Skipping load for '${viewName}'.`);
242
+ continue;
243
+ }
244
+ throw error;
245
+ }
246
+ }
247
+ }
248
+
249
+ /**
250
+ * @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
251
+ */
252
+ async loadAllRecords(): Promise<void> {
253
+ return this.loadMemoryRecords();
254
+ }
255
+
256
+ /**
257
+ * Find a single record by ID from MySQL.
258
+ * Does NOT cache the result in the store for memory: false models.
259
+ */
260
+ async findRecord(modelName: string, id: string | number): Promise<OrmRecord | undefined> {
261
+ const schemas = this.deps.introspectModels();
262
+ let schema: { table: string; columns: Record<string, string>; foreignKeys: Record<string, unknown> } | undefined = schemas[modelName];
263
+
264
+ // Check views if not found in models
265
+ if (!schema) {
266
+ const viewSchemas = this.deps.introspectViews();
267
+ const viewSchema = viewSchemas[modelName];
268
+ if (viewSchema) {
269
+ schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
270
+ }
271
+ }
272
+
273
+ if (!schema) return undefined;
274
+
275
+ const { sql, values } = this.deps.buildSelect(schema.table, { id });
276
+
277
+ try {
278
+ const [rows] = await this.requirePool().execute(sql, values) as [Record<string, unknown>[], unknown];
279
+
280
+ if (rows.length === 0) return undefined;
281
+
282
+ const rawData = this._rowToRawData(rows[0], schema);
283
+ const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
284
+
285
+ // Don't let memory:false records accumulate in the store
286
+ // The caller keeps the reference; the store doesn't retain it
287
+ this._evictIfNotMemory(modelName, record);
288
+
289
+ return record;
290
+ } catch (error) {
291
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') return undefined;
292
+ throw error;
293
+ }
294
+ }
295
+
296
+ /**
297
+ * Find all records of a model from MySQL, with optional conditions.
298
+ */
299
+ async findAll(modelName: string, conditions?: Record<string, unknown>): Promise<OrmRecord[]> {
300
+ const schemas = this.deps.introspectModels();
301
+ let schema: { table: string; columns: Record<string, string>; foreignKeys: Record<string, unknown> } | undefined = schemas[modelName];
302
+
303
+ // Check views if not found in models
304
+ if (!schema) {
305
+ const viewSchemas = this.deps.introspectViews();
306
+ const viewSchema = viewSchemas[modelName];
307
+ if (viewSchema) {
308
+ schema = { table: viewSchema.viewName, columns: viewSchema.columns || {}, foreignKeys: viewSchema.foreignKeys || {} };
309
+ }
310
+ }
311
+
312
+ if (!schema) return [];
313
+
314
+ const { sql, values } = this.deps.buildSelect(schema.table, conditions);
315
+
316
+ try {
317
+ const [rows] = await this.requirePool().execute(sql, values) as [Record<string, unknown>[], unknown];
318
+
319
+ const records = rows.map(row => {
320
+ const rawData = this._rowToRawData(row, schema!);
321
+ return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false }) as unknown as OrmRecord;
322
+ });
323
+
324
+ // Don't let memory:false records accumulate in the store
325
+ for (const record of records) {
326
+ this._evictIfNotMemory(modelName, record);
327
+ }
328
+
329
+ return records;
330
+ } catch (error) {
331
+ if (isDbError(error) && error.code === 'ER_NO_SUCH_TABLE') return [];
332
+ throw error;
333
+ }
334
+ }
335
+
336
+ /**
337
+ * Remove a record from the in-memory store if its model has memory: false.
338
+ * The record object itself survives — the caller retains the reference.
339
+ * This prevents on-demand queries from leaking records into the store.
340
+ */
341
+ private _evictIfNotMemory(modelName: string, record: OrmRecord): void {
342
+ const storeRef = this.deps.store;
343
+
344
+ // Use the memory resolver if available (set by Orm.init)
345
+ if (storeRef._memoryResolver && !storeRef._memoryResolver(modelName)) {
346
+ const modelStore = (storeRef.get?.(modelName) ?? storeRef.data?.get(modelName)) as Map<unknown, unknown> | undefined;
347
+ if (modelStore) modelStore.delete(record.id);
348
+ }
349
+ }
350
+
351
+ private _rowToRawData(row: Record<string, unknown>, schema: { columns: Record<string, string>; foreignKeys: Record<string, unknown> }): Record<string, unknown> {
352
+ const rawData: Record<string, unknown> = { ...row };
353
+
354
+ for (const [col, mysqlType] of Object.entries(schema.columns)) {
355
+ if (rawData[col] == null) continue;
356
+
357
+ // Convert boolean columns from MySQL TINYINT(1) 0/1 to false/true
358
+ if (mysqlType === 'TINYINT(1)') {
359
+ rawData[col] = !!rawData[col];
360
+ }
361
+
362
+ // Parse JSON columns back to JS values (custom transforms stored as JSON)
363
+ if (mysqlType === 'JSON' && typeof rawData[col] === 'string') {
364
+ try { rawData[col] = JSON.parse(rawData[col] as string); } catch { /* keep raw string */ }
365
+ }
366
+ }
367
+
368
+ // Map FK columns back to relationship keys
369
+ // e.g., owner_id -> owner (the belongsTo handler expects the id value under the relationship key name)
370
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
371
+ const relName = fkCol.replace(/_id$/, '');
372
+
373
+ if (rawData[fkCol] !== undefined) {
374
+ rawData[relName] = rawData[fkCol];
375
+ delete rawData[fkCol];
376
+ }
377
+ }
378
+
379
+ // Remove timestamp columns — managed by MySQL
380
+ delete rawData.created_at;
381
+ delete rawData.updated_at;
382
+
383
+ return rawData;
384
+ }
385
+
386
+ async persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
387
+ // Views are read-only — no-op for all write operations
388
+ const Orm = (await import('@stonyx/orm')).default;
389
+ if ((Orm as unknown as { instance?: { isView?: (name: string) => boolean } }).instance?.isView?.(modelName)) return;
390
+
391
+ switch (operation) {
392
+ case 'create':
393
+ return this._persistCreate(modelName, context, response);
394
+ case 'update':
395
+ return this._persistUpdate(modelName, context, response);
396
+ case 'delete':
397
+ return this._persistDelete(modelName, context);
398
+ }
399
+ }
400
+
401
+ private async _persistCreate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
402
+ const schemas = this.deps.introspectModels();
403
+ const schema = schemas[modelName];
404
+
405
+ if (!schema) return;
406
+
407
+ const recordId = response?.data?.id;
408
+ const record = recordId != null ? this.deps.store.get(modelName, (isNaN(recordId as number) ? recordId : parseInt(recordId as string)) as number | string) as OrmRecord | null : null;
409
+
410
+ if (!record) return;
411
+
412
+ const insertData = this._recordToRow(record, schema);
413
+
414
+ // For auto-increment models, remove the pending ID
415
+ const isPendingId = record.__data.__pendingSqlId;
416
+
417
+ if (isPendingId) {
418
+ delete insertData.id;
419
+ } else if (insertData.id !== undefined) {
420
+ // Keep user-provided ID (string IDs or explicit numeric IDs)
421
+ }
422
+
423
+ const { sql, values } = this.deps.buildInsert(schema.table, insertData);
424
+
425
+ const [result] = await this.requirePool().execute(sql, values) as [ExecuteResult, unknown];
426
+
427
+ // Re-key the record in the store if MySQL generated the ID
428
+ if (isPendingId && result.insertId) {
429
+ const pendingId = record.id;
430
+ const realId = result.insertId;
431
+ const modelStore = this.deps.store.get(modelName)!;
432
+
433
+ modelStore.delete(pendingId as number | string);
434
+ record.__data.id = realId;
435
+ record.id = realId;
436
+ modelStore.set(realId as number | string, record);
437
+
438
+ // Update the response data with the real ID
439
+ if (response?.data) {
440
+ response.data.id = realId;
441
+ }
442
+
443
+ delete record.__data.__pendingSqlId;
444
+ }
445
+ }
446
+
447
+ private async _persistUpdate(modelName: string, context: PersistContext, response: PersistResponse): Promise<void> {
448
+ const schemas = this.deps.introspectModels();
449
+ const schema = schemas[modelName];
450
+
451
+ if (!schema) return;
452
+
453
+ const record = context.record;
454
+ if (!record) return;
455
+
456
+ const id = record.id;
457
+ const oldState = context.oldState || {};
458
+ const currentData = record.__data;
459
+
460
+ // Build a diff of changed columns
461
+ const changedData: Record<string, unknown> = {};
462
+
463
+ for (const [col] of Object.entries(schema.columns)) {
464
+ if (currentData[col] !== oldState[col]) {
465
+ changedData[col] = currentData[col] ?? null;
466
+ }
467
+ }
468
+
469
+ // Check FK changes too
470
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
471
+ const relName = fkCol.replace(/_id$/, '');
472
+ const currentFkValue = (record.__relationships[relName] as { id: unknown } | undefined)?.id ?? null;
473
+ const oldFkValue = oldState[relName] ?? null;
474
+
475
+ if (currentFkValue !== oldFkValue) {
476
+ changedData[fkCol] = currentFkValue;
477
+ }
478
+ }
479
+
480
+ if (Object.keys(changedData).length === 0) return;
481
+
482
+ const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
483
+ await this.requirePool().execute(sql, values);
484
+ }
485
+
486
+ private async _persistDelete(modelName: string, context: PersistContext): Promise<void> {
487
+ const schemas = this.deps.introspectModels();
488
+ const schema = schemas[modelName];
489
+
490
+ if (!schema) return;
491
+
492
+ const id = context.recordId;
493
+ if (id == null) return;
494
+
495
+ const { sql, values } = this.deps.buildDelete(schema.table, id);
496
+ await this.requirePool().execute(sql, values);
497
+ }
498
+
499
+ private _recordToRow(record: OrmRecord, schema: ModelSchema): Record<string, unknown> {
500
+ const row: Record<string, unknown> = {};
501
+ const data = record.__data;
502
+
503
+ // ID
504
+ if (data.id !== undefined) {
505
+ row.id = data.id;
506
+ }
507
+
508
+ // Attribute columns
509
+ for (const [col, mysqlType] of Object.entries(schema.columns)) {
510
+ if (data[col] !== undefined) {
511
+ // JSON columns: stringify non-string values for MySQL JSON storage
512
+ row[col] = mysqlType === 'JSON' && typeof data[col] !== 'string'
513
+ ? JSON.stringify(data[col])
514
+ : data[col];
515
+ }
516
+ }
517
+
518
+ // FK columns from relationships
519
+ for (const fkCol of Object.keys(schema.foreignKeys)) {
520
+ const relName = fkCol.replace(/_id$/, '');
521
+ const related = record.__relationships[relName];
522
+
523
+ if (related) {
524
+ row[fkCol] = (related as { id: unknown }).id;
525
+ } else if (data[relName] !== undefined) {
526
+ // Raw FK value (e.g., from create payload)
527
+ row[fkCol] = data[relName];
528
+ }
529
+ }
530
+
531
+ return row;
532
+ }
533
+ }