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

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 (175) 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 +75 -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 +257 -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 +475 -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 +28 -0
  64. package/dist/postgres/schema-introspector.js +280 -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/schema-helpers.d.ts +20 -0
  72. package/dist/schema-helpers.js +48 -0
  73. package/dist/serializer.d.ts +17 -0
  74. package/dist/serializer.js +136 -0
  75. package/dist/setup-rest-server.d.ts +1 -0
  76. package/dist/setup-rest-server.js +52 -0
  77. package/dist/standalone-db.d.ts +58 -0
  78. package/dist/standalone-db.js +142 -0
  79. package/dist/store.d.ts +62 -0
  80. package/dist/store.js +286 -0
  81. package/dist/timescale/query-builder.d.ts +43 -0
  82. package/dist/timescale/query-builder.js +115 -0
  83. package/dist/timescale/timescale-db.d.ts +45 -0
  84. package/dist/timescale/timescale-db.js +84 -0
  85. package/dist/transforms.d.ts +2 -0
  86. package/dist/transforms.js +17 -0
  87. package/dist/types/orm-types.d.ts +142 -0
  88. package/dist/types/orm-types.js +1 -0
  89. package/dist/utils.d.ts +7 -0
  90. package/dist/utils.js +17 -0
  91. package/dist/view-resolver.d.ts +8 -0
  92. package/dist/view-resolver.js +171 -0
  93. package/dist/view.d.ts +11 -0
  94. package/dist/view.js +18 -0
  95. package/package.json +57 -15
  96. package/src/aggregates.ts +109 -0
  97. package/src/{attr.js → attr.ts} +2 -2
  98. package/src/belongs-to.ts +90 -0
  99. package/src/cli.ts +183 -0
  100. package/src/{commands.js → commands.ts} +179 -170
  101. package/src/{db.js → db.ts} +55 -29
  102. package/src/exports/db.ts +7 -0
  103. package/src/has-many.ts +92 -0
  104. package/src/hooks.ts +151 -0
  105. package/src/{index.js → index.ts} +11 -2
  106. package/src/main.ts +229 -0
  107. package/src/manage-record.ts +161 -0
  108. package/src/{meta-request.js → meta-request.ts} +17 -14
  109. package/src/{migrate.js → migrate.ts} +9 -9
  110. package/src/model-property.ts +35 -0
  111. package/src/model.ts +21 -0
  112. package/src/mysql/{connection.js → connection.ts} +43 -28
  113. package/src/mysql/migration-generator.ts +337 -0
  114. package/src/mysql/{migration-runner.js → migration-runner.ts} +121 -110
  115. package/src/mysql/mysql-db.ts +543 -0
  116. package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
  117. package/src/mysql/schema-introspector.ts +310 -0
  118. package/src/mysql/{type-map.js → type-map.ts} +42 -37
  119. package/src/{orm-request.js → orm-request.ts} +187 -108
  120. package/src/plural-registry.ts +12 -0
  121. package/src/postgres/connection.ts +48 -0
  122. package/src/postgres/migration-generator.ts +348 -0
  123. package/src/postgres/migration-runner.ts +115 -0
  124. package/src/postgres/postgres-db.ts +616 -0
  125. package/src/postgres/query-builder.ts +148 -0
  126. package/src/postgres/schema-introspector.ts +343 -0
  127. package/src/postgres/type-map.ts +61 -0
  128. package/src/record.ts +186 -0
  129. package/src/relationships.ts +54 -0
  130. package/src/schema-helpers.ts +59 -0
  131. package/src/serializer.ts +161 -0
  132. package/src/{setup-rest-server.js → setup-rest-server.ts} +18 -16
  133. package/src/standalone-db.ts +185 -0
  134. package/src/store.ts +373 -0
  135. package/src/timescale/query-builder.ts +174 -0
  136. package/src/timescale/timescale-db.ts +119 -0
  137. package/src/transforms.ts +20 -0
  138. package/src/types/mysql2.d.ts +49 -0
  139. package/src/types/orm-types.ts +146 -0
  140. package/src/types/pg.d.ts +32 -0
  141. package/src/types/stonyx-cron.d.ts +5 -0
  142. package/src/types/stonyx-events.d.ts +4 -0
  143. package/src/types/stonyx-rest-server.d.ts +16 -0
  144. package/src/types/stonyx-utils.d.ts +33 -0
  145. package/src/types/stonyx.d.ts +21 -0
  146. package/src/utils.ts +22 -0
  147. package/src/view-resolver.ts +211 -0
  148. package/src/view.ts +22 -0
  149. package/.claude/code-style-rules.md +0 -44
  150. package/.claude/hooks.md +0 -250
  151. package/.claude/index.md +0 -279
  152. package/.claude/usage-patterns.md +0 -217
  153. package/.github/workflows/ci.yml +0 -16
  154. package/.github/workflows/publish.yml +0 -51
  155. package/improvements.md +0 -139
  156. package/project-structure.md +0 -343
  157. package/src/belongs-to.js +0 -63
  158. package/src/has-many.js +0 -61
  159. package/src/hooks.js +0 -124
  160. package/src/main.js +0 -148
  161. package/src/manage-record.js +0 -118
  162. package/src/model-property.js +0 -29
  163. package/src/model.js +0 -9
  164. package/src/mysql/migration-generator.js +0 -188
  165. package/src/mysql/mysql-db.js +0 -320
  166. package/src/mysql/schema-introspector.js +0 -158
  167. package/src/record.js +0 -127
  168. package/src/relationships.js +0 -43
  169. package/src/serializer.js +0 -138
  170. package/src/store.js +0 -211
  171. package/src/transforms.js +0 -20
  172. package/src/utils.js +0 -12
  173. package/test-events-setup.js +0 -41
  174. package/test-hooks-manual.js +0 -54
  175. package/test-hooks-with-logging.js +0 -52
@@ -1,320 +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.loadAllRecords();
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.loadAllRecords();
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.loadAllRecords();
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
- async loadAllRecords() {
115
- const schemas = this.deps.introspectModels();
116
- const order = this.deps.getTopologicalOrder(schemas);
117
-
118
- for (const modelName of order) {
119
- const schema = schemas[modelName];
120
- const { sql, values } = this.deps.buildSelect(schema.table);
121
-
122
- try {
123
- const [rows] = await this.pool.execute(sql, values);
124
-
125
- for (const row of rows) {
126
- const rawData = this._rowToRawData(row, schema);
127
- this.deps.createRecord(modelName, rawData, { isDbRecord: true, serialize: false, transform: false });
128
- }
129
- } catch (error) {
130
- // Table may not exist yet (pre-migration) — skip gracefully
131
- if (error.code === 'ER_NO_SUCH_TABLE') {
132
- this.deps.log.db(`Table '${schema.table}' does not exist yet. Skipping load for '${modelName}'.`);
133
- continue;
134
- }
135
-
136
- throw error;
137
- }
138
- }
139
-
140
- }
141
-
142
- _rowToRawData(row, schema) {
143
- const rawData = { ...row };
144
-
145
- for (const [col, mysqlType] of Object.entries(schema.columns)) {
146
- if (rawData[col] == null) continue;
147
-
148
- // Convert boolean columns from MySQL TINYINT(1) 0/1 to false/true
149
- if (mysqlType === 'TINYINT(1)') {
150
- rawData[col] = !!rawData[col];
151
- }
152
-
153
- // Parse JSON columns back to JS values (custom transforms stored as JSON)
154
- if (mysqlType === 'JSON' && typeof rawData[col] === 'string') {
155
- try { rawData[col] = JSON.parse(rawData[col]); } catch { /* keep raw string */ }
156
- }
157
- }
158
-
159
- // Map FK columns back to relationship keys
160
- // e.g., owner_id → owner (the belongsTo handler expects the id value under the relationship key name)
161
- for (const [fkCol, fkDef] of Object.entries(schema.foreignKeys)) {
162
- const relName = fkCol.replace(/_id$/, '');
163
-
164
- if (rawData[fkCol] !== undefined) {
165
- rawData[relName] = rawData[fkCol];
166
- delete rawData[fkCol];
167
- }
168
- }
169
-
170
- // Remove timestamp columns — managed by MySQL
171
- delete rawData.created_at;
172
- delete rawData.updated_at;
173
-
174
- return rawData;
175
- }
176
-
177
- async persist(operation, modelName, context, response) {
178
- switch (operation) {
179
- case 'create':
180
- return this._persistCreate(modelName, context, response);
181
- case 'update':
182
- return this._persistUpdate(modelName, context, response);
183
- case 'delete':
184
- return this._persistDelete(modelName, context);
185
- }
186
- }
187
-
188
- async _persistCreate(modelName, context, response) {
189
- const schemas = this.deps.introspectModels();
190
- const schema = schemas[modelName];
191
-
192
- if (!schema) return;
193
-
194
- const recordId = response?.data?.id;
195
- const record = recordId != null ? this.deps.store.get(modelName, isNaN(recordId) ? recordId : parseInt(recordId)) : null;
196
-
197
- if (!record) return;
198
-
199
- const insertData = this._recordToRow(record, schema);
200
-
201
- // For auto-increment models, remove the pending ID
202
- const isPendingId = record.__data.__pendingMysqlId;
203
-
204
- if (isPendingId) {
205
- delete insertData.id;
206
- } else if (insertData.id !== undefined) {
207
- // Keep user-provided ID (string IDs or explicit numeric IDs)
208
- }
209
-
210
- const { sql, values } = this.deps.buildInsert(schema.table, insertData);
211
-
212
- const [result] = await this.pool.execute(sql, values);
213
-
214
- // Re-key the record in the store if MySQL generated the ID
215
- if (isPendingId && result.insertId) {
216
- const pendingId = record.id;
217
- const realId = result.insertId;
218
- const modelStore = this.deps.store.get(modelName);
219
-
220
- modelStore.delete(pendingId);
221
- record.__data.id = realId;
222
- record.id = realId;
223
- modelStore.set(realId, record);
224
-
225
- // Update the response data with the real ID
226
- if (response?.data) {
227
- response.data.id = realId;
228
- }
229
-
230
- delete record.__data.__pendingMysqlId;
231
- }
232
- }
233
-
234
- async _persistUpdate(modelName, context, response) {
235
- const schemas = this.deps.introspectModels();
236
- const schema = schemas[modelName];
237
-
238
- if (!schema) return;
239
-
240
- const record = context.record;
241
- if (!record) return;
242
-
243
- const id = record.id;
244
- const oldState = context.oldState || {};
245
- const currentData = record.__data;
246
-
247
- // Build a diff of changed columns
248
- const changedData = {};
249
-
250
- for (const [col] of Object.entries(schema.columns)) {
251
- if (currentData[col] !== oldState[col]) {
252
- changedData[col] = currentData[col] ?? null;
253
- }
254
- }
255
-
256
- // Check FK changes too
257
- for (const fkCol of Object.keys(schema.foreignKeys)) {
258
- const relName = fkCol.replace(/_id$/, '');
259
- const currentFkValue = record.__relationships[relName]?.id ?? null;
260
- const oldFkValue = oldState[relName] ?? null;
261
-
262
- if (currentFkValue !== oldFkValue) {
263
- changedData[fkCol] = currentFkValue;
264
- }
265
- }
266
-
267
- if (Object.keys(changedData).length === 0) return;
268
-
269
- const { sql, values } = this.deps.buildUpdate(schema.table, id, changedData);
270
- await this.pool.execute(sql, values);
271
- }
272
-
273
- async _persistDelete(modelName, context) {
274
- const schemas = this.deps.introspectModels();
275
- const schema = schemas[modelName];
276
-
277
- if (!schema) return;
278
-
279
- const id = context.recordId;
280
- if (id == null) return;
281
-
282
- const { sql, values } = this.deps.buildDelete(schema.table, id);
283
- await this.pool.execute(sql, values);
284
- }
285
-
286
- _recordToRow(record, schema) {
287
- const row = {};
288
- const data = record.__data;
289
-
290
- // ID
291
- if (data.id !== undefined) {
292
- row.id = data.id;
293
- }
294
-
295
- // Attribute columns
296
- for (const [col, mysqlType] of Object.entries(schema.columns)) {
297
- if (data[col] !== undefined) {
298
- // JSON columns: stringify non-string values for MySQL JSON storage
299
- row[col] = mysqlType === 'JSON' && typeof data[col] !== 'string'
300
- ? JSON.stringify(data[col])
301
- : data[col];
302
- }
303
- }
304
-
305
- // FK columns from relationships
306
- for (const fkCol of Object.keys(schema.foreignKeys)) {
307
- const relName = fkCol.replace(/_id$/, '');
308
- const related = record.__relationships[relName];
309
-
310
- if (related) {
311
- row[fkCol] = related.id;
312
- } else if (data[relName] !== undefined) {
313
- // Raw FK value (e.g., from create payload)
314
- row[fkCol] = data[relName];
315
- }
316
- }
317
-
318
- return row;
319
- }
320
- }
@@ -1,158 +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
- };
68
- }
69
-
70
- return schemas;
71
- }
72
-
73
- export function buildTableDDL(name, schema, allSchemas = {}) {
74
- const { table, idType, columns, foreignKeys } = schema;
75
- const lines = [];
76
-
77
- // Primary key
78
- if (idType === 'string') {
79
- lines.push(' `id` VARCHAR(255) PRIMARY KEY');
80
- } else {
81
- lines.push(' `id` INT AUTO_INCREMENT PRIMARY KEY');
82
- }
83
-
84
- // Attribute columns
85
- for (const [col, mysqlType] of Object.entries(columns)) {
86
- lines.push(` \`${col}\` ${mysqlType}`);
87
- }
88
-
89
- // Foreign key columns
90
- for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
91
- const refIdType = getReferencedIdType(fkDef.references, allSchemas);
92
- lines.push(` \`${fkCol}\` ${refIdType}`);
93
- }
94
-
95
- // Timestamps
96
- lines.push(' `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP');
97
- lines.push(' `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP');
98
-
99
- // Foreign key constraints
100
- for (const [fkCol, fkDef] of Object.entries(foreignKeys)) {
101
- lines.push(` FOREIGN KEY (\`${fkCol}\`) REFERENCES \`${fkDef.references}\`(\`${fkDef.column}\`) ON DELETE SET NULL`);
102
- }
103
-
104
- return `CREATE TABLE IF NOT EXISTS \`${table}\` (\n${lines.join(',\n')}\n)`;
105
- }
106
-
107
- function getReferencedIdType(tableName, allSchemas) {
108
- // Look up the referenced table's PK type from schemas
109
- for (const schema of Object.values(allSchemas)) {
110
- if (schema.table === tableName) {
111
- return schema.idType === 'string' ? 'VARCHAR(255)' : 'INT';
112
- }
113
- }
114
-
115
- // Default to INT if referenced table not found in schemas
116
- return 'INT';
117
- }
118
-
119
- export function getTopologicalOrder(schemas) {
120
- const visited = new Set();
121
- const order = [];
122
-
123
- function visit(name) {
124
- if (visited.has(name)) return;
125
- visited.add(name);
126
-
127
- const schema = schemas[name];
128
- if (!schema) return;
129
-
130
- // Visit dependencies (belongsTo targets) first
131
- for (const relName of Object.keys(schema.relationships.belongsTo)) {
132
- visit(relName);
133
- }
134
-
135
- order.push(name);
136
- }
137
-
138
- for (const name of Object.keys(schemas)) {
139
- visit(name);
140
- }
141
-
142
- return order;
143
- }
144
-
145
- export function schemasToSnapshot(schemas) {
146
- const snapshot = {};
147
-
148
- for (const [name, schema] of Object.entries(schemas)) {
149
- snapshot[name] = {
150
- table: schema.table,
151
- idType: schema.idType,
152
- columns: { ...schema.columns },
153
- foreignKeys: { ...schema.foreignKeys },
154
- };
155
- }
156
-
157
- return snapshot;
158
- }
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
- }
@@ -1,43 +0,0 @@
1
- import { relationships } from "@stonyx/orm";
2
-
3
- export default class Relationships {
4
- constructor() {
5
- if (Relationships.instance) return Relationships.instance;
6
- Relationships.instance = this;
7
-
8
- this.data = new Map();
9
- }
10
-
11
- get(key) {
12
- return this.data.get(key);
13
- }
14
-
15
- set(key, value) {
16
- this.data.set(key, value);
17
- }
18
- }
19
-
20
- // TODO: Refactor mapping to remove a level of iteration
21
- export function getRelationships(type, sourceModel, targetModel, relationshipId) {
22
- const allRelationships = relationships.get(type);
23
-
24
- // create relationship map for this type of it doesn't already exist
25
- if (!allRelationships.has(sourceModel)) allRelationships.set(sourceModel, new Map());
26
-
27
- const modelRelationship = allRelationships.get(sourceModel);
28
-
29
- if (!modelRelationship.has(targetModel)) modelRelationship.set(targetModel, new Map());
30
-
31
- const relationship = modelRelationship.get(targetModel);
32
-
33
- // TODO: Determine whether already having id should be handled differently
34
- //if (relationship.has(relationshipId)) return;
35
-
36
- return relationship;
37
- }
38
-
39
- export function getHasManyRelationships(sourceModel, targetModel) {
40
- return relationships.get('hasMany').get(sourceModel)?.get(targetModel);
41
- }
42
-
43
- export const TYPES = ['global', 'hasMany', 'belongsTo', 'pending'];