@danceroutine/tango-migrations 1.11.3 → 1.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{CompilerStrategy-vcZKg8qf.js → CompilerStrategy-Dc5_3-nw.js} +2 -2
  2. package/dist/{CompilerStrategy-vcZKg8qf.js.map → CompilerStrategy-Dc5_3-nw.js.map} +1 -1
  3. package/dist/{InternalOperationKind-M4a4H9OZ.js → InternalOperationKind-BJ7n-pUH.js} +14 -2
  4. package/dist/InternalOperationKind-BJ7n-pUH.js.map +1 -0
  5. package/dist/{IntrospectorStrategy-BijuyIaN.js → IntrospectorStrategy-BCTs_4wl.js} +2 -2
  6. package/dist/{IntrospectorStrategy-BijuyIaN.js.map → IntrospectorStrategy-BCTs_4wl.js.map} +1 -1
  7. package/dist/{MigrationGenerator-BmmerPXJ.js → MigrationGenerator-D-sSbsFG.js} +65 -43
  8. package/dist/MigrationGenerator-D-sSbsFG.js.map +1 -0
  9. package/dist/{MigrationRunner-B5AJel12.js → MigrationRunner-vG1lVlkz.js} +2 -2
  10. package/dist/{MigrationRunner-B5AJel12.js.map → MigrationRunner-vG1lVlkz.js.map} +1 -1
  11. package/dist/{SqliteCompilerFactory-CXlPAclY.js → SqliteCompilerFactory-C_56xoQM.js} +2 -3
  12. package/dist/{SqliteCompilerFactory-CXlPAclY.js.map → SqliteCompilerFactory-C_56xoQM.js.map} +1 -1
  13. package/dist/builder/index.js +1 -1
  14. package/dist/{builder-BSepa_PF.js → builder-Bhm_to6b.js} +2 -3
  15. package/dist/{builder-BSepa_PF.js.map → builder-Bhm_to6b.js.map} +1 -1
  16. package/dist/{cli-e8I1-dab.js → cli-B3MNpH29.js} +6 -6
  17. package/dist/{cli-e8I1-dab.js.map → cli-B3MNpH29.js.map} +1 -1
  18. package/dist/cli.js +1 -1
  19. package/dist/commands/index.js +1 -1
  20. package/dist/compilers/index.js +2 -2
  21. package/dist/{compilers-BW-WALoD.js → compilers-BlLQwwmu.js} +2 -2
  22. package/dist/{compilers-BW-WALoD.js.map → compilers-BlLQwwmu.js.map} +1 -1
  23. package/dist/diff/index.js +1 -1
  24. package/dist/{diff-7Xw8k4vp.js → diff-BsQr9Sl8.js} +2 -2
  25. package/dist/{diff-7Xw8k4vp.js.map → diff-BsQr9Sl8.js.map} +1 -1
  26. package/dist/generator/index.d.ts +1 -1
  27. package/dist/generator/index.js +1 -1
  28. package/dist/{index-B8VoE0M4.d.ts → index-Dcuh1zcQ.d.ts} +5 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.js +9 -9
  31. package/dist/runner/index.js +1 -1
  32. package/dist/strategies/index.js +2 -2
  33. package/package.json +7 -7
  34. package/dist/InternalColumnType-Dzs9T6a6.js +0 -15
  35. package/dist/InternalColumnType-Dzs9T6a6.js.map +0 -1
  36. package/dist/InternalOperationKind-M4a4H9OZ.js.map +0 -1
  37. package/dist/MigrationGenerator-BmmerPXJ.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"SqliteCompilerFactory-CXlPAclY.js","names":["exhaustive"],"sources":["../src/compilers/dialects/PostgresCompiler.ts","../src/compilers/factories/PostgresCompilerFactory.ts","../src/compilers/dialects/SqliteCompiler.ts","../src/compilers/factories/SqliteCompilerFactory.ts"],"sourcesContent":["import type { ForeignKeyCreate, MigrationOperation, TableCreate } 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 * Rewrite migration operations into PostgreSQL's preferred execution\n * order, including separating inline foreign keys from table creation.\n */\n prepareOperations(operations: MigrationOperation[]): MigrationOperation[] {\n const tableCreates: TableCreate[] = [];\n const remainder: MigrationOperation[] = [];\n\n for (const operation of operations) {\n if (operation.kind === InternalOperationKind.TABLE_CREATE) {\n tableCreates.push(operation);\n } else {\n remainder.push(operation);\n }\n }\n\n const strippedCreates: TableCreate[] = [];\n const foreignKeys: ForeignKeyCreate[] = [];\n\n for (const operation of tableCreates) {\n const { create, fks } = this.stripTableCreateForeignKeys(operation);\n strippedCreates.push(create);\n foreignKeys.push(...fks);\n }\n\n return [\n ...strippedCreates.sort((left, right) => left.table.localeCompare(right.table)),\n ...foreignKeys,\n ...remainder,\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 stripTableCreateForeignKeys(op: TableCreate): { create: TableCreate; fks: ForeignKeyCreate[] } {\n const fks: ForeignKeyCreate[] = [];\n const columns = op.columns.map((column) => {\n if (!column.references) {\n return column;\n }\n\n const references = column.references;\n fks.push({\n kind: InternalOperationKind.FK_CREATE,\n table: op.table,\n columns: [column.name],\n refTable: references.table,\n refColumns: [references.column],\n onDelete: references.onDelete,\n onUpdate: references.onUpdate,\n });\n\n const { references: _references, ...rest } = column;\n return { ...rest };\n });\n\n return { create: { ...op, columns }, fks };\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 { ColumnAdd, IndexCreate, MigrationOperation, TableCreate } 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 * Rewrite migration operations into SQLite's safe execution order,\n * including topological table creation and unique-column add expansion.\n */\n prepareOperations(operations: MigrationOperation[]): MigrationOperation[] {\n const tableCreates: TableCreate[] = [];\n const remainder: MigrationOperation[] = [];\n\n for (const operation of operations) {\n if (operation.kind === InternalOperationKind.TABLE_CREATE) {\n tableCreates.push(operation);\n } else {\n remainder.push(operation);\n }\n }\n\n const preparedRemainder = remainder.flatMap((operation) =>\n operation.kind === InternalOperationKind.COLUMN_ADD ? this.prepareColumnAdd(operation) : [operation]\n );\n\n return [...this.topologicalSortTableCreatesWithReferences(tableCreates), ...preparedRemainder];\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({\n ...op.column,\n unique: false,\n })}`,\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 private prepareColumnAdd(op: ColumnAdd): MigrationOperation[] {\n const preparedColumn = op.column;\n if (preparedColumn.notNull && preparedColumn.default === undefined && !preparedColumn.primaryKey) {\n throw new Error(\n `SQLite cannot add NOT NULL column '${preparedColumn.name}' to '${op.table}' without a default or backfill path.`\n );\n }\n\n if (!preparedColumn.unique) {\n return [op];\n }\n\n const addColumn: ColumnAdd = {\n ...op,\n column: {\n ...preparedColumn,\n unique: false,\n },\n };\n const createIndex: IndexCreate = {\n kind: InternalOperationKind.INDEX_CREATE,\n name: `${op.table}_${preparedColumn.name}_idx`,\n table: op.table,\n on: [preparedColumn.name],\n unique: true,\n };\n\n return [addColumn, createIndex];\n }\n\n private topologicalSortTableCreatesWithReferences(creates: TableCreate[]): TableCreate[] {\n if (creates.length <= 1) {\n return creates;\n }\n\n const tableSet = new Set(creates.map((create) => create.table));\n const byTable = new Map(creates.map((create) => [create.table, create]));\n const incoming = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n\n for (const table of tableSet) {\n incoming.set(table, 0);\n }\n\n for (const create of creates) {\n const seenParents = new Set<string>();\n for (const column of create.columns) {\n if (!column.references) {\n continue;\n }\n const refTable = column.references.table;\n if (refTable === create.table || !tableSet.has(refTable)) {\n continue;\n }\n if (seenParents.has(refTable)) {\n continue;\n }\n seenParents.add(refTable);\n incoming.set(create.table, incoming.get(create.table)! + 1);\n if (!dependents.has(refTable)) {\n dependents.set(refTable, new Set());\n }\n dependents.get(refTable)!.add(create.table);\n }\n }\n\n const ready = [...tableSet].filter((table) => incoming.get(table) === 0);\n ready.sort((left, right) => left.localeCompare(right));\n\n const sorted: TableCreate[] = [];\n while (ready.length) {\n const next = ready.shift()!;\n sorted.push(byTable.get(next)!);\n\n for (const dependent of dependents.get(next) ?? []) {\n incoming.set(dependent, incoming.get(dependent)! - 1);\n if (incoming.get(dependent) === 0) {\n ready.push(dependent);\n ready.sort((left, right) => left.localeCompare(right));\n }\n }\n }\n\n if (sorted.length !== creates.length) {\n return [...creates].sort((left, right) => left.table.localeCompare(right.table));\n }\n\n return sorted;\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":";;;;;;;AAYA,IAAa,mBAAb,MAAa,iBAAwC;CACjD,OAAgB,QAAQ;CACxB,eAAuD,iBAAiB;CACxE,YAA6B,IA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,MAAM,cAAc,MAAM,KAAK,CAAC;EAGnF,OAAO;CACX;AACJ;;;;;;ACpQA,IAAa,wBAAb,MAAa,sBAAiD;CAC1D,OAAgB,QAAQ;CACxB,eAA4D,sBAAsB;;;;CAKlF,OAAO,wBAAwB,OAAgD;EAC3E,OACI,OAAO,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,sBAAsB;CAErF;;;;CAKA,SAAsB;EAClB,OAAO,IAAI,eAAe;CAC9B;AACJ"}
1
+ {"version":3,"file":"SqliteCompilerFactory-C_56xoQM.js","names":["exhaustive"],"sources":["../src/compilers/dialects/PostgresCompiler.ts","../src/compilers/factories/PostgresCompilerFactory.ts","../src/compilers/dialects/SqliteCompiler.ts","../src/compilers/factories/SqliteCompilerFactory.ts"],"sourcesContent":["import type { ForeignKeyCreate, MigrationOperation, TableCreate } 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 * Rewrite migration operations into PostgreSQL's preferred execution\n * order, including separating inline foreign keys from table creation.\n */\n prepareOperations(operations: MigrationOperation[]): MigrationOperation[] {\n const tableCreates: TableCreate[] = [];\n const remainder: MigrationOperation[] = [];\n\n for (const operation of operations) {\n if (operation.kind === InternalOperationKind.TABLE_CREATE) {\n tableCreates.push(operation);\n } else {\n remainder.push(operation);\n }\n }\n\n const strippedCreates: TableCreate[] = [];\n const foreignKeys: ForeignKeyCreate[] = [];\n\n for (const operation of tableCreates) {\n const { create, fks } = this.stripTableCreateForeignKeys(operation);\n strippedCreates.push(create);\n foreignKeys.push(...fks);\n }\n\n return [\n ...strippedCreates.sort((left, right) => left.table.localeCompare(right.table)),\n ...foreignKeys,\n ...remainder,\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 stripTableCreateForeignKeys(op: TableCreate): { create: TableCreate; fks: ForeignKeyCreate[] } {\n const fks: ForeignKeyCreate[] = [];\n const columns = op.columns.map((column) => {\n if (!column.references) {\n return column;\n }\n\n const references = column.references;\n fks.push({\n kind: InternalOperationKind.FK_CREATE,\n table: op.table,\n columns: [column.name],\n refTable: references.table,\n refColumns: [references.column],\n onDelete: references.onDelete,\n onUpdate: references.onUpdate,\n });\n\n const { references: _references, ...rest } = column;\n return { ...rest };\n });\n\n return { create: { ...op, columns }, fks };\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 { ColumnAdd, IndexCreate, MigrationOperation, TableCreate } 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 * Rewrite migration operations into SQLite's safe execution order,\n * including topological table creation and unique-column add expansion.\n */\n prepareOperations(operations: MigrationOperation[]): MigrationOperation[] {\n const tableCreates: TableCreate[] = [];\n const remainder: MigrationOperation[] = [];\n\n for (const operation of operations) {\n if (operation.kind === InternalOperationKind.TABLE_CREATE) {\n tableCreates.push(operation);\n } else {\n remainder.push(operation);\n }\n }\n\n const preparedRemainder = remainder.flatMap((operation) =>\n operation.kind === InternalOperationKind.COLUMN_ADD ? this.prepareColumnAdd(operation) : [operation]\n );\n\n return [...this.topologicalSortTableCreatesWithReferences(tableCreates), ...preparedRemainder];\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({\n ...op.column,\n unique: false,\n })}`,\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 private prepareColumnAdd(op: ColumnAdd): MigrationOperation[] {\n const preparedColumn = op.column;\n if (preparedColumn.notNull && preparedColumn.default === undefined && !preparedColumn.primaryKey) {\n throw new Error(\n `SQLite cannot add NOT NULL column '${preparedColumn.name}' to '${op.table}' without a default or backfill path.`\n );\n }\n\n if (!preparedColumn.unique) {\n return [op];\n }\n\n const addColumn: ColumnAdd = {\n ...op,\n column: {\n ...preparedColumn,\n unique: false,\n },\n };\n const createIndex: IndexCreate = {\n kind: InternalOperationKind.INDEX_CREATE,\n name: `${op.table}_${preparedColumn.name}_idx`,\n table: op.table,\n on: [preparedColumn.name],\n unique: true,\n };\n\n return [addColumn, createIndex];\n }\n\n private topologicalSortTableCreatesWithReferences(creates: TableCreate[]): TableCreate[] {\n if (creates.length <= 1) {\n return creates;\n }\n\n const tableSet = new Set(creates.map((create) => create.table));\n const byTable = new Map(creates.map((create) => [create.table, create]));\n const incoming = new Map<string, number>();\n const dependents = new Map<string, Set<string>>();\n\n for (const table of tableSet) {\n incoming.set(table, 0);\n }\n\n for (const create of creates) {\n const seenParents = new Set<string>();\n for (const column of create.columns) {\n if (!column.references) {\n continue;\n }\n const refTable = column.references.table;\n if (refTable === create.table || !tableSet.has(refTable)) {\n continue;\n }\n if (seenParents.has(refTable)) {\n continue;\n }\n seenParents.add(refTable);\n incoming.set(create.table, incoming.get(create.table)! + 1);\n if (!dependents.has(refTable)) {\n dependents.set(refTable, new Set());\n }\n dependents.get(refTable)!.add(create.table);\n }\n }\n\n const ready = [...tableSet].filter((table) => incoming.get(table) === 0);\n ready.sort((left, right) => left.localeCompare(right));\n\n const sorted: TableCreate[] = [];\n while (ready.length) {\n const next = ready.shift()!;\n sorted.push(byTable.get(next)!);\n\n for (const dependent of dependents.get(next) ?? []) {\n incoming.set(dependent, incoming.get(dependent)! - 1);\n if (incoming.get(dependent) === 0) {\n ready.push(dependent);\n ready.sort((left, right) => left.localeCompare(right));\n }\n }\n }\n\n if (sorted.length !== creates.length) {\n return [...creates].sort((left, right) => left.table.localeCompare(right.table));\n }\n\n return sorted;\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":";;;;;;AAYA,IAAa,mBAAb,MAAa,iBAAwC;CACjD,OAAgB,QAAQ;CACxB,eAAuD,iBAAiB;CACxE,YAA6B,IAAI,0BAA0B,UAAU;;;;CAKrE,OAAO,mBAAmB,OAA2C;EACjE,OACI,OAAO,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,iBAAiB;CAEhF;;;;;CAMA,kBAAkB,YAAwD;EACtE,MAAM,eAA8B,CAAC;EACrC,MAAM,YAAkC,CAAC;EAEzC,KAAK,MAAM,aAAa,YACpB,IAAI,UAAU,SAAS,sBAAsB,cACzC,aAAa,KAAK,SAAS;OAE3B,UAAU,KAAK,SAAS;EAIhC,MAAM,kBAAiC,CAAC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ldType, i as OpBuilder, n as runtime_exports, o as contracts_exports, r as ops_exports } from "../builder-BSepa_PF.js";
1
+ import { a as applyFieldType, i as OpBuilder, n as runtime_exports, o as contracts_exports, r as ops_exports } from "../builder-Bhm_to6b.js";
2
2
  import { t as CollectingBuilder } from "../CollectingBuilder-BIfAKs_x.js";
3
3
  export { CollectingBuilder, OpBuilder, OpBuilder as op, applyFieldType, contracts_exports as contracts, ops_exports as ops, runtime_exports as runtime };
@@ -1,6 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { t as InternalColumnType } from "./InternalColumnType-Dzs9T6a6.js";
3
- import { t as InternalOperationKind } from "./InternalOperationKind-M4a4H9OZ.js";
2
+ import { n as InternalColumnType, t as InternalOperationKind } from "./InternalOperationKind-BJ7n-pUH.js";
4
3
  import { t as CollectingBuilder } from "./CollectingBuilder-BIfAKs_x.js";
5
4
  //#region src/builder/contracts/index.ts
6
5
  var contracts_exports = /* @__PURE__ */ __exportAll({});
@@ -263,4 +262,4 @@ var builder_exports = /* @__PURE__ */ __exportAll({
263
262
  //#endregion
264
263
  export { applyFieldType as a, OpBuilder as i, runtime_exports as n, contracts_exports as o, ops_exports as r, builder_exports as t };
265
264
 
266
- //# sourceMappingURL=builder-BSepa_PF.js.map
265
+ //# sourceMappingURL=builder-Bhm_to6b.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"builder-BSepa_PF.js","names":["exhaustive"],"sources":["../src/builder/contracts/index.ts","../src/builder/ops/OpBuilder.ts","../src/builder/ops/index.ts","../src/builder/runtime/index.ts","../src/builder/index.ts"],"sourcesContent":["/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport type { Builder } from './Builder';\nexport type { ColumnSpec } from './ColumnSpec';\nexport type { ColumnType } from './ColumnType';\nexport type { DeleteReferentialAction } from './DeleteReferentialAction';\nexport type { UpdateReferentialAction } from './UpdateReferentialAction';\n","import type { TrustedSqlFragment } from '@danceroutine/tango-core';\nimport type {\n CustomMigrationOperation,\n ForeignKeyCreate,\n ForeignKeyDrop,\n ForeignKeyValidate,\n IndexCreate,\n IndexDrop,\n TableCreate,\n TableDrop,\n ColumnAdd,\n ColumnDrop,\n ColumnAlter,\n ColumnRename,\n} from '../../domain/MigrationOperation';\nimport type { ColumnSpec } from '../contracts/ColumnSpec';\nimport type { ColumnType } from '../contracts/ColumnType';\nimport { InternalColumnType } from '../../domain/internal/InternalColumnType';\nimport type { DeleteReferentialAction } from '../contracts/DeleteReferentialAction';\nimport type { UpdateReferentialAction } from '../contracts/UpdateReferentialAction';\nimport { InternalOperationKind } from '../../domain/internal/InternalOperationKind';\n\n/**\n * Fluent builder for column specifications used by table operations.\n */\nclass ColumnBuilder {\n static readonly BRAND = 'tango.migrations.column_builder' as const;\n readonly __tangoBrand: typeof ColumnBuilder.BRAND = ColumnBuilder.BRAND;\n private spec: Partial<ColumnSpec> = {};\n\n constructor(name: string) {\n this.spec.name = name;\n }\n\n static isColumnBuilder(value: unknown): value is ColumnBuilder {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === ColumnBuilder.BRAND\n );\n }\n\n /** Set column type to serial/auto-increment. */\n serial(): ColumnBuilder {\n this.spec.type = InternalColumnType.SERIAL;\n return this;\n }\n /** Set column type to integer. */\n int(): ColumnBuilder {\n this.spec.type = InternalColumnType.INT;\n return this;\n }\n /** Set column type to bigint. */\n bigint(): ColumnBuilder {\n this.spec.type = InternalColumnType.BIGINT;\n return this;\n }\n /** Set column type to text. */\n text(): ColumnBuilder {\n this.spec.type = InternalColumnType.TEXT;\n return this;\n }\n /** Set column type to boolean. */\n bool(): ColumnBuilder {\n this.spec.type = InternalColumnType.BOOL;\n return this;\n }\n /** Set column type to timestamptz. */\n timestamptz(): ColumnBuilder {\n this.spec.type = InternalColumnType.TIMESTAMPTZ;\n return this;\n }\n /** Set column type to JSONB. */\n jsonb(): ColumnBuilder {\n this.spec.type = InternalColumnType.JSONB;\n return this;\n }\n /** Set column type to UUID. */\n uuid(): ColumnBuilder {\n this.spec.type = InternalColumnType.UUID;\n return this;\n }\n\n /** Mark column as NOT NULL. */\n notNull(): ColumnBuilder {\n this.spec.notNull = true;\n return this;\n }\n /** Set default to current timestamp. */\n defaultNow(): ColumnBuilder {\n this.spec.default = { now: true };\n return this;\n }\n /** Set reviewed raw SQL default expression. */\n default(v: TrustedSqlFragment | null): ColumnBuilder {\n this.spec.default = v;\n return this;\n }\n /** Mark column as part of primary key. */\n primaryKey(): ColumnBuilder {\n this.spec.primaryKey = true;\n return this;\n }\n /** Mark column as unique. */\n unique(): ColumnBuilder {\n this.spec.unique = true;\n return this;\n }\n /** Configure foreign key reference metadata. */\n references(\n table: string,\n column: string,\n opts?: {\n onDelete?: DeleteReferentialAction;\n onUpdate?: UpdateReferentialAction;\n }\n ): ColumnBuilder {\n this.spec.references = {\n table,\n column,\n onDelete: opts?.onDelete,\n onUpdate: opts?.onUpdate,\n };\n return this;\n }\n\n _done(): ColumnSpec {\n return this.spec as ColumnSpec;\n }\n}\n\ntype TableOperationBuilder = {\n create(def: (cols: { add: (name: string, cb: (b: ColumnBuilder) => ColumnBuilder) => void }) => void): TableCreate;\n drop(opts?: { cascade?: boolean }): TableDrop;\n addColumn(name: string, cb: (b: ColumnBuilder) => ColumnBuilder): ColumnAdd;\n dropColumn(name: string): ColumnDrop;\n alterColumn(name: string, to: Partial<ColumnSpec>): ColumnAlter;\n renameColumn(from: string, to: string): ColumnRename;\n};\n\n/**\n * Static factory for migration operations.\n */\nexport class OpBuilder {\n static readonly BRAND = 'tango.migrations.op_builder' as const;\n static index = {\n /** Build an index create operation. */\n create(p: {\n name: string;\n table: string;\n on: string[];\n unique?: boolean;\n where?: TrustedSqlFragment;\n concurrently?: boolean;\n }): IndexCreate {\n return { kind: InternalOperationKind.INDEX_CREATE, ...p };\n },\n /** Build an index drop operation. */\n drop(p: { name: string; table: string; concurrently?: boolean }): IndexDrop {\n return { kind: InternalOperationKind.INDEX_DROP, ...p };\n },\n };\n private static customOperations = new Map<string, (args: Record<string, unknown>) => CustomMigrationOperation>();\n readonly __tangoBrand: typeof OpBuilder.BRAND = OpBuilder.BRAND;\n\n /**\n * Narrow an unknown value to the shared migration operation builder type.\n */\n static isOpBuilder(value: unknown): value is OpBuilder {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === OpBuilder.BRAND\n );\n }\n\n /**\n * Build table-scoped migration operations.\n */\n static table(table: string): TableOperationBuilder {\n return {\n create(\n def: (cols: { add: (name: string, cb: (b: ColumnBuilder) => ColumnBuilder) => void }) => void\n ): TableCreate {\n const columns: ColumnSpec[] = [];\n def({\n add(name, cb) {\n columns.push(cb(new ColumnBuilder(name))._done());\n },\n });\n return { kind: InternalOperationKind.TABLE_CREATE, table, columns };\n },\n drop(opts?: { cascade?: boolean }): TableDrop {\n return { kind: InternalOperationKind.TABLE_DROP, table, cascade: opts?.cascade };\n },\n addColumn(name: string, cb: (b: ColumnBuilder) => ColumnBuilder): ColumnAdd {\n return { kind: InternalOperationKind.COLUMN_ADD, table, column: cb(new ColumnBuilder(name))._done() };\n },\n dropColumn(name: string): ColumnDrop {\n return { kind: InternalOperationKind.COLUMN_DROP, table, column: name };\n },\n alterColumn(name: string, to: Partial<ColumnSpec>): ColumnAlter {\n return { kind: InternalOperationKind.COLUMN_ALTER, table, column: name, to };\n },\n renameColumn(from: string, to: string): ColumnRename {\n return { kind: InternalOperationKind.COLUMN_RENAME, table, from, to };\n },\n };\n }\n\n /** Build a foreign key create operation. */\n static foreignKey(p: {\n table: string;\n name?: string;\n columns: string[];\n references: { table: string; columns: string[] };\n onDelete?: string;\n onUpdate?: string;\n notValid?: boolean;\n }): ForeignKeyCreate {\n return {\n kind: InternalOperationKind.FK_CREATE,\n table: p.table,\n name: p.name,\n columns: p.columns,\n refTable: p.references.table,\n refColumns: p.references.columns,\n onDelete: p.onDelete,\n onUpdate: p.onUpdate,\n notValid: p.notValid,\n };\n }\n\n /** Build a foreign key validation operation. */\n static foreignKeyValidate(p: { table: string; name: string }): ForeignKeyValidate {\n return { kind: InternalOperationKind.FK_VALIDATE, ...p };\n }\n\n /** Build a foreign key drop operation. */\n static foreignKeyDrop(p: { table: string; name: string }): ForeignKeyDrop {\n return { kind: InternalOperationKind.FK_DROP, ...p };\n }\n\n /**\n * Register a custom migration operation builder.\n */\n static registerCustomOperation<TName extends string, TArgs extends object>(\n name: TName,\n builder: (args: TArgs) => CustomMigrationOperation<TName, TArgs>\n ): void {\n this.customOperations.set(name, builder as (args: Record<string, unknown>) => CustomMigrationOperation);\n }\n\n /**\n * Resolve a previously registered custom operation builder.\n */\n static getCustomOperation<TName extends string, TArgs extends object>(\n name: TName\n ): ((args: TArgs) => CustomMigrationOperation<TName, TArgs>) | undefined {\n return this.customOperations.get(name) as ((args: TArgs) => CustomMigrationOperation<TName, TArgs>) | undefined;\n }\n}\n\n/**\n * Apply a domain field type to a column builder.\n */\nexport function applyFieldType(builder: ColumnBuilder, fieldType: ColumnType): ColumnBuilder {\n switch (fieldType) {\n case InternalColumnType.SERIAL:\n return builder.serial();\n case InternalColumnType.INT:\n return builder.int();\n case InternalColumnType.BIGINT:\n return builder.bigint();\n case InternalColumnType.TEXT:\n return builder.text();\n case InternalColumnType.BOOL:\n return builder.bool();\n case InternalColumnType.TIMESTAMPTZ:\n return builder.timestamptz();\n case InternalColumnType.JSONB:\n return builder.jsonb();\n case InternalColumnType.UUID:\n return builder.uuid();\n default: {\n const exhaustive: never = fieldType;\n throw new Error(`Unsupported field type: ${exhaustive}`);\n }\n }\n}\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { OpBuilder, OpBuilder as op, applyFieldType } from './OpBuilder';\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { CollectingBuilder } from './CollectingBuilder';\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 ops from './ops/index';\nexport * as runtime from './runtime/index';\n\nexport type {\n Builder,\n ColumnSpec,\n ColumnType,\n DeleteReferentialAction,\n UpdateReferentialAction,\n} from './contracts/index';\nexport { OpBuilder, op, applyFieldType } from './ops/index';\nexport { CollectingBuilder } from './runtime/index';\n"],"mappings":";;;;;;;;;;;ACyBA,IAAM,gBAAN,MAAM,cAAc;CAChB,OAAgB,QAAQ;CACxB,eAAoD,cAAc;CAClE,OAAoC,CAAC;CAErC,YAAY,MAAc;EACtB,KAAK,KAAK,OAAO;CACrB;CAEA,OAAO,gBAAgB,OAAwC;EAC3D,OACI,OAAO,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,cAAc;CAE7E;;CAGA,SAAwB;EACpB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,MAAqB;EACjB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,SAAwB;EACpB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,OAAsB;EAClB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,OAAsB;EAClB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,cAA6B;EACzB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,QAAuB;EACnB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,OAAsB;EAClB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAGA,UAAyB;EACrB,KAAK,KAAK,UAAU;EACpB,OAAO;CACX;;CAEA,aAA4B;EACxB,KAAK,KAAK,UAAU,EAAE,KAAK,KAAK;EAChC,OAAO;CACX;;CAEA,QAAQ,GAA6C;EACjD,KAAK,KAAK,UAAU;EACpB,OAAO;CACX;;CAEA,aAA4B;EACxB,KAAK,KAAK,aAAa;EACvB,OAAO;CACX;;CAEA,SAAwB;EACpB,K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../src/builder/ops/index.ts","../src/builder/runtime/index.ts","../src/builder/index.ts"],"sourcesContent":["/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport type { Builder } from './Builder';\nexport type { ColumnSpec } from './ColumnSpec';\nexport type { ColumnType } from './ColumnType';\nexport type { DeleteReferentialAction } from './DeleteReferentialAction';\nexport type { UpdateReferentialAction } from './UpdateReferentialAction';\n","import type { TrustedSqlFragment } from '@danceroutine/tango-core';\nimport type {\n CustomMigrationOperation,\n ForeignKeyCreate,\n ForeignKeyDrop,\n ForeignKeyValidate,\n IndexCreate,\n IndexDrop,\n TableCreate,\n TableDrop,\n ColumnAdd,\n ColumnDrop,\n ColumnAlter,\n ColumnRename,\n} from '../../domain/MigrationOperation';\nimport type { ColumnSpec } from '../contracts/ColumnSpec';\nimport type { ColumnType } from '../contracts/ColumnType';\nimport { InternalColumnType } from '../../domain/internal/InternalColumnType';\nimport type { DeleteReferentialAction } from '../contracts/DeleteReferentialAction';\nimport type { UpdateReferentialAction } from '../contracts/UpdateReferentialAction';\nimport { InternalOperationKind } from '../../domain/internal/InternalOperationKind';\n\n/**\n * Fluent builder for column specifications used by table operations.\n */\nclass ColumnBuilder {\n static readonly BRAND = 'tango.migrations.column_builder' as const;\n readonly __tangoBrand: typeof ColumnBuilder.BRAND = ColumnBuilder.BRAND;\n private spec: Partial<ColumnSpec> = {};\n\n constructor(name: string) {\n this.spec.name = name;\n }\n\n static isColumnBuilder(value: unknown): value is ColumnBuilder {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === ColumnBuilder.BRAND\n );\n }\n\n /** Set column type to serial/auto-increment. */\n serial(): ColumnBuilder {\n this.spec.type = InternalColumnType.SERIAL;\n return this;\n }\n /** Set column type to integer. */\n int(): ColumnBuilder {\n this.spec.type = InternalColumnType.INT;\n return this;\n }\n /** Set column type to bigint. */\n bigint(): ColumnBuilder {\n this.spec.type = InternalColumnType.BIGINT;\n return this;\n }\n /** Set column type to text. */\n text(): ColumnBuilder {\n this.spec.type = InternalColumnType.TEXT;\n return this;\n }\n /** Set column type to boolean. */\n bool(): ColumnBuilder {\n this.spec.type = InternalColumnType.BOOL;\n return this;\n }\n /** Set column type to timestamptz. */\n timestamptz(): ColumnBuilder {\n this.spec.type = InternalColumnType.TIMESTAMPTZ;\n return this;\n }\n /** Set column type to JSONB. */\n jsonb(): ColumnBuilder {\n this.spec.type = InternalColumnType.JSONB;\n return this;\n }\n /** Set column type to UUID. */\n uuid(): ColumnBuilder {\n this.spec.type = InternalColumnType.UUID;\n return this;\n }\n\n /** Mark column as NOT NULL. */\n notNull(): ColumnBuilder {\n this.spec.notNull = true;\n return this;\n }\n /** Set default to current timestamp. */\n defaultNow(): ColumnBuilder {\n this.spec.default = { now: true };\n return this;\n }\n /** Set reviewed raw SQL default expression. */\n default(v: TrustedSqlFragment | null): ColumnBuilder {\n this.spec.default = v;\n return this;\n }\n /** Mark column as part of primary key. */\n primaryKey(): ColumnBuilder {\n this.spec.primaryKey = true;\n return this;\n }\n /** Mark column as unique. */\n unique(): ColumnBuilder {\n this.spec.unique = true;\n return this;\n }\n /** Configure foreign key reference metadata. */\n references(\n table: string,\n column: string,\n opts?: {\n onDelete?: DeleteReferentialAction;\n onUpdate?: UpdateReferentialAction;\n }\n ): ColumnBuilder {\n this.spec.references = {\n table,\n column,\n onDelete: opts?.onDelete,\n onUpdate: opts?.onUpdate,\n };\n return this;\n }\n\n _done(): ColumnSpec {\n return this.spec as ColumnSpec;\n }\n}\n\ntype TableOperationBuilder = {\n create(def: (cols: { add: (name: string, cb: (b: ColumnBuilder) => ColumnBuilder) => void }) => void): TableCreate;\n drop(opts?: { cascade?: boolean }): TableDrop;\n addColumn(name: string, cb: (b: ColumnBuilder) => ColumnBuilder): ColumnAdd;\n dropColumn(name: string): ColumnDrop;\n alterColumn(name: string, to: Partial<ColumnSpec>): ColumnAlter;\n renameColumn(from: string, to: string): ColumnRename;\n};\n\n/**\n * Static factory for migration operations.\n */\nexport class OpBuilder {\n static readonly BRAND = 'tango.migrations.op_builder' as const;\n static index = {\n /** Build an index create operation. */\n create(p: {\n name: string;\n table: string;\n on: string[];\n unique?: boolean;\n where?: TrustedSqlFragment;\n concurrently?: boolean;\n }): IndexCreate {\n return { kind: InternalOperationKind.INDEX_CREATE, ...p };\n },\n /** Build an index drop operation. */\n drop(p: { name: string; table: string; concurrently?: boolean }): IndexDrop {\n return { kind: InternalOperationKind.INDEX_DROP, ...p };\n },\n };\n private static customOperations = new Map<string, (args: Record<string, unknown>) => CustomMigrationOperation>();\n readonly __tangoBrand: typeof OpBuilder.BRAND = OpBuilder.BRAND;\n\n /**\n * Narrow an unknown value to the shared migration operation builder type.\n */\n static isOpBuilder(value: unknown): value is OpBuilder {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === OpBuilder.BRAND\n );\n }\n\n /**\n * Build table-scoped migration operations.\n */\n static table(table: string): TableOperationBuilder {\n return {\n create(\n def: (cols: { add: (name: string, cb: (b: ColumnBuilder) => ColumnBuilder) => void }) => void\n ): TableCreate {\n const columns: ColumnSpec[] = [];\n def({\n add(name, cb) {\n columns.push(cb(new ColumnBuilder(name))._done());\n },\n });\n return { kind: InternalOperationKind.TABLE_CREATE, table, columns };\n },\n drop(opts?: { cascade?: boolean }): TableDrop {\n return { kind: InternalOperationKind.TABLE_DROP, table, cascade: opts?.cascade };\n },\n addColumn(name: string, cb: (b: ColumnBuilder) => ColumnBuilder): ColumnAdd {\n return { kind: InternalOperationKind.COLUMN_ADD, table, column: cb(new ColumnBuilder(name))._done() };\n },\n dropColumn(name: string): ColumnDrop {\n return { kind: InternalOperationKind.COLUMN_DROP, table, column: name };\n },\n alterColumn(name: string, to: Partial<ColumnSpec>): ColumnAlter {\n return { kind: InternalOperationKind.COLUMN_ALTER, table, column: name, to };\n },\n renameColumn(from: string, to: string): ColumnRename {\n return { kind: InternalOperationKind.COLUMN_RENAME, table, from, to };\n },\n };\n }\n\n /** Build a foreign key create operation. */\n static foreignKey(p: {\n table: string;\n name?: string;\n columns: string[];\n references: { table: string; columns: string[] };\n onDelete?: string;\n onUpdate?: string;\n notValid?: boolean;\n }): ForeignKeyCreate {\n return {\n kind: InternalOperationKind.FK_CREATE,\n table: p.table,\n name: p.name,\n columns: p.columns,\n refTable: p.references.table,\n refColumns: p.references.columns,\n onDelete: p.onDelete,\n onUpdate: p.onUpdate,\n notValid: p.notValid,\n };\n }\n\n /** Build a foreign key validation operation. */\n static foreignKeyValidate(p: { table: string; name: string }): ForeignKeyValidate {\n return { kind: InternalOperationKind.FK_VALIDATE, ...p };\n }\n\n /** Build a foreign key drop operation. */\n static foreignKeyDrop(p: { table: string; name: string }): ForeignKeyDrop {\n return { kind: InternalOperationKind.FK_DROP, ...p };\n }\n\n /**\n * Register a custom migration operation builder.\n */\n static registerCustomOperation<TName extends string, TArgs extends object>(\n name: TName,\n builder: (args: TArgs) => CustomMigrationOperation<TName, TArgs>\n ): void {\n this.customOperations.set(name, builder as (args: Record<string, unknown>) => CustomMigrationOperation);\n }\n\n /**\n * Resolve a previously registered custom operation builder.\n */\n static getCustomOperation<TName extends string, TArgs extends object>(\n name: TName\n ): ((args: TArgs) => CustomMigrationOperation<TName, TArgs>) | undefined {\n return this.customOperations.get(name) as ((args: TArgs) => CustomMigrationOperation<TName, TArgs>) | undefined;\n }\n}\n\n/**\n * Apply a domain field type to a column builder.\n */\nexport function applyFieldType(builder: ColumnBuilder, fieldType: ColumnType): ColumnBuilder {\n switch (fieldType) {\n case InternalColumnType.SERIAL:\n return builder.serial();\n case InternalColumnType.INT:\n return builder.int();\n case InternalColumnType.BIGINT:\n return builder.bigint();\n case InternalColumnType.TEXT:\n return builder.text();\n case InternalColumnType.BOOL:\n return builder.bool();\n case InternalColumnType.TIMESTAMPTZ:\n return builder.timestamptz();\n case InternalColumnType.JSONB:\n return builder.jsonb();\n case InternalColumnType.UUID:\n return builder.uuid();\n default: {\n const exhaustive: never = fieldType;\n throw new Error(`Unsupported field type: ${exhaustive}`);\n }\n }\n}\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { OpBuilder, OpBuilder as op, applyFieldType } from './OpBuilder';\n","/**\n * Domain boundary barrel: centralizes this subdomain's public contract.\n */\n\nexport { CollectingBuilder } from './CollectingBuilder';\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 ops from './ops/index';\nexport * as runtime from './runtime/index';\n\nexport type {\n Builder,\n ColumnSpec,\n ColumnType,\n DeleteReferentialAction,\n UpdateReferentialAction,\n} from './contracts/index';\nexport { OpBuilder, op, applyFieldType } from './ops/index';\nexport { CollectingBuilder } from './runtime/index';\n"],"mappings":";;;;;;;;;;ACyBA,IAAM,gBAAN,MAAM,cAAc;CAChB,OAAgB,QAAQ;CACxB,eAAoD,cAAc;CAClE,OAAoC,CAAC;CAErC,YAAY,MAAc;EACtB,KAAK,KAAK,OAAO;CACrB;CAEA,OAAO,gBAAgB,OAAwC;EAC3D,OACI,OAAO,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,cAAc;CAE7E;;CAGA,SAAwB;EACpB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,MAAqB;EACjB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,SAAwB;EACpB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,OAAsB;EAClB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,OAAsB;EAClB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,cAA6B;EACzB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,QAAuB;EACnB,KAAK,KAAK,OAAO,mBAAmB;EACpC,OAAO;CACX;;CAEA,OAAsB;EAClB,KAAK,KAAK,OAAO,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;EACxB,KAAK,mBAAmB,aACpB,OAAO,QAAQ,YAAY;EAC/B,KAAK,mBAAmB,OACpB,OAAO,QAAQ,MAAM;EACzB,KAAK,mBAAmB,MACpB,OAAO,QAAQ,KAAK;EACxB,SAEI,MAAM,IAAI,MAAM,2BAA2BA,WAAY;CAE/D;AACJ"}
@@ -1,8 +1,8 @@
1
- import { r as InternalDialect } from "./CompilerStrategy-vcZKg8qf.js";
2
- import { n as loadModule, t as MigrationRunner } from "./MigrationRunner-B5AJel12.js";
3
- import { t as MigrationGenerator } from "./MigrationGenerator-BmmerPXJ.js";
4
- import { n as buildMigrationModelMetadataProjection, r as diffSchema } from "./diff-7Xw8k4vp.js";
5
- import { n as createDefaultIntrospectorStrategy } from "./IntrospectorStrategy-BijuyIaN.js";
1
+ import { r as InternalDialect } from "./CompilerStrategy-Dc5_3-nw.js";
2
+ import { n as loadModule, t as MigrationRunner } from "./MigrationRunner-vG1lVlkz.js";
3
+ import { t as MigrationGenerator } from "./MigrationGenerator-D-sSbsFG.js";
4
+ import { n as buildMigrationModelMetadataProjection, r as diffSchema } from "./diff-BsQr9Sl8.js";
5
+ import { n as createDefaultIntrospectorStrategy } from "./IntrospectorStrategy-BCTs_4wl.js";
6
6
  import { getLogger } from "@danceroutine/tango-core";
7
7
  import { access, mkdir } from "node:fs/promises";
8
8
  import { dirname, resolve } from "node:path";
@@ -324,4 +324,4 @@ function registerMigrationsCommands(yargsBuilder) {
324
324
  //#endregion
325
325
  export { registerMigrationsCommands as t };
326
326
 
327
- //# sourceMappingURL=cli-e8I1-dab.js.map
327
+ //# sourceMappingURL=cli-B3MNpH29.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cli-e8I1-dab.js","names":["fsConstants"],"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 { buildMigrationModelMetadataProjection, diffSchema } from '../diff/index';\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 const projectedModels = buildMigrationModelMetadataProjection(loaded.registry);\n logger.info(\n `Found ${loaded.models.length} exported model(s); ${projectedModels.length} model(s) after projection: ${projectedModels.map((m) => m.table).join(', ')}`\n );\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, projectedModels);\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,kBAAkB;AA6C3C,eAAe,aAAa,YAAsD;CAC9E,OAAO,WAAW,YAAY,EAAE,aAAa,QAAQ,IAAI,EAAE,CAAC;AAChE;AAEA,eAAe,yBACX,eACA,cACkC;CAClC,MAAM,qBAAqB,OAAO,kBAAkB,YAAY,cAAc,KAAK,EAAE,SAAS;CAC9F,MAAM,eAAe,QAAQ,QAAQ,IAAI,GAAG,eAAe,KAAK,KAAK,mBAAmB;CAExF,IAAI;EACA,MAAM,OAAO,cAAc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,IAAI;EAC9C,CAAC;EAGL,MAAM,SAAS,MAAM;CACzB,CACJ;AACR"}
1
+ {"version":3,"file":"cli-B3MNpH29.js","names":["fsConstants"],"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 { buildMigrationModelMetadataProjection, diffSchema } from '../diff/index';\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 const projectedModels = buildMigrationModelMetadataProjection(loaded.registry);\n logger.info(\n `Found ${loaded.models.length} exported model(s); ${projectedModels.length} model(s) after projection: ${projectedModels.map((m) => m.table).join(', ')}`\n );\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, projectedModels);\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,kBAAkB;AA6C3C,eAAe,aAAa,YA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,gBAAgB,SAAS,IAAI,SAAS,OAAO;EAGpE,MAAM,WAAW,MAAM,IADJ,gBAAgB,UAAU,SAAS,SAAS,SAAS,GAC5C,EAAE,OAAO;EAErC,IAAI,SAAS,WAAW,GACpB,OAAO,KAAK,qBAAqB;OAEjC,SAAS,SAAS,eAAe;GAC7B,MAAM,SAAS,WAAW,UAAU,QAAQ;GAC5C,OAAO,KAAK,KAAK,OAAO,GAAG,WAAW,IAAI;EAC9C,CAAC;EAGL,MAAM,SAAS,MAAM;CACzB,CACJ;AACR"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { t as registerMigrationsCommands } from "./cli-e8I1-dab.js";
2
+ import { t as registerMigrationsCommands } from "./cli-B3MNpH29.js";
3
3
  import yargs from "yargs";
4
4
  import { hideBin } from "yargs/helpers";
5
5
  //#region src/cli.ts
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "../chunk-D7D4PA-g.js";
2
- import { t as registerMigrationsCommands } from "../cli-e8I1-dab.js";
2
+ import { t as registerMigrationsCommands } from "../cli-B3MNpH29.js";
3
3
  //#region src/commands/index.ts
4
4
  var commands_exports = /* @__PURE__ */ __exportAll({ registerMigrationsCommands: () => registerMigrationsCommands });
5
5
  //#endregion
@@ -1,3 +1,3 @@
1
- import { i as PostgresCompiler, n as SqliteCompiler, r as PostgresCompilerFactory, t as SqliteCompilerFactory } from "../SqliteCompilerFactory-CXlPAclY.js";
2
- import { i as contracts_exports, n as factories_exports, r as dialects_exports } from "../compilers-BW-WALoD.js";
1
+ import { i as PostgresCompiler, n as SqliteCompiler, r as PostgresCompilerFactory, t as SqliteCompilerFactory } from "../SqliteCompilerFactory-C_56xoQM.js";
2
+ import { i as contracts_exports, n as factories_exports, r as dialects_exports } from "../compilers-BlLQwwmu.js";
3
3
  export { PostgresCompiler, PostgresCompilerFactory, SqliteCompiler, SqliteCompilerFactory, contracts_exports as contracts, dialects_exports as dialects, factories_exports as factories };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { i as PostgresCompiler, n as SqliteCompiler, r as PostgresCompilerFactory, t as SqliteCompilerFactory } from "./SqliteCompilerFactory-CXlPAclY.js";
2
+ import { i as PostgresCompiler, n as SqliteCompiler, r as PostgresCompilerFactory, t as SqliteCompilerFactory } from "./SqliteCompilerFactory-C_56xoQM.js";
3
3
  //#region src/compilers/contracts/index.ts
4
4
  var contracts_exports = /* @__PURE__ */ __exportAll({});
5
5
  //#endregion
@@ -28,4 +28,4 @@ var compilers_exports = /* @__PURE__ */ __exportAll({
28
28
  //#endregion
29
29
  export { contracts_exports as i, factories_exports as n, dialects_exports as r, compilers_exports as t };
30
30
 
31
- //# sourceMappingURL=compilers-BW-WALoD.js.map
31
+ //# sourceMappingURL=compilers-BlLQwwmu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"compilers-BW-WALoD.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":""}
1
+ {"version":3,"file":"compilers-BlLQwwmu.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":""}
@@ -1,2 +1,2 @@
1
- import { n as buildMigrationModelMetadataProjection, r as diffSchema } from "../diff-7Xw8k4vp.js";
1
+ import { n as buildMigrationModelMetadataProjection, r as diffSchema } from "../diff-BsQr9Sl8.js";
2
2
  export { buildMigrationModelMetadataProjection, diffSchema };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./chunk-D7D4PA-g.js";
2
- import { a as applyFieldType, i as OpBuilder } from "./builder-BSepa_PF.js";
2
+ import { a as applyFieldType, i as OpBuilder } from "./builder-Bhm_to6b.js";
3
3
  import { trustedSql } from "@danceroutine/tango-core";
4
4
  //#region src/diff/diffSchema.ts
5
5
  /**
@@ -115,4 +115,4 @@ var diff_exports = /* @__PURE__ */ __exportAll({
115
115
  //#endregion
116
116
  export { buildMigrationModelMetadataProjection as n, diffSchema as r, diff_exports as t };
117
117
 
118
- //# sourceMappingURL=diff-7Xw8k4vp.js.map
118
+ //# sourceMappingURL=diff-BsQr9Sl8.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diff-7Xw8k4vp.js","names":["op"],"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":";;;;;;;;AAyCA,SAAgB,WAAW,IAAc,QAAmD;CACxF,MAAM,MAA4B,CAAC;CACnC,OAAO,SAAS,UAAU;EACtB,IAAI,MAAM,YAAY,OAClB;EAGJ,MAAM,UAAU,GAAG,OAAO,MAAM;EAEhC,IAAI,CAAC,SAAS;GACV,IAAI,KACAA,UAAG,MAAM,MAAM,KAAK,EAAE,QAAQ,SAAS;IACnC,MAAM,OAAO,SAAS,UAAU;KAC5B,KAAK,IAAI,MAAM,OAAO,YAAY;MAC9B,UAAU,eAAe,SAAS,MAAM,IAAI;MAE5C,IAAI,MAAM,SACN,UAAU,QAAQ,QAAQ;MAG9B,IAAI,MAAM,YAAY,MAClB,UAAU,QAAQ,QAAQ,IAAI;WAC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O,MAAM,SAAS;GACtB,SAAS,MAAM,SAAS,WAAW;GACnC,QAAQ,UAAU,IAAI,iBAAiB;GACvC,SAAS,MAAM,SAAS,SAAS,KAAK,WAAW;IAC7C,MAAM,MAAM;IACZ,IAAI,CAAC,GAAG,MAAM,EAAE;IAChB,QAAQ,MAAM;GAClB,EAAE;EACN,CAAC;CACL;CACA,OAAO;AACX"}
1
+ {"version":3,"file":"diff-BsQr9Sl8.js","names":["op"],"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":";;;;;;;;AAyCA,SAAgB,WAAW,IAAc,QAAmD;CACxF,MAAM,MAA4B,CAAC;CACnC,OAAO,SAAS,UAAU;EACtB,IAAI,MAAM,YAAY,OAClB;EAGJ,MAAM,UAAU,GAAG,OAAO,MAAM;EAEhC,IAAI,CAAC,SAAS;GACV,IAAI,KACAA,UAAG,MAAM,MAAM,KAAK,EAAE,QAAQ,SAAS;IACnC,MAAM,OAAO,SAAS,UAAU;KAC5B,KAAK,IAAI,MAAM,OAAO,YAAY;MAC9B,UAAU,eAAe,SAAS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AAS,OAAO,GAAG;EACnC,MAAM,YAAY,SAAS,mBAAmB,MAAM,SAAS,GAAG;EAChE,WAAW,KAAK;GACZ,MAAM,MAAM,SAAS;GACrB,OAAO,MAAM,SAAS;GACtB,SAAS,MAAM,SAAS,WAAW;GACnC,QAAQ,UAAU,IAAI,iBAAiB;GACvC,SAAS,MAAM,SAAS,SAAS,KAAK,WAAW;IAC7C,MAAM,MAAM;IACZ,IAAI,CAAC,GAAG,MAAM,EAAE;IAChB,QAAQ,MAAM;GAClB,EAAE;EACN,CAAC;CACL;CACA,OAAO;AACX"}
@@ -1,2 +1,2 @@
1
- import { n as GenerateMigrationOptions, r as MigrationGenerator } from "../index-B8VoE0M4.js";
1
+ import { n as GenerateMigrationOptions, r as MigrationGenerator } from "../index-Dcuh1zcQ.js";
2
2
  export { type GenerateMigrationOptions, MigrationGenerator };
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "../chunk-D7D4PA-g.js";
2
- import { t as MigrationGenerator } from "../MigrationGenerator-BmmerPXJ.js";
2
+ import { t as MigrationGenerator } from "../MigrationGenerator-D-sSbsFG.js";
3
3
  //#region src/generator/index.ts
4
4
  var generator_exports = /* @__PURE__ */ __exportAll({ MigrationGenerator: () => MigrationGenerator });
5
5
  //#endregion