@danceroutine/tango-migrations 0.1.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +114 -0
  3. package/dist/{CollectingBuilder-C6qnwyrb.js → CollectingBuilder--4fqDQdE.js} +17 -2
  4. package/dist/CollectingBuilder--4fqDQdE.js.map +1 -0
  5. package/dist/{CompilerStrategy-Cv1woBmO.js → CompilerStrategy-yKw-Egxv.js} +19 -8
  6. package/dist/CompilerStrategy-yKw-Egxv.js.map +1 -0
  7. package/dist/InternalColumnType-G9zV9StN.js +16 -0
  8. package/dist/InternalColumnType-G9zV9StN.js.map +1 -0
  9. package/dist/InternalOperationKind-Bt6Weuon.js +19 -0
  10. package/dist/InternalOperationKind-Bt6Weuon.js.map +1 -0
  11. package/dist/{IntrospectorStrategy-BM1Eizfc.js → IntrospectorStrategy-blvwSU3_.js} +13 -4
  12. package/dist/IntrospectorStrategy-blvwSU3_.js.map +1 -0
  13. package/dist/Migration-DYQ0hUG7.js +30 -0
  14. package/dist/Migration-DYQ0hUG7.js.map +1 -0
  15. package/dist/{MigrationGenerator-Z39LTKmC.js → MigrationGenerator-B1p0jHnx.js} +20 -12
  16. package/dist/MigrationGenerator-B1p0jHnx.js.map +1 -0
  17. package/dist/{MigrationRunner-CCFuPUlr.js → MigrationRunner-D1ZfbbS-.js} +52 -9
  18. package/dist/MigrationRunner-D1ZfbbS-.js.map +1 -0
  19. package/dist/MigrationSqlSafetyAdapter-CGRbB2k2.js +62 -0
  20. package/dist/MigrationSqlSafetyAdapter-CGRbB2k2.js.map +1 -0
  21. package/dist/{SqliteCompilerFactory-DwMwO7xY.js → SqliteCompilerFactory-BAodJW9n.js} +73 -51
  22. package/dist/SqliteCompilerFactory-BAodJW9n.js.map +1 -0
  23. package/dist/{SqliteIntrospector-BRdNt6KG.js → SqliteIntrospector-CWwPWhmA.js} +49 -5
  24. package/dist/SqliteIntrospector-CWwPWhmA.js.map +1 -0
  25. package/dist/builder/contracts/ColumnSpec.d.ts +2 -1
  26. package/dist/builder/contracts/UpdateReferentialAction.d.ts +1 -1
  27. package/dist/builder/index.js +4 -4
  28. package/dist/builder/ops/OpBuilder.d.ts +48 -7
  29. package/dist/builder/runtime/CollectingBuilder.d.ts +19 -1
  30. package/dist/{builder-Dtk8oP_Y.js → builder-xJ-Bq2pk.js} +51 -21
  31. package/dist/builder-xJ-Bq2pk.js.map +1 -0
  32. package/dist/cli-DhCn8xiS.js +313 -0
  33. package/dist/cli-DhCn8xiS.js.map +1 -0
  34. package/dist/cli.js +17 -169
  35. package/dist/cli.js.map +1 -1
  36. package/dist/commands/cli.d.ts +5 -0
  37. package/dist/commands/index.d.ts +4 -0
  38. package/dist/commands/index.js +17 -0
  39. package/dist/commands-DIJepqNg.js +10 -0
  40. package/dist/commands-DIJepqNg.js.map +1 -0
  41. package/dist/compilers/contracts/CompilerFactory.d.ts +4 -0
  42. package/dist/compilers/contracts/SQLCompiler.d.ts +4 -0
  43. package/dist/compilers/dialects/PostgresCompiler.d.ts +10 -1
  44. package/dist/compilers/dialects/SqliteCompiler.d.ts +10 -0
  45. package/dist/compilers/factories/PostgresCompilerFactory.d.ts +9 -0
  46. package/dist/compilers/factories/SqliteCompilerFactory.d.ts +9 -0
  47. package/dist/compilers/index.js +5 -4
  48. package/dist/{compilers-D8DJuTnQ.js → compilers-dRN0Hzev.js} +2 -2
  49. package/dist/{compilers-D8DJuTnQ.js.map → compilers-dRN0Hzev.js.map} +1 -1
  50. package/dist/diff/diffSchema.d.ts +6 -1
  51. package/dist/diff/index.js +6 -6
  52. package/dist/{diff-Cs0TPEGR.js → diff-CZZbXAPN.js} +2 -2
  53. package/dist/{diff-Cs0TPEGR.js.map → diff-CZZbXAPN.js.map} +1 -1
  54. package/dist/{diffSchema-KgGHP-s3.js → diffSchema-D4oemTWS.js} +5 -4
  55. package/dist/diffSchema-D4oemTWS.js.map +1 -0
  56. package/dist/domain/Migration.d.ts +17 -0
  57. package/dist/domain/MigrationOperation.d.ts +14 -13
  58. package/dist/domain/index.js +2 -2
  59. package/dist/domain/internal/InternalColumnType.d.ts +11 -10
  60. package/dist/domain/internal/InternalDialect.d.ts +5 -4
  61. package/dist/domain/internal/InternalMigrationMode.d.ts +5 -4
  62. package/dist/domain/internal/InternalOperationKind.d.ts +14 -13
  63. package/dist/domain/internal/InternalReferentialAction.d.ts +7 -6
  64. package/dist/{domain-BXVlG0C0.js → domain-CwR-kUNS.js} +2 -2
  65. package/dist/{domain-BXVlG0C0.js.map → domain-CwR-kUNS.js.map} +1 -1
  66. package/dist/generator/MigrationGenerator.d.ts +13 -0
  67. package/dist/generator/index.js +3 -3
  68. package/dist/{generator-3yC60b1u.js → generator-DK-_f-PF.js} +2 -2
  69. package/dist/{generator-3yC60b1u.js.map → generator-DK-_f-PF.js.map} +1 -1
  70. package/dist/index.d.ts +4 -0
  71. package/dist/index.js +24 -20
  72. package/dist/internal/MigrationSqlSafetyAdapter.d.ts +24 -0
  73. package/dist/introspect/DatabaseIntrospector.d.ts +8 -0
  74. package/dist/introspect/PostgresIntrospector.d.ts +14 -0
  75. package/dist/introspect/SqliteIntrospector.d.ts +13 -0
  76. package/dist/introspect/index.js +3 -2
  77. package/dist/{introspect-ks-QSodq.js → introspect-TPv_jeD6.js} +2 -2
  78. package/dist/{introspect-ks-QSodq.js.map → introspect-TPv_jeD6.js.map} +1 -1
  79. package/dist/runner/MigrationRunner.d.ts +7 -1
  80. package/dist/runner/index.js +9 -8
  81. package/dist/{runner-BOs-tItW.js → runner-C97xT8_W.js} +2 -2
  82. package/dist/{runner-BOs-tItW.js.map → runner-C97xT8_W.js.map} +1 -1
  83. package/dist/runtime/loadModule.d.ts +15 -0
  84. package/dist/strategies/CompilerStrategy.d.ts +19 -1
  85. package/dist/strategies/IntrospectorStrategy.d.ts +16 -1
  86. package/dist/strategies/index.js +8 -7
  87. package/dist/{strategies-BvHwf4as.js → strategies-D9ymSvbG.js} +3 -3
  88. package/dist/{strategies-BvHwf4as.js.map → strategies-D9ymSvbG.js.map} +1 -1
  89. package/package.json +98 -92
  90. package/dist/CollectingBuilder-C6qnwyrb.js.map +0 -1
  91. package/dist/CompilerStrategy-Cv1woBmO.js.map +0 -1
  92. package/dist/InternalColumnType-_YAz7RqI.js +0 -17
  93. package/dist/InternalColumnType-_YAz7RqI.js.map +0 -1
  94. package/dist/InternalOperationKind-BPVoOQwD.js +0 -20
  95. package/dist/InternalOperationKind-BPVoOQwD.js.map +0 -1
  96. package/dist/IntrospectorStrategy-BM1Eizfc.js.map +0 -1
  97. package/dist/Migration-D9J6ZbLP.js +0 -25
  98. package/dist/Migration-D9J6ZbLP.js.map +0 -1
  99. package/dist/MigrationGenerator-Z39LTKmC.js.map +0 -1
  100. package/dist/MigrationRunner-CCFuPUlr.js.map +0 -1
  101. package/dist/SqliteCompilerFactory-DwMwO7xY.js.map +0 -1
  102. package/dist/SqliteIntrospector-BRdNt6KG.js.map +0 -1
  103. package/dist/builder/ops/OpBuilder.js +0 -173
  104. package/dist/builder-Dtk8oP_Y.js.map +0 -1
  105. package/dist/diffSchema-KgGHP-s3.js.map +0 -1
  106. package/dist/domain/MigrationOperation.js +0 -1
@@ -1,25 +0,0 @@
1
-
2
- //#region src/domain/Migration.ts
3
- var Migration = class Migration {
4
- static BRAND = "tango.migration";
5
- __tangoBrand = Migration.BRAND;
6
- mode;
7
- static isMigration(value) {
8
- return typeof value === "object" && value !== null && value.__tangoBrand === Migration.BRAND;
9
- }
10
- static isMigrationConstructor(value) {
11
- if (typeof value !== "function") return false;
12
- const prototype = value.prototype;
13
- if (typeof prototype !== "object" || prototype === null) return false;
14
- let current = prototype;
15
- while (current) {
16
- if (current === Migration.prototype) return true;
17
- current = Object.getPrototypeOf(current);
18
- }
19
- return false;
20
- }
21
- };
22
-
23
- //#endregion
24
- export { Migration };
25
- //# sourceMappingURL=Migration-D9J6ZbLP.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Migration-D9J6ZbLP.js","names":["value: unknown","current: object | null"],"sources":["../src/domain/Migration.ts"],"sourcesContent":["import type { Builder } from '../builder/contracts/Builder';\nimport type { MigrationMode } from './MigrationMode';\n\nexport abstract class Migration {\n static readonly BRAND = 'tango.migration' as const;\n readonly __tangoBrand: typeof Migration.BRAND = Migration.BRAND;\n\n abstract id: string;\n mode?: MigrationMode;\n abstract up(m: Builder): void | Promise<void>;\n abstract down(m: Builder): void | Promise<void>;\n\n static isMigration(value: unknown): value is Migration {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === Migration.BRAND\n );\n }\n\n static isMigrationConstructor(value: unknown): value is new () => Migration {\n if (typeof value !== 'function') {\n return false;\n }\n\n const prototype = (value as { prototype?: unknown }).prototype;\n if (typeof prototype !== 'object' || prototype === null) {\n return false;\n }\n let current: object | null = prototype as object;\n while (current) {\n if (current === Migration.prototype) {\n return true;\n }\n current = Object.getPrototypeOf(current) as object | null;\n }\n return false;\n }\n}\n"],"mappings":";;IAGsB,YAAf,MAAe,UAAU;CAC5B,OAAgB,QAAQ;CACxB,eAAgD,UAAU;CAG1D;CAIA,OAAO,YAAYA,OAAoC;AACnD,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,UAAU;CAExE;CAED,OAAO,uBAAuBA,OAA8C;AACxE,aAAW,UAAU,WACjB,QAAO;EAGX,MAAM,YAAa,MAAkC;AACrD,aAAW,cAAc,YAAY,cAAc,KAC/C,QAAO;EAEX,IAAIC,UAAyB;AAC7B,SAAO,SAAS;AACZ,OAAI,YAAY,UAAU,UACtB,QAAO;AAEX,aAAU,OAAO,eAAe,QAAQ;EAC3C;AACD,SAAO;CACV;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"MigrationGenerator-Z39LTKmC.js","names":["value: unknown","options: GenerateMigrationOptions","id: string","operations: MigrationOperation[]","operation: MigrationOperation","operation: TableCreate","operation: TableDrop","operation: ColumnAdd","operation: ColumnDrop","operation: ColumnAlter","parts: string[]","operation: ColumnRename","operation: IndexCreate","operation: IndexDrop","operation: ForeignKeyCreate","operation: ForeignKeyDrop","col: ColumnSpec","refParts: string[]"],"sources":["../src/generator/MigrationGenerator.ts"],"sourcesContent":["import type {\n MigrationOperation,\n TableCreate,\n TableDrop,\n ColumnAdd,\n ColumnDrop,\n ColumnAlter,\n ColumnRename,\n IndexCreate,\n IndexDrop,\n ForeignKeyCreate,\n ForeignKeyDrop,\n} from '../domain/MigrationOperation';\nimport type { ColumnSpec } from '../builder/contracts/ColumnSpec';\nimport { InternalOperationKind } from '../domain/internal/InternalOperationKind';\nimport { writeFile, mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\n\nexport interface GenerateMigrationOptions {\n name: string;\n operations: MigrationOperation[];\n directory: string;\n}\nexport class MigrationGenerator {\n static readonly BRAND = 'tango.migrations.generator' as const;\n readonly __tangoBrand: typeof MigrationGenerator.BRAND = MigrationGenerator.BRAND;\n\n static isMigrationGenerator(value: unknown): value is MigrationGenerator {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === MigrationGenerator.BRAND\n );\n }\n\n /**\n * Generate a migration file and write it to disk.\n * Returns the file path of the created migration.\n */\n async generate(options: GenerateMigrationOptions): Promise<string> {\n const { name, operations, directory } = options;\n\n if (operations.length === 0) {\n throw new Error('No operations to generate — models and database are in sync');\n }\n\n const timestamp = this.timestamp();\n const id = `${timestamp}_${name}`;\n const filename = `${id}.ts`;\n const filepath = join(directory, filename);\n\n const source = this.render(id, operations);\n\n await mkdir(directory, { recursive: true });\n await writeFile(filepath, source, 'utf-8');\n\n return filepath;\n }\n\n /**\n * Render migration operations to a TypeScript source string without writing to disk.\n */\n render(id: string, operations: MigrationOperation[]): string {\n const upOps = operations.map((operation) => this.renderOperation(operation));\n const downOps = operations.map((operation) => this.renderReverseOperation(operation)).reverse();\n const className = this.renderClassName(id);\n\n const lines = [\n `import { Migration, op } from '@danceroutine/tango-migrations';`,\n ``,\n `export default class ${className} extends Migration {`,\n ` id = '${id}';`,\n ``,\n ` up(m) {`,\n ` m.run(`,\n ...upOps.map((code, index) => {\n const comma = index < upOps.length - 1 ? ',' : '';\n return ` ${code}${comma}`;\n }),\n ` );`,\n ` }`,\n ``,\n ` down(m) {`,\n ` m.run(`,\n ...downOps.map((code, index) => {\n const comma = index < downOps.length - 1 ? ',' : '';\n return ` ${code}${comma}`;\n }),\n ` );`,\n ` }`,\n `}`,\n ``,\n ];\n\n return lines.join('\\n');\n }\n\n private renderClassName(id: string): string {\n const normalized = id.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^(\\d)/, '_$1');\n return `Migration_${normalized}`;\n }\n\n private renderOperation(operation: MigrationOperation): string {\n switch (operation.kind) {\n case InternalOperationKind.TABLE_CREATE:\n return this.renderTableCreate(operation);\n case InternalOperationKind.TABLE_DROP:\n return this.renderTableDrop(operation);\n case InternalOperationKind.COLUMN_ADD:\n return this.renderColumnAdd(operation);\n case InternalOperationKind.COLUMN_DROP:\n return this.renderColumnDrop(operation);\n case InternalOperationKind.COLUMN_ALTER:\n return this.renderColumnAlter(operation);\n case InternalOperationKind.COLUMN_RENAME:\n return this.renderColumnRename(operation);\n case InternalOperationKind.INDEX_CREATE:\n return this.renderIndexCreate(operation);\n case InternalOperationKind.INDEX_DROP:\n return this.renderIndexDrop(operation);\n case InternalOperationKind.FK_CREATE:\n return this.renderForeignKeyCreate(operation);\n case InternalOperationKind.FK_DROP:\n return this.renderForeignKeyDrop(operation);\n case InternalOperationKind.FK_VALIDATE:\n return `op.foreignKeyValidate({ table: '${operation.table}', name: '${operation.name}' })`;\n case 'custom':\n return `/* custom operation '${operation.name}' cannot be code-generated */`;\n default:\n return `/* unsupported operation */`;\n }\n }\n\n private renderReverseOperation(operation: MigrationOperation): string {\n switch (operation.kind) {\n case InternalOperationKind.TABLE_CREATE:\n return `op.table('${operation.table}').drop()`;\n case InternalOperationKind.TABLE_DROP:\n return `/* manual reverse required: recreate dropped table '${operation.table}' */`;\n case InternalOperationKind.COLUMN_ADD:\n return `op.table('${operation.table}').dropColumn('${operation.column.name}')`;\n case InternalOperationKind.COLUMN_DROP:\n return `/* manual reverse required: restore dropped column '${operation.column}' */`;\n case InternalOperationKind.COLUMN_ALTER:\n return `/* manual reverse required: revert ALTER COLUMN '${operation.column}' on '${operation.table}' */`;\n case InternalOperationKind.COLUMN_RENAME:\n return `op.table('${operation.table}').renameColumn('${operation.to}', '${operation.from}')`;\n case InternalOperationKind.INDEX_CREATE:\n return `op.index.drop({ name: '${operation.name}', table: '${operation.table}' })`;\n case InternalOperationKind.INDEX_DROP:\n return `/* manual reverse required: recreate dropped index '${operation.name}' */`;\n case InternalOperationKind.FK_CREATE:\n return `op.foreignKeyDrop({ table: '${operation.table}', name: '${operation.name ?? `${operation.table}_${operation.columns.join('_')}_fkey`}' })`;\n case InternalOperationKind.FK_DROP:\n return `/* manual reverse required: recreate dropped FK '${operation.name}' */`;\n case InternalOperationKind.FK_VALIDATE:\n return `/* no reverse needed for FK_VALIDATE */`;\n case 'custom':\n return `/* manual reverse required: custom operation '${operation.name}' */`;\n default:\n return `/* unsupported reverse operation */`;\n }\n }\n\n private renderTableCreate(operation: TableCreate): string {\n const columnLines = operation.columns.map((col) => {\n const chain = this.renderColumnChain(col);\n return ` cols.add('${col.name}', (b) => b${chain});`;\n });\n\n return [`op.table('${operation.table}').create((cols) => {`, ...columnLines, ` })`].join('\\n');\n }\n\n private renderTableDrop(operation: TableDrop): string {\n if (operation.cascade) {\n return `op.table('${operation.table}').drop({ cascade: true })`;\n }\n return `op.table('${operation.table}').drop()`;\n }\n\n private renderColumnAdd(operation: ColumnAdd): string {\n const chain = this.renderColumnChain(operation.column);\n return `op.table('${operation.table}').addColumn('${operation.column.name}', (b) => b${chain})`;\n }\n\n private renderColumnDrop(operation: ColumnDrop): string {\n return `op.table('${operation.table}').dropColumn('${operation.column}')`;\n }\n\n private renderColumnAlter(operation: ColumnAlter): string {\n const parts: string[] = [];\n if (operation.to.type) {\n parts.push(`type: '${operation.to.type}'`);\n }\n if (operation.to.notNull !== undefined) {\n parts.push(`notNull: ${operation.to.notNull}`);\n }\n if (operation.to.default !== undefined) {\n if (operation.to.default === null) {\n parts.push(`default: null`);\n } else if (typeof operation.to.default === 'string') {\n parts.push(`default: '${operation.to.default}'`);\n } else if (typeof operation.to.default === 'object' && operation.to.default.now) {\n parts.push(`default: { now: true }`);\n }\n }\n return `op.table('${operation.table}').alterColumn('${operation.column}', { ${parts.join(', ')} })`;\n }\n\n private renderColumnRename(operation: ColumnRename): string {\n return `op.table('${operation.table}').renameColumn('${operation.from}', '${operation.to}')`;\n }\n\n private renderIndexCreate(operation: IndexCreate): string {\n const parts: string[] = [\n `name: '${operation.name}'`,\n `table: '${operation.table}'`,\n `on: [${operation.on.map((c) => `'${c}'`).join(', ')}]`,\n ];\n if (operation.unique) {\n parts.push(`unique: true`);\n }\n if (operation.where) {\n parts.push(`where: '${operation.where}'`);\n }\n if (operation.concurrently) {\n parts.push(`concurrently: true`);\n }\n return `op.index.create({ ${parts.join(', ')} })`;\n }\n\n private renderIndexDrop(operation: IndexDrop): string {\n return `op.index.drop({ name: '${operation.name}', table: '${operation.table}' })`;\n }\n\n private renderForeignKeyCreate(operation: ForeignKeyCreate): string {\n const parts: string[] = [\n `table: '${operation.table}'`,\n `columns: [${operation.columns.map((c) => `'${c}'`).join(', ')}]`,\n `references: { table: '${operation.refTable}', columns: [${operation.refColumns.map((c) => `'${c}'`).join(', ')}] }`,\n ];\n if (operation.name) {\n parts.push(`name: '${operation.name}'`);\n }\n if (operation.onDelete) {\n parts.push(`onDelete: '${operation.onDelete}'`);\n }\n if (operation.onUpdate) {\n parts.push(`onUpdate: '${operation.onUpdate}'`);\n }\n if (operation.notValid) {\n parts.push(`notValid: true`);\n }\n return `op.foreignKey({ ${parts.join(', ')} })`;\n }\n\n private renderForeignKeyDrop(operation: ForeignKeyDrop): string {\n return `op.foreignKeyDrop({ table: '${operation.table}', name: '${operation.name}' })`;\n }\n\n private renderColumnChain(col: ColumnSpec): string {\n const parts: string[] = [];\n\n if (col.type) {\n parts.push(`.${col.type}()`);\n }\n if (col.notNull) {\n parts.push(`.notNull()`);\n }\n if (col.default !== undefined && col.default !== null) {\n if (typeof col.default === 'string') {\n parts.push(`.default('${col.default}')`);\n } else if (typeof col.default === 'object' && col.default.now) {\n parts.push(`.defaultNow()`);\n }\n } else if (col.default === null) {\n parts.push(`.default(null)`);\n }\n if (col.primaryKey) {\n parts.push(`.primaryKey()`);\n }\n if (col.unique) {\n parts.push(`.unique()`);\n }\n if (col.references) {\n const refParts: string[] = [];\n if (col.references.onDelete) {\n refParts.push(`onDelete: '${col.references.onDelete}'`);\n }\n if (col.references.onUpdate) {\n refParts.push(`onUpdate: '${col.references.onUpdate}'`);\n }\n const opts = refParts.length > 0 ? `, { ${refParts.join(', ')} }` : '';\n parts.push(`.references('${col.references.table}', '${col.references.column}'${opts})`);\n }\n\n return parts.join('');\n }\n\n private timestamp(): string {\n const now = new Date();\n const year = now.getFullYear();\n const month = String(now.getMonth() + 1).padStart(2, '0');\n const day = String(now.getDate()).padStart(2, '0');\n const hours = String(now.getHours()).padStart(2, '0');\n const minutes = String(now.getMinutes()).padStart(2, '0');\n const seconds = String(now.getSeconds()).padStart(2, '0');\n return `${year}${month}${day}${hours}${minutes}${seconds}`;\n }\n}\n"],"mappings":";;;;;IAuBa,qBAAN,MAAM,mBAAmB;CAC5B,OAAgB,QAAQ;CACxB,eAAyD,mBAAmB;CAE5E,OAAO,qBAAqBA,OAA6C;AACrE,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,mBAAmB;CAEjF;;;;;CAMD,MAAM,SAASC,SAAoD;EAC/D,MAAM,EAAE,MAAM,YAAY,WAAW,GAAG;AAExC,MAAI,WAAW,WAAW,EACtB,OAAM,IAAI,MAAM;EAGpB,MAAM,YAAY,KAAK,WAAW;EAClC,MAAM,MAAM,EAAE,UAAU,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,OAAO,IAAI,YAAY,CAAC,CAAC,SAAS,GAAG,IAAI;AACzD,UAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ;CAC5D;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"MigrationRunner-CCFuPUlr.js","names":["client: DBClient","dialect: Dialect","migrationsDir: string","compilerStrategy?: CompilerStrategy","value: unknown","toId?: string","migrations: Migration[]","migration: Migration","x: unknown","op: MigrationOperation"],"sources":["../src/runner/MigrationRunner.ts"],"sourcesContent":["import { CollectingBuilder } from '../builder/runtime/CollectingBuilder';\nimport type { Dialect } from '../domain/Dialect';\nimport { Migration } from '../domain/Migration';\nimport type { SQL } from '../compilers/contracts/SQL';\nimport type { MigrationOperation } from '../domain/MigrationOperation';\nimport type { CompilerStrategy } from '../strategies/CompilerStrategy';\nimport { createDefaultCompilerStrategy } from '../strategies/CompilerStrategy';\nimport { InternalDialect } from '../domain/internal/InternalDialect';\nimport { readdir } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\nconst JOURNAL = '_tango_migrations';\n\ninterface DBClient {\n query<T = unknown>(sql: string, params?: readonly unknown[]): Promise<{ rows: T[] }>;\n close(): Promise<void>;\n}\n\n/**\n * Manages the lifecycle of database migrations: applying, planning, and tracking status.\n *\n * The runner reads migration files from a directory, compiles operations to SQL\n * for the target dialect, and maintains a journal table to track which migrations\n * have been applied. Each applied migration is checksummed to detect tampering.\n *\n * @example\n * ```typescript\n * const runner = new MigrationRunner(client, 'postgres', './migrations');\n *\n * // Apply all pending migrations\n * await runner.apply();\n *\n * // Apply up to a specific migration\n * await runner.apply('003_add_indexes');\n *\n * // Preview the SQL that would be generated\n * const sql = await runner.plan();\n *\n * // Check which migrations are applied\n * const statuses = await runner.status();\n * ```\n */\nexport class MigrationRunner {\n static readonly BRAND = 'tango.migrations.runner' as const;\n private compilerStrategy: CompilerStrategy;\n readonly __tangoBrand: typeof MigrationRunner.BRAND = MigrationRunner.BRAND;\n\n constructor(\n private client: DBClient,\n private dialect: Dialect,\n private migrationsDir: string = 'migrations',\n compilerStrategy?: CompilerStrategy\n ) {\n this.compilerStrategy = compilerStrategy ?? createDefaultCompilerStrategy();\n }\n\n static isMigrationRunner(value: unknown): value is MigrationRunner {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === MigrationRunner.BRAND\n );\n }\n\n /**\n * Apply all pending migrations, optionally stopping at a specific migration ID.\n * Migrations are applied in file-sort order. Already-applied migrations are skipped.\n * Non-online migrations are wrapped in a transaction on Postgres.\n */\n async apply(toId?: string): Promise<void> {\n await this.ensureJournal();\n const applied = await this.listApplied();\n const migrations = await this.loadMigrations();\n\n for (const migration of migrations) {\n if (toId && migration.id > toId) {\n break;\n }\n if (applied.has(migration.id)) {\n continue;\n }\n\n await this.applyMigration(migration);\n }\n }\n\n /**\n * Generate a dry-run SQL plan for all migrations without executing anything.\n * Useful for reviewing what SQL would be run before applying.\n */\n async plan(): Promise<string> {\n const migrations = await this.loadMigrations();\n let output = '';\n\n migrations.forEach((migration) => {\n const builder = new CollectingBuilder();\n migration.up(builder);\n const sqls = builder.ops.flatMap((op) => this.compileOperation(op));\n\n output += `# ${migration.id}\\n`;\n sqls.forEach((statement) => {\n output += statement.sql + ';\\n';\n });\n if (builder.dataFns.length) {\n output += '-- (data step present)\\n';\n }\n output += '\\n';\n });\n\n return output;\n }\n\n /**\n * Return the applied/pending status of every migration found on disk.\n */\n async status(): Promise<{ id: string; applied: boolean }[]> {\n const applied = await this.listApplied();\n const migrations = await this.loadMigrations();\n\n return migrations.map((m) => ({\n id: m.id,\n applied: applied.has(m.id),\n }));\n }\n\n private async ensureJournal(): Promise<void> {\n const sql =\n this.dialect === InternalDialect.POSTGRES\n ? `CREATE TABLE IF NOT EXISTS \"${JOURNAL}\" (\n id TEXT PRIMARY KEY,\n applied_at TIMESTAMPTZ NOT NULL DEFAULT now(),\n checksum TEXT NOT NULL\n )`\n : `CREATE TABLE IF NOT EXISTS ${JOURNAL} (\n id TEXT PRIMARY KEY,\n applied_at TEXT NOT NULL DEFAULT (datetime('now')),\n checksum TEXT NOT NULL\n )`;\n\n await this.client.query(sql);\n }\n\n private async listApplied(): Promise<Set<string>> {\n const table = this.dialect === InternalDialect.POSTGRES ? `\"${JOURNAL}\"` : JOURNAL;\n const { rows } = await this.client.query<{ id: string }>(`SELECT id FROM ${table}`);\n return new Set(rows.map((r) => r.id));\n }\n\n private async loadMigrations(): Promise<Migration[]> {\n const files = (await readdir(this.migrationsDir)).filter((f) => f.endsWith('.ts') || f.endsWith('.js')).sort();\n\n const migrations: Migration[] = [];\n\n for (const file of files) {\n const mod = await import(resolve(this.migrationsDir, file));\n const loaded = mod.default;\n\n if (Migration.isMigration(loaded)) {\n migrations.push(loaded);\n continue;\n }\n\n if (Migration.isMigrationConstructor(loaded)) {\n migrations.push(new loaded());\n continue;\n }\n\n throw new Error(\n `Invalid migration module '${file}'. Default export must be a Migration subclass or instance.`\n );\n }\n\n return migrations;\n }\n\n private async applyMigration(migration: Migration): Promise<void> {\n const builder = new CollectingBuilder();\n await migration.up(builder);\n\n const sqls = builder.ops.flatMap((op) => this.compileOperation(op));\n const checksum = String(this.hashJSON(builder.ops));\n\n const isOnline = (migration.mode ?? builder.getMode()) === 'online';\n\n if (!isOnline && this.dialect === InternalDialect.POSTGRES) {\n await this.client.query('BEGIN');\n }\n\n try {\n for (const statement of sqls) {\n await this.client.query(statement.sql, statement.params);\n }\n\n for (const fn of builder.dataFns) {\n await fn({ query: (sql, params) => this.client.query(sql, params).then(() => {}) });\n }\n\n const table = this.dialect === InternalDialect.POSTGRES ? `\"${JOURNAL}\"` : JOURNAL;\n const placeholder = this.dialect === InternalDialect.POSTGRES ? '$1, $2' : '?, ?';\n await this.client.query(`INSERT INTO ${table} (id, checksum) VALUES (${placeholder})`, [\n migration.id,\n checksum,\n ]);\n\n if (!isOnline && this.dialect === InternalDialect.POSTGRES) {\n await this.client.query('COMMIT');\n }\n } catch (error) {\n if (!isOnline && this.dialect === InternalDialect.POSTGRES) {\n await this.client.query('ROLLBACK');\n }\n throw error;\n }\n }\n\n /**\n * Compute a simple hash of the migration's operation list.\n * Stored alongside each applied migration in the journal table to detect\n * if a migration file has been modified after it was already applied.\n * Uses a djb2-like hash over the JSON-serialized operations.\n */\n private hashJSON(x: unknown): number {\n const s = JSON.stringify(x);\n let h = 0;\n for (let i = 0; i < s.length; i++) {\n h = Math.imul(31, h) + s.charCodeAt(i);\n h = h | 0;\n }\n return h >>> 0;\n }\n\n private compileOperation(op: MigrationOperation): SQL[] {\n return this.compilerStrategy.compile(this.dialect, op);\n }\n}\n"],"mappings":";;;;;;;AAWA,MAAM,UAAU;IA+BH,kBAAN,MAAM,gBAAgB;CACzB,OAAgB,QAAQ;CACxB;CACA,eAAsD,gBAAgB;CAEtE,YACYA,QACAC,SACAC,gBAAwB,cAChCC,kBACF;AAAA,OAJU,SAAA;AAAA,OACA,UAAA;AAAA,OACA,gBAAA;AAGR,OAAK,mBAAmB,oBAAoB,+BAA+B;CAC9E;CAED,OAAO,kBAAkBC,OAA0C;AAC/D,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,gBAAgB;CAE9E;;;;;;CAOD,MAAM,MAAMC,MAA8B;AACtC,QAAM,KAAK,eAAe;EAC1B,MAAM,UAAU,MAAM,KAAK,aAAa;EACxC,MAAM,aAAa,MAAM,KAAK,gBAAgB;AAE9C,OAAK,MAAM,aAAa,YAAY;AAChC,OAAI,QAAQ,UAAU,KAAK,KACvB;AAEJ,OAAI,QAAQ,IAAI,UAAU,GAAG,CACzB;AAGJ,SAAM,KAAK,eAAe,UAAU;EACvC;CACJ;;;;;CAMD,MAAM,OAAwB;EAC1B,MAAM,aAAa,MAAM,KAAK,gBAAgB;EAC9C,IAAI,SAAS;AAEb,aAAW,QAAQ,CAAC,cAAc;GAC9B,MAAM,UAAU,IAAI;AACpB,aAAU,GAAG,QAAQ;GACrB,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,QAAQ,KAAK;AAC/B,OAAI,KAAK,KAAK,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE;AACtC,OAAI,IAAI;EACX;AACD,SAAO,MAAM;CAChB;CAED,iBAAyBC,IAA+B;AACpD,SAAO,KAAK,iBAAiB,QAAQ,KAAK,SAAS,GAAG;CACzD;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"SqliteCompilerFactory-DwMwO7xY.js","names":["value: unknown","op: MigrationOperation","constraints: string[]","out: SQL[]","table: string","column: string","defaultValue: unknown","identifier: string","column: ColumnSpec","parts: string[]","type: ColumnType","exhaustive: never","value: unknown","value: unknown","op: MigrationOperation","column: ColumnSpec","parts: string[]","value: unknown"],"sources":["../src/compilers/dialects/PostgresCompiler.ts","../src/compilers/factories/PostgresCompilerFactory.ts","../src/compilers/dialects/SqliteCompiler.ts","../src/compilers/factories/SqliteCompilerFactory.ts"],"sourcesContent":["import type { MigrationOperation } from '../../domain/MigrationOperation';\nimport type { SQL } from '../contracts/SQL';\nimport type { ColumnSpec } from '../../builder/contracts/ColumnSpec';\nimport type { ColumnType } from '../../builder/contracts/ColumnType';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { InternalOperationKind } from '../../domain/internal/InternalOperationKind';\nimport { InternalColumnType } from '../../domain/internal/InternalColumnType';\nexport class PostgresCompiler implements SQLCompiler {\n static readonly BRAND = 'tango.migrations.postgres_compiler' as const;\n readonly __tangoBrand: typeof PostgresCompiler.BRAND = PostgresCompiler.BRAND;\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 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.id(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 fkName = `${op.table}_${column.name}_fkey`;\n let fk = `CONSTRAINT ${this.id(fkName)} FOREIGN KEY (${this.id(column.name)}) REFERENCES ${this.id(column.references!.table)}(${this.id(column.references!.column)})`;\n if (column.references!.onDelete) {\n fk += ` ON DELETE ${column.references!.onDelete}`;\n }\n if (column.references!.onUpdate) {\n fk += ` ON UPDATE ${column.references!.onUpdate}`;\n }\n constraints.push(fk);\n });\n\n const allParts = [cols, ...constraints].join(', ');\n const sql = `CREATE TABLE ${this.id(op.table)} (${allParts})`;\n return [{ sql, params: [] }];\n }\n\n case InternalOperationKind.TABLE_DROP:\n return [{ sql: `DROP TABLE ${this.id(op.table)}${op.cascade ? ' CASCADE' : ''}`, params: [] }];\n\n case InternalOperationKind.COLUMN_ADD:\n return [{ sql: `ALTER TABLE ${this.id(op.table)} ADD COLUMN ${this.colDDL(op.column)}`, params: [] }];\n\n case InternalOperationKind.COLUMN_DROP:\n return [{ sql: `ALTER TABLE ${this.id(op.table)} DROP COLUMN ${this.id(op.column)}`, params: [] }];\n\n case InternalOperationKind.COLUMN_ALTER: {\n const out: SQL[] = [];\n if (op.to.type) {\n out.push({\n sql: `ALTER TABLE ${this.id(op.table)} ALTER COLUMN ${this.id(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.id(op.table)} ALTER COLUMN ${this.id(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.id(op.table)} RENAME COLUMN ${this.id(op.from)} TO ${this.id(op.to)}`,\n params: [],\n },\n ];\n\n case InternalOperationKind.INDEX_CREATE: {\n const cols = op.on.join(', ');\n const uniq = op.unique ? 'UNIQUE ' : '';\n const conc = op.concurrently ? 'CONCURRENTLY ' : '';\n const where = op.where ? ` WHERE ${op.where}` : '';\n return [\n {\n sql: `CREATE ${uniq}INDEX ${conc}${this.id(op.name)} ON ${this.id(op.table)} (${cols})${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.id(op.name)}`, params: [] }];\n }\n\n case InternalOperationKind.FK_CREATE: {\n const cols = op.columns.map((c) => this.id(c)).join(', ');\n const refs = op.refColumns.map((c) => this.id(c)).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.id(op.table)} ADD CONSTRAINT ${this.id(name)} FOREIGN KEY (${cols}) REFERENCES ${this.id(op.refTable)} (${refs})${onDel}${onUpd}${notValid}`,\n params: [],\n },\n ];\n }\n\n case InternalOperationKind.FK_VALIDATE:\n return [\n { sql: `ALTER TABLE ${this.id(op.table)} VALIDATE CONSTRAINT ${this.id(op.name)}`, params: [] },\n ];\n\n case InternalOperationKind.FK_DROP:\n return [{ sql: `ALTER TABLE ${this.id(op.table)} DROP CONSTRAINT ${this.id(op.name)}`, params: [] }];\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.id(table)} ALTER COLUMN ${this.id(column)} DROP DEFAULT`,\n params: [],\n },\n ];\n }\n\n if (typeof defaultValue === 'string') {\n return [\n {\n sql: `ALTER TABLE ${this.id(table)} ALTER COLUMN ${this.id(column)} SET 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.id(table)} ALTER COLUMN ${this.id(column)} SET DEFAULT now()`,\n params: [],\n },\n ];\n }\n\n return [];\n }\n\n private id(identifier: string): string {\n return `\"${identifier}\"`;\n }\n\n private colDDL(column: ColumnSpec): string {\n const parts: string[] = [this.id(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 if (column.default) {\n if (typeof column.default === 'string') {\n parts.push(`DEFAULT ${column.default}`);\n } else if (column.default.now) {\n parts.push('DEFAULT now()');\n }\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\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 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 create(): SQLCompiler {\n return new PostgresCompiler();\n }\n}\n","import type { MigrationOperation } from '../../domain/MigrationOperation';\nimport type { SQL } from '../contracts/SQL';\nimport type { ColumnSpec } from '../../builder/contracts/ColumnSpec';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { InternalOperationKind } from '../../domain/internal/InternalOperationKind';\nimport { InternalColumnType } from '../../domain/internal/InternalColumnType';\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\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 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) => 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 cols.push(\n `FOREIGN KEY (${column.name}) REFERENCES ${column.references!.table}(${column.references!.column})${column.references!.onDelete ? ` ON DELETE ${column.references!.onDelete}` : ''}${column.references!.onUpdate ? ` ON UPDATE ${column.references!.onUpdate}` : ''}`\n );\n });\n\n const sql = `CREATE TABLE ${op.table} (${cols.join(', ')})`;\n return [{ sql, params: [] }];\n }\n\n case InternalOperationKind.TABLE_DROP:\n return [{ sql: `DROP TABLE ${op.table}`, params: [] }];\n\n case InternalOperationKind.COLUMN_ADD:\n return [{ sql: `ALTER TABLE ${op.table} ADD COLUMN ${this.colDDL(op.column)}`, params: [] }];\n\n case InternalOperationKind.COLUMN_DROP:\n return [{ sql: `ALTER TABLE ${op.table} DROP COLUMN ${op.column}`, params: [] }];\n\n case InternalOperationKind.COLUMN_RENAME:\n return [{ sql: `ALTER TABLE ${op.table} RENAME COLUMN ${op.from} TO ${op.to}`, params: [] }];\n\n case InternalOperationKind.INDEX_CREATE: {\n const cols = op.on.join(', ');\n const uniq = op.unique ? 'UNIQUE ' : '';\n const where = op.where ? ` WHERE ${op.where}` : '';\n return [{ sql: `CREATE ${uniq}INDEX ${op.name} ON ${op.table} (${cols})${where}`, params: [] }];\n }\n\n case InternalOperationKind.INDEX_DROP:\n return [{ sql: `DROP 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[] = [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 if (column.default) {\n if (typeof column.default === 'string') {\n parts.push(`DEFAULT ${column.default}`);\n } else if (column.default.now) {\n parts.push(\"DEFAULT (datetime('now'))\");\n }\n }\n if (column.unique && !column.primaryKey) {\n parts.push('UNIQUE');\n }\n\n return parts.join(' ');\n }\n}\n","import type { CompilerFactory } from '../contracts/CompilerFactory';\nimport type { SQLCompiler } from '../contracts/SQLCompiler';\nimport { SqliteCompiler } from '../dialects/SqliteCompiler';\n\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 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 create(): SQLCompiler {\n return new SqliteCompiler();\n }\n}\n"],"mappings":";;;;IAOa,mBAAN,MAAM,iBAAwC;CACjD,OAAgB,QAAQ;CACxB,eAAuD,iBAAiB;CAExE,OAAO,mBAAmBA,OAA2C;AACjE,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,iBAAiB;CAE/E;CAED,QAAQC,IAA+B;AACnC,UAAQ,GAAG,MAAX;AACI,QAAK,sBAAsB,cAAc;IACrC,MAAM,OAAO,GAAG,QAAQ,IAAI,CAAC,MAAM,KAAK,OAAO,EAAE,CAAC,CAAC,KAAK,KAAK;IAC7D,MAAM,SAAS,GAAG,QAAQ,OAAO,CAAC,MAAM,EAAE,WAAW,CAAC,IAAI,CAAC,MAAM,KAAK,GAAG,EAAE,KAAK,CAAC;IACjF,MAAMC,cAAwB,CA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3B,QAAK,sBAAsB;AAC3B,QAAK,sBAAsB;AAC3B,QAAK,sBAAsB,QACvB,QAAO,CAAE;AAEb,WACI,QAAO,CAAE;EAChB;CACJ;CAED,OAAeC,QAA4B;EACvC,MAAMC,QAAkB,CAAC,OAAO,IAAK;AAErC,UAAQ,OAAO,MAAf;AACI,QAAK,mBAAmB;AACpB,UAAM,KAAK,oCAAoC;AAC/C,WAAO,MAAM,KAAK,IAAI;AAC1B,QAAK,mBAAmB;AACpB,UAAM,KAAK,UAAU;AACrB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,UAAU;AACrB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,OAAO;AAClB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,UAAU;AACrB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,OAAO;AAClB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,OAAO;AAClB;AACJ,QAAK,mBAAmB;AACpB,UAAM,KAAK,OAAO;AAClB;EACP;AAED,MAAI,OAAO,QACP,OAAM,KAAK,WAAW;AAE1B,MAAI,OAAO,SACP;cAAW,OAAO,YAAY,SAC1B,OAAM,MAAM,UAAU,OAAO,QAAQ,EAAE;SAChC,OAAO,QAAQ,IACtB,OAAM,KAAK,4BAA4B;EAC1C;AAEL,MAAI,OAAO,WAAW,OAAO,WACzB,OAAM,KAAK,SAAS;AAGxB,SAAO,MAAM,KAAK,IAAI;CACzB;AACJ;;;;ICtHY,wBAAN,MAAM,sBAAiD;CAC1D,OAAgB,QAAQ;CACxB,eAA4D,sBAAsB;CAElF,OAAO,wBAAwBC,OAAgD;AAC3E,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,sBAAsB;CAEpF;CAED,SAAsB;AAClB,SAAO,IAAI;CACd;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"SqliteIntrospector-BRdNt6KG.js","names":["value: unknown","client: DBClient","schema: DbSchema","value: unknown","client: DBClient","schema: DbSchema","columns: Record<string, DbColumn>","pks: string[]","indexes: Record<\n string,\n { name: string; table: string; unique: boolean; columns: string[]; where: string | null }\n >"],"sources":["../src/introspect/PostgresIntrospector.ts","../src/introspect/SqliteIntrospector.ts"],"sourcesContent":["import type { DBClient, DatabaseIntrospector } from './DatabaseIntrospector';\n\nexport interface DbColumn {\n name: string;\n type: string;\n notNull: boolean;\n default: string | null;\n isPk: boolean;\n isUnique: boolean;\n}\n\nexport interface DbIndex {\n name: string;\n table: string;\n unique: boolean;\n columns: string[];\n where: string | null;\n}\n\nexport interface DbForeignKey {\n name: string;\n table: string;\n columns: string[];\n refTable: string;\n refColumns: string[];\n onDelete: string | null;\n onUpdate: string | null;\n validated: boolean;\n}\n\nexport interface DbTable {\n name: string;\n columns: Record<string, DbColumn>;\n pks: string[];\n indexes: Record<string, DbIndex>;\n fks: Record<string, DbForeignKey>;\n}\n\nexport interface DbSchema {\n tables: Record<string, DbTable>;\n}\nexport class PostgresIntrospector implements DatabaseIntrospector {\n static readonly BRAND = 'tango.migrations.postgres_introspector' as const;\n readonly __tangoBrand: typeof PostgresIntrospector.BRAND = PostgresIntrospector.BRAND;\n\n static isPostgresIntrospector(value: unknown): value is PostgresIntrospector {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === PostgresIntrospector.BRAND\n );\n }\n\n async introspect(client: DBClient): Promise<DbSchema> {\n const schema: DbSchema = { tables: {} };\n\n const tablesRes = await client.query<{ tbl_oid: string; table: string }>(`\n SELECT c.oid AS tbl_oid, c.relname AS table\n FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog','information_schema')\n `);\n\n await Promise.all(\n tablesRes.rows.map(async (tableRow) => {\n const table = tableRow.table as string;\n\n const colsRes = await client.query<{\n name: string;\n type: string;\n not_null: boolean;\n default_expr: string | null;\n }>(`\n SELECT a.attname AS name,\n pg_catalog.format_type(a.atttypid,a.atttypmod) AS type,\n a.attnotnull AS not_null,\n pg_get_expr(ad.adbin, ad.adrelid) AS default_expr\n FROM pg_attribute a\n LEFT JOIN pg_attrdef ad ON ad.adrelid = a.attrelid AND ad.adnum = a.attnum\n WHERE a.attrelid = '${tableRow.tbl_oid}'::oid AND a.attnum > 0 AND NOT a.attisdropped\n ORDER BY a.attnum\n `);\n\n const pkRes = await client.query<{ col: string }>(`\n SELECT a.attname AS col\n FROM pg_index i\n JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)\n WHERE i.indrelid = '${tableRow.tbl_oid}'::oid AND i.indisprimary\n `);\n const pks = pkRes.rows.map((pkRow) => pkRow.col as string);\n\n const columns = colsRes.rows.reduce<Record<string, DbColumn>>((accumulator, columnRow) => {\n const name = columnRow.name as string;\n const isPk = pks.includes(name);\n accumulator[name] = {\n name,\n type: String(columnRow.type),\n notNull: !!columnRow.not_null,\n default: columnRow.default_expr ? String(columnRow.default_expr) : null,\n isPk,\n isUnique: false,\n };\n return accumulator;\n }, {});\n\n schema.tables[table] = {\n name: table,\n columns,\n pks,\n indexes: {},\n fks: {},\n };\n })\n );\n\n return schema;\n }\n}\n","import type { DBClient, DatabaseIntrospector } from './DatabaseIntrospector';\n\nexport interface DbColumn {\n name: string;\n type: string;\n notNull: boolean;\n default: string | null;\n isPk: boolean;\n isUnique: boolean;\n}\n\nexport interface DbTable {\n name: string;\n columns: Record<string, DbColumn>;\n pks: string[];\n indexes: Record<string, { name: string; table: string; unique: boolean; columns: string[]; where: string | null }>;\n fks: Record<\n string,\n {\n name: string;\n table: string;\n columns: string[];\n refTable: string;\n refColumns: string[];\n onDelete: string | null;\n onUpdate: string | null;\n validated: boolean;\n }\n >;\n}\n\nexport interface DbSchema {\n tables: Record<string, DbTable>;\n}\nexport class SqliteIntrospector implements DatabaseIntrospector {\n static readonly BRAND = 'tango.migrations.sqlite_introspector' as const;\n readonly __tangoBrand: typeof SqliteIntrospector.BRAND = SqliteIntrospector.BRAND;\n\n static isSqliteIntrospector(value: unknown): value is SqliteIntrospector {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as { __tangoBrand?: unknown }).__tangoBrand === SqliteIntrospector.BRAND\n );\n }\n\n async introspect(client: DBClient): Promise<DbSchema> {\n const schema: DbSchema = { tables: {} };\n\n const tablesRes = await client.query<{ name: string }>(`\n SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'\n `);\n\n for (const tableRow of tablesRes.rows) {\n const table = tableRow.name as string;\n\n const colsRes = await client.query<{\n name: string;\n pk: number;\n type: string;\n notnull: number;\n dflt_value: string | null;\n }>(`PRAGMA table_info(${table})`);\n\n const columns: Record<string, DbColumn> = {};\n const pks: string[] = [];\n const indexes: Record<\n string,\n { name: string; table: string; unique: boolean; columns: string[]; where: string | null }\n > = {};\n\n for (const columnRow of colsRes.rows) {\n const name = columnRow.name as string;\n const isPk = columnRow.pk === 1;\n if (isPk) {\n pks.push(name);\n }\n\n columns[name] = {\n name,\n type: String(columnRow.type),\n notNull: columnRow.notnull === 1,\n default: columnRow.dflt_value || null,\n isPk,\n isUnique: false,\n };\n }\n\n const indexListRes = await client.query<{ name: string; unique: number }>(`PRAGMA index_list(${table})`);\n for (const indexRow of indexListRes.rows) {\n const name = String(indexRow.name);\n if (name.startsWith('sqlite_autoindex_')) {\n continue;\n }\n\n const indexInfoRes = await client.query<{ name: string }>(`PRAGMA index_info(${name})`);\n const on = indexInfoRes.rows.map((infoRow) => String(infoRow.name)).filter(Boolean);\n indexes[name] = {\n name,\n table,\n columns: on,\n unique: indexRow.unique === 1,\n where: null,\n };\n }\n\n schema.tables[table] = {\n name: table,\n columns,\n pks,\n indexes,\n fks: {},\n };\n }\n\n return schema;\n }\n}\n"],"mappings":";;IAyCa,uBAAN,MAAM,qBAAqD;CAC9D,OAAgB,QAAQ;CACxB,eAA2D,qBAAqB;CAEhF,OAAO,uBAAuBA,OAA+C;AACzE,gBACW,UAAU,YACjB,UAAU,QACT,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AAO,OAMzB,oBAAoB,MAAM,GAAG;GAEjC,MAAMC,UAAoC,CAAE;GAC5C,MAAMC,MAAgB,CAAE;GACxB,MAAMC,UAGF,CAAE;AAEN,QAAK,MAAM,aAAa,QAAQ,MAAM;IAClC,MAAM,OAAO,UAAU;IACvB,MAAM,OAAO,UAAU,OAAO;AAC9B,QAAI,KACA,KAAI,KAAK,KAAK;AAGlB,YAAQ,QAAQ;KACZ;KACA,MAAM,OAAO,UAAU,KAAK;KAC5B,SAAS,UAAU,YAAY;KAC/B,SAAS,UAAU,cAAc;KACjC;KACA,UAAU;IACb;GACJ;GAED,MAAM,eAAe,MAAM,OAAO,OAAyC,oBAAoB,MAAM,GAAG;AACxG,QAAK,MAAM,YAAY,aAAa,MAAM;IACtC,MAAM,OAAO,OAAO,SAAS,KAAK;AAClC,QAAI,KAAK,WAAW,oBAAoB,CACpC;IAGJ,MAAM,eAAe,MAAM,OAAO,OAAyB,oBAAoB,KAAK,GAAG;IACvF,MAAM,KAAK,aAAa,KAAK,IAAI,CAAC,YAAY,OAAO,QAAQ,KAAK,CAAC,CAAC,OAAO,QAAQ;AACnF,YAAQ,QAAQ;KACZ;KACA;KACA,SAAS;KACT,QAAQ,SAAS,WAAW;KAC5B,OAAO;IACV;GACJ;AAED,UAAO,OAAO,SAAS;IACnB,MAAM;IACN;IACA;IACA;IACA,KAAK,CAAE;GACV;EACJ;AAED,SAAO;CACV;AACJ"}
@@ -1,173 +0,0 @@
1
- import { InternalColumnType } from '../../domain/internal/InternalColumnType';
2
- import { InternalOperationKind } from '../../domain/internal/InternalOperationKind';
3
- class ColumnBuilder {
4
- static BRAND = 'tango.migrations.column_builder';
5
- spec = {};
6
- __tangoBrand = ColumnBuilder.BRAND;
7
- constructor(name) {
8
- this.spec.name = name;
9
- }
10
- static isColumnBuilder(value) {
11
- return (typeof value === 'object' &&
12
- value !== null &&
13
- value.__tangoBrand === ColumnBuilder.BRAND);
14
- }
15
- serial() {
16
- this.spec.type = InternalColumnType.SERIAL;
17
- return this;
18
- }
19
- int() {
20
- this.spec.type = InternalColumnType.INT;
21
- return this;
22
- }
23
- bigint() {
24
- this.spec.type = InternalColumnType.BIGINT;
25
- return this;
26
- }
27
- text() {
28
- this.spec.type = InternalColumnType.TEXT;
29
- return this;
30
- }
31
- bool() {
32
- this.spec.type = InternalColumnType.BOOL;
33
- return this;
34
- }
35
- timestamptz() {
36
- this.spec.type = InternalColumnType.TIMESTAMPTZ;
37
- return this;
38
- }
39
- jsonb() {
40
- this.spec.type = InternalColumnType.JSONB;
41
- return this;
42
- }
43
- uuid() {
44
- this.spec.type = InternalColumnType.UUID;
45
- return this;
46
- }
47
- notNull() {
48
- this.spec.notNull = true;
49
- return this;
50
- }
51
- defaultNow() {
52
- this.spec.default = { now: true };
53
- return this;
54
- }
55
- default(v) {
56
- this.spec.default = v;
57
- return this;
58
- }
59
- primaryKey() {
60
- this.spec.primaryKey = true;
61
- return this;
62
- }
63
- unique() {
64
- this.spec.unique = true;
65
- return this;
66
- }
67
- references(table, column, opts) {
68
- this.spec.references = {
69
- table,
70
- column,
71
- onDelete: opts?.onDelete,
72
- onUpdate: opts?.onUpdate,
73
- };
74
- return this;
75
- }
76
- _done() {
77
- return this.spec;
78
- }
79
- }
80
- export class OpBuilder {
81
- static BRAND = 'tango.migrations.op_builder';
82
- __tangoBrand = OpBuilder.BRAND;
83
- static customOperations = new Map();
84
- static isOpBuilder(value) {
85
- return (typeof value === 'object' &&
86
- value !== null &&
87
- value.__tangoBrand === OpBuilder.BRAND);
88
- }
89
- static table(table) {
90
- return {
91
- create(def) {
92
- const columns = [];
93
- def({
94
- add(name, cb) {
95
- columns.push(cb(new ColumnBuilder(name))._done());
96
- },
97
- });
98
- return { kind: InternalOperationKind.TABLE_CREATE, table, columns };
99
- },
100
- drop(opts) {
101
- return { kind: InternalOperationKind.TABLE_DROP, table, cascade: opts?.cascade };
102
- },
103
- addColumn(name, cb) {
104
- return { kind: InternalOperationKind.COLUMN_ADD, table, column: cb(new ColumnBuilder(name))._done() };
105
- },
106
- dropColumn(name) {
107
- return { kind: InternalOperationKind.COLUMN_DROP, table, column: name };
108
- },
109
- alterColumn(name, to) {
110
- return { kind: InternalOperationKind.COLUMN_ALTER, table, column: name, to };
111
- },
112
- renameColumn(from, to) {
113
- return { kind: InternalOperationKind.COLUMN_RENAME, table, from, to };
114
- },
115
- };
116
- }
117
- static index = {
118
- create(p) {
119
- return { kind: InternalOperationKind.INDEX_CREATE, ...p };
120
- },
121
- drop(p) {
122
- return { kind: InternalOperationKind.INDEX_DROP, ...p };
123
- },
124
- };
125
- static foreignKey(p) {
126
- return {
127
- kind: InternalOperationKind.FK_CREATE,
128
- table: p.table,
129
- name: p.name,
130
- columns: p.columns,
131
- refTable: p.references.table,
132
- refColumns: p.references.columns,
133
- onDelete: p.onDelete,
134
- onUpdate: p.onUpdate,
135
- notValid: p.notValid,
136
- };
137
- }
138
- static foreignKeyValidate(p) {
139
- return { kind: InternalOperationKind.FK_VALIDATE, ...p };
140
- }
141
- static foreignKeyDrop(p) {
142
- return { kind: InternalOperationKind.FK_DROP, ...p };
143
- }
144
- static registerCustomOperation(name, builder) {
145
- this.customOperations.set(name, builder);
146
- }
147
- static getCustomOperation(name) {
148
- return this.customOperations.get(name);
149
- }
150
- }
151
- export function applyFieldType(builder, fieldType) {
152
- switch (fieldType) {
153
- case InternalColumnType.SERIAL:
154
- return builder.serial();
155
- case InternalColumnType.INT:
156
- return builder.int();
157
- case InternalColumnType.BIGINT:
158
- return builder.bigint();
159
- case InternalColumnType.TEXT:
160
- return builder.text();
161
- case InternalColumnType.BOOL:
162
- return builder.bool();
163
- case InternalColumnType.TIMESTAMPTZ:
164
- return builder.timestamptz();
165
- case InternalColumnType.JSONB:
166
- return builder.jsonb();
167
- case InternalColumnType.UUID:
168
- return builder.uuid();
169
- default:
170
- const exhaustive = fieldType;
171
- throw new Error(`Unsupported field type: ${exhaustive}`);
172
- }
173
- }
@@ -1 +0,0 @@
1
- {"version":3,"file":"builder-Dtk8oP_Y.js","names":["name: string","value: unknown","v: string | null","table: string","column: string","opts?: {\n onDelete?: DeleteReferentialAction;\n onUpdate?: UpdateReferentialAction;\n }","def: (cols: { add: (name: string, cb: (b: ColumnBuilder) => ColumnBuilder) => void }) => void","columns: ColumnSpec[]","opts?: { cascade?: boolean }","cb: (b: ColumnBuilder) => ColumnBuilder","to: Partial<ColumnSpec>","from: string","to: string","p: {\n name: string;\n table: string;\n on: string[];\n unique?: boolean;\n where?: string;\n concurrently?: boolean;\n }","p: { name: string; table: string; concurrently?: boolean }","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 }","p: { table: string; name: string }","name: TName","builder: (args: TArgs) => CustomMigrationOperation<TName, TArgs>","builder: ColumnBuilder","fieldType: ColumnType","exhaustive: never"],"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 {\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\nclass ColumnBuilder {\n static readonly BRAND = 'tango.migrations.column_builder' as const;\n private spec: Partial<ColumnSpec> = {};\n readonly __tangoBrand: typeof ColumnBuilder.BRAND = ColumnBuilder.BRAND;\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 serial(): ColumnBuilder {\n this.spec.type = InternalColumnType.SERIAL;\n return this;\n }\n int(): ColumnBuilder {\n this.spec.type = InternalColumnType.INT;\n return this;\n }\n bigint(): ColumnBuilder {\n this.spec.type = InternalColumnType.BIGINT;\n return this;\n }\n text(): ColumnBuilder {\n this.spec.type = InternalColumnType.TEXT;\n return this;\n }\n bool(): ColumnBuilder {\n this.spec.type = InternalColumnType.BOOL;\n return this;\n }\n timestamptz(): ColumnBuilder {\n this.spec.type = InternalColumnType.TIMESTAMPTZ;\n return this;\n }\n jsonb(): ColumnBuilder {\n this.spec.type = InternalColumnType.JSONB;\n return this;\n }\n uuid(): ColumnBuilder {\n this.spec.type = InternalColumnType.UUID;\n return this;\n }\n\n notNull(): ColumnBuilder {\n this.spec.notNull = true;\n return this;\n }\n defaultNow(): ColumnBuilder {\n this.spec.default = { now: true };\n return this;\n }\n default(v: string | null): ColumnBuilder {\n this.spec.default = v;\n return this;\n }\n primaryKey(): ColumnBuilder {\n this.spec.primaryKey = true;\n return this;\n }\n unique(): ColumnBuilder {\n this.spec.unique = true;\n return this;\n }\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\nexport class OpBuilder {\n static readonly BRAND = 'tango.migrations.op_builder' as const;\n readonly __tangoBrand: typeof OpBuilder.BRAND = OpBuilder.BRAND;\n private static customOperations = new Map<\n string,\n (args: Record<string, unknown>) => CustomMigrationOperation\n >();\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 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 static index = {\n create(p: {\n name: string;\n table: string;\n on: string[];\n unique?: boolean;\n where?: string;\n concurrently?: boolean;\n }): IndexCreate {\n return { kind: InternalOperationKind.INDEX_CREATE, ...p };\n },\n drop(p: { name: string; table: string; concurrently?: boolean }): IndexDrop {\n return { kind: InternalOperationKind.INDEX_DROP, ...p };\n },\n };\n\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 static foreignKeyValidate(p: { table: string; name: string }): ForeignKeyValidate {\n return { kind: InternalOperationKind.FK_VALIDATE, ...p };\n }\n\n static foreignKeyDrop(p: { table: string; name: string }): ForeignKeyDrop {\n return { kind: InternalOperationKind.FK_DROP, ...p };\n }\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 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\n | ((args: TArgs) => CustomMigrationOperation<TName, TArgs>)\n | undefined;\n }\n}\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 * 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":";;;;;;;;;;ICqBM,gBAAN,MAAM,cAAc;CAChB,OAAgB,QAAQ;CACxB,OAAoC,CAAE;CACtC,eAAoD,cAAc;CAElE,YAAYA,MAAc;AACtB,OAAK,KAAK,OAAO;CACpB;CAED,OAAO,gBAAgBC,OAAwC;AAC3D,gBACW,UAAU,YACjB,UAAU,QACT,MAAqC,iBAAiB,cAAc;CAE5E;CAED,SAAwB;AACpB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,MAAqB;AACjB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,SAAwB;AACpB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,OAAsB;AAClB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,OAAsB;AAClB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,cAA6B;AACzB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,QAAuB;AACnB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CACD,OAAsB;AAClB,OAAK,KAAK,OAAO,mBAAmB;AACpC,SAAO;CACV;CAED,UAAyB;AACrB,OAAK,KAAK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B,KACpB,QAAO,QAAQ,MAAM;AACzB;GACI,MAAMC,aAAoB;AAC1B,SAAM,IAAI,OAAO,0BAA0B,WAAW;CAC7D;AACJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"diffSchema-KgGHP-s3.js","names":["db: DbSchema","models: ModelMetadataLike[]","ops: MigrationOperation[]"],"sources":["../src/diff/diffSchema.ts"],"sourcesContent":["import 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\ntype ModelMetadataLike = {\n table: string;\n fields: ModelField[];\n indexes?: ModelIndex[];\n};\n\nexport function diffSchema(db: DbSchema, models: ModelMetadataLike[]): MigrationOperation[] {\n const ops: MigrationOperation[] = [];\n const modelTables = new Set(models.map((model) => model.table));\n const internalTables = new Set(['_tango_migrations']);\n\n models.forEach((model) => {\n const dbTable = db.tables[model.table];\n\n if (!dbTable) {\n ops.push(\n op.table(model.table).create((cols) => {\n model.fields.forEach((field) => {\n cols.add(field.name, (builder) => {\n builder = applyFieldType(builder, field.type);\n\n if (field.notNull) {\n builder = builder.notNull();\n }\n\n if (field.default === null) {\n builder = builder.default(null);\n } else if (field.default && typeof field.default === 'object' && 'now' in field.default) {\n builder = builder.defaultNow();\n } else if (typeof field.default === 'string') {\n builder = builder.default(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(field.default);\n }\n if (field.primaryKey) {\n builder = builder.primaryKey();\n }\n if (field.unique) {\n builder = builder.unique();\n }\n if (field.references) {\n builder = builder.references(field.references.table, field.references.column, {\n onDelete: field.references.onDelete,\n onUpdate: field.references.onUpdate,\n });\n }\n\n return builder;\n })\n );\n }\n });\n\n dbFieldNames.forEach((dbColumnName) => {\n if (!modelFieldNames.has(dbColumnName)) {\n ops.push(op.table(model.table).dropColumn(dbColumnName));\n }\n });\n\n const modelIndexes = new Map((model.indexes ?? []).map((index) => [index.name, index] as const));\n const dbIndexNames = new Set(Object.keys(dbTable.indexes));\n\n modelIndexes.forEach((index, indexName) => {\n if (!dbIndexNames.has(indexName)) {\n ops.push(\n op.index.create({\n name: index.name,\n table: model.table,\n on: index.on,\n unique: !!index.unique,\n })\n );\n }\n });\n\n dbIndexNames.forEach((dbIndexName) => {\n if (!modelIndexes.has(dbIndexName)) {\n ops.push(\n op.index.drop({\n name: dbIndexName,\n table: model.table,\n })\n );\n }\n });\n });\n\n Object.keys(db.tables).forEach((dbTableName) => {\n if (internalTables.has(dbTableName)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