@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.
- package/README.md +482 -15
- package/config/environment.js +63 -6
- package/dist/aggregates.d.ts +21 -0
- package/dist/aggregates.js +93 -0
- package/dist/attr.d.ts +2 -0
- package/dist/attr.js +22 -0
- package/dist/belongs-to.d.ts +11 -0
- package/dist/belongs-to.js +59 -0
- package/dist/cli.d.ts +22 -0
- package/dist/cli.js +148 -0
- package/dist/commands.d.ts +7 -0
- package/dist/commands.js +146 -0
- package/dist/db.d.ts +21 -0
- package/dist/db.js +180 -0
- package/dist/exports/db.d.ts +7 -0
- package/{src → dist}/exports/db.js +2 -4
- package/dist/has-many.d.ts +11 -0
- package/dist/has-many.js +58 -0
- package/dist/hooks.d.ts +75 -0
- package/dist/hooks.js +110 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +34 -0
- package/dist/main.d.ts +46 -0
- package/dist/main.js +181 -0
- package/dist/manage-record.d.ts +13 -0
- package/dist/manage-record.js +123 -0
- package/dist/meta-request.d.ts +6 -0
- package/dist/meta-request.js +52 -0
- package/dist/migrate.d.ts +2 -0
- package/dist/migrate.js +57 -0
- package/dist/model-property.d.ts +9 -0
- package/dist/model-property.js +29 -0
- package/dist/model.d.ts +15 -0
- package/dist/model.js +18 -0
- package/dist/mysql/connection.d.ts +14 -0
- package/dist/mysql/connection.js +24 -0
- package/dist/mysql/migration-generator.d.ts +45 -0
- package/dist/mysql/migration-generator.js +254 -0
- package/dist/mysql/migration-runner.d.ts +12 -0
- package/dist/mysql/migration-runner.js +88 -0
- package/dist/mysql/mysql-db.d.ts +100 -0
- package/dist/mysql/mysql-db.js +425 -0
- package/dist/mysql/query-builder.d.ts +10 -0
- package/dist/mysql/query-builder.js +44 -0
- package/dist/mysql/schema-introspector.d.ts +19 -0
- package/dist/mysql/schema-introspector.js +257 -0
- package/dist/mysql/type-map.d.ts +21 -0
- package/dist/mysql/type-map.js +36 -0
- package/dist/orm-request.d.ts +38 -0
- package/dist/orm-request.js +475 -0
- package/dist/plural-registry.d.ts +4 -0
- package/dist/plural-registry.js +9 -0
- package/dist/postgres/connection.d.ts +15 -0
- package/dist/postgres/connection.js +32 -0
- package/dist/postgres/migration-generator.d.ts +45 -0
- package/dist/postgres/migration-generator.js +280 -0
- package/dist/postgres/migration-runner.d.ts +10 -0
- package/dist/postgres/migration-runner.js +87 -0
- package/dist/postgres/postgres-db.d.ts +119 -0
- package/dist/postgres/postgres-db.js +477 -0
- package/dist/postgres/query-builder.d.ts +27 -0
- package/dist/postgres/query-builder.js +98 -0
- package/dist/postgres/schema-introspector.d.ts +29 -0
- package/dist/postgres/schema-introspector.js +296 -0
- package/dist/postgres/type-map.d.ts +23 -0
- package/dist/postgres/type-map.js +56 -0
- package/dist/record.d.ts +75 -0
- package/dist/record.js +129 -0
- package/dist/relationships.d.ts +10 -0
- package/dist/relationships.js +41 -0
- package/dist/schema-helpers.d.ts +20 -0
- package/dist/schema-helpers.js +48 -0
- package/dist/serializer.d.ts +17 -0
- package/dist/serializer.js +136 -0
- package/dist/setup-rest-server.d.ts +1 -0
- package/dist/setup-rest-server.js +52 -0
- package/dist/standalone-db.d.ts +58 -0
- package/dist/standalone-db.js +142 -0
- package/dist/store.d.ts +62 -0
- package/dist/store.js +286 -0
- package/dist/timescale/query-builder.d.ts +43 -0
- package/dist/timescale/query-builder.js +115 -0
- package/dist/timescale/timescale-db.d.ts +45 -0
- package/dist/timescale/timescale-db.js +84 -0
- package/dist/transforms.d.ts +2 -0
- package/dist/transforms.js +17 -0
- package/dist/types/orm-types.d.ts +153 -0
- package/dist/types/orm-types.js +1 -0
- package/dist/utils.d.ts +7 -0
- package/dist/utils.js +17 -0
- package/dist/view-resolver.d.ts +8 -0
- package/dist/view-resolver.js +171 -0
- package/dist/view.d.ts +11 -0
- package/dist/view.js +18 -0
- package/package.json +64 -11
- package/src/aggregates.ts +109 -0
- package/src/{attr.js → attr.ts} +2 -2
- package/src/belongs-to.ts +90 -0
- package/src/cli.ts +183 -0
- package/src/commands.ts +179 -0
- package/src/db.ts +232 -0
- package/src/exports/db.ts +7 -0
- package/src/has-many.ts +92 -0
- package/src/hooks.ts +151 -0
- package/src/{index.js → index.ts} +12 -2
- package/src/main.ts +229 -0
- package/src/manage-record.ts +161 -0
- package/src/{meta-request.js → meta-request.ts} +17 -14
- package/src/migrate.ts +72 -0
- package/src/model-property.ts +35 -0
- package/src/model.ts +21 -0
- package/src/mysql/connection.ts +43 -0
- package/src/mysql/migration-generator.ts +337 -0
- package/src/mysql/migration-runner.ts +121 -0
- package/src/mysql/mysql-db.ts +543 -0
- package/src/mysql/query-builder.ts +69 -0
- package/src/mysql/schema-introspector.ts +310 -0
- package/src/mysql/type-map.ts +42 -0
- package/src/orm-request.ts +582 -0
- package/src/plural-registry.ts +12 -0
- package/src/postgres/connection.ts +48 -0
- package/src/postgres/migration-generator.ts +370 -0
- package/src/postgres/migration-runner.ts +115 -0
- package/src/postgres/postgres-db.ts +616 -0
- package/src/postgres/query-builder.ts +148 -0
- package/src/postgres/schema-introspector.ts +360 -0
- package/src/postgres/type-map.ts +61 -0
- package/src/record.ts +186 -0
- package/src/relationships.ts +54 -0
- package/src/schema-helpers.ts +59 -0
- package/src/serializer.ts +161 -0
- package/src/setup-rest-server.ts +62 -0
- package/src/standalone-db.ts +185 -0
- package/src/store.ts +373 -0
- package/src/timescale/query-builder.ts +174 -0
- package/src/timescale/timescale-db.ts +119 -0
- package/src/transforms.ts +20 -0
- package/src/types/mysql2.d.ts +49 -0
- package/src/types/orm-types.ts +158 -0
- package/src/types/pg.d.ts +32 -0
- package/src/types/stonyx-cron.d.ts +5 -0
- package/src/types/stonyx-events.d.ts +4 -0
- package/src/types/stonyx-rest-server.d.ts +16 -0
- package/src/types/stonyx-utils.d.ts +33 -0
- package/src/types/stonyx.d.ts +21 -0
- package/src/utils.ts +22 -0
- package/src/view-resolver.ts +211 -0
- package/src/view.ts +22 -0
- package/.claude/project-structure.md +0 -578
- package/.github/workflows/ci.yml +0 -36
- package/.github/workflows/publish.yml +0 -143
- package/src/belongs-to.js +0 -63
- package/src/db.js +0 -80
- package/src/has-many.js +0 -61
- package/src/main.js +0 -119
- package/src/manage-record.js +0 -103
- package/src/model-property.js +0 -29
- package/src/model.js +0 -9
- package/src/orm-request.js +0 -249
- package/src/record.js +0 -100
- package/src/relationships.js +0 -43
- package/src/serializer.js +0 -138
- package/src/setup-rest-server.js +0 -57
- package/src/store.js +0 -211
- package/src/transforms.js +0 -20
- package/stonyx-bootstrap.cjs +0 -30
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
import { introspectModels, introspectViews, buildTableDDL, buildViewDDL, schemasToSnapshot, viewSchemasToSnapshot, 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
|
+
export async function generateMigration(description = 'migration') {
|
|
7
|
+
const mysqlConfig = config.orm.mysql;
|
|
8
|
+
if (!mysqlConfig)
|
|
9
|
+
throw new Error('MySQL configuration (config.orm.mysql) is required for migration generation');
|
|
10
|
+
const { migrationsDir } = mysqlConfig;
|
|
11
|
+
if (!migrationsDir)
|
|
12
|
+
throw new Error('MySQL migrationsDir is required in config');
|
|
13
|
+
const rootPath = config.rootPath;
|
|
14
|
+
const migrationsPath = path.resolve(rootPath, migrationsDir);
|
|
15
|
+
await createDirectory(migrationsPath);
|
|
16
|
+
const schemas = introspectModels();
|
|
17
|
+
const currentSnapshot = schemasToSnapshot(schemas);
|
|
18
|
+
const previousSnapshot = await loadLatestSnapshot(migrationsPath);
|
|
19
|
+
const diff = diffSnapshots(previousSnapshot, currentSnapshot);
|
|
20
|
+
// Don't return early — check view changes too before deciding
|
|
21
|
+
if (!diff.hasChanges) {
|
|
22
|
+
// Check if there are view changes before returning null
|
|
23
|
+
const viewSchemasPrelim = introspectViews();
|
|
24
|
+
const currentViewSnapshotPrelim = viewSchemasToSnapshot(viewSchemasPrelim);
|
|
25
|
+
const previousViewSnapshotPrelim = extractViewsFromSnapshot(previousSnapshot);
|
|
26
|
+
const viewDiffPrelim = diffViewSnapshots(previousViewSnapshotPrelim, currentViewSnapshotPrelim);
|
|
27
|
+
if (!viewDiffPrelim.hasChanges) {
|
|
28
|
+
log.db?.('No schema changes detected.');
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const upStatements = [];
|
|
33
|
+
const downStatements = [];
|
|
34
|
+
// New tables — in topological order (parents before children)
|
|
35
|
+
const allOrder = getTopologicalOrder(schemas);
|
|
36
|
+
const addedOrdered = allOrder.filter(name => diff.addedModels.includes(name));
|
|
37
|
+
for (const name of addedOrdered) {
|
|
38
|
+
upStatements.push(buildTableDDL(name, schemas[name], schemas) + ';');
|
|
39
|
+
downStatements.unshift(`DROP TABLE IF EXISTS \`${schemas[name].table}\`;`);
|
|
40
|
+
}
|
|
41
|
+
// Removed tables (warn only, commented out)
|
|
42
|
+
for (const name of diff.removedModels) {
|
|
43
|
+
upStatements.push(`-- WARNING: Model '${name}' was removed. Uncomment to drop table:`);
|
|
44
|
+
upStatements.push(`-- DROP TABLE IF EXISTS \`${previousSnapshot[name].table}\`;`);
|
|
45
|
+
downStatements.push(`-- Recreate table for removed model '${name}' manually if needed`);
|
|
46
|
+
}
|
|
47
|
+
// Added columns
|
|
48
|
+
for (const { model, column, type } of diff.addedColumns) {
|
|
49
|
+
const table = currentSnapshot[model].table;
|
|
50
|
+
upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
|
|
51
|
+
downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
52
|
+
}
|
|
53
|
+
// Removed columns
|
|
54
|
+
for (const { model, column, type } of diff.removedColumns) {
|
|
55
|
+
const table = previousSnapshot[model]?.table;
|
|
56
|
+
if (!table)
|
|
57
|
+
throw new Error(`Missing table name in snapshot for model "${model}"`);
|
|
58
|
+
upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
59
|
+
downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${type};`);
|
|
60
|
+
}
|
|
61
|
+
// Changed column types
|
|
62
|
+
for (const { model, column, from, to } of diff.changedColumns) {
|
|
63
|
+
const table = currentSnapshot[model].table;
|
|
64
|
+
upStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${to};`);
|
|
65
|
+
downStatements.push(`ALTER TABLE \`${table}\` MODIFY COLUMN \`${column}\` ${from};`);
|
|
66
|
+
}
|
|
67
|
+
// Added foreign keys
|
|
68
|
+
for (const { model, column, references } of diff.addedForeignKeys) {
|
|
69
|
+
const table = currentSnapshot[model].table;
|
|
70
|
+
// Resolve FK column type from the referenced table's PK type
|
|
71
|
+
const refModel = Object.entries(currentSnapshot).find(([, s]) => s.table === references.references);
|
|
72
|
+
const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
|
|
73
|
+
upStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
|
|
74
|
+
upStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
|
|
75
|
+
downStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
|
|
76
|
+
downStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
77
|
+
}
|
|
78
|
+
// Removed foreign keys
|
|
79
|
+
for (const { model, column, references } of diff.removedForeignKeys) {
|
|
80
|
+
const table = previousSnapshot[model]?.table;
|
|
81
|
+
if (!table)
|
|
82
|
+
throw new Error(`Missing table name in snapshot for model "${model}"`);
|
|
83
|
+
// Resolve FK column type from the referenced table's PK type in previous snapshot
|
|
84
|
+
const refModel = Object.entries(previousSnapshot).find(([, s]) => s.table === references.references);
|
|
85
|
+
const fkType = refModel && refModel[1].idType === 'string' ? 'VARCHAR(255)' : 'INT';
|
|
86
|
+
upStatements.push(`ALTER TABLE \`${table}\` DROP FOREIGN KEY \`${column}\`;`);
|
|
87
|
+
upStatements.push(`ALTER TABLE \`${table}\` DROP COLUMN \`${column}\`;`);
|
|
88
|
+
downStatements.push(`ALTER TABLE \`${table}\` ADD COLUMN \`${column}\` ${fkType};`);
|
|
89
|
+
downStatements.push(`ALTER TABLE \`${table}\` ADD FOREIGN KEY (\`${column}\`) REFERENCES \`${references.references}\`(\`${references.column}\`) ON DELETE SET NULL;`);
|
|
90
|
+
}
|
|
91
|
+
// View migrations — views are created AFTER tables (dependency order)
|
|
92
|
+
const viewSchemas = introspectViews();
|
|
93
|
+
const currentViewSnapshot = viewSchemasToSnapshot(viewSchemas);
|
|
94
|
+
const previousViewSnapshot = extractViewsFromSnapshot(previousSnapshot);
|
|
95
|
+
const viewDiff = diffViewSnapshots(previousViewSnapshot, currentViewSnapshot);
|
|
96
|
+
if (viewDiff.hasChanges) {
|
|
97
|
+
upStatements.push('');
|
|
98
|
+
upStatements.push('-- Views');
|
|
99
|
+
downStatements.push('');
|
|
100
|
+
downStatements.push('-- Views');
|
|
101
|
+
// Added views
|
|
102
|
+
for (const name of viewDiff.addedViews) {
|
|
103
|
+
try {
|
|
104
|
+
const ddl = buildViewDDL(name, viewSchemas[name], schemas);
|
|
105
|
+
upStatements.push(ddl + ';');
|
|
106
|
+
downStatements.unshift(`DROP VIEW IF EXISTS \`${viewSchemas[name].viewName}\`;`);
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
upStatements.push(`-- WARNING: Could not generate DDL for view '${name}': ${error instanceof Error ? error.message : String(error)}`);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// Removed views
|
|
113
|
+
for (const name of viewDiff.removedViews) {
|
|
114
|
+
upStatements.push(`-- WARNING: View '${name}' was removed. Uncomment to drop view:`);
|
|
115
|
+
upStatements.push(`-- DROP VIEW IF EXISTS \`${previousViewSnapshot[name].viewName}\`;`);
|
|
116
|
+
downStatements.push(`-- Recreate view for removed view '${name}' manually if needed`);
|
|
117
|
+
}
|
|
118
|
+
// Changed views (source or aggregates changed)
|
|
119
|
+
for (const name of viewDiff.changedViews) {
|
|
120
|
+
try {
|
|
121
|
+
const ddl = buildViewDDL(name, viewSchemas[name], schemas);
|
|
122
|
+
upStatements.push(ddl + ';');
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
upStatements.push(`-- WARNING: Could not generate DDL for changed view '${name}': ${error instanceof Error ? error.message : String(error)}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const combinedHasChanges = diff.hasChanges || viewDiff.hasChanges;
|
|
130
|
+
if (!combinedHasChanges) {
|
|
131
|
+
log.db?.('No schema changes detected.');
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
// Merge view snapshot into the main snapshot
|
|
135
|
+
const combinedSnapshot = { ...currentSnapshot };
|
|
136
|
+
for (const [name, viewSnap] of Object.entries(currentViewSnapshot)) {
|
|
137
|
+
combinedSnapshot[name] = viewSnap;
|
|
138
|
+
}
|
|
139
|
+
const sanitizedDescription = description.replace(/\s+/g, '_').replace(/[^a-zA-Z0-9_]/g, '');
|
|
140
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
141
|
+
const filename = `${timestamp}_${sanitizedDescription}.sql`;
|
|
142
|
+
const content = `-- UP\n${upStatements.join('\n')}\n\n-- DOWN\n${downStatements.join('\n')}\n`;
|
|
143
|
+
await createFile(path.join(migrationsPath, filename), content);
|
|
144
|
+
await createFile(path.join(migrationsPath, '.snapshot.json'), JSON.stringify(combinedSnapshot, null, 2));
|
|
145
|
+
log.db?.(`Migration generated: ${filename}`);
|
|
146
|
+
return { filename, content, snapshot: combinedSnapshot };
|
|
147
|
+
}
|
|
148
|
+
export async function loadLatestSnapshot(migrationsPath) {
|
|
149
|
+
const snapshotPath = path.join(migrationsPath, '.snapshot.json');
|
|
150
|
+
const exists = await fileExists(snapshotPath);
|
|
151
|
+
if (!exists)
|
|
152
|
+
return {};
|
|
153
|
+
return readFile(snapshotPath, { json: true });
|
|
154
|
+
}
|
|
155
|
+
export function diffSnapshots(previous, current) {
|
|
156
|
+
const addedModels = [];
|
|
157
|
+
const removedModels = [];
|
|
158
|
+
const addedColumns = [];
|
|
159
|
+
const removedColumns = [];
|
|
160
|
+
const changedColumns = [];
|
|
161
|
+
const addedForeignKeys = [];
|
|
162
|
+
const removedForeignKeys = [];
|
|
163
|
+
// Find added models
|
|
164
|
+
for (const name of Object.keys(current)) {
|
|
165
|
+
if (!previous[name])
|
|
166
|
+
addedModels.push(name);
|
|
167
|
+
}
|
|
168
|
+
// Find removed models
|
|
169
|
+
for (const name of Object.keys(previous)) {
|
|
170
|
+
if (!current[name])
|
|
171
|
+
removedModels.push(name);
|
|
172
|
+
}
|
|
173
|
+
// Find column changes in existing models
|
|
174
|
+
for (const name of Object.keys(current)) {
|
|
175
|
+
if (!previous[name])
|
|
176
|
+
continue;
|
|
177
|
+
const { columns: prevCols = {} } = previous[name];
|
|
178
|
+
const { columns: currCols = {} } = current[name];
|
|
179
|
+
// Added columns
|
|
180
|
+
for (const [col, type] of Object.entries(currCols)) {
|
|
181
|
+
if (!prevCols[col]) {
|
|
182
|
+
addedColumns.push({ model: name, column: col, type });
|
|
183
|
+
}
|
|
184
|
+
else if (prevCols[col] !== type) {
|
|
185
|
+
changedColumns.push({ model: name, column: col, from: prevCols[col], to: type });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// Removed columns
|
|
189
|
+
for (const [col, type] of Object.entries(prevCols)) {
|
|
190
|
+
if (!currCols[col]) {
|
|
191
|
+
removedColumns.push({ model: name, column: col, type });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// Foreign key changes
|
|
195
|
+
const prevFKs = previous[name].foreignKeys || {};
|
|
196
|
+
const currFKs = current[name].foreignKeys || {};
|
|
197
|
+
for (const [col, refs] of Object.entries(currFKs)) {
|
|
198
|
+
if (!prevFKs[col]) {
|
|
199
|
+
addedForeignKeys.push({ model: name, column: col, references: refs });
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
for (const [col, refs] of Object.entries(prevFKs)) {
|
|
203
|
+
if (!currFKs[col]) {
|
|
204
|
+
removedForeignKeys.push({ model: name, column: col, references: refs });
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const hasChanges = addedModels.length > 0 || removedModels.length > 0 ||
|
|
209
|
+
addedColumns.length > 0 || removedColumns.length > 0 ||
|
|
210
|
+
changedColumns.length > 0 || addedForeignKeys.length > 0 || removedForeignKeys.length > 0;
|
|
211
|
+
return {
|
|
212
|
+
hasChanges,
|
|
213
|
+
addedModels,
|
|
214
|
+
removedModels,
|
|
215
|
+
addedColumns,
|
|
216
|
+
removedColumns,
|
|
217
|
+
changedColumns,
|
|
218
|
+
addedForeignKeys,
|
|
219
|
+
removedForeignKeys,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
export function detectSchemaDrift(schemas, snapshot) {
|
|
223
|
+
const current = schemasToSnapshot(schemas);
|
|
224
|
+
return diffSnapshots(snapshot, current);
|
|
225
|
+
}
|
|
226
|
+
export function extractViewsFromSnapshot(snapshot) {
|
|
227
|
+
const views = {};
|
|
228
|
+
for (const [name, entry] of Object.entries(snapshot)) {
|
|
229
|
+
if (entry.isView)
|
|
230
|
+
views[name] = entry;
|
|
231
|
+
}
|
|
232
|
+
return views;
|
|
233
|
+
}
|
|
234
|
+
export function diffViewSnapshots(previous, current) {
|
|
235
|
+
const addedViews = [];
|
|
236
|
+
const removedViews = [];
|
|
237
|
+
const changedViews = [];
|
|
238
|
+
for (const name of Object.keys(current)) {
|
|
239
|
+
if (!previous[name]) {
|
|
240
|
+
addedViews.push(name);
|
|
241
|
+
}
|
|
242
|
+
else if (current[name].viewQuery !== previous[name].viewQuery ||
|
|
243
|
+
current[name].source !== previous[name].source) {
|
|
244
|
+
changedViews.push(name);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
for (const name of Object.keys(previous)) {
|
|
248
|
+
if (!current[name]) {
|
|
249
|
+
removedViews.push(name);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const hasChanges = addedViews.length > 0 || removedViews.length > 0 || changedViews.length > 0;
|
|
253
|
+
return { hasChanges, addedViews, removedViews, changedViews };
|
|
254
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Pool } from 'mysql2/promise';
|
|
2
|
+
interface ParsedMigration {
|
|
3
|
+
up: string;
|
|
4
|
+
down: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function ensureMigrationsTable(pool: Pool, tableName?: string): Promise<void>;
|
|
7
|
+
export declare function getAppliedMigrations(pool: Pool, tableName?: string): Promise<string[]>;
|
|
8
|
+
export declare function getMigrationFiles(migrationsDir: string): Promise<string[]>;
|
|
9
|
+
export declare function parseMigrationFile(content: string): ParsedMigration;
|
|
10
|
+
export declare function applyMigration(pool: Pool, filename: string, upSql: string, tableName?: string): Promise<void>;
|
|
11
|
+
export declare function rollbackMigration(pool: Pool, filename: string, downSql: string, tableName?: string): Promise<void>;
|
|
12
|
+
export {};
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { fileExists } from '@stonyx/utils/file';
|
|
2
|
+
import fs from 'fs/promises';
|
|
3
|
+
import { validateIdentifier } from './query-builder.js';
|
|
4
|
+
export async function ensureMigrationsTable(pool, tableName = '__migrations') {
|
|
5
|
+
validateIdentifier(tableName, 'migration table name');
|
|
6
|
+
await pool.execute(`
|
|
7
|
+
CREATE TABLE IF NOT EXISTS \`${tableName}\` (
|
|
8
|
+
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
9
|
+
filename VARCHAR(255) NOT NULL UNIQUE,
|
|
10
|
+
applied_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
11
|
+
)
|
|
12
|
+
`);
|
|
13
|
+
}
|
|
14
|
+
export async function getAppliedMigrations(pool, tableName = '__migrations') {
|
|
15
|
+
validateIdentifier(tableName, 'migration table name');
|
|
16
|
+
const [rows] = await pool.execute(`SELECT filename FROM \`${tableName}\` ORDER BY id ASC`);
|
|
17
|
+
return rows.map(row => row.filename);
|
|
18
|
+
}
|
|
19
|
+
export async function getMigrationFiles(migrationsDir) {
|
|
20
|
+
const exists = await fileExists(migrationsDir);
|
|
21
|
+
if (!exists)
|
|
22
|
+
return [];
|
|
23
|
+
const entries = await fs.readdir(migrationsDir);
|
|
24
|
+
return entries
|
|
25
|
+
.filter(f => f.endsWith('.sql'))
|
|
26
|
+
.sort();
|
|
27
|
+
}
|
|
28
|
+
export function parseMigrationFile(content) {
|
|
29
|
+
const upMarker = '-- UP';
|
|
30
|
+
const downMarker = '-- DOWN';
|
|
31
|
+
const upIndex = content.indexOf(upMarker);
|
|
32
|
+
const downIndex = content.indexOf(downMarker);
|
|
33
|
+
if (upIndex === -1) {
|
|
34
|
+
return { up: content.trim(), down: '' };
|
|
35
|
+
}
|
|
36
|
+
const upStart = upIndex + upMarker.length;
|
|
37
|
+
const upEnd = downIndex !== -1 ? downIndex : content.length;
|
|
38
|
+
const up = content.slice(upStart, upEnd).trim();
|
|
39
|
+
const down = downIndex !== -1 ? content.slice(downIndex + downMarker.length).trim() : '';
|
|
40
|
+
return { up, down };
|
|
41
|
+
}
|
|
42
|
+
export async function applyMigration(pool, filename, upSql, tableName = '__migrations') {
|
|
43
|
+
validateIdentifier(tableName, 'migration table name');
|
|
44
|
+
const connection = await pool.getConnection();
|
|
45
|
+
try {
|
|
46
|
+
await connection.beginTransaction();
|
|
47
|
+
// Execute each statement separately (split on semicolons)
|
|
48
|
+
const statements = splitStatements(upSql);
|
|
49
|
+
for (const stmt of statements) {
|
|
50
|
+
await connection.execute(stmt);
|
|
51
|
+
}
|
|
52
|
+
await connection.execute(`INSERT INTO \`${tableName}\` (filename) VALUES (?)`, [filename]);
|
|
53
|
+
await connection.commit();
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
await connection.rollback();
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
finally {
|
|
60
|
+
connection.release();
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function rollbackMigration(pool, filename, downSql, tableName = '__migrations') {
|
|
64
|
+
validateIdentifier(tableName, 'migration table name');
|
|
65
|
+
const connection = await pool.getConnection();
|
|
66
|
+
try {
|
|
67
|
+
await connection.beginTransaction();
|
|
68
|
+
const statements = splitStatements(downSql);
|
|
69
|
+
for (const stmt of statements) {
|
|
70
|
+
await connection.execute(stmt);
|
|
71
|
+
}
|
|
72
|
+
await connection.execute(`DELETE FROM \`${tableName}\` WHERE filename = ?`, [filename]);
|
|
73
|
+
await connection.commit();
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
await connection.rollback();
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
connection.release();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
function splitStatements(sql) {
|
|
84
|
+
return sql
|
|
85
|
+
.split(';')
|
|
86
|
+
.map(s => s.trim())
|
|
87
|
+
.filter(s => s.length > 0 && !s.startsWith('--'));
|
|
88
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { getPool, closePool } from './connection.js';
|
|
2
|
+
import type { MysqlConfig } from './connection.js';
|
|
3
|
+
import { ensureMigrationsTable, getAppliedMigrations, getMigrationFiles, applyMigration, parseMigrationFile } from './migration-runner.js';
|
|
4
|
+
import { introspectModels, introspectViews, getTopologicalOrder, schemasToSnapshot } from './schema-introspector.js';
|
|
5
|
+
import { loadLatestSnapshot, detectSchemaDrift } from './migration-generator.js';
|
|
6
|
+
import { buildInsert, buildUpdate, buildDelete, buildSelect } from './query-builder.js';
|
|
7
|
+
import { createRecord } from '../manage-record.js';
|
|
8
|
+
import { confirm } from '@stonyx/utils/prompt';
|
|
9
|
+
import { readFile } from '@stonyx/utils/file';
|
|
10
|
+
import { getPluralName } from '../plural-registry.js';
|
|
11
|
+
import config from 'stonyx/config';
|
|
12
|
+
import path from 'path';
|
|
13
|
+
import type { Pool } from 'mysql2/promise';
|
|
14
|
+
import type { OrmRecord } from '../types/orm-types.js';
|
|
15
|
+
interface PersistContext {
|
|
16
|
+
record?: OrmRecord;
|
|
17
|
+
recordId?: unknown;
|
|
18
|
+
oldState?: Record<string, unknown>;
|
|
19
|
+
}
|
|
20
|
+
interface PersistResponse {
|
|
21
|
+
data?: {
|
|
22
|
+
id?: unknown;
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
interface OrmStore {
|
|
26
|
+
get(key: string): Map<number | string, unknown> | undefined;
|
|
27
|
+
get(key: string, id: number | string): unknown;
|
|
28
|
+
_memoryResolver?: (modelName: string) => boolean;
|
|
29
|
+
data?: Map<string, Map<number | string, unknown>>;
|
|
30
|
+
}
|
|
31
|
+
interface MysqlDBDeps {
|
|
32
|
+
getPool: typeof getPool;
|
|
33
|
+
closePool: typeof closePool;
|
|
34
|
+
ensureMigrationsTable: typeof ensureMigrationsTable;
|
|
35
|
+
getAppliedMigrations: typeof getAppliedMigrations;
|
|
36
|
+
getMigrationFiles: typeof getMigrationFiles;
|
|
37
|
+
applyMigration: typeof applyMigration;
|
|
38
|
+
parseMigrationFile: typeof parseMigrationFile;
|
|
39
|
+
introspectModels: typeof introspectModels;
|
|
40
|
+
introspectViews: typeof introspectViews;
|
|
41
|
+
getTopologicalOrder: typeof getTopologicalOrder;
|
|
42
|
+
schemasToSnapshot: typeof schemasToSnapshot;
|
|
43
|
+
loadLatestSnapshot: typeof loadLatestSnapshot;
|
|
44
|
+
detectSchemaDrift: typeof detectSchemaDrift;
|
|
45
|
+
buildInsert: typeof buildInsert;
|
|
46
|
+
buildUpdate: typeof buildUpdate;
|
|
47
|
+
buildDelete: typeof buildDelete;
|
|
48
|
+
buildSelect: typeof buildSelect;
|
|
49
|
+
createRecord: typeof createRecord;
|
|
50
|
+
store: OrmStore;
|
|
51
|
+
confirm: typeof confirm;
|
|
52
|
+
readFile: typeof readFile;
|
|
53
|
+
getPluralName: typeof getPluralName;
|
|
54
|
+
config: typeof config;
|
|
55
|
+
log: Record<string, ((...args: unknown[]) => void) | undefined>;
|
|
56
|
+
path: typeof path;
|
|
57
|
+
}
|
|
58
|
+
export default class MysqlDB {
|
|
59
|
+
static instance: MysqlDB | undefined;
|
|
60
|
+
deps: MysqlDBDeps;
|
|
61
|
+
pool: Pool | null;
|
|
62
|
+
mysqlConfig: MysqlConfig;
|
|
63
|
+
constructor(deps?: Partial<MysqlDBDeps>);
|
|
64
|
+
private requirePool;
|
|
65
|
+
init(): Promise<void>;
|
|
66
|
+
startup(): Promise<void>;
|
|
67
|
+
shutdown(): Promise<void>;
|
|
68
|
+
save(): Promise<void>;
|
|
69
|
+
/**
|
|
70
|
+
* Loads only models with memory: true into the in-memory store on startup.
|
|
71
|
+
* Models with memory: false are skipped — accessed on-demand via find()/findAll().
|
|
72
|
+
*/
|
|
73
|
+
loadMemoryRecords(): Promise<void>;
|
|
74
|
+
/**
|
|
75
|
+
* @deprecated Use loadMemoryRecords() instead. Kept for backward compatibility.
|
|
76
|
+
*/
|
|
77
|
+
loadAllRecords(): Promise<void>;
|
|
78
|
+
/**
|
|
79
|
+
* Find a single record by ID from MySQL.
|
|
80
|
+
* Does NOT cache the result in the store for memory: false models.
|
|
81
|
+
*/
|
|
82
|
+
findRecord(modelName: string, id: string | number): Promise<OrmRecord | undefined>;
|
|
83
|
+
/**
|
|
84
|
+
* Find all records of a model from MySQL, with optional conditions.
|
|
85
|
+
*/
|
|
86
|
+
findAll(modelName: string, conditions?: Record<string, unknown>): Promise<OrmRecord[]>;
|
|
87
|
+
/**
|
|
88
|
+
* Remove a record from the in-memory store if its model has memory: false.
|
|
89
|
+
* The record object itself survives — the caller retains the reference.
|
|
90
|
+
* This prevents on-demand queries from leaking records into the store.
|
|
91
|
+
*/
|
|
92
|
+
private _evictIfNotMemory;
|
|
93
|
+
private _rowToRawData;
|
|
94
|
+
persist(operation: string, modelName: string, context: PersistContext, response: PersistResponse): Promise<void>;
|
|
95
|
+
private _persistCreate;
|
|
96
|
+
private _persistUpdate;
|
|
97
|
+
private _persistDelete;
|
|
98
|
+
private _recordToRow;
|
|
99
|
+
}
|
|
100
|
+
export {};
|