@stonyx/orm 0.2.1-beta.9 → 0.2.1-beta.90

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