@stonyx/orm 0.2.7-alpha.0 → 0.3.2-alpha.0

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 (166) hide show
  1. package/README.md +482 -15
  2. package/config/environment.js +63 -6
  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 +39 -0
  23. package/dist/main.d.ts +62 -0
  24. package/dist/main.js +231 -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 +280 -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 +296 -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 +153 -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 +64 -11
  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.ts +179 -0
  101. package/src/db.ts +232 -0
  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} +17 -2
  106. package/src/main.ts +288 -0
  107. package/src/manage-record.ts +161 -0
  108. package/src/{meta-request.js → meta-request.ts} +17 -14
  109. package/src/migrate.ts +72 -0
  110. package/src/model-property.ts +35 -0
  111. package/src/model.ts +21 -0
  112. package/src/mysql/connection.ts +43 -0
  113. package/src/mysql/migration-generator.ts +337 -0
  114. package/src/mysql/migration-runner.ts +121 -0
  115. package/src/mysql/mysql-db.ts +543 -0
  116. package/src/mysql/query-builder.ts +69 -0
  117. package/src/mysql/schema-introspector.ts +310 -0
  118. package/src/mysql/type-map.ts +42 -0
  119. package/src/orm-request.ts +582 -0
  120. package/src/plural-registry.ts +12 -0
  121. package/src/postgres/connection.ts +48 -0
  122. package/src/postgres/migration-generator.ts +370 -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 +360 -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.ts +62 -0
  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 +158 -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/project-structure.md +0 -578
  150. package/.github/workflows/ci.yml +0 -36
  151. package/.github/workflows/publish.yml +0 -143
  152. package/src/belongs-to.js +0 -63
  153. package/src/db.js +0 -80
  154. package/src/has-many.js +0 -61
  155. package/src/main.js +0 -119
  156. package/src/manage-record.js +0 -103
  157. package/src/model-property.js +0 -29
  158. package/src/model.js +0 -9
  159. package/src/orm-request.js +0 -249
  160. package/src/record.js +0 -100
  161. package/src/relationships.js +0 -43
  162. package/src/serializer.js +0 -138
  163. package/src/setup-rest-server.js +0 -57
  164. package/src/store.js +0 -211
  165. package/src/transforms.js +0 -20
  166. package/stonyx-bootstrap.cjs +0 -30
@@ -0,0 +1,337 @@
1
+ import { introspectModels, introspectViews, buildTableDDL, buildViewDDL, schemasToSnapshot, viewSchemasToSnapshot, getTopologicalOrder } from './schema-introspector.js';
2
+ import type { ModelSchema, SnapshotEntry, ViewSnapshotEntry, ForeignKeyDef } from './schema-introspector.js';
3
+ import { readFile, createFile, createDirectory, fileExists } from '@stonyx/utils/file';
4
+ import path from 'path';
5
+ import config from 'stonyx/config';
6
+ import log from 'stonyx/log';
7
+
8
+ interface ColumnChange {
9
+ model: string;
10
+ column: string;
11
+ type: string;
12
+ }
13
+
14
+ interface ColumnTypeChange {
15
+ model: string;
16
+ column: string;
17
+ from: string;
18
+ to: string;
19
+ }
20
+
21
+ interface ForeignKeyChange {
22
+ model: string;
23
+ column: string;
24
+ references: ForeignKeyDef;
25
+ }
26
+
27
+ interface SnapshotDiff {
28
+ hasChanges: boolean;
29
+ addedModels: string[];
30
+ removedModels: string[];
31
+ addedColumns: ColumnChange[];
32
+ removedColumns: ColumnChange[];
33
+ changedColumns: ColumnTypeChange[];
34
+ addedForeignKeys: ForeignKeyChange[];
35
+ removedForeignKeys: ForeignKeyChange[];
36
+ }
37
+
38
+ interface ViewDiff {
39
+ hasChanges: boolean;
40
+ addedViews: string[];
41
+ removedViews: string[];
42
+ changedViews: string[];
43
+ }
44
+
45
+ interface GeneratedMigration {
46
+ filename: string;
47
+ content: string;
48
+ snapshot: Record<string, SnapshotEntry | ViewSnapshotEntry>;
49
+ }
50
+
51
+ type Snapshot = Record<string, SnapshotEntry & { isView?: boolean; viewName?: string; viewQuery?: string; source?: string }>;
52
+
53
+ export async function generateMigration(description: string = 'migration'): Promise<GeneratedMigration | null> {
54
+ const mysqlConfig = config.orm.mysql;
55
+ if (!mysqlConfig) throw new Error('MySQL configuration (config.orm.mysql) is required for migration generation');
56
+ const { migrationsDir } = mysqlConfig;
57
+ if (!migrationsDir) throw new Error('MySQL migrationsDir is required in config');
58
+ const rootPath = config.rootPath;
59
+ const migrationsPath = path.resolve(rootPath, migrationsDir);
60
+
61
+ await createDirectory(migrationsPath);
62
+
63
+ const schemas = introspectModels();
64
+ const currentSnapshot = schemasToSnapshot(schemas);
65
+ const previousSnapshot = await loadLatestSnapshot(migrationsPath) as Snapshot;
66
+ const diff = diffSnapshots(previousSnapshot, currentSnapshot);
67
+
68
+ // Don't return early — check view changes too before deciding
69
+ if (!diff.hasChanges) {
70
+ // Check if there are view changes before returning null
71
+ const viewSchemasPrelim = introspectViews();
72
+ const currentViewSnapshotPrelim = viewSchemasToSnapshot(viewSchemasPrelim);
73
+ const previousViewSnapshotPrelim = extractViewsFromSnapshot(previousSnapshot);
74
+ const viewDiffPrelim = diffViewSnapshots(previousViewSnapshotPrelim, currentViewSnapshotPrelim);
75
+
76
+ if (!viewDiffPrelim.hasChanges) {
77
+ log.db?.('No schema changes detected.');
78
+ return null;
79
+ }
80
+ }
81
+
82
+ const upStatements: string[] = [];
83
+ const downStatements: string[] = [];
84
+
85
+ // New tables — in topological order (parents before children)
86
+ const allOrder = getTopologicalOrder(schemas);
87
+ const addedOrdered = allOrder.filter(name => diff.addedModels.includes(name));
88
+
89
+ for (const name of addedOrdered) {
90
+ upStatements.push(buildTableDDL(name, schemas[name], schemas) + ';');
91
+ downStatements.unshift(`DROP TABLE IF EXISTS \`${schemas[name].table}\`;`);
92
+ }
93
+
94
+ // Removed tables (warn only, commented out)
95
+ for (const name of diff.removedModels) {
96
+ upStatements.push(`-- WARNING: Model '${name}' was removed. Uncomment to drop table:`);
97
+ upStatements.push(`-- DROP TABLE IF EXISTS \`${previousSnapshot[name].table}\`;`);
98
+ downStatements.push(`-- Recreate table for removed model '${name}' manually if needed`);
99
+ }
100
+
101
+ // Added columns
102
+ for (const { model, column, type } of diff.addedColumns) {
103
+ const table = currentSnapshot[model].table;
104
+ upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
105
+ downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
106
+ }
107
+
108
+ // Removed columns
109
+ for (const { model, column, type } of diff.removedColumns) {
110
+ const table = previousSnapshot[model]?.table;
111
+ if (!table) throw new Error(`Missing table name in snapshot for model "${model}"`);
112
+ upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
113
+ downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
114
+ }
115
+
116
+ // Changed column types
117
+ for (const { model, column, from, to } of diff.changedColumns) {
118
+ const table = currentSnapshot[model].table;
119
+ upStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${to};`);
120
+ downStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${from};`);
121
+ }
122
+
123
+ // Added foreign keys
124
+ for (const { model, column, references } of diff.addedForeignKeys) {
125
+ const table = currentSnapshot[model].table;
126
+ // Resolve FK column type from the referenced table's PK type
127
+ const refModel = Object.entries(currentSnapshot).find(([, s]) => s.table === references.references);
128
+ const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
129
+ upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
130
+ upStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
131
+ downStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
132
+ downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
133
+ }
134
+
135
+ // Removed foreign keys
136
+ for (const { model, column, references } of diff.removedForeignKeys) {
137
+ const table = previousSnapshot[model]?.table;
138
+ if (!table) throw new Error(`Missing table name in snapshot for model "${model}"`);
139
+ // Resolve FK column type from the referenced table's PK type in previous snapshot
140
+ const refModel = Object.entries(previousSnapshot).find(([, s]) => s.table === references.references);
141
+ const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
142
+ upStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
143
+ upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
144
+ downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
145
+ downStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
146
+ }
147
+
148
+ // View migrations — views are created AFTER tables (dependency order)
149
+ const viewSchemas = introspectViews();
150
+ const currentViewSnapshot = viewSchemasToSnapshot(viewSchemas);
151
+ const previousViewSnapshot = extractViewsFromSnapshot(previousSnapshot);
152
+ const viewDiff = diffViewSnapshots(previousViewSnapshot, currentViewSnapshot);
153
+
154
+ if (viewDiff.hasChanges) {
155
+ upStatements.push('');
156
+ upStatements.push('-- Views');
157
+ downStatements.push('');
158
+ downStatements.push('-- Views');
159
+
160
+ // Added views
161
+ for (const name of viewDiff.addedViews) {
162
+ try {
163
+ const ddl = buildViewDDL(name, viewSchemas[name], schemas);
164
+ upStatements.push(ddl + ';');
165
+ downStatements.unshift(`DROP VIEW IF EXISTS \`${viewSchemas[name].viewName}\`;`);
166
+ } catch (error) {
167
+ upStatements.push(`-- WARNING: Could not generate DDL for view '${name}': ${error instanceof Error ? error.message : String(error)}`);
168
+ }
169
+ }
170
+
171
+ // Removed views
172
+ for (const name of viewDiff.removedViews) {
173
+ upStatements.push(`-- WARNING: View '${name}' was removed. Uncomment to drop view:`);
174
+ upStatements.push(`-- DROP VIEW IF EXISTS \`${previousViewSnapshot[name].viewName}\`;`);
175
+ downStatements.push(`-- Recreate view for removed view '${name}' manually if needed`);
176
+ }
177
+
178
+ // Changed views (source or aggregates changed)
179
+ for (const name of viewDiff.changedViews) {
180
+ try {
181
+ const ddl = buildViewDDL(name, viewSchemas[name], schemas);
182
+ upStatements.push(ddl + ';');
183
+ } catch (error) {
184
+ upStatements.push(`-- WARNING: Could not generate DDL for changed view '${name}': ${error instanceof Error ? error.message : String(error)}`);
185
+ }
186
+ }
187
+ }
188
+
189
+ const combinedHasChanges = diff.hasChanges || viewDiff.hasChanges;
190
+
191
+ if (!combinedHasChanges) {
192
+ log.db?.('No schema changes detected.');
193
+ return null;
194
+ }
195
+
196
+ // Merge view snapshot into the main snapshot
197
+ const combinedSnapshot: Record<string, SnapshotEntry | ViewSnapshotEntry> = { ...currentSnapshot };
198
+ for (const [name, viewSnap] of Object.entries(currentViewSnapshot)) {
199
+ combinedSnapshot[name] = viewSnap;
200
+ }
201
+
202
+ const sanitizedDescription = description.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
203
+ const timestamp = Math.floor(Date.now() / 1000);
204
+ const filename = `${timestamp}_${sanitizedDescription}.sql`;
205
+ const content = `-- UP\n${upStatements.join('\n')}\n\n-- DOWN\n${downStatements.join('\n')}\n`;
206
+
207
+ await createFile(path.join(migrationsPath, filename), content);
208
+ await createFile(path.join(migrationsPath, '.snapshot.json'), JSON.stringify(combinedSnapshot, null, 2));
209
+
210
+ log.db?.(`Migration generated: ${filename}`);
211
+
212
+ return { filename, content, snapshot: combinedSnapshot };
213
+ }
214
+
215
+ export async function loadLatestSnapshot(migrationsPath: string): Promise<Record<string, unknown>> {
216
+ const snapshotPath = path.join(migrationsPath, '.snapshot.json');
217
+ const exists = await fileExists(snapshotPath);
218
+
219
+ if (!exists) return {};
220
+
221
+ return readFile(snapshotPath, { json: true }) as Promise<Record<string, unknown>>;
222
+ }
223
+
224
+ export function diffSnapshots(previous: Record<string, SnapshotEntry>, current: Record<string, SnapshotEntry>): SnapshotDiff {
225
+ const addedModels: string[] = [];
226
+ const removedModels: string[] = [];
227
+ const addedColumns: ColumnChange[] = [];
228
+ const removedColumns: ColumnChange[] = [];
229
+ const changedColumns: ColumnTypeChange[] = [];
230
+ const addedForeignKeys: ForeignKeyChange[] = [];
231
+ const removedForeignKeys: ForeignKeyChange[] = [];
232
+
233
+ // Find added models
234
+ for (const name of Object.keys(current)) {
235
+ if (!previous[name]) addedModels.push(name);
236
+ }
237
+
238
+ // Find removed models
239
+ for (const name of Object.keys(previous)) {
240
+ if (!current[name]) removedModels.push(name);
241
+ }
242
+
243
+ // Find column changes in existing models
244
+ for (const name of Object.keys(current)) {
245
+ if (!previous[name]) continue;
246
+
247
+ const { columns: prevCols = {} } = previous[name];
248
+ const { columns: currCols = {} } = current[name];
249
+
250
+ // Added columns
251
+ for (const [col, type] of Object.entries(currCols)) {
252
+ if (!prevCols[col]) {
253
+ addedColumns.push({ model: name, column: col, type });
254
+ } else if (prevCols[col] !== type) {
255
+ changedColumns.push({ model: name, column: col, from: prevCols[col], to: type });
256
+ }
257
+ }
258
+
259
+ // Removed columns
260
+ for (const [col, type] of Object.entries(prevCols)) {
261
+ if (!currCols[col]) {
262
+ removedColumns.push({ model: name, column: col, type });
263
+ }
264
+ }
265
+
266
+ // Foreign key changes
267
+ const prevFKs = previous[name].foreignKeys || {};
268
+ const currFKs = current[name].foreignKeys || {};
269
+
270
+ for (const [col, refs] of Object.entries(currFKs)) {
271
+ if (!prevFKs[col]) {
272
+ addedForeignKeys.push({ model: name, column: col, references: refs });
273
+ }
274
+ }
275
+
276
+ for (const [col, refs] of Object.entries(prevFKs)) {
277
+ if (!currFKs[col]) {
278
+ removedForeignKeys.push({ model: name, column: col, references: refs });
279
+ }
280
+ }
281
+ }
282
+
283
+ const hasChanges = addedModels.length > 0 || removedModels.length > 0 ||
284
+ addedColumns.length > 0 || removedColumns.length > 0 ||
285
+ changedColumns.length > 0 || addedForeignKeys.length > 0 || removedForeignKeys.length > 0;
286
+
287
+ return {
288
+ hasChanges,
289
+ addedModels,
290
+ removedModels,
291
+ addedColumns,
292
+ removedColumns,
293
+ changedColumns,
294
+ addedForeignKeys,
295
+ removedForeignKeys,
296
+ };
297
+ }
298
+
299
+ export function detectSchemaDrift(schemas: Record<string, ModelSchema>, snapshot: Record<string, SnapshotEntry>): SnapshotDiff {
300
+ const current = schemasToSnapshot(schemas);
301
+ return diffSnapshots(snapshot, current);
302
+ }
303
+
304
+ export function extractViewsFromSnapshot(snapshot: Record<string, unknown>): Record<string, ViewSnapshotEntry> {
305
+ const views: Record<string, ViewSnapshotEntry> = {};
306
+ for (const [name, entry] of Object.entries(snapshot)) {
307
+ if ((entry as { isView?: boolean }).isView) views[name] = entry as ViewSnapshotEntry;
308
+ }
309
+ return views;
310
+ }
311
+
312
+ export function diffViewSnapshots(previous: Record<string, ViewSnapshotEntry>, current: Record<string, ViewSnapshotEntry>): ViewDiff {
313
+ const addedViews: string[] = [];
314
+ const removedViews: string[] = [];
315
+ const changedViews: string[] = [];
316
+
317
+ for (const name of Object.keys(current)) {
318
+ if (!previous[name]) {
319
+ addedViews.push(name);
320
+ } else if (
321
+ current[name].viewQuery !== previous[name].viewQuery ||
322
+ current[name].source !== previous[name].source
323
+ ) {
324
+ changedViews.push(name);
325
+ }
326
+ }
327
+
328
+ for (const name of Object.keys(previous)) {
329
+ if (!current[name]) {
330
+ removedViews.push(name);
331
+ }
332
+ }
333
+
334
+ const hasChanges = addedViews.length > 0 || removedViews.length > 0 || changedViews.length > 0;
335
+
336
+ return { hasChanges, addedViews, removedViews, changedViews };
337
+ }
@@ -0,0 +1,121 @@
1
+ import { readFile, fileExists } from '@stonyx/utils/file';
2
+ import path from 'path';
3
+ import fs from 'fs/promises';
4
+ import type { Pool, PoolConnection } from 'mysql2/promise';
5
+ import { validateIdentifier } from './query-builder.js';
6
+
7
+ interface ParsedMigration {
8
+ up: string;
9
+ down: string;
10
+ }
11
+
12
+ export async function ensureMigrationsTable(pool: Pool, tableName: string = '__migrations'): Promise<void> {
13
+ validateIdentifier(tableName, 'migration table name');
14
+ await pool.execute(`
15
+ CREATE TABLE IF NOT EXISTS \`${tableName}\` (
16
+ id INT AUTO_INCREMENT PRIMARY KEY,
17
+ filename VARCHAR(255) NOT NULL UNIQUE,
18
+ applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
19
+ )
20
+ `);
21
+ }
22
+
23
+ export async function getAppliedMigrations(pool: Pool, tableName: string = '__migrations'): Promise<string[]> {
24
+ validateIdentifier(tableName, 'migration table name');
25
+ const [rows] = await pool.execute(
26
+ `SELECT filename FROM \`${tableName}\` ORDER BY id ASC`
27
+ ) as [Array<{ filename: string }>, unknown];
28
+
29
+ return rows.map(row => row.filename);
30
+ }
31
+
32
+ export async function getMigrationFiles(migrationsDir: string): Promise<string[]> {
33
+ const exists = await fileExists(migrationsDir);
34
+ if (!exists) return [];
35
+
36
+ const entries = await fs.readdir(migrationsDir);
37
+
38
+ return entries
39
+ .filter(f => f.endsWith('.sql'))
40
+ .sort();
41
+ }
42
+
43
+ export function parseMigrationFile(content: string): ParsedMigration {
44
+ const upMarker = '-- UP';
45
+ const downMarker = '-- DOWN';
46
+ const upIndex = content.indexOf(upMarker);
47
+ const downIndex = content.indexOf(downMarker);
48
+
49
+ if (upIndex === -1) {
50
+ return { up: content.trim(), down: '' };
51
+ }
52
+
53
+ const upStart = upIndex + upMarker.length;
54
+ const upEnd = downIndex !== -1 ? downIndex : content.length;
55
+ const up = content.slice(upStart, upEnd).trim();
56
+ const down = downIndex !== -1 ? content.slice(downIndex + downMarker.length).trim() : '';
57
+
58
+ return { up, down };
59
+ }
60
+
61
+ export async function applyMigration(pool: Pool, filename: string, upSql: string, tableName: string = '__migrations'): Promise<void> {
62
+ validateIdentifier(tableName, 'migration table name');
63
+ const connection = await pool.getConnection();
64
+
65
+ try {
66
+ await connection.beginTransaction();
67
+
68
+ // Execute each statement separately (split on semicolons)
69
+ const statements = splitStatements(upSql);
70
+
71
+ for (const stmt of statements) {
72
+ await connection.execute(stmt);
73
+ }
74
+
75
+ await connection.execute(
76
+ `INSERT INTO \`${tableName}\` (filename) VALUES (?)`,
77
+ [filename]
78
+ );
79
+
80
+ await connection.commit();
81
+ } catch (error) {
82
+ await connection.rollback();
83
+ throw error;
84
+ } finally {
85
+ connection.release();
86
+ }
87
+ }
88
+
89
+ export async function rollbackMigration(pool: Pool, filename: string, downSql: string, tableName: string = '__migrations'): Promise<void> {
90
+ validateIdentifier(tableName, 'migration table name');
91
+ const connection = await pool.getConnection();
92
+
93
+ try {
94
+ await connection.beginTransaction();
95
+
96
+ const statements = splitStatements(downSql);
97
+
98
+ for (const stmt of statements) {
99
+ await connection.execute(stmt);
100
+ }
101
+
102
+ await connection.execute(
103
+ `DELETE FROM \`${tableName}\` WHERE filename = ?`,
104
+ [filename]
105
+ );
106
+
107
+ await connection.commit();
108
+ } catch (error) {
109
+ await connection.rollback();
110
+ throw error;
111
+ } finally {
112
+ connection.release();
113
+ }
114
+ }
115
+
116
+ function splitStatements(sql: string): string[] {
117
+ return sql
118
+ .split(';')
119
+ .map(s => s.trim())
120
+ .filter(s => s.length > 0 && !s.startsWith('--'));
121
+ }