@stonyx/orm 0.2.5-alpha.0 → 0.3.1

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