@stonyx/orm 0.2.1-beta.2 → 0.2.1-beta.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 +281 -0
- package/.claude/usage-patterns.md +234 -0
- package/.github/workflows/publish.yml +17 -1
- package/README.md +440 -15
- package/config/environment.js +26 -5
- package/improvements.md +139 -0
- package/package.json +19 -8
- package/project-structure.md +343 -0
- package/src/commands.js +170 -0
- package/src/db.js +132 -6
- package/src/hooks.js +124 -0
- package/src/index.js +8 -1
- package/src/main.js +47 -3
- package/src/manage-record.js +19 -4
- package/src/migrate.js +72 -0
- package/src/model.js +11 -0
- package/src/mysql/connection.js +28 -0
- package/src/mysql/migration-generator.js +188 -0
- package/src/mysql/migration-runner.js +110 -0
- package/src/mysql/mysql-db.js +422 -0
- package/src/mysql/query-builder.js +64 -0
- package/src/mysql/schema-introspector.js +160 -0
- package/src/mysql/type-map.js +37 -0
- package/src/orm-request.js +307 -53
- package/src/plural-registry.js +12 -0
- package/src/record.js +35 -8
- package/src/serializer.js +2 -2
- package/src/setup-rest-server.js +4 -1
- package/src/store.js +105 -0
- package/src/utils.js +12 -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,422 @@
|
|
|
1
|
+
import { getPool, closePool } from './connection.js';
|
|
2
|
+
import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
|
|
3
|
+
import { introspectModels, 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, 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
|
+
|
|
153
|
+
/**
|
|
154
|
+
* @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
|
|
155
|
+
*/
|
|
156
|
+
async loadAllRecords() {
|
|
157
|
+
return this.loadMemoryRecords();
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Find a single record by ID from MySQL.
|
|
162
|
+
* Does NOT cache the result in the store for memory: false models.
|
|
163
|
+
* @param {string} modelName
|
|
164
|
+
* @param {string|number} id
|
|
165
|
+
* @returns {Promise<Record|undefined>}
|
|
166
|
+
*/
|
|
167
|
+
async findRecord(modelName, id) {
|
|
168
|
+
const schemas = this.deps.introspectModels();
|
|
169
|
+
const schema = schemas[modelName];
|
|
170
|
+
|
|
171
|
+
if (!schema) return undefined;
|
|
172
|
+
|
|
173
|
+
const { sql, values } = this.deps.buildSelect(schema.table, { id });
|
|
174
|
+
|
|
175
|
+
try {
|
|
176
|
+
const [rows] = await this.pool.execute(sql, values);
|
|
177
|
+
|
|
178
|
+
if (rows.length === 0) return undefined;
|
|
179
|
+
|
|
180
|
+
const rawData = this._rowToRawData(rows[0], schema);
|
|
181
|
+
const record = this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
|
|
182
|
+
|
|
183
|
+
// Don't let memory:false records accumulate in the store
|
|
184
|
+
// The caller keeps the reference; the store doesn't retain it
|
|
185
|
+
this._evictIfNotMemory(modelName, record);
|
|
186
|
+
|
|
187
|
+
return record;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if (error.code === 'ER_NO_SUCH_TABLE') return undefined;
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Find all records of a model from MySQL, with optional conditions.
|
|
196
|
+
* @param {string} modelName
|
|
197
|
+
* @param {Object} [conditions] - Optional WHERE conditions (key-value pairs)
|
|
198
|
+
* @returns {Promise<Record[]>}
|
|
199
|
+
*/
|
|
200
|
+
async findAll(modelName, conditions) {
|
|
201
|
+
const schemas = this.deps.introspectModels();
|
|
202
|
+
const schema = schemas[modelName];
|
|
203
|
+
|
|
204
|
+
if (!schema) return [];
|
|
205
|
+
|
|
206
|
+
const { sql, values } = this.deps.buildSelect(schema.table, conditions);
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
const [rows] = await this.pool.execute(sql, values);
|
|
210
|
+
|
|
211
|
+
const records = rows.map(row => {
|
|
212
|
+
const rawData = this._rowToRawData(row, schema);
|
|
213
|
+
return this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
// Don't let memory:false records accumulate in the store
|
|
217
|
+
for (const record of records) {
|
|
218
|
+
this._evictIfNotMemory(modelName, record);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return records;
|
|
222
|
+
} catch (error) {
|
|
223
|
+
if (error.code === 'ER_NO_SUCH_TABLE') return [];
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Remove a record from the in-memory store if its model has memory: false.
|
|
230
|
+
* The record object itself survives — the caller retains the reference.
|
|
231
|
+
* This prevents on-demand queries from leaking records into the store.
|
|
232
|
+
* @private
|
|
233
|
+
*/
|
|
234
|
+
_evictIfNotMemory(modelName, record) {
|
|
235
|
+
const store = this.deps.store;
|
|
236
|
+
|
|
237
|
+
// Use the memory resolver if available (set by Orm.init)
|
|
238
|
+
if (store._memoryResolver && !store._memoryResolver(modelName)) {
|
|
239
|
+
const modelStore = store.get?.(modelName) ?? store.data?.get(modelName);
|
|
240
|
+
if (modelStore) modelStore.delete(record.id);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
_rowToRawData(row, schema) {
|
|
245
|
+
const rawData = { ...row };
|
|
246
|
+
|
|
247
|
+
for (const [col, mysqlType] of Object.entries(schema.columns)) {
|
|
248
|
+
if (rawData[col] == null) continue;
|
|
249
|
+
|
|
250
|
+
// Convert boolean columns from MySQL TINYINT(1) 0/1 to false/true
|
|
251
|
+
if (mysqlType === 'TINYINT(1)') {
|
|
252
|
+
rawData[col] = !!rawData[col];
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Parse JSON columns back to JS values (custom transforms stored as JSON)
|
|
256
|
+
if (mysqlType === 'JSON' && typeof rawData[col] === 'string') {
|
|
257
|
+
try { rawData[col] = JSON.parse(rawData[col]); } catch { /* keep raw string */ }
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Map FK columns back to relationship keys
|
|
262
|
+
// e.g., owner_id → owner (the belongsTo handler expects the id value under the relationship key name)
|
|
263
|
+
for (const [fkCol, fkDef] of Object.entries(schema.foreignKeys)) {
|
|
264
|
+
const relName = fkCol.replace(/_id$/, '');
|
|
265
|
+
|
|
266
|
+
if (rawData[fkCol] !== undefined) {
|
|
267
|
+
rawData[relName] = rawData[fkCol];
|
|
268
|
+
delete rawData[fkCol];
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Remove timestamp columns — managed by MySQL
|
|
273
|
+
delete rawData.created_at;
|
|
274
|
+
delete rawData.updated_at;
|
|
275
|
+
|
|
276
|
+
return rawData;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
async persist(operation, modelName, context, response) {
|
|
280
|
+
switch (operation) {
|
|
281
|
+
case 'create':
|
|
282
|
+
return this._persistCreate(modelName, context, response);
|
|
283
|
+
case 'update':
|
|
284
|
+
return this._persistUpdate(modelName, context, response);
|
|
285
|
+
case 'delete':
|
|
286
|
+
return this._persistDelete(modelName, context);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async _persistCreate(modelName, context, response) {
|
|
291
|
+
const schemas = this.deps.introspectModels();
|
|
292
|
+
const schema = schemas[modelName];
|
|
293
|
+
|
|
294
|
+
if (!schema) return;
|
|
295
|
+
|
|
296
|
+
const recordId = response?.data?.id;
|
|
297
|
+
const record = recordId != null ? this.deps.store.get(modelName, isNaN(recordId) ? recordId : parseInt(recordId)) : null;
|
|
298
|
+
|
|
299
|
+
if (!record) return;
|
|
300
|
+
|
|
301
|
+
const insertData = this._recordToRow(record, schema);
|
|
302
|
+
|
|
303
|
+
// For auto-increment models, remove the pending ID
|
|
304
|
+
const isPendingId = record.__data.__pendingMysqlId;
|
|
305
|
+
|
|
306
|
+
if (isPendingId) {
|
|
307
|
+
delete insertData.id;
|
|
308
|
+
} else if (insertData.id !== undefined) {
|
|
309
|
+
// Keep user-provided ID (string IDs or explicit numeric IDs)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
const { sql, values } = this.deps.buildInsert(schema.table, insertData);
|
|
313
|
+
|
|
314
|
+
const [result] = await this.pool.execute(sql, values);
|
|
315
|
+
|
|
316
|
+
// Re-key the record in the store if MySQL generated the ID
|
|
317
|
+
if (isPendingId && result.insertId) {
|
|
318
|
+
const pendingId = record.id;
|
|
319
|
+
const realId = result.insertId;
|
|
320
|
+
const modelStore = this.deps.store.get(modelName);
|
|
321
|
+
|
|
322
|
+
modelStore.delete(pendingId);
|
|
323
|
+
record.__data.id = realId;
|
|
324
|
+
record.id = realId;
|
|
325
|
+
modelStore.set(realId, record);
|
|
326
|
+
|
|
327
|
+
// Update the response data with the real ID
|
|
328
|
+
if (response?.data) {
|
|
329
|
+
response.data.id = realId;
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
delete record.__data.__pendingMysqlId;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
async _persistUpdate(modelName, context, response) {
|
|
337
|
+
const schemas = this.deps.introspectModels();
|
|
338
|
+
const schema = schemas[modelName];
|
|
339
|
+
|
|
340
|
+
if (!schema) return;
|
|
341
|
+
|
|
342
|
+
const record = context.record;
|
|
343
|
+
if (!record) return;
|
|
344
|
+
|
|
345
|
+
const id = record.id;
|
|
346
|
+
const oldState = context.oldState || {};
|
|
347
|
+
const currentData = record.__data;
|
|
348
|
+
|
|
349
|
+
// Build a diff of changed columns
|
|
350
|
+
const changedData = {};
|
|
351
|
+
|
|
352
|
+
for (const [col] of Object.entries(schema.columns)) {
|
|
353
|
+
if (currentData[col] !== oldState[col]) {
|
|
354
|
+
changedData[col] = currentData[col] ?? null;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Check FK changes too
|
|
359
|
+
for (const fkCol of Object.keys(schema.foreignKeys)) {
|
|
360
|
+
const relName = fkCol.replace(/_id$/, '');
|
|
361
|
+
const currentFkValue = record.__relationships[relName]?.id ?? null;
|
|
362
|
+
const oldFkValue = oldState[relName] ?? null;
|
|
363
|
+
|
|
364
|
+
if (currentFkValue !== oldFkValue) {
|
|
365
|
+
changedData[fkCol] = currentFkValue;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
if (Object.keys(changedData).length === 0) return;
|
|
370
|
+
|
|
371
|
+
const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
|
|
372
|
+
await this.pool.execute(sql, values);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
async _persistDelete(modelName, context) {
|
|
376
|
+
const schemas = this.deps.introspectModels();
|
|
377
|
+
const schema = schemas[modelName];
|
|
378
|
+
|
|
379
|
+
if (!schema) return;
|
|
380
|
+
|
|
381
|
+
const id = context.recordId;
|
|
382
|
+
if (id == null) return;
|
|
383
|
+
|
|
384
|
+
const { sql, values } = this.deps.buildDelete(schema.table, id);
|
|
385
|
+
await this.pool.execute(sql, values);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
_recordToRow(record, schema) {
|
|
389
|
+
const row = {};
|
|
390
|
+
const data = record.__data;
|
|
391
|
+
|
|
392
|
+
// ID
|
|
393
|
+
if (data.id !== undefined) {
|
|
394
|
+
row.id = data.id;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Attribute columns
|
|
398
|
+
for (const [col, mysqlType] of Object.entries(schema.columns)) {
|
|
399
|
+
if (data[col] !== undefined) {
|
|
400
|
+
// JSON columns: stringify non-string values for MySQL JSON storage
|
|
401
|
+
row[col] = mysqlType === 'JSON' && typeof data[col] !== 'string'
|
|
402
|
+
? JSON.stringify(data[col])
|
|
403
|
+
: data[col];
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// FK columns from relationships
|
|
408
|
+
for (const fkCol of Object.keys(schema.foreignKeys)) {
|
|
409
|
+
const relName = fkCol.replace(/_id$/, '');
|
|
410
|
+
const related = record.__relationships[relName];
|
|
411
|
+
|
|
412
|
+
if (related) {
|
|
413
|
+
row[fkCol] = related.id;
|
|
414
|
+
} else if (data[relName] !== undefined) {
|
|
415
|
+
// Raw FK value (e.g., from create payload)
|
|
416
|
+
row[fkCol] = data[relName];
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return row;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import Orm from '@stonyx/orm';
|
|
2
|
+
import { getMysqlType } from './type-map.js';
|
|
3
|
+
import { camelCaseToKebabCase } from '@stonyx/utils/string';
|
|
4
|
+
import { getPluralName } from '../plural-registry.js';
|
|
5
|
+
import { dbKey } from '../db.js';
|
|
6
|
+
|
|
7
|
+
function getRelationshipInfo(property) {
|
|
8
|
+
if (typeof property !== 'function') return null;
|
|
9
|
+
const fnStr = property.toString();
|
|
10
|
+
|
|
11
|
+
if (fnStr.includes(`getRelationships('belongsTo',`)) return 'belongsTo';
|
|
12
|
+
if (fnStr.includes(`getRelationships('hasMany',`)) return 'hasMany';
|
|
13
|
+
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function introspectModels() {
|
|
18
|
+
const { models } = Orm.instance;
|
|
19
|
+
const schemas = {};
|
|
20
|
+
|
|
21
|
+
for (const [modelKey, modelClass] of Object.entries(models)) {
|
|
22
|
+
const name = camelCaseToKebabCase(modelKey.slice(0, -5));
|
|
23
|
+
|
|
24
|
+
if (name === dbKey) continue;
|
|
25
|
+
|
|
26
|
+
const model = new modelClass(modelKey);
|
|
27
|
+
const columns = {};
|
|
28
|
+
const foreignKeys = {};
|
|
29
|
+
const relationships = { belongsTo: {}, hasMany: {} };
|
|
30
|
+
let idType = 'number';
|
|
31
|
+
|
|
32
|
+
const transforms = Orm.instance.transforms;
|
|
33
|
+
|
|
34
|
+
for (const [key, property] of Object.entries(model)) {
|
|
35
|
+
if (key.startsWith('__')) continue;
|
|
36
|
+
|
|
37
|
+
const relType = getRelationshipInfo(property);
|
|
38
|
+
|
|
39
|
+
if (relType === 'belongsTo') {
|
|
40
|
+
relationships.belongsTo[key] = true;
|
|
41
|
+
} else if (relType === 'hasMany') {
|
|
42
|
+
relationships.hasMany[key] = true;
|
|
43
|
+
} else if (property?.constructor?.name === 'ModelProperty') {
|
|
44
|
+
if (key === 'id') {
|
|
45
|
+
idType = property.type;
|
|
46
|
+
} else {
|
|
47
|
+
columns[key] = getMysqlType(property.type, transforms[property.type]);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Build foreign keys from belongsTo relationships
|
|
53
|
+
for (const relName of Object.keys(relationships.belongsTo)) {
|
|
54
|
+
const modelName = camelCaseToKebabCase(relName);
|
|
55
|
+
const fkColumn = `${relName}_id`;
|
|
56
|
+
foreignKeys[fkColumn] = {
|
|
57
|
+
references: getPluralName(modelName),
|
|
58
|
+
column: 'id',
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
schemas[name] = {
|
|
63
|
+
table: getPluralName(name),
|
|
64
|
+
idType,
|
|
65
|
+
columns,
|
|
66
|
+
foreignKeys,
|
|
67
|
+
relationships,
|
|
68
|
+
memory: modelClass.memory !== false, // default true for backward compat
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return schemas;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function buildTableDDL(name, schema, allSchemas = {}) {
|
|
76
|
+
const { table, idType, columns, foreignKeys } = schema;
|
|
77
|
+
const lines = [];
|
|
78
|
+
|
|
79
|
+
// Primary key
|
|
80
|
+
if (idType === 'string') {
|
|
81
|
+
lines.push(' `id` VARCHAR(255) PRIMARY KEY');
|
|
82
|
+
} else {
|
|
83
|
+
lines.push(' `id` INT AUTO_INCREMENT PRIMARY KEY');
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Attribute columns
|
|
87
|
+
for (const [col, mysqlType] of Object.entries(columns)) {
|
|
88
|
+
lines.push(` \`${col}\` ${mysqlType}`);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Foreign key columns
|
|
92
|
+
for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
|
|
93
|
+
const refIdType = getReferencedIdType(fkDef.references, allSchemas);
|
|
94
|
+
lines.push(` \`${fkCol}\` ${refIdType}`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Timestamps
|
|
98
|
+
lines.push(' `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP');
|
|
99
|
+
lines.push(' `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
|
|
100
|
+
|
|
101
|
+
// Foreign key constraints
|
|
102
|
+
for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
|
|
103
|
+
lines.push(` FOREIGN KEY (\`${fkCol}\`) REFERENCES \`${fkDef.references}\`(\`${fkDef.column}\`) ON DELETE SET NULL`);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return `CREATE TABLE IF NOT EXISTS \`${table}\` (\n${lines.join(',\n')}\n)`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function getReferencedIdType(tableName, allSchemas) {
|
|
110
|
+
// Look up the referenced table's PK type from schemas
|
|
111
|
+
for (const schema of Object.values(allSchemas)) {
|
|
112
|
+
if (schema.table === tableName) {
|
|
113
|
+
return schema.idType === 'string' ? 'VARCHAR(255)' : 'INT';
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Default to INT if referenced table not found in schemas
|
|
118
|
+
return 'INT';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function getTopologicalOrder(schemas) {
|
|
122
|
+
const visited = new Set();
|
|
123
|
+
const order = [];
|
|
124
|
+
|
|
125
|
+
function visit(name) {
|
|
126
|
+
if (visited.has(name)) return;
|
|
127
|
+
visited.add(name);
|
|
128
|
+
|
|
129
|
+
const schema = schemas[name];
|
|
130
|
+
if (!schema) return;
|
|
131
|
+
|
|
132
|
+
// Visit dependencies (belongsTo targets) first
|
|
133
|
+
for (const relName of Object.keys(schema.relationships.belongsTo)) {
|
|
134
|
+
visit(camelCaseToKebabCase(relName));
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
order.push(name);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
for (const name of Object.keys(schemas)) {
|
|
141
|
+
visit(name);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return order;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function schemasToSnapshot(schemas) {
|
|
148
|
+
const snapshot = {};
|
|
149
|
+
|
|
150
|
+
for (const [name, schema] of Object.entries(schemas)) {
|
|
151
|
+
snapshot[name] = {
|
|
152
|
+
table: schema.table,
|
|
153
|
+
idType: schema.idType,
|
|
154
|
+
columns: { ...schema.columns },
|
|
155
|
+
foreignKeys: { ...schema.foreignKeys },
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return snapshot;
|
|
160
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const typeMap = {
|
|
2
|
+
string: 'VARCHAR(255)',
|
|
3
|
+
number: 'INT',
|
|
4
|
+
float: 'FLOAT',
|
|
5
|
+
boolean: 'TINYINT(1)',
|
|
6
|
+
date: 'DATETIME',
|
|
7
|
+
timestamp: 'BIGINT',
|
|
8
|
+
passthrough: 'TEXT',
|
|
9
|
+
trim: 'VARCHAR(255)',
|
|
10
|
+
uppercase: 'VARCHAR(255)',
|
|
11
|
+
ceil: 'INT',
|
|
12
|
+
floor: 'INT',
|
|
13
|
+
round: 'INT',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Resolves a Stonyx ORM attribute type to a MySQL column type.
|
|
18
|
+
*
|
|
19
|
+
* For built-in types, returns the mapped MySQL type directly.
|
|
20
|
+
*
|
|
21
|
+
* For custom transforms (e.g. an `animal` transform that maps strings to ints):
|
|
22
|
+
* - If the transform function exports a `mysqlType` property, that value is used.
|
|
23
|
+
* Example: `const transform = (v) => codeMap[v]; transform.mysqlType = 'INT'; export default transform;`
|
|
24
|
+
* - Otherwise, defaults to JSON. Values are JSON-stringified on write and
|
|
25
|
+
* JSON-parsed on read. This handles primitives and plain objects correctly.
|
|
26
|
+
* Class instances will be reduced to plain objects — if a custom transform
|
|
27
|
+
* produces class instances, it must declare a `mysqlType` and handle
|
|
28
|
+
* serialization itself.
|
|
29
|
+
*/
|
|
30
|
+
export function getMysqlType(attrType, transformFn) {
|
|
31
|
+
if (typeMap[attrType]) return typeMap[attrType];
|
|
32
|
+
if (transformFn?.mysqlType) return transformFn.mysqlType;
|
|
33
|
+
|
|
34
|
+
return 'JSON';
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export default typeMap;
|