@stonyx/orm 0.2.1-alpha.4 → 0.2.1-alpha.41
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 +64 -6
- package/config/environment.js +37 -1
- 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 +62 -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 +291 -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 +474 -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 +261 -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 +314 -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/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 +142 -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 +57 -15
- 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.js → commands.ts} +179 -170
- package/src/{db.js → db.ts} +55 -29
- package/src/exports/db.ts +7 -0
- package/src/has-many.ts +92 -0
- package/src/{hooks.js → hooks.ts} +41 -27
- package/src/{index.js → index.ts} +8 -5
- 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.js → migrate.ts} +9 -9
- package/src/model-property.ts +35 -0
- package/src/model.ts +21 -0
- package/src/mysql/{connection.js → connection.ts} +43 -28
- package/src/mysql/migration-generator.ts +337 -0
- package/src/mysql/{migration-runner.js → migration-runner.ts} +121 -110
- package/src/mysql/mysql-db.ts +543 -0
- package/src/mysql/{query-builder.js → query-builder.ts} +69 -64
- package/src/mysql/schema-introspector.ts +358 -0
- package/src/mysql/{type-map.js → type-map.ts} +42 -37
- package/src/{orm-request.js → orm-request.ts} +181 -103
- package/src/plural-registry.ts +12 -0
- package/src/postgres/connection.ts +48 -0
- package/src/postgres/migration-generator.ts +348 -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 +386 -0
- package/src/postgres/type-map.ts +61 -0
- package/src/record.ts +186 -0
- package/src/relationships.ts +54 -0
- package/src/serializer.ts +161 -0
- package/src/{setup-rest-server.js → setup-rest-server.ts} +18 -16
- 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 +146 -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/code-style-rules.md +0 -44
- package/.claude/hooks.md +0 -250
- package/.claude/index.md +0 -279
- package/.claude/usage-patterns.md +0 -217
- package/.github/workflows/ci.yml +0 -16
- package/.github/workflows/publish.yml +0 -51
- package/improvements.md +0 -139
- package/project-structure.md +0 -343
- package/src/belongs-to.js +0 -63
- package/src/has-many.js +0 -61
- package/src/main.js +0 -159
- package/src/manage-record.js +0 -118
- package/src/model-property.js +0 -29
- package/src/model.js +0 -19
- package/src/mysql/migration-generator.js +0 -188
- package/src/mysql/mysql-db.js +0 -422
- package/src/mysql/schema-introspector.js +0 -159
- package/src/record.js +0 -127
- package/src/relationships.js +0 -43
- package/src/serializer.js +0 -138
- package/src/store.js +0 -316
- package/src/transforms.js +0 -20
- package/src/utils.js +0 -12
- package/test-events-setup.js +0 -41
- package/test-hooks-manual.js +0 -54
- package/test-hooks-with-logging.js +0 -52
package/src/manage-record.js
DELETED
|
@@ -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
|
-
}
|
package/src/model-property.js
DELETED
|
@@ -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,19 +0,0 @@
|
|
|
1
|
-
import { attr } from '@stonyx/orm';
|
|
2
|
-
|
|
3
|
-
export default class Model {
|
|
4
|
-
/**
|
|
5
|
-
* Controls whether records of this model are loaded into memory on startup.
|
|
6
|
-
*
|
|
7
|
-
* - true → loaded on boot, kept in store (default for backward compatibility)
|
|
8
|
-
* - false → never cached; find() always queries MySQL
|
|
9
|
-
*
|
|
10
|
-
* Override in subclass: static memory = false;
|
|
11
|
-
*/
|
|
12
|
-
static memory = true;
|
|
13
|
-
|
|
14
|
-
id = attr('number');
|
|
15
|
-
|
|
16
|
-
constructor(name) {
|
|
17
|
-
this.__name = name;
|
|
18
|
-
}
|
|
19
|
-
}
|
|
@@ -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
|
-
}
|