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