@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
@@ -1,118 +0,0 @@
1
- import Orm, { store, relationships } from '@stonyx/orm';
2
- import Record from './record.js';
3
-
4
- const defaultOptions = {
5
- isDbRecord: false,
6
- serialize: true,
7
- transform: true
8
- };
9
-
10
- export function createRecord(modelName, rawData={}, userOptions={}) {
11
- const orm = Orm.instance;
12
- const { initialized } = Orm;
13
- const options = { ...defaultOptions, ...userOptions };
14
-
15
- if (!initialized && !options.isDbRecord) throw new Error('ORM is not ready');
16
-
17
- const modelStore = store.get(modelName);
18
- const globalRelationships = relationships.get('global');
19
- const pendingRelationships = relationships.get('pending');
20
-
21
- assignRecordId(modelName, rawData);
22
- if (modelStore.has(rawData.id)) return modelStore.get(rawData.id);
23
-
24
- const { modelClass, serializerClass } = orm.getRecordClasses(modelName);
25
-
26
- if (!modelClass) throw new Error(`A model named '${modelName}' does not exist`);
27
-
28
- const model = new modelClass(modelName);
29
- const serializer = new serializerClass(model);
30
- const record = new Record(model, serializer);
31
-
32
- record.serialize(rawData, options);
33
- modelStore.set(record.id, record);
34
-
35
- // populate global hasMany relationships
36
- const globalHasMany = globalRelationships.get(modelName);
37
- if (globalHasMany) for (const relationship of globalHasMany) relationship.push(record);
38
-
39
- // populate pending hasMany relationships and clear the queue
40
- const pendingHasMany = pendingRelationships.get(modelName)?.get(record.id);
41
- if (pendingHasMany) {
42
- for (const relationship of pendingHasMany) relationship.push(record);
43
- pendingHasMany.splice(0);
44
- }
45
-
46
- // Fulfill pending belongsTo relationships
47
- const pendingBelongsToQueue = relationships.get('pendingBelongsTo');
48
- const pendingBelongsTo = pendingBelongsToQueue.get(modelName)?.get(record.id);
49
-
50
- if (pendingBelongsTo) {
51
- const belongsToReg = relationships.get('belongsTo');
52
- const hasManyReg = relationships.get('hasMany');
53
-
54
- for (const { sourceRecord, sourceModelName, relationshipKey, relationshipId } of pendingBelongsTo) {
55
- // Update the belongsTo relationship on the source record
56
- sourceRecord.__relationships[relationshipKey] = record;
57
- sourceRecord[relationshipKey] = record; // Also update the direct property
58
-
59
- // Update the belongsTo relationship registry
60
- const sourceModelReg = belongsToReg.get(sourceModelName);
61
- if (sourceModelReg) {
62
- const targetModelReg = sourceModelReg.get(modelName);
63
- if (targetModelReg) {
64
- targetModelReg.set(relationshipId, record);
65
- }
66
- }
67
-
68
- // Wire inverse hasMany if it exists
69
- const inverseHasMany = hasManyReg.get(modelName)?.get(sourceModelName)?.get(record.id);
70
-
71
- if (inverseHasMany && !inverseHasMany.includes(sourceRecord)) {
72
- inverseHasMany.push(sourceRecord);
73
- }
74
- }
75
-
76
- // Clear the pending queue
77
- pendingBelongsTo.length = 0;
78
- }
79
-
80
- return record;
81
- }
82
-
83
- export function updateRecord(record, rawData, userOptions={}) {
84
- if (!rawData) throw new Error('rawData must be passed in to updateRecord call');
85
-
86
- const options = { ...defaultOptions, ...userOptions, update:true };
87
-
88
- record.serialize(rawData, options);
89
- }
90
-
91
- /**
92
- * gets the next available id based on last record entry.
93
- *
94
- * In MySQL mode with numeric IDs, assigns a temporary pending ID.
95
- * MySQL's AUTO_INCREMENT provides the real ID after INSERT.
96
- */
97
- function assignRecordId(modelName, rawData) {
98
- if (rawData.id) return;
99
-
100
- // In MySQL mode with numeric IDs, defer to MySQL auto-increment
101
- if (Orm.instance?.mysqlDb && !isStringIdModel(modelName)) {
102
- rawData.id = `__pending_${Date.now()}_${Math.random()}`;
103
- rawData.__pendingMysqlId = true;
104
- return;
105
- }
106
-
107
- const modelStore = Array.from(store.get(modelName).values());
108
- rawData.id = modelStore.length ? modelStore.at(-1).id + 1 : 1;
109
- }
110
-
111
- function isStringIdModel(modelName) {
112
- const { modelClass } = Orm.instance.getRecordClasses(modelName);
113
- if (!modelClass) return false;
114
-
115
- const model = new modelClass(modelName);
116
-
117
- return model.id?.type === 'string';
118
- }
@@ -1,29 +0,0 @@
1
- import Orm from '@stonyx/orm';
2
-
3
- function validType(type) {
4
- return Object.keys(Orm.instance.transforms).includes(type);
5
- }
6
-
7
- export default class ModelProperty {
8
- constructor(type='passthrough', defaultValue) {
9
- if (!validType(type)) throw new Error(`Invalid model property type: ${type}`);
10
-
11
- this.type = type;
12
- this.value = defaultValue;
13
- }
14
-
15
- get value() {
16
- return this._value;
17
- }
18
-
19
- set value(newValue) {
20
- if (this.ignoreFirstTransform) {
21
- delete this.ignoreFirstTransform;
22
- return this._value = newValue;
23
- }
24
-
25
- if (newValue === undefined || newValue === null) return;
26
-
27
- this._value = Orm.instance.transforms[this.type](newValue);
28
- }
29
- }
package/src/model.js DELETED
@@ -1,9 +0,0 @@
1
- import { attr } from '@stonyx/orm';
2
-
3
- export default class Model {
4
- id = attr('number');
5
-
6
- constructor(name) {
7
- this.__name = name;
8
- }
9
- }
@@ -1,188 +0,0 @@
1
- import { introspectModels, buildTableDDL, schemasToSnapshot, getTopologicalOrder } from './schema-introspector.js';
2
- import { readFile, createFile, createDirectory, fileExists } from '@stonyx/utils/file';
3
- import path from 'path';
4
- import config from 'stonyx/config';
5
- import log from 'stonyx/log';
6
-
7
- export async function generateMigration(description = 'migration') {
8
- const { migrationsDir } = config.orm.mysql;
9
- const rootPath = config.rootPath;
10
- const migrationsPath = path.resolve(rootPath, migrationsDir);
11
-
12
- await createDirectory(migrationsPath);
13
-
14
- const schemas = introspectModels();
15
- const currentSnapshot = schemasToSnapshot(schemas);
16
- const previousSnapshot = await loadLatestSnapshot(migrationsPath);
17
- const diff = diffSnapshots(previousSnapshot, currentSnapshot);
18
-
19
- if (!diff.hasChanges) {
20
- log.db('No schema changes detected.');
21
- return null;
22
- }
23
-
24
- const upStatements = [];
25
- const downStatements = [];
26
-
27
- // New tables — in topological order (parents before children)
28
- const allOrder = getTopologicalOrder(schemas);
29
- const addedOrdered = allOrder.filter(name => diff.addedModels.includes(name));
30
-
31
- for (const name of addedOrdered) {
32
- upStatements.push(buildTableDDL(name, schemas[name], schemas) + ';');
33
- downStatements.unshift(`DROP TABLE IF EXISTS \`${schemas[name].table}\`;`);
34
- }
35
-
36
- // Removed tables (warn only, commented out)
37
- for (const name of diff.removedModels) {
38
- upStatements.push(`-- WARNING: Model '${name}' was removed. Uncomment to drop table:`);
39
- upStatements.push(`-- DROP TABLE IF EXISTS \`${previousSnapshot[name].table}\`;`);
40
- downStatements.push(`-- Recreate table for removed model '${name}' manually if needed`);
41
- }
42
-
43
- // Added columns
44
- for (const { model, column, type } of diff.addedColumns) {
45
- const table = currentSnapshot[model].table;
46
- upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
47
- downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
48
- }
49
-
50
- // Removed columns
51
- for (const { model, column, type } of diff.removedColumns) {
52
- const table = previousSnapshot[model].table;
53
- upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
54
- downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
55
- }
56
-
57
- // Changed column types
58
- for (const { model, column, from, to } of diff.changedColumns) {
59
- const table = currentSnapshot[model].table;
60
- upStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${to};`);
61
- downStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${from};`);
62
- }
63
-
64
- // Added foreign keys
65
- for (const { model, column, references } of diff.addedForeignKeys) {
66
- const table = currentSnapshot[model].table;
67
- // Resolve FK column type from the referenced table's PK type
68
- const refModel = Object.entries(currentSnapshot).find(([, s]) => s.table === references.references);
69
- const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
70
- upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
71
- upStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
72
- downStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
73
- downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
74
- }
75
-
76
- // Removed foreign keys
77
- for (const { model, column, references } of diff.removedForeignKeys) {
78
- const table = previousSnapshot[model].table;
79
- // Resolve FK column type from the referenced table's PK type in previous snapshot
80
- const refModel = Object.entries(previousSnapshot).find(([, s]) => s.table === references.references);
81
- const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
82
- upStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
83
- upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
84
- downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
85
- downStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
86
- }
87
-
88
- const sanitizedDescription = description.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
89
- const timestamp = Math.floor(Date.now() / 1000);
90
- const filename = `${timestamp}_${sanitizedDescription}.sql`;
91
- const content = `-- UP\n${upStatements.join('\n')}\n\n-- DOWN\n${downStatements.join('\n')}\n`;
92
-
93
- await createFile(path.join(migrationsPath, filename), content);
94
- await createFile(path.join(migrationsPath, '.snapshot.json'), JSON.stringify(currentSnapshot, null, 2));
95
-
96
- log.db(`Migration generated: ${filename}`);
97
-
98
- return { filename, content, snapshot: currentSnapshot };
99
- }
100
-
101
- export async function loadLatestSnapshot(migrationsPath) {
102
- const snapshotPath = path.join(migrationsPath, '.snapshot.json');
103
- const exists = await fileExists(snapshotPath);
104
-
105
- if (!exists) return {};
106
-
107
- return readFile(snapshotPath, { json: true });
108
- }
109
-
110
- export function diffSnapshots(previous, current) {
111
- const addedModels = [];
112
- const removedModels = [];
113
- const addedColumns = [];
114
- const removedColumns = [];
115
- const changedColumns = [];
116
- const addedForeignKeys = [];
117
- const removedForeignKeys = [];
118
-
119
- // Find added models
120
- for (const name of Object.keys(current)) {
121
- if (!previous[name]) addedModels.push(name);
122
- }
123
-
124
- // Find removed models
125
- for (const name of Object.keys(previous)) {
126
- if (!current[name]) removedModels.push(name);
127
- }
128
-
129
- // Find column changes in existing models
130
- for (const name of Object.keys(current)) {
131
- if (!previous[name]) continue;
132
-
133
- const { columns: prevCols = {} } = previous[name];
134
- const { columns: currCols = {} } = current[name];
135
-
136
- // Added columns
137
- for (const [col, type] of Object.entries(currCols)) {
138
- if (!prevCols[col]) {
139
- addedColumns.push({ model: name, column: col, type });
140
- } else if (prevCols[col] !== type) {
141
- changedColumns.push({ model: name, column: col, from: prevCols[col], to: type });
142
- }
143
- }
144
-
145
- // Removed columns
146
- for (const [col, type] of Object.entries(prevCols)) {
147
- if (!currCols[col]) {
148
- removedColumns.push({ model: name, column: col, type });
149
- }
150
- }
151
-
152
- // Foreign key changes
153
- const prevFKs = previous[name].foreignKeys || {};
154
- const currFKs = current[name].foreignKeys || {};
155
-
156
- for (const [col, refs] of Object.entries(currFKs)) {
157
- if (!prevFKs[col]) {
158
- addedForeignKeys.push({ model: name, column: col, references: refs });
159
- }
160
- }
161
-
162
- for (const [col, refs] of Object.entries(prevFKs)) {
163
- if (!currFKs[col]) {
164
- removedForeignKeys.push({ model: name, column: col, references: refs });
165
- }
166
- }
167
- }
168
-
169
- const hasChanges = addedModels.length > 0 || removedModels.length > 0 ||
170
- addedColumns.length > 0 || removedColumns.length > 0 ||
171
- changedColumns.length > 0 || addedForeignKeys.length > 0 || removedForeignKeys.length > 0;
172
-
173
- return {
174
- hasChanges,
175
- addedModels,
176
- removedModels,
177
- addedColumns,
178
- removedColumns,
179
- changedColumns,
180
- addedForeignKeys,
181
- removedForeignKeys,
182
- };
183
- }
184
-
185
- export function detectSchemaDrift(schemas, snapshot) {
186
- const current = schemasToSnapshot(schemas);
187
- return diffSnapshots(snapshot, current);
188
- }
@@ -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
- }