@stonyx/orm 0.2.1-alpha.4 → 0.2.1-alpha.40

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 +47 -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} +25 -27
  103. package/src/{index.js → index.ts} +8 -5
  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} +196 -103
  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 +30 -0
  136. package/src/types/orm-types.ts +146 -0
  137. package/src/types/pg.d.ts +28 -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 +11 -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 -159
  157. package/src/manage-record.js +0 -118
  158. package/src/model-property.js +0 -29
  159. package/src/model.js +0 -19
  160. package/src/mysql/migration-generator.js +0 -188
  161. package/src/mysql/mysql-db.js +0 -422
  162. package/src/mysql/schema-introspector.js +0 -159
  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 -316
  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
@@ -1,422 +0,0 @@
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 { pluralize } from '../utils.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, pluralize, 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
- }
@@ -1,159 +0,0 @@
1
- import Orm from '@stonyx/orm';
2
- import { getMysqlType } from './type-map.js';
3
- import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
- import { pluralize } from '../utils.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 fkColumn = `${relName}_id`;
55
- foreignKeys[fkColumn] = {
56
- references: pluralize(relName),
57
- column: 'id',
58
- };
59
- }
60
-
61
- schemas[name] = {
62
- table: pluralize(name),
63
- idType,
64
- columns,
65
- foreignKeys,
66
- relationships,
67
- memory: modelClass.memory !== false, // default true for backward compat
68
- };
69
- }
70
-
71
- return schemas;
72
- }
73
-
74
- export function buildTableDDL(name, schema, allSchemas = {}) {
75
- const { table, idType, columns, foreignKeys } = schema;
76
- const lines = [];
77
-
78
- // Primary key
79
- if (idType === 'string') {
80
- lines.push(' `id` VARCHAR(255) PRIMARY KEY');
81
- } else {
82
- lines.push(' `id` INT AUTO_INCREMENT PRIMARY KEY');
83
- }
84
-
85
- // Attribute columns
86
- for (const [col, mysqlType] of Object.entries(columns)) {
87
- lines.push(` \`${col}\` ${mysqlType}`);
88
- }
89
-
90
- // Foreign key columns
91
- for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
92
- const refIdType = getReferencedIdType(fkDef.references, allSchemas);
93
- lines.push(` \`${fkCol}\` ${refIdType}`);
94
- }
95
-
96
- // Timestamps
97
- lines.push(' `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP');
98
- lines.push(' `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
99
-
100
- // Foreign key constraints
101
- for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
102
- lines.push(` FOREIGN KEY (\`${fkCol}\`) REFERENCES \`${fkDef.references}\`(\`${fkDef.column}\`) ON DELETE SET NULL`);
103
- }
104
-
105
- return `CREATE TABLE IF NOT EXISTS \`${table}\` (\n${lines.join(',\n')}\n)`;
106
- }
107
-
108
- function getReferencedIdType(tableName, allSchemas) {
109
- // Look up the referenced table's PK type from schemas
110
- for (const schema of Object.values(allSchemas)) {
111
- if (schema.table === tableName) {
112
- return schema.idType === 'string' ? 'VARCHAR(255)' : 'INT';
113
- }
114
- }
115
-
116
- // Default to INT if referenced table not found in schemas
117
- return 'INT';
118
- }
119
-
120
- export function getTopologicalOrder(schemas) {
121
- const visited = new Set();
122
- const order = [];
123
-
124
- function visit(name) {
125
- if (visited.has(name)) return;
126
- visited.add(name);
127
-
128
- const schema = schemas[name];
129
- if (!schema) return;
130
-
131
- // Visit dependencies (belongsTo targets) first
132
- for (const relName of Object.keys(schema.relationships.belongsTo)) {
133
- visit(relName);
134
- }
135
-
136
- order.push(name);
137
- }
138
-
139
- for (const name of Object.keys(schemas)) {
140
- visit(name);
141
- }
142
-
143
- return order;
144
- }
145
-
146
- export function schemasToSnapshot(schemas) {
147
- const snapshot = {};
148
-
149
- for (const [name, schema] of Object.entries(schemas)) {
150
- snapshot[name] = {
151
- table: schema.table,
152
- idType: schema.idType,
153
- columns: { ...schema.columns },
154
- foreignKeys: { ...schema.foreignKeys },
155
- };
156
- }
157
-
158
- return snapshot;
159
- }
package/src/record.js DELETED
@@ -1,127 +0,0 @@
1
- import { store } from './index.js';
2
- import { getComputedProperties } from "./serializer.js";
3
- import { camelCaseToKebabCase } from '@stonyx/utils/string';
4
- import { pluralize } from './utils.js';
5
- export default class Record {
6
- __data = {};
7
- __relationships = {};
8
- __serialized = false;
9
-
10
- constructor(model, serializer) {
11
- this.__model = model;
12
- this.__serializer = serializer;
13
-
14
- }
15
-
16
- serialize(rawData, options={}) {
17
- const { __data:data } = this;
18
-
19
- if (this.__serialized && !options.update) {
20
- const relatedIds = {};
21
-
22
- for (const [ key, childRecord ] of Object.entries(this.__relationships)) {
23
- relatedIds[key] = Array.isArray(childRecord)
24
- ? childRecord.map(r => r.id)
25
- : childRecord?.id ?? null;
26
- }
27
-
28
- return { ...data, ...relatedIds };
29
- }
30
-
31
- const normalizedData = this.__serializer.normalize(rawData);
32
- this.__serializer.setProperties(normalizedData, this, options);
33
-
34
- return data;
35
- }
36
-
37
- // Similar to serialize, but preserves top level relationship records
38
- format() {
39
- if (!this.__serialized) throw new Error('Record must be serialized before being converted to JSON');
40
-
41
- const { __data:data } = this;
42
- const records = {};
43
-
44
- for (const [ key, childRecord ] of Object.entries(this.__relationships)) {
45
- records[key] = Array.isArray(childRecord)
46
- ? childRecord.map(r => r.serialize())
47
- : childRecord?.serialize() ?? null;
48
- }
49
-
50
- return { ...data, ...records };
51
- }
52
-
53
- // Formats record for JSON API output
54
- toJSON(options = {}) {
55
- if (!this.__serialized) throw new Error('Record must be serialized before being converted to JSON');
56
-
57
- const { fields, baseUrl } = options;
58
- const { __data:data } = this;
59
- const modelName = this.__model.__name;
60
- const pluralizedModelName = pluralize(modelName);
61
- const recordId = data.id;
62
- const relationships = {};
63
- const attributes = {};
64
-
65
- for (const [key, value] of Object.entries(data)) {
66
- if (key === 'id') continue;
67
- if (fields && !fields.has(key)) continue;
68
- attributes[key] = value;
69
- }
70
-
71
- for (const [key, getter] of getComputedProperties(this.__model)) {
72
- if (fields && !fields.has(key)) continue;
73
- attributes[key] = getter.call(this);
74
- }
75
-
76
- for (const [key, childRecord] of Object.entries(this.__relationships)) {
77
- if (fields && !fields.has(key)) continue;
78
-
79
- const relationshipData = Array.isArray(childRecord)
80
- ? childRecord.map(r => ({ type: r.__model.__name, id: r.id }))
81
- : childRecord ? { type: childRecord.__model.__name, id: childRecord.id } : null;
82
-
83
- // Dasherize the key for URL paths (e.g., accessLinks -> access-links)
84
- const dasherizedKey = camelCaseToKebabCase(key);
85
-
86
- relationships[dasherizedKey] = { data: relationshipData };
87
-
88
- // Add links to relationship if baseUrl provided
89
- if (baseUrl) {
90
- relationships[dasherizedKey].links = {
91
- self: `${baseUrl}/${pluralizedModelName}/${recordId}/relationships/${dasherizedKey}`,
92
- related: `${baseUrl}/${pluralizedModelName}/${recordId}/${dasherizedKey}`
93
- };
94
- }
95
- }
96
-
97
- const result = {
98
- attributes,
99
- relationships,
100
- id: recordId,
101
- type: modelName,
102
- };
103
-
104
- // Add resource links if baseUrl provided
105
- if (baseUrl) {
106
- result.links = {
107
- self: `${baseUrl}/${pluralizedModelName}/${recordId}`
108
- };
109
- }
110
-
111
- return result;
112
- }
113
-
114
- unload(options={}) {
115
- store.unloadRecord(this.__model.__name, this.id, options);
116
- }
117
-
118
- clean() {
119
- try {
120
- for (const key of Object.keys(this)) {
121
- delete this[key];
122
- }
123
- } catch {
124
- // Ignore errors during cleanup, as some keys may not be deletable
125
- }
126
- }
127
- }