@stonyx/orm 0.2.5-alpha.0 → 0.3.1

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 +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 +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} +12 -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.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,370 @@
1
+ import { introspectModels, introspectViews, buildTableDDL, buildViewDDL, buildVectorIndexDDL, schemasToSnapshot, viewSchemasToSnapshot, getTopologicalOrder } from './schema-introspector.js';
2
+ import { buildCreateHypertable, buildEnableCompression, buildCompressionPolicy } from '../timescale/query-builder.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
+ import type { ForeignKeyDef, SnapshotEntry } from '../types/orm-types.js';
8
+
9
+ interface ColumnChange {
10
+ model: string;
11
+ column: string;
12
+ type: string;
13
+ }
14
+
15
+ interface ColumnTypeChange {
16
+ model: string;
17
+ column: string;
18
+ from: string;
19
+ to: string;
20
+ }
21
+
22
+ interface ForeignKeyChange {
23
+ model: string;
24
+ column: string;
25
+ references: ForeignKeyDef;
26
+ }
27
+
28
+ interface DiffResult {
29
+ hasChanges: boolean;
30
+ addedModels: string[];
31
+ removedModels: string[];
32
+ addedColumns: ColumnChange[];
33
+ removedColumns: ColumnChange[];
34
+ changedColumns: ColumnTypeChange[];
35
+ addedForeignKeys: ForeignKeyChange[];
36
+ removedForeignKeys: ForeignKeyChange[];
37
+ }
38
+
39
+ interface ViewDiffResult {
40
+ hasChanges: boolean;
41
+ addedViews: string[];
42
+ removedViews: string[];
43
+ changedViews: string[];
44
+ }
45
+
46
+ interface MigrationResult {
47
+ filename: string;
48
+ content: string;
49
+ snapshot: Record<string, unknown>;
50
+ }
51
+
52
+ export async function generateMigration(description: string = 'migration', configKey: string = 'postgres'): Promise<MigrationResult | null> {
53
+ const { migrationsDir } = config.orm[configKey] as { migrationsDir: string };
54
+ const rootPath = config.rootPath;
55
+ const migrationsPath = path.resolve(rootPath, migrationsDir);
56
+
57
+ await createDirectory(migrationsPath);
58
+
59
+ const schemas = introspectModels();
60
+ const currentSnapshot = schemasToSnapshot(schemas);
61
+ const previousSnapshot = await loadLatestSnapshot(migrationsPath) as Record<string, SnapshotEntry>;
62
+ const diff = diffSnapshots(previousSnapshot, currentSnapshot);
63
+
64
+ // Don't return early -- check view changes too before deciding
65
+ if (!diff.hasChanges) {
66
+ const viewSchemasPrelim = introspectViews();
67
+ const currentViewSnapshotPrelim = viewSchemasToSnapshot(viewSchemasPrelim);
68
+ const previousViewSnapshotPrelim = extractViewsFromSnapshot(previousSnapshot);
69
+ const viewDiffPrelim = diffViewSnapshots(previousViewSnapshotPrelim, currentViewSnapshotPrelim);
70
+
71
+ if (!viewDiffPrelim.hasChanges) {
72
+ log.db?.('No schema changes detected.');
73
+ return null;
74
+ }
75
+ }
76
+
77
+ const upStatements: string[] = [];
78
+ const downStatements: string[] = [];
79
+
80
+ // pgvector extension (include in initial migration)
81
+ if (Object.keys(previousSnapshot).length === 0) {
82
+ upStatements.push('CREATE EXTENSION IF NOT EXISTS vector;');
83
+ }
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
+
92
+ // HNSW indexes for vector columns
93
+ const indexStatements = buildVectorIndexDDL(name, schemas[name]);
94
+ for (const stmt of indexStatements) {
95
+ upStatements.push(stmt + ';');
96
+ }
97
+
98
+ downStatements.unshift(`DROP TABLE IF EXISTS "${schemas[name].table}" CASCADE;`);
99
+ }
100
+
101
+ // Hypertable conversion + compression (TimescaleDB only)
102
+ if (configKey === 'timescale') {
103
+ for (const name of addedOrdered) {
104
+ const schema = schemas[name];
105
+ if (!schema.hypertable) continue;
106
+
107
+ const { timeColumn, chunkInterval } = schema.hypertable;
108
+ upStatements.push(buildCreateHypertable(schema.table, timeColumn, { chunkInterval }).sql + ';');
109
+
110
+ if (schema.hypertable.compress) {
111
+ const { segmentBy, orderBy, after } = schema.hypertable.compress;
112
+ upStatements.push(buildEnableCompression(schema.table, segmentBy, orderBy).sql + ';');
113
+ if (after) {
114
+ upStatements.push(buildCompressionPolicy(schema.table, after).sql + ';');
115
+ }
116
+ }
117
+
118
+ downStatements.unshift('-- Hypertable conversion is not reversible; table drop handles cleanup');
119
+ }
120
+ }
121
+
122
+ // Removed tables (warn only, commented out)
123
+ for (const name of diff.removedModels) {
124
+ upStatements.push(`-- WARNING: Model '${name}' was removed. Uncomment to drop table:`);
125
+ upStatements.push(`-- DROP TABLE IF EXISTS "${previousSnapshot[name].table}" CASCADE;`);
126
+ downStatements.push(`-- Recreate table for removed model '${name}' manually if needed`);
127
+ }
128
+
129
+ // Added columns
130
+ for (const { model, column, type } of diff.addedColumns) {
131
+ const table = currentSnapshot[model].table;
132
+ upStatements.push(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type};`);
133
+ downStatements.push(`ALTER TABLE "${table}" DROP COLUMN "${column}";`);
134
+
135
+ // Add HNSW index if it's a vector column
136
+ if (type.startsWith('vector(')) {
137
+ upStatements.push(`CREATE INDEX IF NOT EXISTS "idx_${table}_${column}_hnsw" ON "${table}" USING hnsw ("${column}" vector_cosine_ops) WITH (m = 16, ef_construction = 200);`);
138
+ }
139
+ }
140
+
141
+ // Removed columns
142
+ for (const { model, column, type } of diff.removedColumns) {
143
+ const table = previousSnapshot[model]?.table;
144
+ if (!table) throw new Error(`Missing table name in snapshot for model "${model}"`);
145
+ upStatements.push(`ALTER TABLE "${table}" DROP COLUMN "${column}";`);
146
+ downStatements.push(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${type};`);
147
+ }
148
+
149
+ // Changed column types
150
+ for (const { model, column, from, to } of diff.changedColumns) {
151
+ const table = currentSnapshot[model].table;
152
+ upStatements.push(`ALTER TABLE "${table}" ALTER COLUMN "${column}" TYPE ${to};`);
153
+ downStatements.push(`ALTER TABLE "${table}" ALTER COLUMN "${column}" TYPE ${from};`);
154
+ }
155
+
156
+ // Added foreign keys
157
+ for (const { model, column, references } of diff.addedForeignKeys) {
158
+ const table = currentSnapshot[model].table;
159
+ const refModel = Object.entries(currentSnapshot).find(([, s]) => s.table === references.references);
160
+ const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INTEGER';
161
+ const constraintName = `fk_${table}_${column}`;
162
+ upStatements.push(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${fkType};`);
163
+ upStatements.push(`ALTER TABLE "${table}" ADD CONSTRAINT "${constraintName}" FOREIGN KEY ("${column}") REFERENCES "${references.references}"("${references.column}") ON DELETE SET NULL;`);
164
+ downStatements.push(`ALTER TABLE "${table}" DROP CONSTRAINT "${constraintName}";`);
165
+ downStatements.push(`ALTER TABLE "${table}" DROP COLUMN "${column}";`);
166
+ }
167
+
168
+ // Removed foreign keys
169
+ for (const { model, column, references } of diff.removedForeignKeys) {
170
+ const table = previousSnapshot[model]?.table;
171
+ if (!table) throw new Error(`Missing table name in snapshot for model "${model}"`);
172
+ const refModel = Object.entries(previousSnapshot).find(([, s]) => s.table === references.references);
173
+ const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INTEGER';
174
+ const constraintName = `fk_${table}_${column}`;
175
+ upStatements.push(`ALTER TABLE "${table}" DROP CONSTRAINT "${constraintName}";`);
176
+ upStatements.push(`ALTER TABLE "${table}" DROP COLUMN "${column}";`);
177
+ downStatements.push(`ALTER TABLE "${table}" ADD COLUMN "${column}" ${fkType};`);
178
+ downStatements.push(`ALTER TABLE "${table}" ADD CONSTRAINT "${constraintName}" FOREIGN KEY ("${column}") REFERENCES "${references.references}"("${references.column}") ON DELETE SET NULL;`);
179
+ }
180
+
181
+ // View migrations -- views are created AFTER tables (dependency order)
182
+ const viewSchemas = introspectViews();
183
+ const currentViewSnapshot = viewSchemasToSnapshot(viewSchemas);
184
+ const previousViewSnapshot = extractViewsFromSnapshot(previousSnapshot);
185
+ const viewDiff = diffViewSnapshots(previousViewSnapshot, currentViewSnapshot);
186
+
187
+ if (viewDiff.hasChanges) {
188
+ upStatements.push('');
189
+ upStatements.push('-- Views');
190
+ downStatements.push('');
191
+ downStatements.push('-- Views');
192
+
193
+ // Added views
194
+ for (const name of viewDiff.addedViews) {
195
+ try {
196
+ const ddl = buildViewDDL(name, viewSchemas[name], schemas);
197
+ upStatements.push(ddl + ';');
198
+ downStatements.unshift(`DROP VIEW IF EXISTS "${viewSchemas[name].viewName}";`);
199
+ } catch (error) {
200
+ upStatements.push(`-- WARNING: Could not generate DDL for view '${name}': ${error instanceof Error ? error.message : String(error)}`);
201
+ }
202
+ }
203
+
204
+ // Removed views
205
+ for (const name of viewDiff.removedViews) {
206
+ upStatements.push(`-- WARNING: View '${name}' was removed. Uncomment to drop view:`);
207
+ upStatements.push(`-- DROP VIEW IF EXISTS "${previousViewSnapshot[name].viewName}";`);
208
+ downStatements.push(`-- Recreate view for removed view '${name}' manually if needed`);
209
+ }
210
+
211
+ // Changed views (source or aggregates changed)
212
+ for (const name of viewDiff.changedViews) {
213
+ try {
214
+ const ddl = buildViewDDL(name, viewSchemas[name], schemas);
215
+ upStatements.push(ddl + ';');
216
+ } catch (error) {
217
+ upStatements.push(`-- WARNING: Could not generate DDL for changed view '${name}': ${error instanceof Error ? error.message : String(error)}`);
218
+ }
219
+ }
220
+ }
221
+
222
+ const combinedHasChanges = diff.hasChanges || viewDiff.hasChanges;
223
+
224
+ if (!combinedHasChanges) {
225
+ log.db?.('No schema changes detected.');
226
+ return null;
227
+ }
228
+
229
+ // Merge view snapshot into the main snapshot
230
+ const combinedSnapshot: Record<string, unknown> = { ...currentSnapshot };
231
+ for (const [name, viewSnap] of Object.entries(currentViewSnapshot)) {
232
+ combinedSnapshot[name] = viewSnap;
233
+ }
234
+
235
+ const sanitizedDescription = description.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
236
+ const timestamp = Math.floor(Date.now() / 1000);
237
+ const filename = `${timestamp}_${sanitizedDescription}.sql`;
238
+ const content = `-- UP\n${upStatements.join('\n')}\n\n-- DOWN\n${downStatements.join('\n')}\n`;
239
+
240
+ await createFile(path.join(migrationsPath, filename), content);
241
+ await createFile(path.join(migrationsPath, '.snapshot.json'), JSON.stringify(combinedSnapshot, null, 2));
242
+
243
+ log.db?.(`Migration generated: ${filename}`);
244
+
245
+ return { filename, content, snapshot: combinedSnapshot };
246
+ }
247
+
248
+ export async function loadLatestSnapshot(migrationsPath: string): Promise<Record<string, unknown>> {
249
+ const snapshotPath = path.join(migrationsPath, '.snapshot.json');
250
+ const exists = await fileExists(snapshotPath);
251
+
252
+ if (!exists) return {};
253
+
254
+ return readFile(snapshotPath, { json: true }) as Promise<Record<string, unknown>>;
255
+ }
256
+
257
+ export function diffSnapshots(previous: Record<string, SnapshotEntry>, current: Record<string, SnapshotEntry>): DiffResult {
258
+ const addedModels: string[] = [];
259
+ const removedModels: string[] = [];
260
+ const addedColumns: ColumnChange[] = [];
261
+ const removedColumns: ColumnChange[] = [];
262
+ const changedColumns: ColumnTypeChange[] = [];
263
+ const addedForeignKeys: ForeignKeyChange[] = [];
264
+ const removedForeignKeys: ForeignKeyChange[] = [];
265
+
266
+ // Find added models
267
+ for (const name of Object.keys(current)) {
268
+ if (!previous[name]) addedModels.push(name);
269
+ }
270
+
271
+ // Find removed models
272
+ for (const name of Object.keys(previous)) {
273
+ if (!current[name]) removedModels.push(name);
274
+ }
275
+
276
+ // Find column changes in existing models
277
+ for (const name of Object.keys(current)) {
278
+ if (!previous[name]) continue;
279
+
280
+ const prevCols: Record<string, string> = previous[name].columns || {};
281
+ const currCols: Record<string, string> = current[name].columns || {};
282
+
283
+ // Added columns
284
+ for (const [col, type] of Object.entries(currCols)) {
285
+ if (!prevCols[col]) {
286
+ addedColumns.push({ model: name, column: col, type });
287
+ } else if (prevCols[col] !== type) {
288
+ changedColumns.push({ model: name, column: col, from: prevCols[col], to: type });
289
+ }
290
+ }
291
+
292
+ // Removed columns
293
+ for (const [col, type] of Object.entries(prevCols)) {
294
+ if (!currCols[col]) {
295
+ removedColumns.push({ model: name, column: col, type });
296
+ }
297
+ }
298
+
299
+ // Foreign key changes
300
+ const prevFKs: Record<string, ForeignKeyDef> = previous[name].foreignKeys || {};
301
+ const currFKs: Record<string, ForeignKeyDef> = current[name].foreignKeys || {};
302
+
303
+ for (const [col, refs] of Object.entries(currFKs)) {
304
+ if (!prevFKs[col]) {
305
+ addedForeignKeys.push({ model: name, column: col, references: refs });
306
+ }
307
+ }
308
+
309
+ for (const [col, refs] of Object.entries(prevFKs)) {
310
+ if (!currFKs[col]) {
311
+ removedForeignKeys.push({ model: name, column: col, references: refs });
312
+ }
313
+ }
314
+ }
315
+
316
+ const hasChanges = addedModels.length > 0 || removedModels.length > 0 ||
317
+ addedColumns.length > 0 || removedColumns.length > 0 ||
318
+ changedColumns.length > 0 || addedForeignKeys.length > 0 || removedForeignKeys.length > 0;
319
+
320
+ return {
321
+ hasChanges,
322
+ addedModels,
323
+ removedModels,
324
+ addedColumns,
325
+ removedColumns,
326
+ changedColumns,
327
+ addedForeignKeys,
328
+ removedForeignKeys,
329
+ };
330
+ }
331
+
332
+ export function detectSchemaDrift(schemas: Record<string, unknown>, snapshot: Record<string, SnapshotEntry>): DiffResult {
333
+ const current = schemasToSnapshot(schemas as Parameters<typeof schemasToSnapshot>[0]);
334
+ return diffSnapshots(snapshot, current);
335
+ }
336
+
337
+ export function extractViewsFromSnapshot(snapshot: Record<string, SnapshotEntry>): Record<string, SnapshotEntry> {
338
+ const views: Record<string, SnapshotEntry> = {};
339
+ for (const [name, entry] of Object.entries(snapshot)) {
340
+ if (entry.isView) views[name] = entry;
341
+ }
342
+ return views;
343
+ }
344
+
345
+ export function diffViewSnapshots(previous: Record<string, SnapshotEntry>, current: Record<string, SnapshotEntry>): ViewDiffResult {
346
+ const addedViews: string[] = [];
347
+ const removedViews: string[] = [];
348
+ const changedViews: string[] = [];
349
+
350
+ for (const name of Object.keys(current)) {
351
+ if (!previous[name]) {
352
+ addedViews.push(name);
353
+ } else if (
354
+ current[name].viewQuery !== previous[name].viewQuery ||
355
+ current[name].source !== previous[name].source
356
+ ) {
357
+ changedViews.push(name);
358
+ }
359
+ }
360
+
361
+ for (const name of Object.keys(previous)) {
362
+ if (!current[name]) {
363
+ removedViews.push(name);
364
+ }
365
+ }
366
+
367
+ const hasChanges = addedViews.length > 0 || removedViews.length > 0 || changedViews.length > 0;
368
+
369
+ return { hasChanges, addedViews, removedViews, changedViews };
370
+ }
@@ -0,0 +1,115 @@
1
+ import { readFile, fileExists } from '@stonyx/utils/file';
2
+ import path from 'path';
3
+ import fs from 'fs/promises';
4
+ import type { Pool, PoolClient } from 'pg';
5
+ import { validateIdentifier } from './query-builder.js';
6
+
7
+ export async function ensureMigrationsTable(pool: Pool, tableName: string = '__migrations'): Promise<void> {
8
+ validateIdentifier(tableName, 'migration table name');
9
+ await pool.query(`
10
+ CREATE TABLE IF NOT EXISTS "${tableName}" (
11
+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
12
+ filename VARCHAR(255) NOT NULL UNIQUE,
13
+ applied_at TIMESTAMPTZ DEFAULT NOW()
14
+ )
15
+ `);
16
+ }
17
+
18
+ export async function getAppliedMigrations(pool: Pool, tableName: string = '__migrations'): Promise<string[]> {
19
+ validateIdentifier(tableName, 'migration table name');
20
+ const result = await pool.query(
21
+ `SELECT filename FROM "${tableName}" ORDER BY id ASC`
22
+ );
23
+
24
+ return result.rows.map(row => row.filename as string);
25
+ }
26
+
27
+ export async function getMigrationFiles(migrationsDir: string): Promise<string[]> {
28
+ const exists = await fileExists(migrationsDir);
29
+ if (!exists) return [];
30
+
31
+ const entries = await fs.readdir(migrationsDir);
32
+
33
+ return entries
34
+ .filter(f => f.endsWith('.sql'))
35
+ .sort();
36
+ }
37
+
38
+ export function parseMigrationFile(content: string): { up: string; down: string } {
39
+ const upMarker = '-- UP';
40
+ const downMarker = '-- DOWN';
41
+ const upIndex = content.indexOf(upMarker);
42
+ const downIndex = content.indexOf(downMarker);
43
+
44
+ if (upIndex === -1) {
45
+ return { up: content.trim(), down: '' };
46
+ }
47
+
48
+ const upStart = upIndex + upMarker.length;
49
+ const upEnd = downIndex !== -1 ? downIndex : content.length;
50
+ const up = content.slice(upStart, upEnd).trim();
51
+ const down = downIndex !== -1 ? content.slice(downIndex + downMarker.length).trim() : '';
52
+
53
+ return { up, down };
54
+ }
55
+
56
+ export async function applyMigration(pool: Pool, filename: string, upSql: string, tableName: string = '__migrations'): Promise<void> {
57
+ validateIdentifier(tableName, 'migration table name');
58
+ const client: PoolClient = await pool.connect();
59
+
60
+ try {
61
+ await client.query('BEGIN');
62
+
63
+ const statements = splitStatements(upSql);
64
+
65
+ for (const stmt of statements) {
66
+ await client.query(stmt);
67
+ }
68
+
69
+ await client.query(
70
+ `INSERT INTO "${tableName}" (filename) VALUES ($1)`,
71
+ [filename]
72
+ );
73
+
74
+ await client.query('COMMIT');
75
+ } catch (error) {
76
+ await client.query('ROLLBACK');
77
+ throw error;
78
+ } finally {
79
+ client.release();
80
+ }
81
+ }
82
+
83
+ export async function rollbackMigration(pool: Pool, filename: string, downSql: string, tableName: string = '__migrations'): Promise<void> {
84
+ validateIdentifier(tableName, 'migration table name');
85
+ const client: PoolClient = await pool.connect();
86
+
87
+ try {
88
+ await client.query('BEGIN');
89
+
90
+ const statements = splitStatements(downSql);
91
+
92
+ for (const stmt of statements) {
93
+ await client.query(stmt);
94
+ }
95
+
96
+ await client.query(
97
+ `DELETE FROM "${tableName}" WHERE filename = $1`,
98
+ [filename]
99
+ );
100
+
101
+ await client.query('COMMIT');
102
+ } catch (error) {
103
+ await client.query('ROLLBACK');
104
+ throw error;
105
+ } finally {
106
+ client.release();
107
+ }
108
+ }
109
+
110
+ function splitStatements(sql: string): string[] {
111
+ return sql
112
+ .split(';')
113
+ .map(s => s.trim())
114
+ .filter(s => s.length > 0 && !s.startsWith('--'));
115
+ }