@danceroutine/tango-migrations 1.6.0 → 1.8.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.
- package/dist/{CompilerStrategy-yKw-Egxv.js → CompilerStrategy-_AiXiyjS.js} +9 -2
- package/dist/CompilerStrategy-_AiXiyjS.js.map +1 -0
- package/dist/{IntrospectorStrategy-blvwSU3_.js → IntrospectorStrategy-BEIG5GqA.js} +2 -2
- package/dist/{IntrospectorStrategy-blvwSU3_.js.map → IntrospectorStrategy-BEIG5GqA.js.map} +1 -1
- package/dist/{MigrationRunner-CSt99m9K.js → MigrationRunner-DomrOZIn.js} +6 -4
- package/dist/MigrationRunner-DomrOZIn.js.map +1 -0
- package/dist/{SqliteCompilerFactory-BAodJW9n.js → SqliteCompilerFactory-BvdJ0kBl.js} +121 -2
- package/dist/SqliteCompilerFactory-BvdJ0kBl.js.map +1 -0
- package/dist/{cli-DOBziuSJ.js → cli-7j3R1Y1r.js} +8 -7
- package/dist/cli-7j3R1Y1r.js.map +1 -0
- package/dist/cli.js +6 -6
- package/dist/commands/index.js +7 -7
- package/dist/{commands-DIJepqNg.js → commands-Cl2MU7tq.js} +2 -2
- package/dist/{commands-DIJepqNg.js.map → commands-Cl2MU7tq.js.map} +1 -1
- package/dist/compilers/contracts/SQLCompiler.d.ts +2 -0
- package/dist/compilers/dialects/PostgresCompiler.d.ts +6 -0
- package/dist/compilers/dialects/SqliteCompiler.d.ts +7 -0
- package/dist/compilers/index.js +2 -2
- package/dist/{compilers-dRN0Hzev.js → compilers-C-GiumJB.js} +2 -2
- package/dist/{compilers-dRN0Hzev.js.map → compilers-C-GiumJB.js.map} +1 -1
- package/dist/diff/diffSchema.d.ts +1 -0
- package/dist/diff/index.d.ts +1 -0
- package/dist/diff/index.js +2 -3
- package/dist/{diffSchema-D4oemTWS.js → diff-B9MhagJF.js} +45 -14
- package/dist/diff-B9MhagJF.js.map +1 -0
- package/dist/index.js +10 -11
- package/dist/introspect/index.js +1 -1
- package/dist/{introspect-TPv_jeD6.js → introspect-DD3fm15e.js} +1 -1
- package/dist/{introspect-TPv_jeD6.js.map → introspect-DD3fm15e.js.map} +1 -1
- package/dist/runner/index.js +3 -3
- package/dist/runner-C97xT8_W.js +1 -1
- package/dist/schema/buildMigrationModelMetadataProjection.d.ts +3 -0
- package/dist/strategies/CompilerStrategy.d.ts +4 -0
- package/dist/strategies/index.js +4 -4
- package/dist/{strategies-D9ymSvbG.js → strategies-HwUWvmLC.js} +3 -3
- package/dist/{strategies-D9ymSvbG.js.map → strategies-HwUWvmLC.js.map} +1 -1
- package/package.json +8 -7
- package/dist/CompilerStrategy-yKw-Egxv.js.map +0 -1
- package/dist/MigrationRunner-CSt99m9K.js.map +0 -1
- package/dist/SqliteCompilerFactory-BAodJW9n.js.map +0 -1
- package/dist/cli-DOBziuSJ.js.map +0 -1
- package/dist/diff-CZZbXAPN.js +0 -10
- package/dist/diff-CZZbXAPN.js.map +0 -1
- package/dist/diffSchema-D4oemTWS.js.map +0 -1
|
@@ -12,9 +12,16 @@ export declare class SqliteCompiler implements SQLCompiler {
|
|
|
12
12
|
* Narrow an unknown value to the SQLite migration compiler implementation.
|
|
13
13
|
*/
|
|
14
14
|
static isSqliteCompiler(value: unknown): value is SqliteCompiler;
|
|
15
|
+
/**
|
|
16
|
+
* Rewrite migration operations into SQLite's safe execution order,
|
|
17
|
+
* including topological table creation and unique-column add expansion.
|
|
18
|
+
*/
|
|
19
|
+
prepareOperations(operations: MigrationOperation[]): MigrationOperation[];
|
|
15
20
|
/**
|
|
16
21
|
* Compile a migration operation into one or more SQLite statements.
|
|
17
22
|
*/
|
|
18
23
|
compile(op: MigrationOperation): SQL[];
|
|
19
24
|
private colDDL;
|
|
25
|
+
private prepareColumnAdd;
|
|
26
|
+
private topologicalSortTableCreatesWithReferences;
|
|
20
27
|
}
|
package/dist/compilers/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "../InternalOperationKind-Bt6Weuon.js";
|
|
2
2
|
import "../InternalColumnType-G9zV9StN.js";
|
|
3
3
|
import "../MigrationSqlSafetyAdapter-CGRbB2k2.js";
|
|
4
|
-
import { PostgresCompiler, PostgresCompilerFactory, SqliteCompiler, SqliteCompilerFactory } from "../SqliteCompilerFactory-
|
|
5
|
-
import { contracts_exports$1 as contracts_exports, dialects_exports, factories_exports } from "../compilers-
|
|
4
|
+
import { PostgresCompiler, PostgresCompilerFactory, SqliteCompiler, SqliteCompilerFactory } from "../SqliteCompilerFactory-BvdJ0kBl.js";
|
|
5
|
+
import { contracts_exports$1 as contracts_exports, dialects_exports, factories_exports } from "../compilers-C-GiumJB.js";
|
|
6
6
|
|
|
7
7
|
export { PostgresCompiler, PostgresCompilerFactory, SqliteCompiler, SqliteCompilerFactory, contracts_exports as contracts, dialects_exports as dialects, factories_exports as factories };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { __export } from "./chunk-BkvOhyD0.js";
|
|
2
|
-
import { PostgresCompiler, PostgresCompilerFactory, SqliteCompiler, SqliteCompilerFactory } from "./SqliteCompilerFactory-
|
|
2
|
+
import { PostgresCompiler, PostgresCompilerFactory, SqliteCompiler, SqliteCompilerFactory } from "./SqliteCompilerFactory-BvdJ0kBl.js";
|
|
3
3
|
|
|
4
4
|
//#region src/compilers/contracts/index.ts
|
|
5
5
|
var contracts_exports = {};
|
|
@@ -35,4 +35,4 @@ __export(compilers_exports, {
|
|
|
35
35
|
|
|
36
36
|
//#endregion
|
|
37
37
|
export { compilers_exports, contracts_exports as contracts_exports$1, dialects_exports, factories_exports };
|
|
38
|
-
//# sourceMappingURL=compilers-
|
|
38
|
+
//# sourceMappingURL=compilers-C-GiumJB.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compilers-
|
|
1
|
+
{"version":3,"file":"compilers-C-GiumJB.js","names":[],"sources":["../src/compilers/contracts/index.ts","../src/compilers/dialects/index.ts","../src/compilers/factories/index.ts","../src/compilers/index.ts"],"sourcesContent":["/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport type { SQL } from './SQL';\nexport type { SQLCompiler } from './SQLCompiler';\nexport type { CompilerFactory } from './CompilerFactory';\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { PostgresCompiler } from './PostgresCompiler';\nexport { SqliteCompiler } from './SqliteCompiler';\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { PostgresCompilerFactory } from './PostgresCompilerFactory';\nexport { SqliteCompilerFactory } from './SqliteCompilerFactory';\n","/**\n * Domain boundary barrel: exposes namespaced exports for Django-style drill-down\n * imports and curated flat exports for TS-native ergonomics.\n */\n\nexport * as contracts from './contracts/index';\nexport * as dialects from './dialects/index';\nexport * as factories from './factories/index';\n\nexport type { SQL, SQLCompiler, CompilerFactory } from './contracts/index';\nexport { PostgresCompiler, SqliteCompiler } from './dialects/index';\nexport * from './factories/index';\n"],"mappings":""}
|
package/dist/diff/index.d.ts
CHANGED
package/dist/diff/index.js
CHANGED
|
@@ -2,7 +2,6 @@ import "../CollectingBuilder--4fqDQdE.js";
|
|
|
2
2
|
import "../InternalOperationKind-Bt6Weuon.js";
|
|
3
3
|
import "../InternalColumnType-G9zV9StN.js";
|
|
4
4
|
import "../builder-xJ-Bq2pk.js";
|
|
5
|
-
import { diffSchema } from "../
|
|
6
|
-
import "../diff-CZZbXAPN.js";
|
|
5
|
+
import { buildMigrationModelMetadataProjection, diffSchema } from "../diff-B9MhagJF.js";
|
|
7
6
|
|
|
8
|
-
export { diffSchema };
|
|
7
|
+
export { buildMigrationModelMetadataProjection, diffSchema };
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
+
import { __export } from "./chunk-BkvOhyD0.js";
|
|
1
2
|
import { OpBuilder, applyFieldType } from "./builder-xJ-Bq2pk.js";
|
|
2
3
|
import { trustedSql } from "@danceroutine/tango-core";
|
|
3
4
|
|
|
4
5
|
//#region src/diff/diffSchema.ts
|
|
5
6
|
function diffSchema(db, models) {
|
|
6
7
|
const ops = [];
|
|
7
|
-
const modelTables = new Set(models.map((model) => model.table));
|
|
8
|
-
const internalTables = new Set(["_tango_migrations"]);
|
|
9
8
|
models.forEach((model) => {
|
|
9
|
+
if (model.managed === false) return;
|
|
10
10
|
const dbTable = db.tables[model.table];
|
|
11
11
|
if (!dbTable) {
|
|
12
12
|
ops.push(OpBuilder.table(model.table).create((cols) => {
|
|
@@ -68,20 +68,51 @@ else if (typeof field.default === "string") builder = builder.default(trustedSql
|
|
|
68
68
|
unique: !!index.unique
|
|
69
69
|
}));
|
|
70
70
|
});
|
|
71
|
-
dbIndexNames.forEach((dbIndexName) => {
|
|
72
|
-
if (!modelIndexes.has(dbIndexName)) ops.push(OpBuilder.index.drop({
|
|
73
|
-
name: dbIndexName,
|
|
74
|
-
table: model.table
|
|
75
|
-
}));
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
Object.keys(db.tables).forEach((dbTableName) => {
|
|
79
|
-
if (internalTables.has(dbTableName)) return;
|
|
80
|
-
if (!modelTables.has(dbTableName)) ops.push(OpBuilder.table(dbTableName).drop());
|
|
81
71
|
});
|
|
82
72
|
return ops;
|
|
83
73
|
}
|
|
84
74
|
|
|
85
75
|
//#endregion
|
|
86
|
-
|
|
87
|
-
|
|
76
|
+
//#region src/schema/buildMigrationModelMetadataProjection.ts
|
|
77
|
+
function fieldToModelField(field) {
|
|
78
|
+
return {
|
|
79
|
+
name: field.name,
|
|
80
|
+
type: field.type,
|
|
81
|
+
notNull: field.notNull,
|
|
82
|
+
default: field.default,
|
|
83
|
+
primaryKey: field.primaryKey,
|
|
84
|
+
unique: field.unique,
|
|
85
|
+
references: field.references
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function buildMigrationModelMetadataProjection(registry) {
|
|
89
|
+
registry.finalizeStorageArtifacts();
|
|
90
|
+
const projection = [];
|
|
91
|
+
for (const model of registry.values()) {
|
|
92
|
+
const finalized = registry.getFinalizedFields(model.metadata.key);
|
|
93
|
+
projection.push({
|
|
94
|
+
name: model.metadata.name,
|
|
95
|
+
table: model.metadata.table,
|
|
96
|
+
managed: model.metadata.managed ?? true,
|
|
97
|
+
fields: finalized.map(fieldToModelField),
|
|
98
|
+
indexes: model.metadata.indexes?.map((index) => ({
|
|
99
|
+
name: index.name,
|
|
100
|
+
on: [...index.on],
|
|
101
|
+
unique: index.unique
|
|
102
|
+
}))
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
return projection;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/diff/index.ts
|
|
110
|
+
var diff_exports = {};
|
|
111
|
+
__export(diff_exports, {
|
|
112
|
+
buildMigrationModelMetadataProjection: () => buildMigrationModelMetadataProjection,
|
|
113
|
+
diffSchema: () => diffSchema
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
//#endregion
|
|
117
|
+
export { buildMigrationModelMetadataProjection, diffSchema, diff_exports };
|
|
118
|
+
//# sourceMappingURL=diff-B9MhagJF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diff-B9MhagJF.js","names":["db: DbSchema","models: ModelMetadataLike[]","ops: MigrationOperation[]","field: Field","registry: ModelRegistry","projection: ModelMetadataLike[]"],"sources":["../src/diff/diffSchema.ts","../src/schema/buildMigrationModelMetadataProjection.ts","../src/diff/index.ts"],"sourcesContent":["import { trustedSql } from '@danceroutine/tango-core';\nimport type { DbSchema } from '../introspect/PostgresIntrospector';\nimport type { MigrationOperation } from '../domain/MigrationOperation';\nimport type { ColumnType } from '../builder/contracts/ColumnType';\nimport type { DeleteReferentialAction } from '../builder/contracts/DeleteReferentialAction';\nimport type { UpdateReferentialAction } from '../builder/contracts/UpdateReferentialAction';\nimport { op, applyFieldType } from '../builder/index';\n\ntype ModelField = {\n name: string;\n type: ColumnType;\n notNull?: boolean;\n default?: string | { now: true } | null;\n primaryKey?: boolean;\n unique?: boolean;\n references?: {\n table: string;\n column: string;\n onDelete?: DeleteReferentialAction;\n onUpdate?: UpdateReferentialAction;\n };\n};\n\ntype ModelIndex = {\n name: string;\n on: string[];\n unique?: boolean;\n};\n\nexport type ModelMetadataLike = {\n name?: string;\n table: string;\n fields: ModelField[];\n indexes?: ModelIndex[];\n managed?: boolean;\n};\n\n/**\n * Compare model metadata with an introspected database schema and return the\n * operations needed to bring the database into alignment.\n */\nexport function diffSchema(db: DbSchema, models: ModelMetadataLike[]): MigrationOperation[] {\n const ops: MigrationOperation[] = [];\n models.forEach((model) => {\n if (model.managed === false) {\n return;\n }\n\n const dbTable = db.tables[model.table];\n\n if (!dbTable) {\n ops.push(\n op.table(model.table).create((cols) => {\n model.fields.forEach((field) => {\n cols.add(field.name, (builder) => {\n builder = applyFieldType(builder, field.type);\n\n if (field.notNull) {\n builder = builder.notNull();\n }\n\n if (field.default === null) {\n builder = builder.default(null);\n } else if (field.default && typeof field.default === 'object' && 'now' in field.default) {\n builder = builder.defaultNow();\n } else if (typeof field.default === 'string') {\n builder = builder.default(trustedSql(field.default));\n }\n\n if (field.primaryKey) {\n builder = builder.primaryKey();\n }\n\n if (field.unique) {\n builder = builder.unique();\n }\n\n if (field.references) {\n builder = builder.references(field.references.table, field.references.column, {\n onDelete: field.references.onDelete,\n onUpdate: field.references.onUpdate,\n });\n }\n\n return builder;\n });\n });\n })\n );\n\n (model.indexes ?? []).forEach((index) => {\n ops.push(\n op.index.create({\n name: index.name,\n table: model.table,\n on: index.on,\n unique: !!index.unique,\n })\n );\n });\n return;\n }\n\n const modelFieldNames = new Set(model.fields.map((field) => field.name));\n const dbFieldNames = new Set(Object.keys(dbTable.columns));\n\n model.fields.forEach((field) => {\n if (!dbFieldNames.has(field.name)) {\n ops.push(\n op.table(model.table).addColumn(field.name, (builder) => {\n builder = applyFieldType(builder, field.type);\n\n if (field.notNull) {\n builder = builder.notNull();\n }\n if (field.default === null) {\n builder = builder.default(null);\n } else if (field.default && typeof field.default === 'object' && 'now' in field.default) {\n builder = builder.defaultNow();\n } else if (typeof field.default === 'string') {\n builder = builder.default(trustedSql(field.default));\n }\n if (field.primaryKey) {\n builder = builder.primaryKey();\n }\n if (field.unique) {\n builder = builder.unique();\n }\n if (field.references) {\n builder = builder.references(field.references.table, field.references.column, {\n onDelete: field.references.onDelete,\n onUpdate: field.references.onUpdate,\n });\n }\n\n return builder;\n })\n );\n }\n });\n\n dbFieldNames.forEach((dbColumnName) => {\n if (!modelFieldNames.has(dbColumnName)) {\n ops.push(op.table(model.table).dropColumn(dbColumnName));\n }\n });\n\n const modelIndexes = new Map((model.indexes ?? []).map((index) => [index.name, index] as const));\n const dbIndexNames = new Set(Object.keys(dbTable.indexes));\n\n modelIndexes.forEach((index, indexName) => {\n if (!dbIndexNames.has(indexName)) {\n ops.push(\n op.index.create({\n name: index.name,\n table: model.table,\n on: index.on,\n unique: !!index.unique,\n })\n );\n }\n });\n\n // Index drift is intentionally conservative. Extra indexes in the live\n // database may be app-owned or dialect-managed, so migrations only add\n // missing declared indexes and avoid destructive index drops here.\n });\n\n return ops;\n}\n","import type { ModelRegistry } from '@danceroutine/tango-schema';\nimport type { Field } from '@danceroutine/tango-schema/domain';\nimport type { ColumnType } from '../builder/contracts/ColumnType';\nimport type { ModelMetadataLike } from '../diff/diffSchema';\n\nfunction fieldToModelField(field: Field): ModelMetadataLike['fields'][number] {\n return {\n name: field.name,\n type: field.type as ColumnType,\n notNull: field.notNull,\n default: field.default,\n primaryKey: field.primaryKey,\n unique: field.unique,\n references: field.references as ModelMetadataLike['fields'][number]['references'],\n };\n}\n\nexport function buildMigrationModelMetadataProjection(registry: ModelRegistry): ModelMetadataLike[] {\n registry.finalizeStorageArtifacts();\n const projection: ModelMetadataLike[] = [];\n for (const model of registry.values()) {\n const finalized = registry.getFinalizedFields(model.metadata.key);\n projection.push({\n name: model.metadata.name,\n table: model.metadata.table,\n managed: model.metadata.managed ?? true,\n fields: finalized.map(fieldToModelField),\n indexes: model.metadata.indexes?.map((index) => ({\n name: index.name,\n on: [...index.on],\n unique: index.unique,\n })),\n });\n }\n return projection;\n}\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { diffSchema } from './diffSchema';\nexport { buildMigrationModelMetadataProjection } from '../schema/buildMigrationModelMetadataProjection';\n"],"mappings":";;;;;AAyCO,SAAS,WAAWA,IAAcC,QAAmD;CACxF,MAAMC,MAA4B,CAAE;AACpC,QAAO,QAAQ,CAAC,UAAU;AACtB,MAAI,MAAM,YAAY,MAClB;EAGJ,MAAM,UAAU,GAAG,OAAO,MAAM;AAEhC,OAAK,SAAS;AACV,OAAI,KACA,UAAG,MAAM,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS;AACnC,UAAM,OAAO,QAAQ,CAAC,UAAU;AAC5B,UAAK,IAAI,MAAM,MAAM,CAAC,YAAY;AAC9B,gBAAU,eAAe,SAAS,MAAM,KAAK;AAE7C,UAAI,MAAM,QACN,WAAU,QAAQ,SAAS;AAG/B,UAAI,MAAM,YAAY,KAClB,WAAU,QAAQ,QAAQ,KAAK;SACxB,MAAM,kBAAkB,MAAM,YAAY,YAAY,SAAS,MAAM,QAC5E,WAAU,QAAQ,YAAY;gBAChB,MAAM,YAAY,SAChC,WAAU,QAAQ,QAAQ,WAAW,MAAM,QAAQ,CAAC;AAGxD,UAAI,MAAM,WACN,WAAU,QAAQ,YAAY;AAGlC,UAAI,MAAM,OACN,WAAU,QAAQ,QAAQ;AAG9B,UAAI,MAAM,WACN,WAAU,QAAQ,WAAW,MAAM,WAAW,OAAO,MAAM,WAAW,QAAQ;OAC1E,UAAU,MAAM,WAAW;OAC3B,UAAU,MAAM,WAAW;MAC9B,EAAC;AAGN,aAAO;KACV,EAAC;IACL,EAAC;GACL,EAAC,CACL;AAED,IAAC,MAAM,WAAW,CAAE,GAAE,QAAQ,CAAC,UAAU;AACrC,QAAI,KACA,UAAG,MAAM,OAAO;KACZ,MAAM,MAAM;KACZ,OAAO,MAAM;KACb,IAAI,MAAM;KACV,UA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Ac;AACvC,QAAK,aAAa,IAAI,UAAU,CAC5B,KAAI,KACA,UAAG,MAAM,OAAO;IACZ,MAAM,MAAM;IACZ,OAAO,MAAM;IACb,IAAI,MAAM;IACV,UAAU,MAAM;GACnB,EAAC,CACL;EAER,EAAC;CAKL,EAAC;AAEF,QAAO;AACV;;;;ACpKD,SAAS,kBAAkBC,OAAmD;AAC1E,QAAO;EACH,MAAM,MAAM;EACZ,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,SAAS,MAAM;EACf,YAAY,MAAM;EAClB,QAAQ,MAAM;EACd,YAAY,MAAM;CACrB;AACJ;AAEM,SAAS,sCAAsCC,UAA8C;AAChG,UAAS,0BAA0B;CACnC,MAAMC,aAAkC,CAAE;AAC1C,MAAK,MAAM,SAAS,SAAS,QAAQ,EAAE;EACnC,MAAM,YAAY,SAAS,mBAAmB,MAAM,SAAS,IAAI;AACjE,aAAW,KAAK;GACZ,MAAM,MAAM,SAAS;GACrB,OAAO,MAAM,SAAS;GACtB,SAAS,MAAM,SAAS,WAAW;GACnC,QAAQ,UAAU,IAAI,kBAAkB;GACxC,SAAS,MAAM,SAAS,SAAS,IAAI,CAAC,WAAW;IAC7C,MAAM,MAAM;IACZ,IAAI,CAAC,GAAG,MAAM,EAAG;IACjB,QAAQ,MAAM;GACjB,GAAE;EACN,EAAC;CACL;AACD,QAAO;AACV"}
|
package/dist/index.js
CHANGED
|
@@ -3,23 +3,22 @@ import { Migration } from "./Migration-DYQ0hUG7.js";
|
|
|
3
3
|
import "./InternalOperationKind-Bt6Weuon.js";
|
|
4
4
|
import "./InternalColumnType-G9zV9StN.js";
|
|
5
5
|
import "./MigrationSqlSafetyAdapter-CGRbB2k2.js";
|
|
6
|
-
import { PostgresCompiler, SqliteCompiler } from "./SqliteCompilerFactory-
|
|
7
|
-
import { CompilerStrategy, createDefaultCompilerStrategy } from "./CompilerStrategy-
|
|
8
|
-
import { MigrationRunner } from "./MigrationRunner-
|
|
6
|
+
import { PostgresCompiler, SqliteCompiler } from "./SqliteCompilerFactory-BvdJ0kBl.js";
|
|
7
|
+
import { CompilerStrategy, createDefaultCompilerStrategy } from "./CompilerStrategy-_AiXiyjS.js";
|
|
8
|
+
import { MigrationRunner } from "./MigrationRunner-DomrOZIn.js";
|
|
9
9
|
import { MigrationGenerator } from "./MigrationGenerator-B1p0jHnx.js";
|
|
10
10
|
import { OpBuilder, applyFieldType, builder_exports } from "./builder-xJ-Bq2pk.js";
|
|
11
|
-
import { diffSchema } from "./
|
|
11
|
+
import { diffSchema, diff_exports } from "./diff-B9MhagJF.js";
|
|
12
12
|
import { PostgresIntrospector, SqliteIntrospector } from "./SqliteIntrospector-CWwPWhmA.js";
|
|
13
|
-
import { IntrospectorStrategy, createDefaultIntrospectorStrategy } from "./IntrospectorStrategy-
|
|
14
|
-
import { registerMigrationsCommands } from "./cli-
|
|
13
|
+
import { IntrospectorStrategy, createDefaultIntrospectorStrategy } from "./IntrospectorStrategy-BEIG5GqA.js";
|
|
14
|
+
import { registerMigrationsCommands } from "./cli-7j3R1Y1r.js";
|
|
15
15
|
import { domain_exports } from "./domain-CwR-kUNS.js";
|
|
16
16
|
import { runner_exports } from "./runner-C97xT8_W.js";
|
|
17
17
|
import { generator_exports } from "./generator-DK-_f-PF.js";
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import { commands_exports } from "./commands-DIJepqNg.js";
|
|
18
|
+
import { compilers_exports } from "./compilers-C-GiumJB.js";
|
|
19
|
+
import { introspect_exports } from "./introspect-DD3fm15e.js";
|
|
20
|
+
import { strategies_exports } from "./strategies-HwUWvmLC.js";
|
|
21
|
+
import { commands_exports } from "./commands-Cl2MU7tq.js";
|
|
23
22
|
import { trustedSql } from "@danceroutine/tango-core";
|
|
24
23
|
|
|
25
24
|
export { CollectingBuilder, CompilerStrategy, IntrospectorStrategy, Migration, MigrationGenerator, MigrationRunner, OpBuilder, PostgresCompiler, PostgresIntrospector, SqliteCompiler, SqliteIntrospector, applyFieldType, builder_exports as builder, commands_exports as commands, compilers_exports as compilers, createDefaultCompilerStrategy, createDefaultIntrospectorStrategy, diff_exports as diff, diffSchema, domain_exports as domain, generator_exports as generator, introspect_exports as introspect, OpBuilder as op, registerMigrationsCommands, runner_exports as runner, strategies_exports as strategies, trustedSql };
|
package/dist/introspect/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../MigrationSqlSafetyAdapter-CGRbB2k2.js";
|
|
2
2
|
import { PostgresIntrospector, SqliteIntrospector } from "../SqliteIntrospector-CWwPWhmA.js";
|
|
3
|
-
import "../introspect-
|
|
3
|
+
import "../introspect-DD3fm15e.js";
|
|
4
4
|
|
|
5
5
|
export { PostgresIntrospector, SqliteIntrospector };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"introspect-
|
|
1
|
+
{"version":3,"file":"introspect-DD3fm15e.js","names":[],"sources":["../src/introspect/index.ts"],"sourcesContent":["/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport type { DBClient, DatabaseIntrospector } from './DatabaseIntrospector';\nexport {\n PostgresIntrospector,\n type DbColumn as PostgresDbColumn,\n type DbForeignKey as PostgresDbForeignKey,\n type DbIndex as PostgresDbIndex,\n type DbSchema as PostgresDbSchema,\n type DbTable as PostgresDbTable,\n} from './PostgresIntrospector';\nexport {\n SqliteIntrospector,\n type DbColumn as SqliteDbColumn,\n type DbSchema as SqliteDbSchema,\n type DbTable as SqliteDbTable,\n} from './SqliteIntrospector';\n"],"mappings":""}
|
package/dist/runner/index.js
CHANGED
|
@@ -3,9 +3,9 @@ import "../Migration-DYQ0hUG7.js";
|
|
|
3
3
|
import "../InternalOperationKind-Bt6Weuon.js";
|
|
4
4
|
import "../InternalColumnType-G9zV9StN.js";
|
|
5
5
|
import "../MigrationSqlSafetyAdapter-CGRbB2k2.js";
|
|
6
|
-
import "../SqliteCompilerFactory-
|
|
7
|
-
import "../CompilerStrategy-
|
|
8
|
-
import { MigrationRunner } from "../MigrationRunner-
|
|
6
|
+
import "../SqliteCompilerFactory-BvdJ0kBl.js";
|
|
7
|
+
import "../CompilerStrategy-_AiXiyjS.js";
|
|
8
|
+
import { MigrationRunner } from "../MigrationRunner-DomrOZIn.js";
|
|
9
9
|
import "../runner-C97xT8_W.js";
|
|
10
10
|
|
|
11
11
|
export { MigrationRunner };
|
package/dist/runner-C97xT8_W.js
CHANGED
|
@@ -18,6 +18,10 @@ export declare class CompilerStrategy {
|
|
|
18
18
|
* Narrow an unknown value to the dialect-aware migration compiler strategy.
|
|
19
19
|
*/
|
|
20
20
|
static isCompilerStrategy(value: unknown): value is CompilerStrategy;
|
|
21
|
+
/**
|
|
22
|
+
* Prepare a batch of migration operations for a target dialect.
|
|
23
|
+
*/
|
|
24
|
+
prepareOperations(dialect: Dialect, operations: MigrationOperation[]): MigrationOperation[];
|
|
21
25
|
/**
|
|
22
26
|
* Compile a migration operation to SQL for a target dialect.
|
|
23
27
|
*/
|
package/dist/strategies/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import "../InternalOperationKind-Bt6Weuon.js";
|
|
2
2
|
import "../InternalColumnType-G9zV9StN.js";
|
|
3
3
|
import "../MigrationSqlSafetyAdapter-CGRbB2k2.js";
|
|
4
|
-
import "../SqliteCompilerFactory-
|
|
5
|
-
import { CompilerStrategy, createDefaultCompilerStrategy } from "../CompilerStrategy-
|
|
4
|
+
import "../SqliteCompilerFactory-BvdJ0kBl.js";
|
|
5
|
+
import { CompilerStrategy, createDefaultCompilerStrategy } from "../CompilerStrategy-_AiXiyjS.js";
|
|
6
6
|
import "../SqliteIntrospector-CWwPWhmA.js";
|
|
7
|
-
import { IntrospectorStrategy, createDefaultIntrospectorStrategy } from "../IntrospectorStrategy-
|
|
8
|
-
import "../strategies-
|
|
7
|
+
import { IntrospectorStrategy, createDefaultIntrospectorStrategy } from "../IntrospectorStrategy-BEIG5GqA.js";
|
|
8
|
+
import "../strategies-HwUWvmLC.js";
|
|
9
9
|
|
|
10
10
|
export { CompilerStrategy, IntrospectorStrategy, createDefaultCompilerStrategy, createDefaultIntrospectorStrategy };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { __export } from "./chunk-BkvOhyD0.js";
|
|
2
|
-
import { CompilerStrategy, createDefaultCompilerStrategy } from "./CompilerStrategy-
|
|
3
|
-
import { IntrospectorStrategy, createDefaultIntrospectorStrategy } from "./IntrospectorStrategy-
|
|
2
|
+
import { CompilerStrategy, createDefaultCompilerStrategy } from "./CompilerStrategy-_AiXiyjS.js";
|
|
3
|
+
import { IntrospectorStrategy, createDefaultIntrospectorStrategy } from "./IntrospectorStrategy-BEIG5GqA.js";
|
|
4
4
|
|
|
5
5
|
//#region src/strategies/index.ts
|
|
6
6
|
var strategies_exports = {};
|
|
@@ -13,4 +13,4 @@ __export(strategies_exports, {
|
|
|
13
13
|
|
|
14
14
|
//#endregion
|
|
15
15
|
export { strategies_exports };
|
|
16
|
-
//# sourceMappingURL=strategies-
|
|
16
|
+
//# sourceMappingURL=strategies-HwUWvmLC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strategies-
|
|
1
|
+
{"version":3,"file":"strategies-HwUWvmLC.js","names":[],"sources":["../src/strategies/index.ts"],"sourcesContent":["/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { CompilerStrategy, createDefaultCompilerStrategy } from './CompilerStrategy';\nexport { IntrospectorStrategy, createDefaultIntrospectorStrategy } from './IntrospectorStrategy';\n"],"mappings":""}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@danceroutine/tango-migrations",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.8.0",
|
|
4
4
|
"description": "Auto-migration system with ops DSL for Tango",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -67,10 +67,10 @@
|
|
|
67
67
|
"jiti": "^2.6.1",
|
|
68
68
|
"kleur": "^4.1.5",
|
|
69
69
|
"yargs": "^17.7.2",
|
|
70
|
-
"@danceroutine/tango-config": "1.
|
|
71
|
-
"@danceroutine/tango-codegen": "1.
|
|
72
|
-
"@danceroutine/tango-core": "1.
|
|
73
|
-
"@danceroutine/tango-schema": "1.
|
|
70
|
+
"@danceroutine/tango-config": "1.8.0",
|
|
71
|
+
"@danceroutine/tango-codegen": "1.8.0",
|
|
72
|
+
"@danceroutine/tango-core": "1.8.0",
|
|
73
|
+
"@danceroutine/tango-schema": "1.8.0"
|
|
74
74
|
},
|
|
75
75
|
"peerDependencies": {
|
|
76
76
|
"pg": "^8.13.1",
|
|
@@ -94,8 +94,9 @@
|
|
|
94
94
|
"tsdown": "^0.4.0",
|
|
95
95
|
"typescript": "^5.6.3",
|
|
96
96
|
"vitest": "^4.0.6",
|
|
97
|
-
"
|
|
98
|
-
"@danceroutine/tango-
|
|
97
|
+
"zod": "^4.0.0",
|
|
98
|
+
"@danceroutine/tango-testing": "1.8.0",
|
|
99
|
+
"@danceroutine/tango-orm": "1.8.0"
|
|
99
100
|
},
|
|
100
101
|
"scripts": {
|
|
101
102
|
"build": "tsdown",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"CompilerStrategy-yKw-Egxv.js","names":["factories: CompilerFactoryRegistry","value: unknown","dialect: Dialect","operation: MigrationOperation","name: TName","handler: (dialect: Dialect, op: CustomMigrationOperation<TName, TArgs>) => SQL[]"],"sources":["../src/domain/internal/InternalDialect.ts","../src/strategies/CompilerStrategy.ts"],"sourcesContent":["export const InternalDialect = {\n POSTGRES: 'postgres',\n SQLITE: 'sqlite',\n} as const;\n\nexport type InternalDialect = (typeof InternalDialect)[keyof typeof InternalDialect];\n","import { PostgresCompilerFactory } from '../compilers/factories/PostgresCompilerFactory';\nimport { SqliteCompilerFactory } from '../compilers/factories/SqliteCompilerFactory';\nimport type { CompilerFactory } from '../compilers/contracts/CompilerFactory';\nimport type { Dialect } from '../domain/Dialect';\nimport type { CustomMigrationOperation, MigrationOperation } from '../domain/MigrationOperation';\nimport type { SQL } from '../compilers/contracts/SQL';\nimport type { SQLCompiler } from '../compilers/contracts/SQLCompiler';\nimport { InternalDialect } from '../domain/internal/InternalDialect';\n\ntype CompilerFactoryRegistry = Record<Dialect, CompilerFactory>;\n\n/**\n * Dialect-aware SQL compiler orchestration with optional custom-op handlers.\n */\nexport class CompilerStrategy {\n static readonly BRAND = 'tango.migrations.compiler_strategy' as const;\n readonly __tangoBrand: typeof CompilerStrategy.BRAND = CompilerStrategy.BRAND;\n private readonly compilerCache = new Map<Dialect, SQLCompiler>();\n private readonly customHandlers = new Map<string, (dialect: Dialect, op: CustomMigrationOperation) => SQL[]>();\n\n constructor(private readonly factories: CompilerFactoryRegistry) {}\n\n /**\n * Narrow an unknown value to the dialect-aware migration compiler strategy.\n */\n static isCompilerStrategy(value: unknown): value is CompilerStrategy {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === CompilerStrategy.BRAND\n );\n }\n\n /**\n * Compile a migration operation to SQL for a target dialect.\n */\n compile(dialect: Dialect, operation: MigrationOperation): SQL[] {\n if (operation.kind === 'custom') {\n const handler = this.customHandlers.get(operation.name);\n if (!handler) {\n throw new Error(`Unsupported custom migration op: ${operation.name}`);\n }\n return handler(dialect, operation);\n }\n const compiler = this.getCompiler(dialect);\n return compiler.compile(operation);\n }\n\n /**\n * Register a handler for custom migration operations.\n */\n registerCustomHandler<TName extends string, TArgs extends object>(\n name: TName,\n handler: (dialect: Dialect, op: CustomMigrationOperation<TName, TArgs>) => SQL[]\n ): this {\n this.customHandlers.set(name, handler as (dialect: Dialect, op: CustomMigrationOperation) => SQL[]);\n return this;\n }\n\n /**\n * Resolve and cache a compiler instance for a dialect.\n */\n getCompiler(dialect: Dialect): SQLCompiler {\n const cached = this.compilerCache.get(dialect);\n if (cached) {\n return cached;\n }\n\n const factory = this.factories[dialect];\n if (!factory) {\n throw new Error(`No SQL compiler factory registered for dialect: ${String(dialect)}`);\n }\n const compiler = factory.create();\n this.compilerCache.set(dialect, compiler);\n return compiler;\n }\n}\n\n/**\n * Create the default compiler strategy with built-in dialect factories.\n */\nexport function createDefaultCompilerStrategy(): CompilerStrategy {\n return new CompilerStrategy({\n [InternalDialect.POSTGRES]: new PostgresCompilerFactory(),\n [InternalDialect.SQLITE]: new SqliteCompilerFactory(),\n });\n}\n"],"mappings":";;;MAAa,kBAAkB;CAC3B,UAAU;CACV,QAAQ;AACX;;;;ICWY,mBAAN,MAAM,iBAAiB;CAC1B,OAAgB,QAAQ;CACxB,eAAuD,iBAAiB;CACxE,gBAAiC,IAAI;CACrC,iBAAkC,IAAI;CAEtC,YAA6BA,WAAoC;AAAA,OAApC,YAAA;CAAsC;;;;CAKnE,OAAO,mBAAmBC,OAA2C;AACjE,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,iBAAiB;CAE/E;;;;CAKD,QAAQC,SAAkBC,WAAsC;AAC5D,MAAI,UAAU,SAAS,UAAU;GAC7B,MAAM,UAAU,KAAK,eAAe,IAAI,UAAU,KAAK;AACvD,QAAK,QACD,OAAM,IAAI,OAAO,mCAAmC,UAAU,KAAK;AAEvE,UAAO,QAAQ,SAAS,UAAU;EACrC;EACD,MAAM,WAAW,KAAK,YAAY,QAAQ;AAC1C,SAAO,SAAS,QAAQ,UAAU;CACrC;;;;CAKD,sBACIC,MACAC,SACI;AACJ,OAAK,eAAe,IAAI,MAAM,QAAqE;AACnG,SAAO;CACV;;;;CAKD,YAAYH,SAA+B;EACvC,MAAM,SAAS,KAAK,cAAc,IAAI,QAAQ;AAC9C,MAAI,OACA,QAAO;EAGX,MAAM,UAAU,KAAK,UAAU;AAC/B,OAAK,QACD,OAAM,IAAI,OAAO,kDAAkD,OAAO,QAAQ,CAAC;EAEvF,MAAM,WAAW,QAAQ,QAAQ;AACjC,OAAK,cAAc,IAAI,SAAS,SAAS;AACzC,SAAO;CACV;AACJ;AAKM,SAAS,gCAAkD;AAC9D,QAAO,IAAI,iBAAiB;GACvB,gBAAgB,WAAW,IAAI;GAC/B,gBAAgB,SAAS,IAAI;CACjC;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MigrationRunner-CSt99m9K.js","names":["modulePath: string","projectRoot: string","options?: { projectRoot?: string; registry?: ModelRegistry; moduleCache?: boolean }","options?: { projectRoot?: string }","client: DBClient","dialect: Dialect","migrationsDir: string","compilerStrategy?: CompilerStrategy","value: unknown","toId?: string","migrations: Migration[]","loaded: unknown","migration: Migration","x: unknown","op: MigrationOperation"],"sources":["../src/runtime/loadModule.ts","../src/runner/MigrationRunner.ts"],"sourcesContent":["import { resolve, extname } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { createJiti } from 'jiti';\nimport { ModelRegistry } from '@danceroutine/tango-schema';\n\nconst TS_EXTENSIONS = new Set(['.ts', '.tsx', '.mts', '.cts']);\n\nfunction toAbsolutePath(modulePath: string, projectRoot: string): string {\n return resolve(projectRoot, modulePath);\n}\n\nfunction isTypeScriptModule(modulePath: string): boolean {\n return TS_EXTENSIONS.has(extname(modulePath).toLowerCase());\n}\n\n/**\n * Load a module from a Tango app project root.\n *\n * TypeScript modules are loaded through jiti and JavaScript/ESM modules are loaded\n * through native dynamic import so published installs behave like end-user runtime.\n */\nexport async function loadModule(\n modulePath: string,\n options?: { projectRoot?: string; registry?: ModelRegistry; moduleCache?: boolean }\n): Promise<Record<string, unknown>> {\n const projectRoot = options?.projectRoot ?? process.cwd();\n const absolutePath = toAbsolutePath(modulePath, projectRoot);\n const executeImport = async (): Promise<Record<string, unknown>> => {\n if (isTypeScriptModule(absolutePath)) {\n const jiti = createJiti(resolve(projectRoot, 'tango.config.ts'), {\n interopDefault: true,\n moduleCache: options?.moduleCache ?? true,\n });\n return (await jiti.import<Record<string, unknown>>(absolutePath)) as Record<string, unknown>;\n }\n\n return (await import(pathToFileURL(absolutePath).href)) as Record<string, unknown>;\n };\n\n if (options?.registry) {\n return ModelRegistry.runWithRegistry(options.registry, executeImport);\n }\n\n return executeImport();\n}\n\n/**\n * Load a module and return default export when present.\n */\nexport async function loadDefaultExport(modulePath: string, options?: { projectRoot?: string }): Promise<unknown> {\n const loaded = await loadModule(modulePath, options);\n return loaded.default ?? loaded;\n}\n","import { CollectingBuilder } from '../builder/runtime/CollectingBuilder';\nimport type { Dialect } from '../domain/Dialect';\nimport { Migration } from '../domain/Migration';\nimport type { SQL } from '../compilers/contracts/SQL';\nimport type { MigrationOperation } from '../domain/MigrationOperation';\nimport type { CompilerStrategy } from '../strategies/CompilerStrategy';\nimport { createDefaultCompilerStrategy } from '../strategies/CompilerStrategy';\nimport { InternalDialect } from '../domain/internal/InternalDialect';\nimport { isError } from '@danceroutine/tango-core';\nimport { readdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { loadDefaultExport } from '../runtime/loadModule';\n\nconst JOURNAL = '_tango_migrations';\n\n/** DB client contract required by migration execution. */\ninterface DBClient {\n /** Execute SQL with optional parameters. */\n query<T = unknown>(sql: string, params?: readonly unknown[]): Promise<{ rows: T[] }>;\n /** Release underlying database resources. */\n close(): Promise<void>;\n}\n\n/**\n * Manages the lifecycle of database migrations: applying, planning, and tracking status.\n *\n * The runner reads migration files from a directory, compiles operations to SQL\n * for the target dialect, and maintains a journal table to track which migrations\n * have been applied. Each applied migration is checksummed to detect tampering.\n *\n * @example\n * ```typescript\n * const runner = new MigrationRunner(client, 'postgres', './migrations');\n *\n * // Apply all pending migrations\n * await runner.apply();\n *\n * // Apply up to a specific migration\n * await runner.apply('003_add_indexes');\n *\n * // Preview the SQL that would be generated\n * const sql = await runner.plan();\n *\n * // Check which migrations are applied\n * const statuses = await runner.status();\n * ```\n */\nexport class MigrationRunner {\n static readonly BRAND = 'tango.migrations.runner' as const;\n readonly __tangoBrand: typeof MigrationRunner.BRAND = MigrationRunner.BRAND;\n private compilerStrategy: CompilerStrategy;\n\n constructor(\n private client: DBClient,\n private dialect: Dialect,\n private migrationsDir: string = 'migrations',\n compilerStrategy?: CompilerStrategy\n ) {\n this.compilerStrategy = compilerStrategy ?? createDefaultCompilerStrategy();\n }\n\n /**\n * Narrow an unknown value to `MigrationRunner`.\n */\n static isMigrationRunner(value: unknown): value is MigrationRunner {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === MigrationRunner.BRAND\n );\n }\n\n /**\n * Apply all pending migrations, optionally stopping at a specific migration ID.\n * Migrations are applied in file-sort order. Already-applied migrations are skipped.\n * Non-online migrations are wrapped in a transaction on Postgres.\n */\n async apply(toId?: string): Promise<void> {\n await this.ensureJournal();\n const applied = await this.listApplied();\n const migrations = await this.loadMigrations();\n\n for (const migration of migrations) {\n if (toId && migration.id > toId) {\n break;\n }\n if (applied.has(migration.id)) {\n continue;\n }\n\n await this.applyMigration(migration);\n }\n }\n\n /**\n * Generate a dry-run SQL plan for all migrations without executing anything.\n * Useful for reviewing what SQL would be run before applying.\n */\n async plan(): Promise<string> {\n const migrations = await this.loadMigrations();\n let output = '';\n\n migrations.forEach((migration) => {\n const builder = new CollectingBuilder();\n migration.up(builder);\n const sqls = builder.ops.flatMap((op) => this.compileOperation(op));\n\n output += `# ${migration.id}\\n`;\n sqls.forEach((statement) => {\n output += statement.sql + ';\\n';\n });\n if (builder.dataFns.length) {\n output += '-- (data step present)\\n';\n }\n output += '\\n';\n });\n\n return output;\n }\n\n /**\n * Return the applied/pending status of every migration found on disk.\n */\n async status(): Promise<{ id: string; applied: boolean }[]> {\n const applied = await this.listApplied();\n const migrations = await this.loadMigrations();\n\n return migrations.map((m) => ({\n id: m.id,\n applied: applied.has(m.id),\n }));\n }\n\n private async ensureJournal(): Promise<void> {\n const sql =\n this.dialect === InternalDialect.POSTGRES\n ? `CREATE TABLE IF NOT EXISTS \"${JOURNAL}\" (\n id TEXT PRIMARY KEY,\n applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n checksum TEXT NOT NULL\n )`\n : `CREATE TABLE IF NOT EXISTS ${JOURNAL} (\n id TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL DEFAULT (datetime('now')),\n checksum TEXT NOT NULL\n )`;\n\n await this.client.query(sql);\n }\n\n private async listApplied(): Promise<Set<string>> {\n const table = this.dialect === InternalDialect.POSTGRES ? `\"${JOURNAL}\"` : JOURNAL;\n const { rows } = await this.client.query<{ id: string }>(`SELECT id FROM ${table}`);\n return new Set(rows.map((r) => r.id));\n }\n\n private async loadMigrations(): Promise<Migration[]> {\n const files = (await readdir(this.migrationsDir)).filter((f) => f.endsWith('.ts') || f.endsWith('.js')).sort();\n\n const migrations: Migration[] = [];\n\n for (const file of files) {\n const absolutePath = resolve(this.migrationsDir, file);\n let loaded: unknown;\n try {\n loaded = await loadDefaultExport(absolutePath, { projectRoot: process.cwd() });\n } catch (error) {\n const reason = isError(error) ? error.message : String(error);\n throw new Error(`Failed to load migration module '${file}': ${reason}`, { cause: error });\n }\n\n if (Migration.isMigration(loaded)) {\n migrations.push(loaded);\n continue;\n }\n\n if (Migration.isMigrationConstructor(loaded)) {\n migrations.push(new loaded());\n continue;\n }\n\n throw new Error(\n `Invalid migration module '${file}'. Default export must be a Migration subclass or instance.`\n );\n }\n\n return migrations;\n }\n\n private async applyMigration(migration: Migration): Promise<void> {\n const builder = new CollectingBuilder();\n await migration.up(builder);\n\n const sqls = builder.ops.flatMap((op) => this.compileOperation(op));\n const checksum = String(this.hashJSON(builder.ops));\n\n const isOnline = (migration.mode ?? builder.getMode()) === 'online';\n\n if (!isOnline && this.dialect === InternalDialect.POSTGRES) {\n await this.client.query('BEGIN');\n }\n\n try {\n for (const statement of sqls) {\n await this.client.query(statement.sql, statement.params);\n }\n\n for (const fn of builder.dataFns) {\n await fn({ query: (sql, params) => this.client.query(sql, params).then(() => {}) });\n }\n\n const table = this.dialect === InternalDialect.POSTGRES ? `\"${JOURNAL}\"` : JOURNAL;\n const placeholder = this.dialect === InternalDialect.POSTGRES ? '$1, $2' : '?, ?';\n await this.client.query(`INSERT INTO ${table} (id, checksum) VALUES (${placeholder})`, [\n migration.id,\n checksum,\n ]);\n\n if (!isOnline && this.dialect === InternalDialect.POSTGRES) {\n await this.client.query('COMMIT');\n }\n } catch (error) {\n if (!isOnline && this.dialect === InternalDialect.POSTGRES) {\n await this.client.query('ROLLBACK');\n }\n throw error;\n }\n }\n\n /**\n * Compute a simple hash of the migration's operation list.\n * Stored alongside each applied migration in the journal table to detect\n * if a migration file has been modified after it was already applied.\n * Uses a djb2-like hash over the JSON-serialized operations.\n */\n private hashJSON(x: unknown): number {\n const s = JSON.stringify(x);\n let h = 0;\n for (let i = 0; i < s.length; i++) {\n // oxlint-disable-next-line prefer-code-point\n h = Math.imul(31, h) + s.charCodeAt(i);\n // oxlint-disable-next-line prefer-math-trunc\n h = h | 0;\n }\n // oxlint-disable-next-line unicorn/prefer-math-trunc\n return h >>> 0;\n }\n\n private compileOperation(op: MigrationOperation): SQL[] {\n return this.compilerStrategy.compile(this.dialect, op);\n }\n}\n"],"mappings":";;;;;;;;;;;AAKA,MAAM,gBAAgB,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAQ;AAAO;AAE7D,SAAS,eAAeA,YAAoBC,aAA6B;AACrE,QAAO,UAAQ,aAAa,WAAW;AAC1C;AAED,SAAS,mBAAmBD,YAA6B;AACrD,QAAO,cAAc,IAAI,QAAQ,WAAW,CAAC,aAAa,CAAC;AAC9D;AAQM,eAAe,WAClBA,YACAE,SACgC;CAChC,MAAM,cAAc,SAAS,eAAe,QAAQ,KAAK;CACzD,MAAM,eAAe,eAAe,YAAY,YAAY;CAC5D,MAAM,gBAAgB,YAA8C;AAChE,MAAI,mBAAmB,aAAa,EAAE;GAClC,MAAM,OAAO,WAAW,UAAQ,aAAa,kBAAkB,EAAE;IAC7D,gBAAgB;IAChB,aAAa,SAAS,eAAe;GACxC,EAAC;AACF,UAAQ,MAAM,KAAK,OAAgC,aAAa;EACnE;AAED,SAAQ,MAAM,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,GAAG,IAAI,EAAE,QAAQ,KAAK;AAE/B,OAAI,KAAK,KAAK,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE;AAEtC,OAAI,IAAI;EACX;AAED,SAAO,MAAM;CAChB;CAED,iBAAyBC,IAA+B;AACpD,SAAO,KAAK,iBAAiB,QAAQ,KAAK,SAAS,GAAG;CACzD;AACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"SqliteCompilerFactory-BAodJW9n.js","names":["value: unknown","op: MigrationOperation","constraints: string[]","out: SQL[]","table: string","column: string","defaultValue: unknown","column: ColumnSpec","parts: string[]","type: ColumnType","exhaustive: never","value: unknown","value: unknown","op: MigrationOperation","column: ColumnSpec","parts: string[]","value: unknown"],"sources":["../src/compilers/dialects/PostgresCompiler.ts","../src/compilers/factories/PostgresCompilerFactory.ts","../src/compilers/dialects/SqliteCompiler.ts","../src/compilers/factories/SqliteCompilerFactory.ts"],"sourcesContent":["import type { MigrationOperation } from '../../domain/MigrationOperation';\nimport type { SQL } from '../contracts/SQL';\nimport type { ColumnSpec } from '../../builder/contracts/ColumnSpec';\nimport type { ColumnType } from '../../builder/contracts/ColumnType';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { InternalOperationKind } from '../../domain/internal/InternalOperationKind';\nimport { InternalColumnType } from '../../domain/internal/InternalColumnType';\nimport { MigrationSqlSafetyAdapter } from '../../internal/MigrationSqlSafetyAdapter';\n\n/**\n * PostgreSQL SQL compiler for migration operations.\n */\nexport class PostgresCompiler implements SQLCompiler {\n static readonly BRAND = 'tango.migrations.postgres_compiler' as const;\n readonly __tangoBrand: typeof PostgresCompiler.BRAND = PostgresCompiler.BRAND;\n private readonly sqlSafety = new MigrationSqlSafetyAdapter('postgres');\n\n /**\n * Narrow an unknown value to the PostgreSQL migration compiler implementation.\n */\n static isPostgresCompiler(value: unknown): value is PostgresCompiler {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === PostgresCompiler.BRAND\n );\n }\n\n /**\n * Compile a migration operation into one or more PostgreSQL statements.\n */\n compile(op: MigrationOperation): SQL[] {\n switch (op.kind) {\n case InternalOperationKind.TABLE_CREATE: {\n const cols = op.columns.map((c) => this.colDDL(c)).join(', ');\n const pkCols = op.columns.filter((c) => c.primaryKey).map((c) => this.sqlSafety.column(c.name));\n const constraints: string[] = [];\n\n if (pkCols.length) {\n constraints.push(`PRIMARY KEY (${pkCols.join(', ')})`);\n }\n\n op.columns\n .filter((column) => column.references)\n .forEach((column) => {\n const references = column.references!;\n const fkName = `${op.table}_${column.name}_fkey`;\n let fk = `CONSTRAINT ${this.sqlSafety.constraint(fkName)} FOREIGN KEY (${this.sqlSafety.column(column.name)}) REFERENCES ${this.sqlSafety.table(references.table)}(${this.sqlSafety.column(references.column)})`;\n if (references.onDelete) {\n fk += ` ON DELETE ${references.onDelete}`;\n }\n if (references.onUpdate) {\n fk += ` ON UPDATE ${references.onUpdate}`;\n }\n constraints.push(fk);\n });\n\n const allParts = [cols, ...constraints].join(', ');\n const sql = `CREATE TABLE ${this.sqlSafety.table(op.table)} (${allParts})`;\n return [{ sql, params: [] }];\n }\n\n case InternalOperationKind.TABLE_DROP:\n return [\n { sql: `DROP TABLE ${this.sqlSafety.table(op.table)}${op.cascade ? ' CASCADE' : ''}`, params: [] },\n ];\n\n case InternalOperationKind.COLUMN_ADD:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} ADD COLUMN ${this.colDDL(op.column)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.COLUMN_DROP:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} DROP COLUMN ${this.sqlSafety.column(op.column)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.COLUMN_ALTER: {\n const out: SQL[] = [];\n if (op.to.type) {\n out.push({\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} ALTER COLUMN ${this.sqlSafety.column(op.column)} TYPE ${this.typeToSQL(op.to.type)}`,\n params: [],\n });\n }\n if (op.to.notNull !== undefined) {\n out.push({\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} ALTER COLUMN ${this.sqlSafety.column(op.column)} ${op.to.notNull ? 'SET NOT NULL' : 'DROP NOT NULL'}`,\n params: [],\n });\n }\n out.push(...this.compileDefaultChange(op.table, op.column, op.to.default));\n return out;\n }\n\n case InternalOperationKind.COLUMN_RENAME:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} RENAME COLUMN ${this.sqlSafety.column(op.from)} TO ${this.sqlSafety.column(op.to)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.INDEX_CREATE: {\n const cols = this.sqlSafety.columns(op.on).join(', ');\n const uniq = op.unique ? 'UNIQUE ' : '';\n const conc = op.concurrently ? 'CONCURRENTLY ' : '';\n const where = this.sqlSafety.optionalRawFragment('where', op.where);\n return [\n {\n sql: `CREATE ${uniq}INDEX ${conc}${this.sqlSafety.index(op.name)} ON ${this.sqlSafety.table(op.table)} (${cols})${where ? ` WHERE ${where}` : ''}`,\n params: [],\n },\n ];\n }\n\n case InternalOperationKind.INDEX_DROP: {\n const conc = op.concurrently ? 'CONCURRENTLY ' : '';\n return [{ sql: `DROP INDEX ${conc}${this.sqlSafety.index(op.name)}`, params: [] }];\n }\n\n case InternalOperationKind.FK_CREATE: {\n const cols = this.sqlSafety.columns(op.columns).join(', ');\n const refs = this.sqlSafety.columns(op.refColumns).join(', ');\n const name = op.name ?? `${op.table}_${op.columns.join('_')}_fkey`;\n const notValid = op.notValid ? ' NOT VALID' : '';\n const onDel = op.onDelete ? ` ON DELETE ${op.onDelete}` : '';\n const onUpd = op.onUpdate ? ` ON UPDATE ${op.onUpdate}` : '';\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} ADD CONSTRAINT ${this.sqlSafety.constraint(name)} FOREIGN KEY (${cols}) REFERENCES ${this.sqlSafety.table(op.refTable)} (${refs})${onDel}${onUpd}${notValid}`,\n params: [],\n },\n ];\n }\n\n case InternalOperationKind.FK_VALIDATE:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} VALIDATE CONSTRAINT ${this.sqlSafety.constraint(op.name)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.FK_DROP:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} DROP CONSTRAINT ${this.sqlSafety.constraint(op.name)}`,\n params: [],\n },\n ];\n\n default:\n return [];\n }\n }\n\n /**\n * Compile a DEFAULT value change into ALTER TABLE statements.\n * Extracted to flatten the nested conditional logic.\n */\n private compileDefaultChange(table: string, column: string, defaultValue: unknown): SQL[] {\n if (defaultValue === undefined) {\n return [];\n }\n\n if (defaultValue === null) {\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(table)} ALTER COLUMN ${this.sqlSafety.column(column)} DROP DEFAULT`,\n params: [],\n },\n ];\n }\n\n if (this.sqlSafety.isTrustedFragment(defaultValue)) {\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(table)} ALTER COLUMN ${this.sqlSafety.column(column)} SET DEFAULT ${this.sqlSafety.rawFragment('default', defaultValue)}`,\n params: [],\n },\n ];\n }\n\n if (\n defaultValue &&\n typeof defaultValue === 'object' &&\n 'now' in defaultValue &&\n (defaultValue as { now?: unknown }).now\n ) {\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(table)} ALTER COLUMN ${this.sqlSafety.column(column)} SET DEFAULT now()`,\n params: [],\n },\n ];\n }\n\n return [];\n }\n\n private colDDL(column: ColumnSpec): string {\n const parts: string[] = [this.sqlSafety.column(column.name)];\n\n switch (column.type) {\n case InternalColumnType.SERIAL:\n parts.push('SERIAL');\n break;\n case InternalColumnType.INT:\n parts.push('INTEGER');\n break;\n case InternalColumnType.BIGINT:\n parts.push('BIGINT');\n break;\n case InternalColumnType.TEXT:\n parts.push('TEXT');\n break;\n case InternalColumnType.BOOL:\n parts.push('BOOLEAN');\n break;\n case InternalColumnType.TIMESTAMPTZ:\n parts.push('TIMESTAMPTZ');\n break;\n case InternalColumnType.JSONB:\n parts.push('JSONB');\n break;\n case InternalColumnType.UUID:\n parts.push('UUID');\n break;\n }\n\n if (column.notNull) {\n parts.push('NOT NULL');\n }\n const defaultSql = this.sqlSafety.rawDefault(column.default, 'now()');\n if (defaultSql) {\n parts.push(`DEFAULT ${defaultSql}`);\n }\n if (column.unique && !column.primaryKey) {\n parts.push('UNIQUE');\n }\n\n return parts.join(' ');\n }\n\n private typeToSQL(type: ColumnType): string {\n switch (type) {\n case InternalColumnType.SERIAL:\n return 'SERIAL';\n case InternalColumnType.INT:\n return 'INTEGER';\n case InternalColumnType.BIGINT:\n return 'BIGINT';\n case InternalColumnType.TEXT:\n return 'TEXT';\n case InternalColumnType.BOOL:\n return 'BOOLEAN';\n case InternalColumnType.TIMESTAMPTZ:\n return 'TIMESTAMPTZ';\n case InternalColumnType.JSONB:\n return 'JSONB';\n case InternalColumnType.UUID:\n return 'UUID';\n default: {\n const exhaustive: never = type;\n throw new Error(`Unsupported column type: ${exhaustive}`);\n }\n }\n }\n}\n","import type { CompilerFactory } from '../contracts/CompilerFactory';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { PostgresCompiler } from '../dialects/PostgresCompiler';\n\n/**\n * Factory for PostgreSQL migration compilers.\n */\nexport class PostgresCompilerFactory implements CompilerFactory {\n static readonly BRAND = 'tango.migrations.postgres_compiler_factory' as const;\n readonly __tangoBrand: typeof PostgresCompilerFactory.BRAND = PostgresCompilerFactory.BRAND;\n\n /**\n * Narrow an unknown value to the factory that provisions PostgreSQL compilers.\n */\n static isPostgresCompilerFactory(value: unknown): value is PostgresCompilerFactory {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === PostgresCompilerFactory.BRAND\n );\n }\n\n /**\n * Create a PostgreSQL SQL compiler instance.\n */\n create(): SQLCompiler {\n return new PostgresCompiler();\n }\n}\n","import type { MigrationOperation } from '../../domain/MigrationOperation';\nimport type { SQL } from '../contracts/SQL';\nimport type { ColumnSpec } from '../../builder/contracts/ColumnSpec';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { InternalOperationKind } from '../../domain/internal/InternalOperationKind';\nimport { InternalColumnType } from '../../domain/internal/InternalColumnType';\nimport { MigrationSqlSafetyAdapter } from '../../internal/MigrationSqlSafetyAdapter';\n\n/**\n * SQLite SQL compiler for migration operations.\n */\nexport class SqliteCompiler implements SQLCompiler {\n static readonly BRAND = 'tango.migrations.sqlite_compiler' as const;\n readonly __tangoBrand: typeof SqliteCompiler.BRAND = SqliteCompiler.BRAND;\n private readonly sqlSafety = new MigrationSqlSafetyAdapter('sqlite');\n\n /**\n * Narrow an unknown value to the SQLite migration compiler implementation.\n */\n static isSqliteCompiler(value: unknown): value is SqliteCompiler {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === SqliteCompiler.BRAND\n );\n }\n\n /**\n * Compile a migration operation into one or more SQLite statements.\n */\n compile(op: MigrationOperation): SQL[] {\n switch (op.kind) {\n case InternalOperationKind.TABLE_CREATE: {\n const cols = op.columns.map((c) => this.colDDL(c));\n const pkCols = op.columns\n .filter((c) => c.primaryKey && c.type !== InternalColumnType.SERIAL)\n .map((c) => this.sqlSafety.column(c.name));\n\n if (pkCols.length) {\n cols.push(`PRIMARY KEY (${pkCols.join(', ')})`);\n }\n\n op.columns\n .filter((column) => column.references)\n .forEach((column) => {\n const references = column.references!;\n cols.push(\n `FOREIGN KEY (${this.sqlSafety.column(column.name)}) REFERENCES ${this.sqlSafety.table(references.table)}(${this.sqlSafety.column(references.column)})${references.onDelete ? ` ON DELETE ${references.onDelete}` : ''}${references.onUpdate ? ` ON UPDATE ${references.onUpdate}` : ''}`\n );\n });\n\n const sql = `CREATE TABLE ${this.sqlSafety.table(op.table)} (${cols.join(', ')})`;\n return [{ sql, params: [] }];\n }\n\n case InternalOperationKind.TABLE_DROP:\n return [{ sql: `DROP TABLE ${this.sqlSafety.table(op.table)}`, params: [] }];\n\n case InternalOperationKind.COLUMN_ADD:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} ADD COLUMN ${this.colDDL(op.column)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.COLUMN_DROP:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} DROP COLUMN ${this.sqlSafety.column(op.column)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.COLUMN_RENAME:\n return [\n {\n sql: `ALTER TABLE ${this.sqlSafety.table(op.table)} RENAME COLUMN ${this.sqlSafety.column(op.from)} TO ${this.sqlSafety.column(op.to)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.INDEX_CREATE: {\n const cols = this.sqlSafety.columns(op.on).join(', ');\n const uniq = op.unique ? 'UNIQUE ' : '';\n const where = this.sqlSafety.optionalRawFragment('where', op.where);\n return [\n {\n sql: `CREATE ${uniq}INDEX ${this.sqlSafety.index(op.name)} ON ${this.sqlSafety.table(op.table)} (${cols})${where ? ` WHERE ${where}` : ''}`,\n params: [],\n },\n ];\n }\n\n case InternalOperationKind.INDEX_DROP:\n return [{ sql: `DROP INDEX ${this.sqlSafety.index(op.name)}`, params: [] }];\n\n case InternalOperationKind.COLUMN_ALTER:\n case InternalOperationKind.FK_CREATE:\n case InternalOperationKind.FK_VALIDATE:\n case InternalOperationKind.FK_DROP:\n return [];\n\n default:\n return [];\n }\n }\n\n private colDDL(column: ColumnSpec): string {\n const parts: string[] = [this.sqlSafety.column(column.name)];\n\n switch (column.type) {\n case InternalColumnType.SERIAL:\n parts.push('INTEGER PRIMARY KEY AUTOINCREMENT');\n return parts.join(' ');\n case InternalColumnType.INT:\n parts.push('INTEGER');\n break;\n case InternalColumnType.BIGINT:\n parts.push('INTEGER');\n break;\n case InternalColumnType.TEXT:\n parts.push('TEXT');\n break;\n case InternalColumnType.BOOL:\n parts.push('INTEGER');\n break;\n case InternalColumnType.TIMESTAMPTZ:\n parts.push('TEXT');\n break;\n case InternalColumnType.JSONB:\n parts.push('TEXT');\n break;\n case InternalColumnType.UUID:\n parts.push('TEXT');\n break;\n }\n\n if (column.notNull) {\n parts.push('NOT NULL');\n }\n const defaultSql = this.sqlSafety.rawDefault(column.default, \"(datetime('now'))\");\n if (defaultSql) {\n parts.push(`DEFAULT ${defaultSql}`);\n }\n if (column.unique && !column.primaryKey) {\n parts.push('UNIQUE');\n }\n\n return parts.join(' ');\n }\n}\n","import type { CompilerFactory } from '../contracts/CompilerFactory';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { SqliteCompiler } from '../dialects/SqliteCompiler';\n\n/**\n * Factory for SQLite migration compilers.\n */\nexport class SqliteCompilerFactory implements CompilerFactory {\n static readonly BRAND = 'tango.migrations.sqlite_compiler_factory' as const;\n readonly __tangoBrand: typeof SqliteCompilerFactory.BRAND = SqliteCompilerFactory.BRAND;\n\n /**\n * Narrow an unknown value to the factory that provisions SQLite compilers.\n */\n static isSqliteCompilerFactory(value: unknown): value is SqliteCompilerFactory {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === SqliteCompilerFactory.BRAND\n );\n }\n\n /**\n * Create a SQLite SQL compiler instance.\n */\n create(): SQLCompiler {\n return new SqliteCompiler();\n }\n}\n"],"mappings":";;;;;IAYa,mBAAN,MAAM,iBAAwC;CACjD,OAAgB,QAAQ;CACxB,eAAuD,iBAAiB;CACxE,YAA6B,IAAI,0BAA0B;;;;CAK3D,OAAO,mBAAmBA,OAA2C;AACjE,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,iBAAiB;CAE/E;;;;CAKD,QAAQC,IAA+B;AACnC,UAAQ,GAAG,MAAX;AACI,QAAK,sBAAsB,cAAc;IACrC,MAAM,OAAO,GAAG,QAAQ,IAAI,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC,CAAC,KAAK,KAAK;IAC7D,MAAM,SAAS,GAAG,QAAQ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B,UAAM,KAAK,OAAO;AAClB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,OAAO;AAClB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,OAAO;AAClB;EACP;AAED,MAAI,OAAO,QACP,OAAM,KAAK,WAAW;EAE1B,MAAM,aAAa,KAAK,UAAU,WAAW,OAAO,SAAS,oBAAoB;AACjF,MAAI,WACA,OAAM,MAAM,UAAU,WAAW,EAAE;AAEvC,MAAI,OAAO,WAAW,OAAO,WACzB,OAAM,KAAK,SAAS;AAGxB,SAAO,MAAM,KAAK,IAAI;CACzB;AACJ;;;;IChJY,wBAAN,MAAM,sBAAiD;CAC1D,OAAgB,QAAQ;CACxB,eAA4D,sBAAsB;;;;CAKlF,OAAO,wBAAwBC,OAAgD;AAC3E,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,sBAAsB;CAEpF;;;;CAKD,SAAsB;AAClB,SAAO,IAAI;CACd;AACJ"}
|
package/dist/cli-DOBziuSJ.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"cli-DOBziuSJ.js","names":["modulePath: string","configPathArg: string | undefined","configEnvArg: ConfigEnvironment | undefined","db: {\n adapter: string;\n url?: string;\n filename?: string;\n host?: string;\n port?: number;\n database?: string;\n user?: string;\n password?: string;\n}","argv: {\n dialect?: string;\n dir?: string;\n db?: string;\n config?: string;\n env?: ConfigEnvironment;\n}","value: unknown","moduleValue: unknown","models: ModelMetadataLike[]","modelsPath: string","dbUrl: string","dialect: string","db: string","dialect: Dialect","sql: string","params?: readonly unknown[]","filename: string","yargsBuilder: Argv","dbState: DbSchema"],"sources":["../src/commands/cli.ts"],"sourcesContent":["import { access, mkdir } from 'node:fs/promises';\nimport { constants as fsConstants } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport type { Argv } from 'yargs';\nimport { MigrationRunner } from '../runner/MigrationRunner';\nimport { MigrationGenerator } from '../generator/MigrationGenerator';\nimport { diffSchema } from '../diff/diffSchema';\nimport type { DbSchema } from '../introspect/PostgresIntrospector';\nimport type { Dialect } from '../domain/Dialect';\nimport type { ColumnType } from '../builder/contracts/ColumnType';\nimport type { DeleteReferentialAction } from '../builder/contracts/DeleteReferentialAction';\nimport type { UpdateReferentialAction } from '../builder/contracts/UpdateReferentialAction';\nimport { createDefaultIntrospectorStrategy } from '../strategies/IntrospectorStrategy';\nimport { InternalDialect } from '../domain/internal/InternalDialect';\nimport { loadConfig } from '@danceroutine/tango-config';\nimport { loadProjectModule } from '@danceroutine/tango-codegen/commands';\nimport { writeRelationRegistryArtifacts } from '@danceroutine/tango-codegen/generators';\nimport { getLogger } from '@danceroutine/tango-core';\nimport { GENERATED_RELATION_REGISTRY_DIRNAME, ModelRegistry } from '@danceroutine/tango-schema';\nimport { loadModule } from '../runtime/loadModule';\n\nconst logger = getLogger('tango.migrations');\n\ntype ConfigEnvironment = 'development' | 'test' | 'production';\n\ntype OptionalMigrationDefaults = {\n dialect?: Dialect;\n db?: string;\n dir?: string;\n autoApply?: boolean;\n};\n\ntype ModelMetadataLike = {\n table: string;\n fields: Array<{\n name: string;\n type: ColumnType;\n notNull?: boolean;\n default?: string | { now: true } | null;\n primaryKey?: boolean;\n unique?: boolean;\n references?: {\n table: string;\n column: string;\n onDelete?: DeleteReferentialAction;\n onUpdate?: UpdateReferentialAction;\n };\n }>;\n indexes?: Array<{ name: string; on: string[]; unique?: boolean }>;\n};\n\ntype CliDbClient = {\n query<T = unknown>(sql: string, params?: readonly unknown[]): Promise<{ rows: T[] }>;\n close(): Promise<void>;\n};\n\ntype LoadedModelsResult = {\n models: ModelMetadataLike[];\n registry: ModelRegistry;\n modelTypeAccessors: Record<string, string>;\n};\n\ntype ModelContainerLike = {\n metadata: ModelMetadataLike;\n};\n\nasync function importModule(modulePath: string): Promise<Record<string, unknown>> {\n return loadModule(modulePath, { projectRoot: process.cwd() });\n}\n\nasync function tryLoadMigrationDefaults(\n configPathArg: string | undefined,\n configEnvArg: ConfigEnvironment | undefined\n): Promise<OptionalMigrationDefaults> {\n const explicitConfigPath = typeof configPathArg === 'string' && configPathArg.trim().length > 0;\n const resolvedPath = resolve(process.cwd(), configPathArg?.trim() || './tango.config.ts');\n\n try {\n await access(resolvedPath, fsConstants.F_OK);\n } catch (error) {\n if (explicitConfigPath) {\n throw new Error(`Config file not found: ${resolvedPath}`, { cause: error });\n }\n return {};\n }\n\n const module = await importModule(resolvedPath);\n const fileConfig = (module.default ?? module) as { current?: ConfigEnvironment } & Record<string, unknown>;\n\n const loaded = loadConfig(() => ({\n ...fileConfig,\n ...(configEnvArg ? { current: configEnvArg } : {}),\n }));\n\n const { db, migrations } = loaded.current;\n const inferredDialect = db.adapter as Dialect;\n const inferredDb = resolveDbTarget(db);\n\n return {\n dialect: inferredDialect,\n db: inferredDb,\n dir: migrations.dir,\n autoApply: (migrations as { autoApply?: boolean }).autoApply,\n };\n}\n\nfunction resolveDbTarget(db: {\n adapter: string;\n url?: string;\n filename?: string;\n host?: string;\n port?: number;\n database?: string;\n user?: string;\n password?: string;\n}): string | undefined {\n if (db.adapter === InternalDialect.SQLITE) {\n return db.filename ?? db.url;\n }\n\n if (db.url) {\n return db.url;\n }\n\n if (!db.database) {\n return undefined;\n }\n\n const host = db.host ?? 'localhost';\n const port = db.port ?? 5432;\n const encodedUser = db.user ? encodeURIComponent(db.user) : '';\n const encodedPassword = db.password ? encodeURIComponent(db.password) : '';\n const userInfo =\n encodedUser.length > 0\n ? encodedPassword.length > 0\n ? `${encodedUser}:${encodedPassword}@`\n : `${encodedUser}@`\n : '';\n\n return `postgres://${userInfo}${host}:${String(port)}/${db.database}`;\n}\n\nasync function resolveCommandInputs(argv: {\n dialect?: string;\n dir?: string;\n db?: string;\n config?: string;\n env?: ConfigEnvironment;\n}): Promise<{ dialect: Dialect; dir: string; db?: string; autoApply: boolean }> {\n const defaults = await tryLoadMigrationDefaults(argv.config, argv.env);\n\n const resolvedDialect = (argv.dialect as Dialect | undefined) ?? defaults.dialect ?? InternalDialect.POSTGRES;\n const resolvedDir = argv.dir ?? defaults.dir ?? 'migrations';\n const resolvedDb = argv.db ?? defaults.db;\n\n return {\n dialect: resolvedDialect,\n dir: resolvedDir,\n db: resolvedDb,\n autoApply: defaults.autoApply ?? true,\n };\n}\n\nfunction isModelContainerLike(value: unknown): value is ModelContainerLike {\n return typeof value === 'object' && value !== null && 'metadata' in value;\n}\n\nfunction collectExportedModels(moduleValue: unknown): ModelMetadataLike[] {\n if (!moduleValue || typeof moduleValue !== 'object') {\n return [];\n }\n\n const models: ModelMetadataLike[] = [];\n for (const value of Object.values(moduleValue as Record<string, unknown>)) {\n if (isModelContainerLike(value)) {\n models.push(value.metadata);\n continue;\n }\n\n if (!value || typeof value !== 'object') {\n continue;\n }\n\n for (const nestedValue of Object.values(value as Record<string, unknown>)) {\n if (isModelContainerLike(nestedValue)) {\n models.push(nestedValue.metadata);\n }\n }\n }\n\n return models;\n}\n\nasync function loadModels(modelsPath: string): Promise<LoadedModelsResult> {\n const {\n loaded: mod,\n registry,\n modelTypeAccessors,\n } = await loadProjectModule(modelsPath, {\n projectRoot: process.cwd(),\n outputDir: resolve(process.cwd(), GENERATED_RELATION_REGISTRY_DIRNAME),\n });\n const moduleValue = (mod.default ?? mod) as unknown;\n\n const models = isModelContainerLike(moduleValue)\n ? [moduleValue.metadata, ...collectExportedModels(moduleValue)]\n : collectExportedModels(moduleValue);\n\n if (models.length === 0) {\n throw new Error(`No models found in '${modelsPath}'. Ensure the module exports Model() definitions.`);\n }\n\n return {\n models,\n registry,\n modelTypeAccessors,\n };\n}\n\nasync function connectAndIntrospect(dbUrl: string, dialect: string): Promise<DbSchema> {\n const dbClient = await connectDbClient(dbUrl, dialect as Dialect);\n\n try {\n const strategy = createDefaultIntrospectorStrategy();\n return await strategy.introspect(dialect as Dialect, dbClient);\n } finally {\n await dbClient.close();\n }\n}\n\nasync function connectDbClient(db: string, dialect: Dialect): Promise<CliDbClient> {\n if (dialect === InternalDialect.POSTGRES) {\n const pg = await import('pg');\n const client = new pg.default.Client({ connectionString: db });\n await client.connect();\n\n return {\n async query<T = unknown>(sql: string, params?: readonly unknown[]): Promise<{ rows: T[] }> {\n const result = await client.query(sql, params as unknown[] | undefined);\n return { rows: result.rows as T[] };\n },\n async close(): Promise<void> {\n await client.end();\n },\n };\n }\n\n if (dialect === InternalDialect.SQLITE) {\n const sqlite = await import('better-sqlite3');\n const DatabaseCtor = (sqlite.default ?? sqlite) as new (filename: string) => {\n prepare(sql: string): {\n all(...params: unknown[]): unknown[];\n run(...params: unknown[]): unknown;\n };\n close(): void;\n };\n\n const filename = normalizeSqliteFilename(db);\n await ensureSqliteParentDirectory(filename);\n const connection = new DatabaseCtor(filename);\n\n return {\n async query<T = unknown>(sql: string, params?: readonly unknown[]): Promise<{ rows: T[] }> {\n const statement = connection.prepare(sql);\n const values = [...(params ?? [])];\n const isSelectLike = /^\\s*(SELECT|PRAGMA|WITH)\\b/i.test(sql);\n if (isSelectLike) {\n return { rows: statement.all(...values) as T[] };\n }\n\n statement.run(...values);\n return { rows: [] as T[] };\n },\n async close(): Promise<void> {\n connection.close();\n },\n };\n }\n\n throw new Error(`Unsupported dialect: ${dialect}`);\n}\n\nasync function ensureSqliteParentDirectory(filename: string): Promise<void> {\n if (filename === ':memory:' || filename === 'file::memory:') {\n return;\n }\n const directory = dirname(filename);\n if (directory === '.' || directory.length === 0) {\n return;\n }\n await mkdir(directory, { recursive: true });\n}\n\nfunction normalizeSqliteFilename(db: string): string {\n if (db.startsWith('sqlite://')) {\n return db.slice('sqlite://'.length);\n }\n return db;\n}\n\n/**\n * Register Tango's migration commands on an existing yargs parser.\n */\nexport function registerMigrationsCommands(yargsBuilder: Argv): Argv {\n return yargsBuilder\n .command(\n 'migrate',\n 'Apply pending migrations to the database',\n (builder) =>\n builder\n .option('dir', {\n type: 'string',\n describe: 'Migrations directory',\n })\n .option('db', {\n type: 'string',\n describe: 'Database connection URL',\n })\n .option('dialect', {\n type: 'string',\n choices: ['postgres', 'sqlite'] as const,\n describe: 'Database dialect',\n })\n .option('config', {\n type: 'string',\n describe: 'Path to tango.config.ts (auto-loads ./tango.config.ts when present)',\n })\n .option('env', {\n type: 'string',\n choices: ['development', 'test', 'production'] as const,\n describe: 'Config environment override',\n })\n .option('to', {\n type: 'string',\n describe: 'Target migration ID (apply up to this migration)',\n }),\n async (argv) => {\n const resolved = await resolveCommandInputs({\n dialect: argv.dialect as string | undefined,\n dir: argv.dir as string | undefined,\n db: argv.db as string | undefined,\n config: argv.config as string | undefined,\n env: argv.env as ConfigEnvironment | undefined,\n });\n\n if (!resolved.autoApply) {\n logger.info('Auto-migration disabled (autoApply: false). Skipping.');\n return;\n }\n\n if (!resolved.db) {\n throw new Error('No database target provided. Pass --db or define db settings in tango.config.ts.');\n }\n\n const dbClient = await connectDbClient(resolved.db, resolved.dialect);\n\n const runner = new MigrationRunner(dbClient, resolved.dialect, resolved.dir);\n await runner.apply(argv.to);\n\n await dbClient.close();\n logger.info('Migrations applied successfully');\n }\n )\n .command(\n 'make:migrations',\n 'Generate migration file by comparing models to database',\n (builder) =>\n builder\n .option('dir', {\n type: 'string',\n describe: 'Migrations directory',\n })\n .option('name', {\n type: 'string',\n demandOption: true,\n describe: 'Migration name (e.g. \"create_users\")',\n })\n .option('models', {\n type: 'string',\n demandOption: true,\n describe: 'Path to module exporting Model definitions (e.g. \"./src/models.ts\")',\n })\n .option('db', {\n type: 'string',\n describe: 'Database connection URL for introspection (omit for initial migration)',\n })\n .option('dialect', {\n type: 'string',\n choices: ['postgres', 'sqlite'] as const,\n describe: 'Database dialect',\n })\n .option('config', {\n type: 'string',\n describe: 'Path to tango.config.ts (auto-loads ./tango.config.ts when present)',\n })\n .option('env', {\n type: 'string',\n choices: ['development', 'test', 'production'] as const,\n describe: 'Config environment override',\n }),\n async (argv) => {\n const resolved = await resolveCommandInputs({\n dialect: argv.dialect as string | undefined,\n dir: argv.dir as string | undefined,\n db: argv.db as string | undefined,\n config: argv.config as string | undefined,\n env: argv.env as ConfigEnvironment | undefined,\n });\n const loaded = await loadModels(argv.models);\n logger.info(`Found ${loaded.models.length} model(s): ${loaded.models.map((m) => m.table).join(', ')}`);\n try {\n await writeRelationRegistryArtifacts({\n registry: loaded.registry,\n modelTypeAccessors: loaded.modelTypeAccessors,\n outputDir: resolve(process.cwd(), GENERATED_RELATION_REGISTRY_DIRNAME),\n });\n } catch (error) {\n logger.warn(\n `Unable to refresh generated relation registry during make:migrations. Continuing without updated relation artifacts: ${error instanceof Error ? error.message : String(error)}`\n );\n }\n\n let dbState: DbSchema;\n if (resolved.db) {\n logger.info('Introspecting database...');\n dbState = await connectAndIntrospect(resolved.db, resolved.dialect);\n } else {\n dbState = { tables: {} };\n }\n\n const operations = diffSchema(dbState, loaded.models);\n\n if (operations.length === 0) {\n logger.info('No changes detected — models and database are in sync');\n return;\n }\n\n const generator = new MigrationGenerator();\n const filepath = await generator.generate({\n name: argv.name,\n operations,\n directory: resolved.dir,\n });\n\n logger.info(`Generated migration: ${filepath}`);\n logger.info(` ${operations.length} operation(s)`);\n }\n )\n .command(\n 'plan',\n 'Print migration SQL without applying',\n (builder) =>\n builder\n .option('dir', {\n type: 'string',\n describe: 'Migrations directory',\n })\n .option('dialect', {\n type: 'string',\n choices: ['postgres', 'sqlite'] as const,\n describe: 'Database dialect',\n })\n .option('config', {\n type: 'string',\n describe: 'Path to tango.config.ts (auto-loads ./tango.config.ts when present)',\n })\n .option('env', {\n type: 'string',\n choices: ['development', 'test', 'production'] as const,\n describe: 'Config environment override',\n }),\n async (argv) => {\n const resolved = await resolveCommandInputs({\n dialect: argv.dialect as string | undefined,\n dir: argv.dir as string | undefined,\n db: argv.db as string | undefined,\n config: argv.config as string | undefined,\n env: argv.env as ConfigEnvironment | undefined,\n });\n const runner = new MigrationRunner(\n { query: async () => ({ rows: [] }), close: async () => {} },\n resolved.dialect,\n resolved.dir\n );\n const output = await runner.plan();\n logger.info(output);\n }\n )\n .command(\n 'status',\n 'Show applied/pending status of all migrations',\n (builder) =>\n builder\n .option('dir', {\n type: 'string',\n describe: 'Migrations directory',\n })\n .option('db', {\n type: 'string',\n describe: 'Database connection URL',\n })\n .option('dialect', {\n type: 'string',\n choices: ['postgres', 'sqlite'] as const,\n describe: 'Database dialect',\n })\n .option('config', {\n type: 'string',\n describe: 'Path to tango.config.ts (auto-loads ./tango.config.ts when present)',\n })\n .option('env', {\n type: 'string',\n choices: ['development', 'test', 'production'] as const,\n describe: 'Config environment override',\n }),\n async (argv) => {\n const resolved = await resolveCommandInputs({\n dialect: argv.dialect as string | undefined,\n dir: argv.dir as string | undefined,\n db: argv.db as string | undefined,\n config: argv.config as string | undefined,\n env: argv.env as ConfigEnvironment | undefined,\n });\n if (!resolved.db) {\n throw new Error('No database target provided. Pass --db or define db settings in tango.config.ts.');\n }\n\n const dbClient = await connectDbClient(resolved.db, resolved.dialect);\n\n const runner = new MigrationRunner(dbClient, resolved.dialect, resolved.dir);\n const statuses = await runner.status();\n\n if (statuses.length === 0) {\n logger.info('No migrations found');\n } else {\n statuses.forEach((statusItem) => {\n const marker = statusItem.applied ? '[x]' : '[ ]';\n logger.info(` ${marker} ${statusItem.id}`);\n });\n }\n\n await dbClient.close();\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAM,SAAS,UAAU,mBAAmB;AA6C5C,eAAe,aAAaA,YAAsD;AAC9E,QAAO,WAAW,YAAY,EAAE,aAAa,QAAQ,KAAK,CAAE,EAAC;AAChE;AAED,eAAe,yBACXC,eACAC,cACkC;CAClC,MAAM,4BAA4B,kBAAkB,YAAY,cAAc,MAAM,CAAC,SAAS;CAC9F,MAAM,eAAe,QAAQ,QAAQ,KAAK,EAAE,eAAe,MAAM,IAAI,oBAAoB;AAEzF,KAAI;AACA,QAAM,OAAO,cAAc,YAAY,KAAK;CAC/C,SAAQ,OAAO;AACZ,MAAI,mBACA,OAAM,IAAI,OAAO,yBAAyB,aAAa,GAAG,EAAE,OAAO,MAAO;AAE9E,SAAO,CAAE;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AU,QAAQ;AAC5C,UAAO,MAAM,IAAI,OAAO,GAAG,WAAW,GAAG,EAAE;EAC9C,EAAC;AAGN,QAAM,SAAS,OAAO;CACzB,EACJ;AACR"}
|
package/dist/diff-CZZbXAPN.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import { __export } from "./chunk-BkvOhyD0.js";
|
|
2
|
-
import { diffSchema } from "./diffSchema-D4oemTWS.js";
|
|
3
|
-
|
|
4
|
-
//#region src/diff/index.ts
|
|
5
|
-
var diff_exports = {};
|
|
6
|
-
__export(diff_exports, { diffSchema: () => diffSchema });
|
|
7
|
-
|
|
8
|
-
//#endregion
|
|
9
|
-
export { diff_exports };
|
|
10
|
-
//# sourceMappingURL=diff-CZZbXAPN.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"diff-CZZbXAPN.js","names":[],"sources":["../src/diff/index.ts"],"sourcesContent":["/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { diffSchema } from './diffSchema';\n"],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"diffSchema-D4oemTWS.js","names":["db: DbSchema","models: ModelMetadataLike[]","ops: MigrationOperation[]"],"sources":["../src/diff/diffSchema.ts"],"sourcesContent":["import { trustedSql } from '@danceroutine/tango-core';\nimport type { DbSchema } from '../introspect/PostgresIntrospector';\nimport type { MigrationOperation } from '../domain/MigrationOperation';\nimport type { ColumnType } from '../builder/contracts/ColumnType';\nimport type { DeleteReferentialAction } from '../builder/contracts/DeleteReferentialAction';\nimport type { UpdateReferentialAction } from '../builder/contracts/UpdateReferentialAction';\nimport { op, applyFieldType } from '../builder/index';\n\ntype ModelField = {\n name: string;\n type: ColumnType;\n notNull?: boolean;\n default?: string | { now: true } | null;\n primaryKey?: boolean;\n unique?: boolean;\n references?: {\n table: string;\n column: string;\n onDelete?: DeleteReferentialAction;\n onUpdate?: UpdateReferentialAction;\n };\n};\n\ntype ModelIndex = {\n name: string;\n on: string[];\n unique?: boolean;\n};\n\nexport type ModelMetadataLike = {\n name?: string;\n table: string;\n fields: ModelField[];\n indexes?: ModelIndex[];\n};\n\n/**\n * Compare model metadata with an introspected database schema and return the\n * operations needed to bring the database into alignment.\n */\nexport function diffSchema(db: DbSchema, models: ModelMetadataLike[]): MigrationOperation[] {\n const ops: MigrationOperation[] = [];\n const modelTables = new Set(models.map((model) => model.table));\n const internalTables = new Set(['_tango_migrations']);\n\n models.forEach((model) => {\n const dbTable = db.tables[model.table];\n\n if (!dbTable) {\n ops.push(\n op.table(model.table).create((cols) => {\n model.fields.forEach((field) => {\n cols.add(field.name, (builder) => {\n builder = applyFieldType(builder, field.type);\n\n if (field.notNull) {\n builder = builder.notNull();\n }\n\n if (field.default === null) {\n builder = builder.default(null);\n } else if (field.default && typeof field.default === 'object' && 'now' in field.default) {\n builder = builder.defaultNow();\n } else if (typeof field.default === 'string') {\n builder = builder.default(trustedSql(field.default));\n }\n\n if (field.primaryKey) {\n builder = builder.primaryKey();\n }\n\n if (field.unique) {\n builder = builder.unique();\n }\n\n if (field.references) {\n builder = builder.references(field.references.table, field.references.column, {\n onDelete: field.references.onDelete,\n onUpdate: field.references.onUpdate,\n });\n }\n\n return builder;\n });\n });\n })\n );\n\n (model.indexes ?? []).forEach((index) => {\n ops.push(\n op.index.create({\n name: index.name,\n table: model.table,\n on: index.on,\n unique: !!index.unique,\n })\n );\n });\n return;\n }\n\n const modelFieldNames = new Set(model.fields.map((field) => field.name));\n const dbFieldNames = new Set(Object.keys(dbTable.columns));\n\n model.fields.forEach((field) => {\n if (!dbFieldNames.has(field.name)) {\n ops.push(\n op.table(model.table).addColumn(field.name, (builder) => {\n builder = applyFieldType(builder, field.type);\n\n if (field.notNull) {\n builder = builder.notNull();\n }\n if (field.default === null) {\n builder = builder.default(null);\n } else if (field.default && typeof field.default === 'object' && 'now' in field.default) {\n builder = builder.defaultNow();\n } else if (typeof field.default === 'string') {\n builder = builder.default(trustedSql(field.default));\n }\n if (field.primaryKey) {\n builder = builder.primaryKey();\n }\n if (field.unique) {\n builder = builder.unique();\n }\n if (field.references) {\n builder = builder.references(field.references.table, field.references.column, {\n onDelete: field.references.onDelete,\n onUpdate: field.references.onUpdate,\n });\n }\n\n return builder;\n })\n );\n }\n });\n\n dbFieldNames.forEach((dbColumnName) => {\n if (!modelFieldNames.has(dbColumnName)) {\n ops.push(op.table(model.table).dropColumn(dbColumnName));\n }\n });\n\n const modelIndexes = new Map((model.indexes ?? []).map((index) => [index.name, index] as const));\n const dbIndexNames = new Set(Object.keys(dbTable.indexes));\n\n modelIndexes.forEach((index, indexName) => {\n if (!dbIndexNames.has(indexName)) {\n ops.push(\n op.index.create({\n name: index.name,\n table: model.table,\n on: index.on,\n unique: !!index.unique,\n })\n );\n }\n });\n\n dbIndexNames.forEach((dbIndexName) => {\n if (!modelIndexes.has(dbIndexName)) {\n ops.push(\n op.index.drop({\n name: dbIndexName,\n table: model.table,\n })\n );\n }\n });\n });\n\n Object.keys(db.tables).forEach((dbTableName) => {\n if (internalTables.has(dbTableName)) {\n return;\n }\n if (!modelTables.has(dbTableName)) {\n ops.push(op.table(dbTableName).drop());\n }\n });\n\n return ops;\n}\n"],"mappings":";;;;AAwCO,SAAS,WAAWA,IAAcC,QAAmD;CACxF,MAAMC,MAA4B,CAAE;CACpC,MAAM,cAAc,IAAI,IAAI,OAAO,IAAI,CAAC,UAAU,MAAM,MAAM;CAC9D,MAAM,iBAAiB,IAAI,IAAI,CAAC,mBAAoB;AAEpD,QAAO,QAAQ,CAAC,UAAU;EACtB,MAAM,UAAU,GAAG,OAAO,MAAM;AAEhC,OAAK,SAAS;AACV,OAAI,KACA,UAAG,MAAM,MAAM,MAAM,CAAC,OAAO,CAAC,SAAS;AACnC,UAAM,OAAO,QAAQ,CAAC,UAAU;AAC5B,UAAK,IAAI,MAAM,MAAM,CAAC,YAAY;AAC9B,gBAAU,eAAe,SAAS,MAAM,KAAK;AAE7C,UAAI,MAAM,QACN,WAA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