@stonyx/orm 0.2.1-alpha.2 → 0.2.1-alpha.21
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.
- package/.claude/code-style-rules.md +44 -0
- package/.claude/hooks.md +250 -0
- package/.claude/index.md +292 -0
- package/.claude/usage-patterns.md +300 -0
- package/.claude/views.md +292 -0
- package/.github/workflows/ci.yml +5 -25
- package/.github/workflows/publish.yml +24 -116
- package/README.md +461 -15
- package/config/environment.js +29 -6
- package/improvements.md +139 -0
- package/package.json +24 -8
- package/project-structure.md +343 -0
- package/scripts/setup-test-db.sh +21 -0
- package/src/aggregates.js +93 -0
- package/src/belongs-to.js +4 -1
- package/src/commands.js +170 -0
- package/src/db.js +132 -6
- package/src/has-many.js +4 -1
- package/src/hooks.js +124 -0
- package/src/index.js +12 -2
- package/src/main.js +77 -4
- package/src/manage-record.js +30 -4
- package/src/migrate.js +72 -0
- package/src/model-property.js +2 -2
- package/src/model.js +11 -0
- package/src/mysql/connection.js +28 -0
- package/src/mysql/migration-generator.js +286 -0
- package/src/mysql/migration-runner.js +110 -0
- package/src/mysql/mysql-db.js +473 -0
- package/src/mysql/query-builder.js +64 -0
- package/src/mysql/schema-introspector.js +325 -0
- package/src/mysql/type-map.js +37 -0
- package/src/orm-request.js +313 -53
- package/src/plural-registry.js +12 -0
- package/src/record.js +35 -8
- package/src/serializer.js +9 -2
- package/src/setup-rest-server.js +5 -2
- package/src/store.js +130 -1
- package/src/utils.js +1 -1
- package/src/view-resolver.js +183 -0
- package/src/view.js +21 -0
- package/test-events-setup.js +41 -0
- package/test-hooks-manual.js +54 -0
- package/test-hooks-with-logging.js +52 -0
- package/.claude/project-structure.md +0 -578
- package/stonyx-bootstrap.cjs +0 -30
|
@@ -0,0 +1,473 @@
|
|
|
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.__pendingMysqlId;
|
|
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.__pendingMysqlId;
|
|
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
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
const SAFE_IDENTIFIER = /^[a-zA-Z_][a-zA-Z0-9_-]*$/;
|
|
2
|
+
|
|
3
|
+
export function validateIdentifier(name, context = 'identifier') {
|
|
4
|
+
if (!name || typeof name !== 'string' || !SAFE_IDENTIFIER.test(name)) {
|
|
5
|
+
throw new Error(`Invalid SQL ${context}: "${name}". Identifiers must match ${SAFE_IDENTIFIER}`);
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
return name;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function buildInsert(table, data) {
|
|
12
|
+
validateIdentifier(table, 'table name');
|
|
13
|
+
|
|
14
|
+
const keys = Object.keys(data);
|
|
15
|
+
keys.forEach(k => validateIdentifier(k, 'column name'));
|
|
16
|
+
|
|
17
|
+
const placeholders = keys.map(() => '?');
|
|
18
|
+
const values = keys.map(k => data[k]);
|
|
19
|
+
|
|
20
|
+
const sql = `INSERT INTO \`${table}\` (${keys.map(k => `\`${k}\``).join(', ')}) VALUES (${placeholders.join(', ')})`;
|
|
21
|
+
|
|
22
|
+
return { sql, values };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function buildUpdate(table, id, data) {
|
|
26
|
+
validateIdentifier(table, 'table name');
|
|
27
|
+
|
|
28
|
+
const keys = Object.keys(data);
|
|
29
|
+
keys.forEach(k => validateIdentifier(k, 'column name'));
|
|
30
|
+
|
|
31
|
+
const setClauses = keys.map(k => `\`${k}\` = ?`);
|
|
32
|
+
const values = [...keys.map(k => data[k]), id];
|
|
33
|
+
|
|
34
|
+
const sql = `UPDATE \`${table}\` SET ${setClauses.join(', ')} WHERE \`id\` = ?`;
|
|
35
|
+
|
|
36
|
+
return { sql, values };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function buildDelete(table, id) {
|
|
40
|
+
validateIdentifier(table, 'table name');
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
sql: `DELETE FROM \`${table}\` WHERE \`id\` = ?`,
|
|
44
|
+
values: [id],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function buildSelect(table, conditions) {
|
|
49
|
+
validateIdentifier(table, 'table name');
|
|
50
|
+
|
|
51
|
+
if (!conditions || Object.keys(conditions).length === 0) {
|
|
52
|
+
return { sql: `SELECT * FROM \`${table}\``, values: [] };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const keys = Object.keys(conditions);
|
|
56
|
+
keys.forEach(k => validateIdentifier(k, 'column name'));
|
|
57
|
+
|
|
58
|
+
const whereClauses = keys.map(k => `\`${k}\` = ?`);
|
|
59
|
+
const values = keys.map(k => conditions[k]);
|
|
60
|
+
|
|
61
|
+
const sql = `SELECT * FROM \`${table}\` WHERE ${whereClauses.join(' AND ')}`;
|
|
62
|
+
|
|
63
|
+
return { sql, values };
|
|
64
|
+
}
|