viborm 0.1.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 (113) hide show
  1. package/README.md +529 -0
  2. package/dist/adapters.d.mts +2 -0
  3. package/dist/adapters.mjs +1 -0
  4. package/dist/bun-sql.d.mts +3 -0
  5. package/dist/bun-sql.mjs +2 -0
  6. package/dist/bun-sql.mjs.map +1 -0
  7. package/dist/bun-sqlite.d.mts +3 -0
  8. package/dist/bun-sqlite.mjs +2 -0
  9. package/dist/bun-sqlite.mjs.map +1 -0
  10. package/dist/cache/cloudflare-kv.d.mts +3 -0
  11. package/dist/cache/cloudflare-kv.mjs +2 -0
  12. package/dist/cache/cloudflare-kv.mjs.map +1 -0
  13. package/dist/cache/memory.d.mts +3 -0
  14. package/dist/cache/memory.mjs +2 -0
  15. package/dist/cache/memory.mjs.map +1 -0
  16. package/dist/cache.d.mts +4 -0
  17. package/dist/cache.mjs +1 -0
  18. package/dist/cli.d.mts +1 -0
  19. package/dist/cli.mjs +41 -0
  20. package/dist/cli.mjs.map +1 -0
  21. package/dist/client-CgdtiDGV.mjs +2 -0
  22. package/dist/client-CgdtiDGV.mjs.map +1 -0
  23. package/dist/client.d.mts +3 -0
  24. package/dist/client.mjs +1 -0
  25. package/dist/cloudflare-kv-DauXhtnT.d.mts +1110 -0
  26. package/dist/d1-http.d.mts +3 -0
  27. package/dist/d1-http.mjs +2 -0
  28. package/dist/d1-http.mjs.map +1 -0
  29. package/dist/d1.d.mts +3 -0
  30. package/dist/d1.mjs +2 -0
  31. package/dist/d1.mjs.map +1 -0
  32. package/dist/driver-B_vBzQ6A.mjs +2 -0
  33. package/dist/driver-B_vBzQ6A.mjs.map +1 -0
  34. package/dist/driver-Cj1EbciY.mjs +2 -0
  35. package/dist/driver-Cj1EbciY.mjs.map +1 -0
  36. package/dist/driver.d.mts +2 -0
  37. package/dist/driver.mjs +1 -0
  38. package/dist/errors-DvcqIdEo.mjs +2 -0
  39. package/dist/errors-DvcqIdEo.mjs.map +1 -0
  40. package/dist/helper-cDCDjRAD.d.mts +3020 -0
  41. package/dist/helpers-WNr9B-2U.mjs +2 -0
  42. package/dist/helpers-WNr9B-2U.mjs.map +1 -0
  43. package/dist/hydration-CFnwc7j6.mjs +2 -0
  44. package/dist/hydration-CFnwc7j6.mjs.map +1 -0
  45. package/dist/index-3sdVKfeG.d.mts +1447 -0
  46. package/dist/index-BGmpst1h.d.mts +2158 -0
  47. package/dist/index.d.mts +46 -0
  48. package/dist/index.mjs +2 -0
  49. package/dist/index.mjs.map +1 -0
  50. package/dist/instrumentation.d.mts +2 -0
  51. package/dist/instrumentation.mjs +1 -0
  52. package/dist/libsql.d.mts +3 -0
  53. package/dist/libsql.mjs +2 -0
  54. package/dist/libsql.mjs.map +1 -0
  55. package/dist/migrations.d.mts +1588 -0
  56. package/dist/migrations.mjs +11 -0
  57. package/dist/migrations.mjs.map +1 -0
  58. package/dist/mysql-adapter-0catKeCI.mjs +6 -0
  59. package/dist/mysql-adapter-0catKeCI.mjs.map +1 -0
  60. package/dist/mysql-utils-BPw9qhac.mjs +2 -0
  61. package/dist/mysql-utils-BPw9qhac.mjs.map +1 -0
  62. package/dist/mysql2.d.mts +3 -0
  63. package/dist/mysql2.mjs +2 -0
  64. package/dist/mysql2.mjs.map +1 -0
  65. package/dist/native-types-BwICkVjz.mjs +2 -0
  66. package/dist/native-types-BwICkVjz.mjs.map +1 -0
  67. package/dist/neon-http.d.mts +3 -0
  68. package/dist/neon-http.mjs +2 -0
  69. package/dist/neon-http.mjs.map +1 -0
  70. package/dist/pending-operation-CkzYTpi4.mjs +2 -0
  71. package/dist/pending-operation-CkzYTpi4.mjs.map +1 -0
  72. package/dist/pg.d.mts +3 -0
  73. package/dist/pg.mjs +2 -0
  74. package/dist/pg.mjs.map +1 -0
  75. package/dist/pglite.d.mts +3 -0
  76. package/dist/pglite.mjs +2 -0
  77. package/dist/pglite.mjs.map +1 -0
  78. package/dist/planetscale.d.mts +3 -0
  79. package/dist/planetscale.mjs +2 -0
  80. package/dist/planetscale.mjs.map +1 -0
  81. package/dist/postgres-adapter-Blzqj1bl.mjs +6 -0
  82. package/dist/postgres-adapter-Blzqj1bl.mjs.map +1 -0
  83. package/dist/postgres.d.mts +3 -0
  84. package/dist/postgres.mjs +2 -0
  85. package/dist/postgres.mjs.map +1 -0
  86. package/dist/push-qZreXYkb.mjs +252 -0
  87. package/dist/push-qZreXYkb.mjs.map +1 -0
  88. package/dist/result-parsing-FNQbuHvC.mjs +2 -0
  89. package/dist/result-parsing-FNQbuHvC.mjs.map +1 -0
  90. package/dist/schema-DeAJZocc.mjs +2 -0
  91. package/dist/schema-DeAJZocc.mjs.map +1 -0
  92. package/dist/schema.d.mts +293 -0
  93. package/dist/schema.mjs +2 -0
  94. package/dist/schema.mjs.map +1 -0
  95. package/dist/spans-CJt5UgbJ.mjs +2 -0
  96. package/dist/spans-CJt5UgbJ.mjs.map +1 -0
  97. package/dist/sqlite-adapter-5Em_-oGU.mjs +6 -0
  98. package/dist/sqlite-adapter-5Em_-oGU.mjs.map +1 -0
  99. package/dist/sqlite-utils-BW7elKTz.mjs +2 -0
  100. package/dist/sqlite-utils-BW7elKTz.mjs.map +1 -0
  101. package/dist/sqlite3.d.mts +3 -0
  102. package/dist/sqlite3.mjs +2 -0
  103. package/dist/sqlite3.mjs.map +1 -0
  104. package/dist/tracer-CGzIAsj8.mjs +2 -0
  105. package/dist/tracer-CGzIAsj8.mjs.map +1 -0
  106. package/dist/validation-RtU-wu4N.mjs +2 -0
  107. package/dist/validation-RtU-wu4N.mjs.map +1 -0
  108. package/dist/validation.d.mts +2 -0
  109. package/dist/validation.mjs +1 -0
  110. package/dist/validator-DpJsJcd7.mjs +3 -0
  111. package/dist/validator-DpJsJcd7.mjs.map +1 -0
  112. package/package.json +278 -0
  113. package/readme/README.md +69 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"push-qZreXYkb.mjs","names":["mapReferentialAction","introspect","introspect","TABLES_QUERY","COLUMNS_QUERY","PRIMARY_KEYS_QUERY","INDEXES_QUERY","FOREIGN_KEYS_QUERY","UNIQUE_CONSTRAINTS_QUERY","mapReferentialAction","formatColumnType","isAutoIncrement","introspect","introspect","mapReferentialAction","introspect","introspect","sortOperations","formatMigrationFilename","normalizeType","sortOperations","sortOperations","sql","resolve"],"sources":["../src/migrations/drivers/base.ts","../src/migrations/drivers/type-mapping.ts","../src/migrations/drivers/sqlite/introspect.ts","../src/migrations/drivers/sqlite/index.ts","../src/migrations/drivers/libsql/index.ts","../src/migrations/drivers/utils.ts","../src/migrations/drivers/mysql/introspect.ts","../src/migrations/drivers/mysql/index.ts","../src/migrations/drivers/postgres/introspect.ts","../src/migrations/drivers/postgres/index.ts","../src/migrations/drivers/index.ts","../src/migrations/utils.ts","../src/migrations/context.ts","../src/migrations/generate/file-writer.ts","../src/migrations/storage/driver.ts","../src/migrations/apply/index.ts","../src/migrations/differ.ts","../src/migrations/resolver.ts","../src/migrations/serializer.ts","../src/migrations/generate/index.ts","../src/migrations/types.ts","../src/migrations/push.ts"],"sourcesContent":["/**\n * MigrationDriver Base Class\n *\n * Abstract base class for database-specific migration drivers.\n * Each driver implements DDL generation and introspection for its database.\n */\n\nimport type { Field, FieldState } from \"@schema/fields\";\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type {\n ColumnDef,\n DiffOperation,\n ReferentialAction,\n SchemaSnapshot,\n} from \"../types\";\nimport type { Dialect, MigrationCapabilities } from \"./types\";\n\n/**\n * Context passed to DDL generation methods.\n * Contains information needed for operations that require knowledge of the current schema.\n */\nexport interface DDLContext {\n /**\n * Current database schema snapshot.\n * Required for SQLite table recreation operations.\n */\n currentSchema?: SchemaSnapshot;\n}\n\n// Extract individual operation types from the DiffOperation union\nexport type CreateTableOperation = Extract<\n DiffOperation,\n { type: \"createTable\" }\n>;\nexport type DropTableOperation = Extract<DiffOperation, { type: \"dropTable\" }>;\nexport type RenameTableOperation = Extract<\n DiffOperation,\n { type: \"renameTable\" }\n>;\nexport type AddColumnOperation = Extract<DiffOperation, { type: \"addColumn\" }>;\nexport type DropColumnOperation = Extract<\n DiffOperation,\n { type: \"dropColumn\" }\n>;\nexport type RenameColumnOperation = Extract<\n DiffOperation,\n { type: \"renameColumn\" }\n>;\nexport type AlterColumnOperation = Extract<\n DiffOperation,\n { type: \"alterColumn\" }\n>;\nexport type CreateIndexOperation = Extract<\n DiffOperation,\n { type: \"createIndex\" }\n>;\nexport type DropIndexOperation = Extract<DiffOperation, { type: \"dropIndex\" }>;\nexport type AddForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"addForeignKey\" }\n>;\nexport type DropForeignKeyOperation = Extract<\n DiffOperation,\n { type: \"dropForeignKey\" }\n>;\nexport type AddUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"addUniqueConstraint\" }\n>;\nexport type DropUniqueConstraintOperation = Extract<\n DiffOperation,\n { type: \"dropUniqueConstraint\" }\n>;\nexport type AddPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"addPrimaryKey\" }\n>;\nexport type DropPrimaryKeyOperation = Extract<\n DiffOperation,\n { type: \"dropPrimaryKey\" }\n>;\nexport type CreateEnumOperation = Extract<\n DiffOperation,\n { type: \"createEnum\" }\n>;\nexport type DropEnumOperation = Extract<DiffOperation, { type: \"dropEnum\" }>;\nexport type AlterEnumOperation = Extract<DiffOperation, { type: \"alterEnum\" }>;\n\n/**\n * Abstract base class for migration drivers.\n *\n * Each database (PostgreSQL, SQLite, LibSQL, etc.) extends this class\n * to provide database-specific DDL generation and schema introspection.\n */\nexport abstract class MigrationDriver {\n /**\n * The SQL dialect this driver targets.\n */\n abstract readonly dialect: Dialect;\n\n /**\n * The specific driver name (e.g., \"pg\", \"postgres\", \"pglite\", \"sqlite3\", \"libsql\").\n * Used for driver-specific registration and lookup.\n */\n abstract readonly driverName: string;\n\n /**\n * Capabilities supported by this driver.\n */\n abstract readonly capabilities: MigrationCapabilities;\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n /**\n * Introspects the current database schema.\n *\n * @param executeRaw - Function to execute raw SQL queries\n * @returns The current schema snapshot\n */\n abstract introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n ): Promise<SchemaSnapshot>;\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n /**\n * Maps a VibORM field type to the native database column type.\n *\n * @param field - The field definition\n * @param fieldState - The field state with type info\n * @returns The native column type string\n */\n abstract mapFieldType(field: Field, fieldState: FieldState): string;\n\n // Note: getDefaultExpression is implemented below as a common method\n // Override it in subclasses only if database-specific behavior is needed\n\n /**\n * Gets the column type for an enum field.\n *\n * @param tableName - The table name\n * @param columnName - The column name\n * @param values - The enum values\n * @returns The column type (e.g., \"users_status_enum\" for PG, \"TEXT\" for SQLite)\n */\n abstract getEnumColumnType(\n tableName: string,\n columnName: string,\n values: string[]\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n abstract generateCreateTable(op: CreateTableOperation): string;\n abstract generateDropTable(op: DropTableOperation): string;\n abstract generateRenameTable(op: RenameTableOperation): string;\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n abstract generateAddColumn(op: AddColumnOperation): string;\n abstract generateDropColumn(op: DropColumnOperation): string;\n abstract generateRenameColumn(op: RenameColumnOperation): string;\n abstract generateAlterColumn(\n op: AlterColumnOperation,\n context?: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n abstract generateCreateIndex(op: CreateIndexOperation): string;\n abstract generateDropIndex(op: DropIndexOperation): string;\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n abstract generateAddForeignKey(\n op: AddForeignKeyOperation,\n context?: DDLContext\n ): string;\n abstract generateDropForeignKey(\n op: DropForeignKeyOperation,\n context?: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n abstract generateAddUniqueConstraint(\n op: AddUniqueConstraintOperation\n ): string;\n abstract generateDropUniqueConstraint(\n op: DropUniqueConstraintOperation\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n abstract generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context?: DDLContext\n ): string;\n abstract generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context?: DDLContext\n ): string;\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n abstract generateCreateEnum(\n op: CreateEnumOperation,\n context?: DDLContext\n ): string;\n abstract generateDropEnum(\n op: DropEnumOperation,\n context?: DDLContext\n ): string;\n abstract generateAlterEnum(\n op: AlterEnumOperation,\n context?: DDLContext\n ): string;\n\n // ===========================================================================\n // HELPER METHODS (can be overridden)\n // ===========================================================================\n\n /**\n * Escapes an identifier (table name, column name, etc.).\n * Default uses double quotes with proper escaping.\n */\n escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\"${String(name).replace(/\"/g, '\"\"')}\"`;\n }\n\n /**\n * Escapes a string value for SQL.\n * Default uses single quotes with proper escaping.\n * Returns \"NULL\" for null/undefined values.\n */\n escapeValue(value: string | null | undefined): string {\n if (value == null) {\n return \"NULL\";\n }\n return `'${String(value).replace(/'/g, \"''\")}'`;\n }\n\n /**\n * Formats a referential action for foreign keys.\n */\n formatReferentialAction(action: ReferentialAction): string {\n switch (action) {\n case \"cascade\":\n return \"CASCADE\";\n case \"setNull\":\n return \"SET NULL\";\n case \"restrict\":\n return \"RESTRICT\";\n case \"setDefault\":\n return \"SET DEFAULT\";\n default:\n return \"NO ACTION\";\n }\n }\n\n // ===========================================================================\n // COMMON IMPLEMENTATIONS (can be overridden for database-specific behavior)\n // ===========================================================================\n\n /**\n * Gets the SQL default expression for a field.\n * Common implementation that handles most cases.\n * Override for database-specific behavior (e.g., UUID generation, boolean representation).\n *\n * @param fieldState - The field state\n * @returns SQL default expression or undefined if no default\n */\n getDefaultExpression(fieldState: FieldState): string | undefined {\n // Auto-generated values - check for database-level support first\n if (fieldState.autoGenerate) {\n return this.getAutoGenerateExpression(fieldState.autoGenerate);\n }\n\n // Check for explicit default value\n if (!fieldState.hasDefault || fieldState.default === undefined) {\n return undefined;\n }\n\n const defaultVal = fieldState.default;\n\n // Function defaults are generated at runtime\n if (typeof defaultVal === \"function\") {\n return undefined;\n }\n\n // Null default\n if (defaultVal === null) {\n return \"NULL\";\n }\n\n // Primitive defaults\n if (typeof defaultVal === \"string\") {\n return this.escapeValue(defaultVal);\n }\n if (typeof defaultVal === \"number\") {\n if (!Number.isFinite(defaultVal)) {\n throw new MigrationError(\n `Invalid default value: ${defaultVal} is not a finite number`,\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return String(defaultVal);\n }\n if (typeof defaultVal === \"boolean\") {\n return this.formatBooleanDefault(defaultVal);\n }\n\n // Arrays and objects are handled at application level, not as SQL defaults\n if (typeof defaultVal === \"object\") {\n return undefined;\n }\n\n return undefined;\n }\n\n /**\n * Formats a boolean default value.\n * Override for databases that use different representations (e.g., SQLite uses 1/0).\n */\n protected formatBooleanDefault(value: boolean): string {\n return value ? \"true\" : \"false\";\n }\n\n /**\n * Gets the SQL expression for an auto-generated value.\n * Override for databases that support specific generation functions.\n *\n * By default, returns undefined for all types (handled at application level).\n * PostgreSQL overrides this to use gen_random_uuid() for UUID.\n *\n * @param autoGenerate - The auto-generate type\n * @returns SQL expression or undefined if handled at application level\n */\n protected getAutoGenerateExpression(\n _autoGenerate: FieldState[\"autoGenerate\"]\n ): string | undefined {\n // By default, all auto-generate types are handled at application level\n // Databases can override to provide native support (e.g., gen_random_uuid())\n return undefined;\n }\n\n /**\n * Validates an index type against supported capabilities.\n * Throws MigrationError if the index type is not supported.\n *\n * @param indexType - The index type to validate (e.g., \"btree\", \"hash\", \"gin\")\n * @param indexName - The index name (for error messages)\n */\n protected validateIndexType(\n indexType: string | undefined,\n indexName: string\n ): void {\n if (!indexType) return; // Default index type is always supported\n\n const supported = this.capabilities.supportsIndexTypes;\n if (!supported.includes(indexType)) {\n throw new MigrationError(\n `Index \"${indexName}\" uses unsupported index type \"${indexType}\". ` +\n `Supported types for ${this.dialect}: ${supported.join(\", \")}`,\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n }\n\n /**\n * Generates a column definition string.\n * Common implementation that can be overridden for database-specific syntax.\n *\n * @param column - The column definition\n * @returns SQL column definition string\n */\n protected generateColumnDef(column: ColumnDef): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n\n // Handle type (may be overridden for auto-increment handling)\n const columnType = this.formatColumnType(column);\n parts.push(columnType);\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // DEFAULT clause (skip for auto-increment columns)\n if (column.default !== undefined && !column.autoIncrement) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n return parts.join(\" \");\n }\n\n /**\n * Formats the column type, handling auto-increment and other special cases.\n * Override for database-specific type handling (e.g., PostgreSQL SERIAL).\n */\n protected formatColumnType(column: ColumnDef): string {\n return column.type;\n }\n\n // ===========================================================================\n // MIGRATION TRACKING TABLE\n // ===========================================================================\n\n /**\n * Generates DDL for creating the migration tracking table.\n * Override for database-specific syntax.\n *\n * @param tableName - The tracking table name (already validated)\n * @returns SQL DDL statement\n */\n abstract generateCreateTrackingTable(tableName: string): string;\n\n /**\n * Generates SQL for selecting applied migrations.\n *\n * @param tableName - The tracking table name\n * @returns SQL SELECT statement\n */\n generateSelectAppliedMigrations(tableName: string): string {\n const table = this.escapeIdentifier(tableName);\n return `SELECT name, checksum, applied_at FROM ${table} ORDER BY id ASC`;\n }\n\n /**\n * Generates SQL for inserting a migration record.\n *\n * @param tableName - The tracking table name\n * @returns SQL INSERT statement with placeholders\n */\n abstract generateInsertMigration(tableName: string): {\n sql: string;\n paramCount: number;\n };\n\n /**\n * Generates SQL for deleting a migration record.\n *\n * @param tableName - The tracking table name\n * @returns SQL DELETE statement with placeholders\n */\n abstract generateDeleteMigration(tableName: string): {\n sql: string;\n paramCount: number;\n };\n\n /**\n * Generates SQL for clearing all migration records.\n * Used by reset command.\n *\n * @param tableName - The tracking table name\n * @returns SQL DELETE statement\n */\n generateClearMigrations(tableName: string): string {\n const table = this.escapeIdentifier(tableName);\n return `DELETE FROM ${table}`;\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n /**\n * Generates SQL for acquiring a migration lock.\n * Returns null if locking is handled differently (e.g., SQLite transactions).\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateAcquireLock(lockId: number): string | null;\n\n /**\n * Generates SQL for releasing a migration lock.\n * Returns null if locking is handled differently (e.g., SQLite transactions).\n *\n * @param lockId - A numeric lock identifier\n * @returns SQL statement or null\n */\n abstract generateReleaseLock(lockId: number): string | null;\n\n /**\n * Generates SQL statements for resetting the database (dropping all tables and enums).\n * Used by `--force-reset` flag in CLI.\n *\n * @returns Array of SQL statements to execute\n */\n abstract generateResetSQL(): string[];\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n /**\n * Generates SQL for listing all user tables.\n * Used by reset command.\n *\n * @returns SQL SELECT statement that returns rows with 'name' column\n */\n abstract generateListTables(): string;\n\n /**\n * Generates SQL for listing all enum types.\n * Returns null for databases that don't support enums.\n *\n * @returns SQL SELECT statement or null\n */\n abstract generateListEnums(): string | null;\n\n /**\n * Generates SQL for dropping a table.\n *\n * @param tableName - The table name\n * @param cascade - Whether to cascade (drop dependent objects)\n * @returns SQL DROP TABLE statement\n */\n generateDropTableSQL(tableName: string, cascade = false): string {\n const table = this.escapeIdentifier(tableName);\n return cascade\n ? `DROP TABLE IF EXISTS ${table} CASCADE`\n : `DROP TABLE IF EXISTS ${table}`;\n }\n\n /**\n * Generates SQL for dropping an enum type.\n * Returns null for databases that don't support enums.\n *\n * @param enumName - The enum name\n * @returns SQL DROP TYPE statement or null\n */\n generateDropEnumSQL(_enumName: string): string | null {\n return null; // Override in PostgreSQL driver\n }\n\n // ===========================================================================\n // DISPATCH (final - not meant to be overridden)\n // ===========================================================================\n\n /**\n * Generates DDL for a diff operation.\n * Dispatches to the appropriate generate* method.\n *\n * @param operation - The diff operation\n * @param context - Optional context for operations that need schema info (e.g., SQLite table recreation)\n * @returns SQL DDL statement(s)\n */\n generateDDL(operation: DiffOperation, context?: DDLContext): string {\n switch (operation.type) {\n case \"createTable\":\n return this.generateCreateTable(operation);\n case \"dropTable\":\n return this.generateDropTable(operation);\n case \"renameTable\":\n return this.generateRenameTable(operation);\n case \"addColumn\":\n return this.generateAddColumn(operation);\n case \"dropColumn\":\n return this.generateDropColumn(operation);\n case \"renameColumn\":\n return this.generateRenameColumn(operation);\n case \"alterColumn\":\n return this.generateAlterColumn(operation, context);\n case \"createIndex\":\n return this.generateCreateIndex(operation);\n case \"dropIndex\":\n return this.generateDropIndex(operation);\n case \"addForeignKey\":\n return this.generateAddForeignKey(operation, context);\n case \"dropForeignKey\":\n return this.generateDropForeignKey(operation, context);\n case \"addUniqueConstraint\":\n return this.generateAddUniqueConstraint(operation);\n case \"dropUniqueConstraint\":\n return this.generateDropUniqueConstraint(operation);\n case \"addPrimaryKey\":\n return this.generateAddPrimaryKey(operation, context);\n case \"dropPrimaryKey\":\n return this.generateDropPrimaryKey(operation, context);\n case \"createEnum\":\n return this.generateCreateEnum(operation, context);\n case \"dropEnum\":\n return this.generateDropEnum(operation, context);\n case \"alterEnum\":\n return this.generateAlterEnum(operation, context);\n default:\n throw new MigrationError(\n `Unknown operation type: ${(operation as any).type}`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n }\n}\n","/**\n * Centralized Type Mapping for Migration Drivers\n *\n * Maps VibORM field types to native database column types.\n * Uses constants from native-types.ts to ensure consistency.\n */\n\nimport { PG, SQLITE } from \"@schema/fields/native-types\";\n\n// =============================================================================\n// TYPE MAPPING CONSTANTS\n// =============================================================================\n\n/**\n * Default PostgreSQL type mappings for each VibORM field type.\n * Uses the same type names as defined in native-types.ts.\n */\nexport const PG_TYPE_DEFAULTS = {\n string: PG.STRING.TEXT.type,\n int: PG.INT.INTEGER.type,\n float: PG.FLOAT.DOUBLE_PRECISION.type,\n decimal: \"numeric\", // PG.DECIMAL.NUMERIC() returns a function, use literal\n boolean: PG.BOOLEAN.BOOLEAN.type,\n datetime: \"timestamp\",\n datetimetz: \"timestamptz\",\n date: PG.DATETIME.DATE.type,\n time: \"time\",\n timetz: \"timetz\",\n bigint: PG.BIGINT.BIGINT.type,\n json: PG.JSON.JSONB.type,\n blob: PG.BLOB.BYTEA.type,\n vector: \"vector\",\n point: PG.POINT.POINT.type,\n enum: PG.STRING.TEXT.type,\n} as const;\n\n/**\n * Default SQLite type mappings for each VibORM field type.\n * SQLite has limited type affinity - most types map to TEXT, INTEGER, REAL, or BLOB.\n */\nexport const SQLITE_TYPE_DEFAULTS = {\n string: SQLITE.STRING.TEXT.type,\n int: SQLITE.INT.INTEGER.type,\n float: SQLITE.FLOAT.REAL.type,\n decimal: SQLITE.DECIMAL.REAL.type,\n boolean: SQLITE.BOOLEAN.INTEGER.type,\n datetime: SQLITE.DATETIME.TEXT.type,\n date: SQLITE.DATETIME.TEXT.type,\n time: SQLITE.DATETIME.TEXT.type,\n bigint: SQLITE.BIGINT.INTEGER.type,\n json: \"JSON\", // SQLite JSON functions work with TEXT but JSON is more semantic\n blob: SQLITE.BLOB.BLOB.type,\n vector: \"JSON\", // Store as JSON array in SQLite\n point: \"JSON\", // Store as JSON object in SQLite\n enum: SQLITE.STRING.TEXT.type,\n} as const;\n\n/**\n * Default MySQL type mappings for each VibORM field type.\n * MySQL has full type support but uses TINYINT(1) for booleans\n * and doesn't support native arrays (use JSON instead).\n */\nexport const MYSQL_TYPE_DEFAULTS = {\n string: \"TEXT\",\n int: \"INT\",\n float: \"DOUBLE\",\n decimal: \"DECIMAL\",\n boolean: \"TINYINT(1)\", // MySQL uses TINYINT(1) for boolean\n datetime: \"DATETIME(3)\", // Use DATETIME(3) to preserve JavaScript Date millisecond precision\n datetimetz: \"DATETIME(3)\", // MySQL DATETIME can store with timezone via application\n date: \"DATE\",\n time: \"TIME(3)\", // Use TIME(3) to preserve millisecond precision\n timetz: \"TIME(3)\", // MySQL TIME doesn't have timezone variant\n bigint: \"BIGINT\",\n json: \"JSON\",\n blob: \"BLOB\",\n vector: \"JSON\", // No native vector support, use JSON\n point: \"POINT\", // MySQL has native POINT type\n enum: \"TEXT\", // Default for unspecified enums; usually use inline ENUM()\n} as const;\n\n// =============================================================================\n// TYPE MAPPING FUNCTIONS\n// =============================================================================\n\nexport type VibORMFieldType =\n | \"string\"\n | \"int\"\n | \"float\"\n | \"decimal\"\n | \"boolean\"\n | \"datetime\"\n | \"date\"\n | \"time\"\n | \"bigint\"\n | \"json\"\n | \"blob\"\n | \"vector\"\n | \"point\"\n | \"enum\";\n\nexport interface FieldTypeContext {\n type: string;\n array?: boolean;\n withTimezone?: boolean;\n}\n\n/**\n * Gets the PostgreSQL column type for a VibORM field type.\n */\nexport function getPostgresType(context: FieldTypeContext): string {\n let baseType: string;\n\n switch (context.type) {\n case \"string\":\n baseType = PG_TYPE_DEFAULTS.string;\n break;\n case \"int\":\n baseType = PG_TYPE_DEFAULTS.int;\n break;\n case \"float\":\n baseType = PG_TYPE_DEFAULTS.float;\n break;\n case \"decimal\":\n baseType = PG_TYPE_DEFAULTS.decimal;\n break;\n case \"boolean\":\n baseType = PG_TYPE_DEFAULTS.boolean;\n break;\n case \"datetime\":\n baseType = context.withTimezone\n ? PG_TYPE_DEFAULTS.datetimetz\n : PG_TYPE_DEFAULTS.datetime;\n break;\n case \"date\":\n baseType = PG_TYPE_DEFAULTS.date;\n break;\n case \"time\":\n baseType = context.withTimezone\n ? PG_TYPE_DEFAULTS.timetz\n : PG_TYPE_DEFAULTS.time;\n break;\n case \"bigint\":\n baseType = PG_TYPE_DEFAULTS.bigint;\n break;\n case \"json\":\n baseType = PG_TYPE_DEFAULTS.json;\n break;\n case \"blob\":\n baseType = PG_TYPE_DEFAULTS.blob;\n break;\n case \"vector\":\n baseType = PG_TYPE_DEFAULTS.vector;\n break;\n case \"point\":\n baseType = PG_TYPE_DEFAULTS.point;\n break;\n case \"enum\":\n baseType = PG_TYPE_DEFAULTS.enum;\n break;\n default:\n baseType = PG_TYPE_DEFAULTS.string;\n }\n\n return context.array ? `${baseType}[]` : baseType;\n}\n\n/**\n * Gets the SQLite column type for a VibORM field type.\n * SQLite doesn't support native arrays - they are stored as JSON.\n */\nexport function getSQLiteType(context: FieldTypeContext): string {\n // SQLite doesn't support native arrays - use JSON\n if (context.array) {\n return \"JSON\";\n }\n\n switch (context.type) {\n case \"string\":\n case \"enum\":\n return SQLITE_TYPE_DEFAULTS.string;\n case \"json\":\n case \"vector\":\n case \"point\":\n return \"JSON\";\n case \"int\":\n case \"bigint\":\n case \"boolean\":\n return SQLITE_TYPE_DEFAULTS.int;\n case \"float\":\n case \"decimal\":\n return SQLITE_TYPE_DEFAULTS.float;\n case \"datetime\":\n case \"date\":\n case \"time\":\n return SQLITE_TYPE_DEFAULTS.datetime;\n case \"blob\":\n return SQLITE_TYPE_DEFAULTS.blob;\n default:\n return SQLITE_TYPE_DEFAULTS.string;\n }\n}\n\n/**\n * Gets the MySQL column type for a VibORM field type.\n * MySQL doesn't support native arrays - they are stored as JSON.\n */\nexport function getMySQLType(context: FieldTypeContext): string {\n // MySQL doesn't support native arrays - use JSON\n if (context.array) {\n return \"JSON\";\n }\n\n switch (context.type) {\n case \"string\":\n return MYSQL_TYPE_DEFAULTS.string;\n case \"int\":\n return MYSQL_TYPE_DEFAULTS.int;\n case \"float\":\n return MYSQL_TYPE_DEFAULTS.float;\n case \"decimal\":\n return MYSQL_TYPE_DEFAULTS.decimal;\n case \"boolean\":\n return MYSQL_TYPE_DEFAULTS.boolean;\n case \"datetime\":\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.datetimetz\n : MYSQL_TYPE_DEFAULTS.datetime;\n case \"date\":\n return MYSQL_TYPE_DEFAULTS.date;\n case \"time\":\n return context.withTimezone\n ? MYSQL_TYPE_DEFAULTS.timetz\n : MYSQL_TYPE_DEFAULTS.time;\n case \"bigint\":\n return MYSQL_TYPE_DEFAULTS.bigint;\n case \"json\":\n return MYSQL_TYPE_DEFAULTS.json;\n case \"blob\":\n return MYSQL_TYPE_DEFAULTS.blob;\n case \"vector\":\n return MYSQL_TYPE_DEFAULTS.vector;\n case \"point\":\n return MYSQL_TYPE_DEFAULTS.point;\n case \"enum\":\n return MYSQL_TYPE_DEFAULTS.enum;\n default:\n return MYSQL_TYPE_DEFAULTS.string;\n }\n}\n","/**\n * SQLite Schema Introspection\n *\n * Reads the current database schema from SQLite's PRAGMA statements\n * and sqlite_master, returning a normalized SchemaSnapshot.\n */\n\nimport type {\n ColumnDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport type {\n SqliteColumn,\n SqliteForeignKey,\n SqliteIndex,\n SqliteIndexColumn,\n SqliteTable,\n} from \"./types\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction escapeIdentifier(name: string): string {\n return `\"${name.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n case \"NO ACTION\":\n default:\n return \"noAction\";\n }\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n): Promise<SchemaSnapshot> {\n // Get all tables\n const tablesResult = await executeRaw<SqliteTable>(`\n SELECT name\n FROM sqlite_master\n WHERE type = 'table'\n AND name NOT LIKE 'sqlite_%'\n ORDER BY name\n `);\n\n const tables: TableDef[] = [];\n\n for (const tableRow of tablesResult.rows) {\n const tableName = tableRow.name;\n\n // Get columns using PRAGMA\n const columnsResult = await executeRaw<SqliteColumn>(\n `PRAGMA table_info(${escapeIdentifier(tableName)})`\n );\n\n // Get indexes\n const indexesResult = await executeRaw<SqliteIndex>(\n `PRAGMA index_list(${escapeIdentifier(tableName)})`\n );\n\n // Get foreign keys\n const fksResult = await executeRaw<SqliteForeignKey>(\n `PRAGMA foreign_key_list(${escapeIdentifier(tableName)})`\n );\n\n // Build columns\n const columns: ColumnDef[] = [];\n const pkColumns: { name: string; position: number }[] = [];\n\n for (const col of columnsResult.rows) {\n columns.push({\n name: col.name,\n type: col.type || \"TEXT\",\n nullable: col.notnull === 0,\n default: col.dflt_value ?? undefined,\n autoIncrement:\n col.pk === 1 && col.type.toUpperCase() === \"INTEGER\" ? true : false,\n });\n\n if (col.pk > 0) {\n pkColumns.push({ name: col.name, position: col.pk });\n }\n }\n\n // Build primary key (sort by pk position)\n let primaryKey: PrimaryKeyDef | undefined;\n if (pkColumns.length > 0) {\n pkColumns.sort((a, b) => a.position - b.position);\n primaryKey = {\n name: `${tableName}_pkey`,\n columns: pkColumns.map((p) => p.name),\n };\n }\n\n // Build indexes and unique constraints\n const indexes: IndexDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n\n for (const idx of indexesResult.rows) {\n // Skip auto-created indexes for primary keys\n if (idx.origin === \"pk\") continue;\n\n // Get index columns\n const indexColsResult = await executeRaw<SqliteIndexColumn>(\n `PRAGMA index_info(${escapeIdentifier(idx.name)})`\n );\n\n const indexColumns = indexColsResult.rows\n .sort((a, b) => a.seqno - b.seqno)\n .map((c) => c.name);\n\n if (idx.unique && idx.origin === \"u\") {\n // This is a unique constraint\n uniqueConstraints.push({\n name: idx.name,\n columns: indexColumns,\n });\n } else {\n indexes.push({\n name: idx.name,\n columns: indexColumns,\n unique: idx.unique === 1,\n });\n }\n }\n\n // Build foreign keys - group by id (constraint)\n const fkMap = new Map<number, SqliteForeignKey[]>();\n for (const fk of fksResult.rows) {\n const existing = fkMap.get(fk.id) || [];\n existing.push(fk);\n fkMap.set(fk.id, existing);\n }\n\n const foreignKeys: ForeignKeyDef[] = [];\n for (const [id, fkCols] of fkMap) {\n const sorted = fkCols.sort((a, b) => a.seq - b.seq);\n const first = sorted[0];\n if (first) {\n foreignKeys.push({\n name: `${tableName}_fk_${id}`,\n columns: sorted.map((f) => f.from),\n referencedTable: first.table,\n referencedColumns: sorted.map((f) => f.to),\n onDelete: mapReferentialAction(first.on_delete),\n onUpdate: mapReferentialAction(first.on_update),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // SQLite doesn't have native enum types\n return { tables, enums: [] };\n}\n","/**\n * SQLite Migration Driver\n *\n * Implements the MigrationDriver interface for SQLite databases.\n * Uses table recreation for operations SQLite doesn't support natively.\n */\n\nimport type { Field, FieldState } from \"@schema/fields\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { ColumnDef, TableDef } from \"../../types\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport { getSQLiteType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect } from \"./introspect\";\n\n/**\n * SQLite3 Migration Driver\n *\n * Handles migrations for better-sqlite3 and similar synchronous SQLite drivers.\n * Uses table recreation for operations SQLite doesn't support natively:\n * - ALTER COLUMN (type, default, NOT NULL changes)\n * - ADD/DROP FOREIGN KEY\n * - ADD/DROP PRIMARY KEY\n *\n * LibSQL extends this class and overrides methods for operations it supports.\n */\nexport class SQLite3MigrationDriver extends MigrationDriver {\n readonly dialect = \"sqlite\" as const;\n readonly driverName: string = \"sqlite3\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true, // N/A but doesn't matter\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n introspect = introspect;\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapFieldType(field: Field, fieldState: FieldState): string {\n const nativeType = field[\"~\"].nativeType;\n\n // If a native type is specified and it's for SQLite, use it\n if (nativeType && nativeType.db === \"sqlite\") {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getSQLiteType({\n type: fieldState.type,\n array: fieldState.array,\n });\n }\n\n // getDefaultExpression is inherited from base class\n // Override formatBooleanDefault for SQLite's 1/0 representation\n\n /**\n * SQLite uses 1/0 for boolean values instead of true/false.\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n getEnumColumnType(\n _tableName: string,\n columnName: string,\n values: string[]\n ): string {\n // SQLite uses TEXT with CHECK constraint for enum validation\n const escapedValues = values\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return `TEXT CHECK(${this.escapeIdentifier(columnName)} IN (${escapedValues}))`;\n }\n\n // ===========================================================================\n // HELPER: Column Definition\n // ===========================================================================\n\n protected generateColumnDef(column: ColumnDef): string {\n // SQLite auto-increment only works with INTEGER PRIMARY KEY\n // Validate that autoIncrement columns use INTEGER type\n if (column.autoIncrement && column.type.toUpperCase() !== \"INTEGER\") {\n throw new MigrationError(\n \"SQLite auto-increment requires INTEGER type. \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment. ` +\n \"Note: SQLite auto-increment is implicit when using INTEGER PRIMARY KEY.\",\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // TABLE RECREATION\n // ===========================================================================\n\n /**\n * Generates SQL for table recreation.\n * This is the Drizzle-style pattern for operations SQLite doesn't support.\n *\n * Steps:\n * 1. PRAGMA foreign_keys=OFF\n * 2. Create new table with desired schema\n * 3. Copy data from old table (using explicit column mapping by name)\n * 4. Drop old table\n * 5. Rename new table\n * 6. Recreate indexes\n * 7. PRAGMA foreign_keys=ON\n *\n * @param tableName - The table to recreate\n * @param newTable - The new table definition\n * @param currentTable - The current table definition (required for safe column mapping)\n * @param columnRenames - Optional map of old column name → new column name (for renames)\n */\n protected generateTableRecreation(\n tableName: string,\n newTable: TableDef,\n currentTable: TableDef,\n columnRenames?: Map<string, string>\n ): string {\n const statements: string[] = [];\n const tempName = `__new_${tableName}`;\n\n // 1. Disable foreign keys\n statements.push(\"PRAGMA foreign_keys=OFF\");\n\n // 2. Create new table\n statements.push(\n this.generateCreateTableDef({ ...newTable, name: tempName })\n );\n\n // 3. Copy data - EXPLICIT column mapping by NAME, not position\n // Build a set of current column names for quick lookup\n const currentColumnNames = new Set(currentTable.columns.map((c) => c.name));\n\n // For each column in the new table, find the corresponding source column\n const copyColumns: Array<{ source: string; target: string }> = [];\n\n for (const col of newTable.columns) {\n // Check if this column was renamed\n let sourceName = col.name;\n if (columnRenames) {\n // columnRenames maps old name → new name, so we need to reverse lookup\n for (const [oldName, newName] of columnRenames) {\n if (newName === col.name) {\n sourceName = oldName;\n break;\n }\n }\n }\n\n // Only copy if source column exists in current table\n if (currentColumnNames.has(sourceName)) {\n copyColumns.push({ source: sourceName, target: col.name });\n } else if (!col.nullable && col.default === undefined) {\n // New NOT NULL column without default - INSERT will fail\n throw new MigrationError(\n `Cannot add NOT NULL column \"${col.name}\" without a default value during table recreation. ` +\n \"SQLite requires a default value or nullable column for table recreation.\",\n VibORMErrorCode.FEATURE_NOT_SUPPORTED\n );\n }\n // New columns with defaults or nullable will get their default/NULL values\n }\n\n if (copyColumns.length > 0) {\n const selectCols = copyColumns\n .map((c) => this.escapeIdentifier(c.source))\n .join(\", \");\n const insertCols = copyColumns\n .map((c) => this.escapeIdentifier(c.target))\n .join(\", \");\n\n statements.push(\n `INSERT INTO ${this.escapeIdentifier(tempName)} (${insertCols}) ` +\n `SELECT ${selectCols} FROM ${this.escapeIdentifier(tableName)}`\n );\n }\n\n // 4. Drop old table\n statements.push(`DROP TABLE ${this.escapeIdentifier(tableName)}`);\n\n // 5. Rename new table\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tempName)} RENAME TO ${this.escapeIdentifier(tableName)}`\n );\n\n // 6. Recreate indexes (they were dropped with the old table)\n for (const idx of newTable.indexes) {\n statements.push(\n this.generateCreateIndex({ type: \"createIndex\", tableName, index: idx })\n );\n }\n\n // 7. Re-enable foreign keys\n statements.push(\"PRAGMA foreign_keys=ON\");\n\n return statements.join(\";\\n\");\n }\n\n /**\n * Helper to generate CREATE TABLE DDL without indexes\n */\n protected generateCreateTableDef(table: TableDef): string {\n const parts: string[] = [];\n\n // Columns\n for (const col of table.columns) {\n parts.push(this.generateColumnDef(col));\n }\n\n // Primary key (if composite or not INTEGER autoincrement)\n if (table.primaryKey) {\n const isSingleIntegerPK =\n table.primaryKey.columns.length === 1 &&\n table.columns.find(\n (c) =>\n c.name === table.primaryKey!.columns[0] &&\n c.type.toUpperCase() === \"INTEGER\" &&\n c.autoIncrement\n );\n\n if (!isSingleIntegerPK) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n parts.push(`PRIMARY KEY (${pkCols})`);\n }\n }\n\n // Unique constraints\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n parts.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys\n for (const fk of table.foreignKeys) {\n const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n\n parts.push(fkDef);\n }\n\n return `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${parts.join(\",\\n \")}\\n)`;\n }\n\n /**\n * Gets the current table definition from the schema context.\n */\n protected getCurrentTable(\n tableName: string,\n context?: DDLContext\n ): TableDef | undefined {\n return context?.currentSchema?.tables.find((t) => t.name === tableName);\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(op: CreateTableOperation): string {\n const { table } = op;\n const statements: string[] = [this.generateCreateTableDef(table)];\n\n // Create indexes separately\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex({\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n })\n );\n }\n\n return statements.join(\";\\n\");\n }\n\n generateDropTable(op: DropTableOperation): string {\n return `DROP TABLE ${this.escapeIdentifier(op.tableName)}`;\n }\n\n generateRenameTable(op: RenameTableOperation): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation): string {\n const colDef = this.generateColumnDef(op.column);\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation): string {\n // SQLite 3.35.0+ supports DROP COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(op: RenameColumnOperation): string {\n // SQLite 3.25.0+ supports RENAME COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(op: AlterColumnOperation, context?: DDLContext): string {\n // SQLite doesn't support ALTER COLUMN - need table recreation\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot alter column: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext or call setCurrentSchema() before generating DDL.\"\n );\n }\n\n // Build new table definition with the altered column\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === op.columnName) {\n return op.to;\n }\n return col;\n });\n\n const newTable: TableDef = {\n ...currentTable,\n columns: newColumns,\n };\n\n return this.generateTableRecreation(op.tableName, newTable, currentTable);\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation): string {\n const { tableName, index } = op;\n\n // Validate index type against capabilities (SQLite only supports btree)\n this.validateIndexType(index.type, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n // SQLite doesn't support USING clause - it only has btree indexes\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} (${cols})`;\n }\n\n generateDropIndex(op: DropIndexOperation): string {\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n context?: DDLContext\n ): string {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext or call setCurrentSchema() before generating DDL.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n foreignKeys: [...currentTable.foreignKeys, op.fk],\n };\n\n return this.generateTableRecreation(op.tableName, newTable, currentTable);\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n context?: DDLContext\n ): string {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext or call setCurrentSchema() before generating DDL.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n foreignKeys: currentTable.foreignKeys.filter(\n (fk) => fk.name !== op.fkName\n ),\n };\n\n return this.generateTableRecreation(op.tableName, newTable, currentTable);\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(op: AddUniqueConstraintOperation): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `CREATE UNIQUE INDEX ${this.escapeIdentifier(constraint.name)} ON ${this.escapeIdentifier(tableName)} (${cols})`;\n }\n\n generateDropUniqueConstraint(op: DropUniqueConstraintOperation): string {\n return `DROP INDEX ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations (require table recreation)\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n context?: DDLContext\n ): string {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add primary key: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext or call setCurrentSchema() before generating DDL.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n primaryKey: op.primaryKey,\n };\n\n return this.generateTableRecreation(op.tableName, newTable, currentTable);\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n context?: DDLContext\n ): string {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop primary key: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext or call setCurrentSchema() before generating DDL.\"\n );\n }\n\n const newTable: TableDef = {\n ...currentTable,\n primaryKey: undefined,\n };\n\n return this.generateTableRecreation(op.tableName, newTable, currentTable);\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context?: DDLContext): string {\n // SQLite enums use CHECK constraints embedded in column definitions\n // No separate enum type creation needed\n return \"-- SQLite: enum CHECK constraint is part of column definition\";\n }\n\n generateDropEnum(op: DropEnumOperation, context?: DDLContext): string {\n // Dropping an enum means removing CHECK constraints from dependent columns\n // This requires table recreation for each dependent table\n const { enumName, dependentColumns } = op;\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns for enum \"${enumName}\"`;\n }\n\n const statements: string[] = [];\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n throw new MigrationError(\n `Table \"${dep.tableName}\" not found for enum \"${enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n\n // Change the column type to plain TEXT (remove CHECK constraint)\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName && col.type.includes(\"CHECK\")) {\n return { ...col, type: \"TEXT\" };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n statements.push(\n this.generateTableRecreation(dep.tableName, newTable, currentTable)\n );\n }\n\n return statements.join(\";\\n\");\n }\n\n generateAlterEnum(op: AlterEnumOperation, context?: DDLContext): string {\n // Altering an enum means updating CHECK constraints on dependent columns\n // This requires table recreation for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n const statements: string[] = [];\n\n if (!newValues || newValues.length === 0) {\n return `-- SQLite: no new values provided for enum \"${enumName}\"`;\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- SQLite: no dependent columns found for enum \"${enumName}\"`;\n }\n\n // Generate new CHECK constraint\n const escapedValues = newValues\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n\n for (const dep of dependentColumns) {\n const currentTable = this.getCurrentTable(dep.tableName, context);\n if (!currentTable) {\n statements.push(`-- SQLite: table \"${dep.tableName}\" not found`);\n continue;\n }\n\n // Build new CHECK constraint for this column\n const newCheckType = `TEXT CHECK(${this.escapeIdentifier(dep.columnName)} IN (${escapedValues}))`;\n\n // Update the column type with new CHECK\n const newColumns = currentTable.columns.map((col) => {\n if (col.name === dep.columnName) {\n return { ...col, type: newCheckType };\n }\n return col;\n });\n\n const newTable: TableDef = { ...currentTable, columns: newColumns };\n statements.push(\n this.generateTableRecreation(dep.tableName, newTable, currentTable)\n );\n }\n\n return statements.join(\";\\n\\n\");\n }\n\n // ===========================================================================\n // MIGRATION TRACKING TABLE\n // ===========================================================================\n\n generateCreateTrackingTable(tableName: string): string {\n const table = this.escapeIdentifier(tableName);\n return `CREATE TABLE IF NOT EXISTS ${table} (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL UNIQUE,\n checksum TEXT NOT NULL,\n applied_at TEXT DEFAULT (datetime('now'))\n)`;\n }\n\n generateInsertMigration(tableName: string): {\n sql: string;\n paramCount: number;\n } {\n const table = this.escapeIdentifier(tableName);\n return {\n sql: `INSERT INTO ${table} (name, checksum) VALUES (?, ?)`,\n paramCount: 2,\n };\n }\n\n generateDeleteMigration(tableName: string): {\n sql: string;\n paramCount: number;\n } {\n const table = this.escapeIdentifier(tableName);\n return {\n sql: `DELETE FROM ${table} WHERE name = ?`,\n paramCount: 1,\n };\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n // Return null to signal that locking is handled differently\n return null;\n }\n\n generateReleaseLock(_lockId: number): string | null {\n // SQLite uses file-based locking via transactions\n return null;\n }\n\n generateResetSQL(): string[] {\n // SQLite doesn't support dynamic SQL in a single statement.\n // The CLI should:\n // 1. Query sqlite_master for tables\n // 2. Execute DROP TABLE for each\n // Return empty to signal programmatic reset is needed.\n return [];\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateListTables(): string {\n return `SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name`;\n }\n\n generateListEnums(): string | null {\n // SQLite doesn't support enums\n return null;\n }\n}\n\n// Export singleton instance\nexport const sqlite3MigrationDriver = new SQLite3MigrationDriver();\n","/**\n * LibSQL Migration Driver\n *\n * Extends SQLite3 driver with native ALTER COLUMN support.\n * LibSQL supports ALTER TABLE ALTER COLUMN syntax that SQLite doesn't,\n * avoiding expensive table recreation for column modifications.\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This differs from PostgreSQL's behavior where constraints\n * are validated against all existing rows.\n */\n\nimport type { ColumnDef, ReferentialAction } from \"../../types\";\nimport type {\n AddForeignKeyOperation,\n AlterColumnOperation,\n DDLContext,\n DropForeignKeyOperation,\n} from \"../base\";\nimport { SQLite3MigrationDriver } from \"../sqlite\";\nimport type { MigrationCapabilities } from \"../types\";\n\nexport class LibSQLMigrationDriver extends SQLite3MigrationDriver {\n override readonly driverName: string = \"libsql\";\n\n // Same capabilities as SQLite3 (no native enums, no arrays, btree only)\n override readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: false,\n supportsAddEnumValueInTransaction: true,\n supportsIndexTypes: [\"btree\"],\n supportsNativeArrays: false,\n };\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: ALTER COLUMN (native support)\n // ===========================================================================\n\n /**\n * LibSQL supports ALTER TABLE ... ALTER COLUMN ... TO syntax.\n * This avoids table recreation for column type/default/nullable changes.\n *\n * Syntax: ALTER TABLE t ALTER COLUMN c TO c <new_column_def>\n *\n * CAVEAT: LibSQL's ALTER COLUMN only validates newly inserted/updated rows,\n * NOT existing data. This is different from PostgreSQL's behavior.\n */\n override generateAlterColumn(\n op: AlterColumnOperation,\n _context?: DDLContext\n ): string {\n const { tableName, columnName, to } = op;\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(columnName);\n\n // Build new column definition\n const colDef = this.generateColumnDef(to);\n\n // LibSQL syntax: ALTER TABLE t ALTER COLUMN old_name TO new_def\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n // ===========================================================================\n // HELPER: Build column definition with optional REFERENCES\n // ===========================================================================\n\n /**\n * Builds a column definition string with optional foreign key REFERENCES clause.\n * Used for LibSQL's ALTER COLUMN TO syntax.\n */\n private buildColumnDefWithReferences(\n column: ColumnDef,\n fkRef?: {\n refTable: string;\n refCol: string;\n onDelete?: ReferentialAction;\n onUpdate?: ReferentialAction;\n }\n ): string {\n const parts: string[] = [this.escapeIdentifier(column.name), column.type];\n\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n if (column.default !== undefined) {\n parts.push(`DEFAULT ${column.default}`);\n }\n\n if (fkRef) {\n parts.push(\n `REFERENCES ${this.escapeIdentifier(fkRef.refTable)}(${this.escapeIdentifier(fkRef.refCol)})`\n );\n if (fkRef.onDelete && fkRef.onDelete !== \"noAction\") {\n parts.push(`ON DELETE ${this.formatReferentialAction(fkRef.onDelete)}`);\n }\n if (fkRef.onUpdate && fkRef.onUpdate !== \"noAction\") {\n parts.push(`ON UPDATE ${this.formatReferentialAction(fkRef.onUpdate)}`);\n }\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // LIBSQL-SPECIFIC: FOREIGN KEYS (native support via ALTER COLUMN)\n // ===========================================================================\n\n /**\n * LibSQL can add foreign keys by redefining the column with REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n *\n * Note: Multi-column FKs still require table recreation.\n */\n override generateAddForeignKey(\n op: AddForeignKeyOperation,\n context?: DDLContext\n ): string {\n const { tableName, fk } = op;\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateAddForeignKey(op, context);\n }\n\n // Validate columns exist FIRST (before any array access)\n const fkColumn = fk.columns[0];\n const refColumn = fk.referencedColumns[0];\n if (!(fkColumn && refColumn)) {\n throw new Error(\n `Invalid foreign key: columns array is empty for table \"${tableName}\".`\n );\n }\n\n const currentTable = this.getCurrentTable(tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot add foreign key: table \"${tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the column to alter\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot add foreign key: column \"${fkColumn}\" not found in table \"${tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Build column definition with REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column, {\n refTable: fk.referencedTable,\n refCol: refColumn,\n onDelete: fk.onDelete,\n onUpdate: fk.onUpdate,\n });\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n /**\n * LibSQL can drop foreign keys by redefining the column without REFERENCES.\n * This avoids table recreation for single-column foreign keys.\n */\n override generateDropForeignKey(\n op: DropForeignKeyOperation,\n context?: DDLContext\n ): string {\n const currentTable = this.getCurrentTable(op.tableName, context);\n if (!currentTable) {\n throw new Error(\n `Cannot drop foreign key: table \"${op.tableName}\" not found in current schema. ` +\n \"Pass currentSchema in DDLContext.\"\n );\n }\n\n // Find the FK to drop\n const fk = currentTable.foreignKeys.find((f) => f.name === op.fkName);\n if (!fk) {\n throw new Error(\n `Cannot drop foreign key: constraint \"${op.fkName}\" not found in table \"${op.tableName}\".`\n );\n }\n\n // For multi-column FKs, fall back to table recreation\n if (fk.columns.length > 1) {\n return super.generateDropForeignKey(op, context);\n }\n\n const fkColumn = fk.columns[0];\n if (!fkColumn) {\n throw new Error(\n `Invalid foreign key: columns array is empty for constraint \"${op.fkName}\".`\n );\n }\n\n // Find the column\n const column = currentTable.columns.find((c) => c.name === fkColumn);\n if (!column) {\n throw new Error(\n `Cannot drop foreign key: column \"${fkColumn}\" not found in table \"${op.tableName}\".`\n );\n }\n\n const table = this.escapeIdentifier(op.tableName);\n const col = this.escapeIdentifier(fkColumn);\n\n // Rebuild column definition WITHOUT REFERENCES using helper\n const colDef = this.buildColumnDefWithReferences(column);\n\n return `ALTER TABLE ${table} ALTER COLUMN ${col} TO ${colDef}`;\n }\n\n // ===========================================================================\n // PRIMARY KEY OPERATIONS\n // LibSQL still requires table recreation for PK changes\n // ===========================================================================\n\n // generateAddPrimaryKey and generateDropPrimaryKey inherit from SQLite3\n // which uses table recreation. LibSQL does not support native PK modifications.\n}\n\n// Export singleton instance\nexport const libsqlMigrationDriver = new LibSQLMigrationDriver();\n","/**\n * Migration Driver Utilities\n *\n * Shared helper functions used across multiple migration drivers.\n */\n\n/**\n * Groups items by a key function.\n *\n * @param items - Array of items to group\n * @param keyFn - Function to extract the grouping key\n * @returns Map from key to array of items\n */\nexport function groupBy<T>(\n items: T[],\n keyFn: (item: T) => string\n): Map<string, T[]> {\n const map = new Map<string, T[]>();\n for (const item of items) {\n const key = keyFn(item);\n const existing = map.get(key);\n if (existing) {\n existing.push(item);\n } else {\n map.set(key, [item]);\n }\n }\n return map;\n}\n\n/**\n * Groups items by two levels of keys (nested grouping).\n *\n * @param items - Array of items to group\n * @param primaryKeyFn - Function to extract the primary grouping key\n * @param secondaryKeyFn - Function to extract the secondary grouping key\n * @returns Nested Map structure\n */\nexport function groupByNested<T>(\n items: T[],\n primaryKeyFn: (item: T) => string,\n secondaryKeyFn: (item: T) => string\n): Map<string, Map<string, T[]>> {\n const map = new Map<string, Map<string, T[]>>();\n for (const item of items) {\n const pk = primaryKeyFn(item);\n const sk = secondaryKeyFn(item);\n\n let secondary = map.get(pk);\n if (!secondary) {\n secondary = new Map();\n map.set(pk, secondary);\n }\n\n const existing = secondary.get(sk);\n if (existing) {\n existing.push(item);\n } else {\n secondary.set(sk, [item]);\n }\n }\n return map;\n}\n","/**\n * MySQL Schema Introspection\n *\n * Reads the current database schema from MySQL's information_schema,\n * returning a normalized SchemaSnapshot.\n */\n\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { groupBy, groupByNested } from \"../utils\";\nimport type {\n MySQLColumn,\n MySQLForeignKey,\n MySQLIndex,\n MySQLPrimaryKey,\n MySQLTable,\n MySQLUniqueConstraint,\n} from \"./types\";\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\n// Note: DATABASE() returns current database name in MySQL\nconst TABLES_QUERY = `\nSELECT TABLE_NAME\nFROM information_schema.TABLES\nWHERE TABLE_SCHEMA = DATABASE()\n AND TABLE_TYPE = 'BASE TABLE'\nORDER BY TABLE_NAME\n`;\n\nconst COLUMNS_QUERY = `\nSELECT\n TABLE_NAME,\n COLUMN_NAME,\n DATA_TYPE,\n COLUMN_TYPE,\n IS_NULLABLE,\n COLUMN_DEFAULT,\n CHARACTER_MAXIMUM_LENGTH,\n NUMERIC_PRECISION,\n NUMERIC_SCALE,\n EXTRA\nFROM information_schema.COLUMNS\nWHERE TABLE_SCHEMA = DATABASE()\nORDER BY TABLE_NAME, ORDINAL_POSITION\n`;\n\nconst PRIMARY_KEYS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nWHERE tc.TABLE_SCHEMA = DATABASE()\n AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'\nORDER BY tc.TABLE_NAME, kcu.ORDINAL_POSITION\n`;\n\nconst INDEXES_QUERY = `\nSELECT\n TABLE_NAME,\n INDEX_NAME,\n COLUMN_NAME,\n NON_UNIQUE,\n INDEX_TYPE,\n SEQ_IN_INDEX\nFROM information_schema.STATISTICS\nWHERE TABLE_SCHEMA = DATABASE()\n AND INDEX_NAME != 'PRIMARY'\nORDER BY TABLE_NAME, INDEX_NAME, SEQ_IN_INDEX\n`;\n\nconst FOREIGN_KEYS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.REFERENCED_TABLE_NAME,\n kcu.REFERENCED_COLUMN_NAME,\n rc.DELETE_RULE,\n rc.UPDATE_RULE,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nJOIN information_schema.REFERENTIAL_CONSTRAINTS rc\n ON rc.CONSTRAINT_NAME = tc.CONSTRAINT_NAME\n AND rc.CONSTRAINT_SCHEMA = tc.TABLE_SCHEMA\nWHERE tc.TABLE_SCHEMA = DATABASE()\n AND tc.CONSTRAINT_TYPE = 'FOREIGN KEY'\nORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION\n`;\n\nconst UNIQUE_CONSTRAINTS_QUERY = `\nSELECT\n tc.TABLE_NAME,\n tc.CONSTRAINT_NAME,\n kcu.COLUMN_NAME,\n kcu.ORDINAL_POSITION\nFROM information_schema.TABLE_CONSTRAINTS tc\nJOIN information_schema.KEY_COLUMN_USAGE kcu\n ON tc.CONSTRAINT_NAME = kcu.CONSTRAINT_NAME\n AND tc.TABLE_SCHEMA = kcu.TABLE_SCHEMA\n AND tc.TABLE_NAME = kcu.TABLE_NAME\nWHERE tc.TABLE_SCHEMA = DATABASE()\n AND tc.CONSTRAINT_TYPE = 'UNIQUE'\nORDER BY tc.TABLE_NAME, tc.CONSTRAINT_NAME, kcu.ORDINAL_POSITION\n`;\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nconst ENUM_VALUES_REGEX = /enum\\((.+)\\)/i;\n\n/**\n * Parse enum values from MySQL COLUMN_TYPE string.\n * Handles values containing commas, doubled single quotes (''), and backslash escapes (\\').\n * Example: \"enum('a,b','it''s','c')\" -> ['a,b', \"it's\", 'c']\n * Example: \"enum('it\\\\'s')\" -> [\"it's\"]\n */\nfunction parseEnumValues(columnType: string): string[] | null {\n const match = columnType.match(ENUM_VALUES_REGEX);\n if (!match?.[1]) return null;\n\n const content = match[1];\n const values: string[] = [];\n let i = 0;\n\n while (i < content.length) {\n // Skip whitespace and commas\n while (i < content.length && (content[i] === \" \" || content[i] === \",\")) {\n i++;\n }\n if (i >= content.length) break;\n\n // Expect opening quote\n if (content[i] !== \"'\") {\n i++;\n continue;\n }\n i++; // Skip opening quote\n\n // Collect value until closing quote (handle escaped quotes '' and \\')\n let value = \"\";\n while (i < content.length) {\n if (content[i] === \"\\\\\" && i + 1 < content.length) {\n // Backslash escape - append next char and skip both\n value += content[i + 1];\n i += 2;\n } else if (content[i] === \"'\" && content[i + 1] === \"'\") {\n // Doubled quote escape - add single quote and skip both\n value += \"'\";\n i += 2;\n } else if (content[i] === \"'\") {\n // Closing quote\n i++;\n break;\n } else {\n value += content[i];\n i++;\n }\n }\n values.push(value);\n }\n\n return values.length > 0 ? values : null;\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction mapReferentialAction(rule: string): ReferentialAction {\n switch (rule.toUpperCase()) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\nfunction formatColumnType(col: MySQLColumn): string {\n // For ENUM types, return the full COLUMN_TYPE which includes values\n if (col.DATA_TYPE === \"enum\") {\n return col.COLUMN_TYPE; // e.g., \"enum('active','inactive')\"\n }\n\n // For types with modifiers (unsigned, zerofill) or size info in COLUMN_TYPE,\n // prefer COLUMN_TYPE to preserve full type specification\n // Examples: \"int unsigned\", \"bigint unsigned zerofill\", \"varbinary(255)\", \"bit(8)\", \"timestamp(6)\"\n const columnType = col.COLUMN_TYPE.toLowerCase();\n const hasModifiers =\n columnType.includes(\"unsigned\") ||\n columnType.includes(\"zerofill\") ||\n // Has parentheses with size/precision info (but not enum which is handled above)\n (columnType.includes(\"(\") && col.DATA_TYPE !== \"enum\");\n\n if (hasModifiers) {\n return col.COLUMN_TYPE;\n }\n\n // Fallback: construct from DATA_TYPE with precision info\n if (col.DATA_TYPE === \"varchar\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `VARCHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"char\" && col.CHARACTER_MAXIMUM_LENGTH) {\n return `CHAR(${col.CHARACTER_MAXIMUM_LENGTH})`;\n }\n if (col.DATA_TYPE === \"decimal\" && col.NUMERIC_PRECISION) {\n if (col.NUMERIC_SCALE !== null && col.NUMERIC_SCALE !== undefined) {\n return `DECIMAL(${col.NUMERIC_PRECISION},${col.NUMERIC_SCALE})`;\n }\n return `DECIMAL(${col.NUMERIC_PRECISION})`;\n }\n\n return col.DATA_TYPE.toUpperCase();\n}\n\nfunction isAutoIncrement(extra: string): boolean {\n return extra.toLowerCase().includes(\"auto_increment\");\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n): Promise<SchemaSnapshot> {\n // Execute all queries in parallel\n const [\n tablesResult,\n columnsResult,\n primaryKeysResult,\n indexesResult,\n foreignKeysResult,\n uniqueConstraintsResult,\n ] = await Promise.all([\n executeRaw<MySQLTable>(TABLES_QUERY),\n executeRaw<MySQLColumn>(COLUMNS_QUERY),\n executeRaw<MySQLPrimaryKey>(PRIMARY_KEYS_QUERY),\n executeRaw<MySQLIndex>(INDEXES_QUERY),\n executeRaw<MySQLForeignKey>(FOREIGN_KEYS_QUERY),\n executeRaw<MySQLUniqueConstraint>(UNIQUE_CONSTRAINTS_QUERY),\n ]);\n\n // Group results\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.TABLE_NAME);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.TABLE_NAME);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.TABLE_NAME,\n (idx) => idx.INDEX_NAME\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows,\n (fk) => fk.TABLE_NAME,\n (fk) => fk.CONSTRAINT_NAME\n );\n const uniqueByTable = groupByNested(\n uniqueConstraintsResult.rows,\n (uq) => uq.TABLE_NAME,\n (uq) => uq.CONSTRAINT_NAME\n );\n\n // Track enum definitions found in columns\n const enumDefs: EnumDef[] = [];\n const seenEnums = new Set<string>();\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.TABLE_NAME;\n\n // Build columns\n const columns: ColumnDef[] = [];\n for (const col of columnsByTable.get(tableName) || []) {\n // Extract enum values if this is an enum column\n if (col.DATA_TYPE === \"enum\") {\n // Use $ as delimiter and escape any $ in names to prevent collisions\n // e.g. table \"foo$bar\" col \"baz\" -> \"foo$$bar$baz$enum\"\n const escapedTable = tableName.replace(/\\$/g, \"$$\");\n const escapedCol = col.COLUMN_NAME.replace(/\\$/g, \"$$\");\n const enumName = `${escapedTable}$${escapedCol}$enum`;\n if (!seenEnums.has(enumName)) {\n // Parse enum values from COLUMN_TYPE: enum('val1','val2')\n // Uses stateful parser to handle commas and escaped quotes in values\n const values = parseEnumValues(col.COLUMN_TYPE);\n if (values) {\n enumDefs.push({ name: enumName, values });\n seenEnums.add(enumName);\n }\n }\n }\n\n columns.push({\n name: col.COLUMN_NAME,\n type: formatColumnType(col),\n nullable: col.IS_NULLABLE === \"YES\",\n default: col.COLUMN_DEFAULT ?? undefined,\n autoIncrement: isAutoIncrement(col.EXTRA),\n });\n }\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstPkCol = pkCols[0];\n if (firstPkCol) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.COLUMN_NAME),\n name: firstPkCol.CONSTRAINT_NAME,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n indexCols.sort((a, b) => a.SEQ_IN_INDEX - b.SEQ_IN_INDEX);\n const firstCol = indexCols[0];\n if (firstCol) {\n const rawIndexType = firstCol.INDEX_TYPE.toLowerCase();\n // MySQL INFORMATION_SCHEMA reports RTREE for spatial indexes, normalize to \"spatial\"\n const indexType = rawIndexType === \"rtree\" ? \"spatial\" : rawIndexType;\n indexes.push({\n name: indexName,\n columns: indexCols.map((idx) => idx.COLUMN_NAME),\n unique: firstCol.NON_UNIQUE === 0,\n // MySQL uses BTREE, HASH, FULLTEXT, SPATIAL (reported as RTREE) - preserve all supported types\n type:\n indexType === \"btree\" ||\n indexType === \"hash\" ||\n indexType === \"fulltext\" ||\n indexType === \"spatial\"\n ? (indexType as \"btree\" | \"hash\" | \"fulltext\" | \"spatial\")\n : undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.COLUMN_NAME),\n referencedTable: firstFk.REFERENCED_TABLE_NAME,\n referencedColumns: fkCols.map((fk) => fk.REFERENCED_COLUMN_NAME),\n onDelete: mapReferentialAction(firstFk.DELETE_RULE),\n onUpdate: mapReferentialAction(firstFk.UPDATE_RULE),\n });\n }\n }\n }\n\n // Build unique constraints\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const tableUniques = uniqueByTable.get(tableName);\n if (tableUniques) {\n for (const [constraintName, uqCols] of tableUniques) {\n uqCols.sort((a, b) => a.ORDINAL_POSITION - b.ORDINAL_POSITION);\n uniqueConstraints.push({\n name: constraintName,\n columns: uqCols.map((uq) => uq.COLUMN_NAME),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // MySQL doesn't have standalone enum types, but we track them for compatibility\n return {\n tables,\n enums: enumDefs.length > 0 ? enumDefs : undefined,\n };\n}\n","/**\n * MySQL Migration Driver\n *\n * Implements the MigrationDriver interface for MySQL databases.\n * Supports all DDL operations natively with MySQL-specific syntax.\n */\n\nimport type { Field, FieldState } from \"@schema/fields\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { ColumnDef } from \"../../types\";\n\n// Regex patterns for spatial type detection\nconst SPATIAL_TYPE_PATTERNS = [\n /^GEOMETRY\\b/,\n /^POINT\\b/,\n /^LINESTRING\\b/,\n /^POLYGON\\b/,\n /^MULTIPOINT\\b/,\n /^MULTILINESTRING\\b/,\n /^MULTIPOLYGON\\b/,\n /^GEOMETRYCOLLECTION\\b/,\n] as const;\n\n// Regex pattern for extracting base type from column type string\n// e.g., \"INT UNSIGNED\" -> \"int\", \"BIGINT(20)\" -> \"bigint\"\nconst BASE_TYPE_PATTERN = /[\\s(]/;\n\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\n\nimport { getMySQLType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect } from \"./introspect\";\n\nexport class MySQLMigrationDriver extends MigrationDriver {\n readonly dialect = \"mysql\" as const;\n readonly driverName = \"mysql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true, // MySQL has inline ENUM type\n supportsAddEnumValueInTransaction: false, // MODIFY COLUMN is DDL and causes implicit commit\n supportsIndexTypes: [\"btree\", \"fulltext\", \"spatial\"], // InnoDB does not support user-defined HASH indexes\n supportsNativeArrays: false, // Use JSON instead\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n introspect = introspect;\n\n // ===========================================================================\n // IDENTIFIER ESCAPING (MySQL uses backticks)\n // ===========================================================================\n\n override escapeIdentifier(name: string): string {\n if (name == null) {\n throw new MigrationError(\n \"Cannot escape null or undefined identifier\",\n VibORMErrorCode.INVALID_INPUT\n );\n }\n return `\\`${String(name).replace(/`/g, \"``\")}\\``;\n }\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapFieldType(field: Field, fieldState: FieldState): string {\n const nativeType = field[\"~\"].nativeType;\n\n // If a native type is specified and it's for MySQL, use it\n if (nativeType && nativeType.db === \"mysql\") {\n return nativeType.type;\n }\n\n // Use centralized type mapping\n return getMySQLType({\n type: fieldState.type,\n array: fieldState.array,\n });\n }\n\n /**\n * MySQL uses 1/0 for boolean values (TINYINT(1)).\n */\n protected override formatBooleanDefault(value: boolean): string {\n return value ? \"1\" : \"0\";\n }\n\n /**\n * MySQL supports native auto-generation for certain values.\n */\n protected override getAutoGenerateExpression(\n autoGenerate: FieldState[\"autoGenerate\"]\n ): string | undefined {\n switch (autoGenerate) {\n case \"now\":\n return \"CURRENT_TIMESTAMP\";\n case \"uuid\":\n // MySQL 8.0+ has UUID() function, but it's not suitable for DEFAULT\n // Use application-level generation instead\n return undefined;\n default:\n return undefined;\n }\n }\n\n /**\n * MySQL enum values are part of the column definition.\n * Returns ENUM('val1', 'val2', ...) syntax.\n */\n getEnumColumnType(\n _tableName: string,\n _columnName: string,\n values: string[]\n ): string {\n const escapedValues = values\n .map((v) => `'${v.replace(/'/g, \"''\")}'`)\n .join(\", \");\n return `ENUM(${escapedValues})`;\n }\n\n // ===========================================================================\n // HELPER METHODS\n // ===========================================================================\n\n /**\n * MySQL integer types that support AUTO_INCREMENT.\n * Includes variations with UNSIGNED modifier.\n */\n private static readonly AUTO_INCREMENT_TYPES = new Set([\n \"tinyint\",\n \"smallint\",\n \"mediumint\",\n \"int\",\n \"integer\",\n \"bigint\",\n ]);\n\n /**\n * Validates that a column type is compatible with AUTO_INCREMENT.\n * Returns true if valid, throws MigrationError if invalid.\n */\n private validateAutoIncrementType(column: ColumnDef): void {\n // Extract base type (e.g., \"INT UNSIGNED\" -> \"int\", \"BIGINT(20)\" -> \"bigint\")\n const baseType =\n column.type.toLowerCase().split(BASE_TYPE_PATTERN)[0] ?? \"\";\n\n if (!MySQLMigrationDriver.AUTO_INCREMENT_TYPES.has(baseType)) {\n throw new MigrationError(\n \"MySQL AUTO_INCREMENT requires an integer type (TINYINT, SMALLINT, MEDIUMINT, INT, INTEGER, BIGINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with AUTO_INCREMENT.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: { column: column.name, type: column.type, autoIncrement: true },\n }\n );\n }\n }\n\n /**\n * Generates a column definition string for MySQL.\n */\n protected override generateColumnDef(column: ColumnDef): string {\n const parts: string[] = [this.escapeIdentifier(column.name)];\n\n // Handle auto-increment (MySQL uses AUTO_INCREMENT keyword)\n if (column.autoIncrement) {\n // Validate that the column type supports AUTO_INCREMENT\n this.validateAutoIncrementType(column);\n // Preserve the original type (including modifiers like UNSIGNED)\n parts.push(column.type);\n parts.push(\"AUTO_INCREMENT\");\n } else {\n parts.push(column.type);\n }\n\n // NOT NULL constraint\n if (!column.nullable) {\n parts.push(\"NOT NULL\");\n }\n\n // DEFAULT clause (skip for auto-increment columns and types that don't support simple DEFAULT)\n // MySQL doesn't allow DEFAULT values for TEXT/BLOB, JSON, and spatial types\n if (column.default !== undefined && !column.autoIncrement) {\n const upperType = column.type.toUpperCase();\n const isTextOrBlob =\n upperType.includes(\"TEXT\") ||\n upperType.includes(\"BLOB\") ||\n upperType === \"TINYTEXT\" ||\n upperType === \"MEDIUMTEXT\" ||\n upperType === \"LONGTEXT\" ||\n upperType === \"TINYBLOB\" ||\n upperType === \"MEDIUMBLOB\" ||\n upperType === \"LONGBLOB\";\n const isJson = upperType.includes(\"JSON\");\n const isSpatial = SPATIAL_TYPE_PATTERNS.some((pattern) =>\n pattern.test(upperType)\n );\n\n if (!(isTextOrBlob || isJson || isSpatial)) {\n parts.push(`DEFAULT ${column.default}`);\n }\n }\n\n return parts.join(\" \");\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(op: CreateTableOperation): string {\n const { table } = op;\n const columnDefs = table.columns.map((col) => this.generateColumnDef(col));\n\n // Primary key\n if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n columnDefs.push(`PRIMARY KEY (${pkCols})`);\n }\n\n // Unique constraints\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n columnDefs.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n // Foreign keys (inline in CREATE TABLE for MySQL)\n for (const fk of table.foreignKeys) {\n const fkCols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n let fkDef = `CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n fkDef += `FOREIGN KEY (${fkCols}) `;\n fkDef += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n fkDef += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n fkDef += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n columnDefs.push(fkDef);\n }\n\n const sql = `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${columnDefs.join(\",\\n \")}\\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;\n\n const statements = [sql];\n\n // Indexes are created separately\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex({\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n })\n );\n }\n\n return statements.join(\";\\n\");\n }\n\n generateDropTable(op: DropTableOperation): string {\n // MySQL doesn't have CASCADE for DROP TABLE in the same way\n // Foreign key checks need to be disabled or FKs dropped first\n return `DROP TABLE IF EXISTS ${this.escapeIdentifier(op.tableName)}`;\n }\n\n generateRenameTable(op: RenameTableOperation): string {\n return `RENAME TABLE ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation): string {\n const colDef = this.generateColumnDef(op.column);\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(op: RenameColumnOperation): string {\n // MySQL 8.0+ supports RENAME COLUMN\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(op: AlterColumnOperation, _context?: DDLContext): string {\n const { tableName, columnName, to } = op;\n const table = this.escapeIdentifier(tableName);\n\n // Build the new column definition\n const colDef = this.generateColumnDef(to);\n\n // If column name changed, use CHANGE COLUMN (which handles rename + alter)\n if (columnName !== to.name) {\n return `ALTER TABLE ${table} CHANGE COLUMN ${this.escapeIdentifier(columnName)} ${colDef}`;\n }\n\n // Otherwise use MODIFY COLUMN for same-name alterations\n return `ALTER TABLE ${table} MODIFY COLUMN ${colDef}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation): string {\n const { tableName, index } = op;\n\n // Validate index type\n this.validateIndexType(index.type, index.name);\n\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n\n // MySQL index type syntax varies by type:\n // - FULLTEXT and SPATIAL are prefixes: CREATE FULLTEXT INDEX ...\n // - BTREE is default, no clause needed\n // Note: HASH indexes are not supported by InnoDB (only MEMORY engine supports them)\n let indexPrefix = \"\";\n\n if (index.type === \"fulltext\") {\n indexPrefix = \"FULLTEXT \";\n } else if (index.type === \"spatial\") {\n indexPrefix = \"SPATIAL \";\n }\n // btree is default, no prefix needed\n\n // UNIQUE cannot be combined with FULLTEXT or SPATIAL in MySQL\n if (index.unique && indexPrefix) {\n throw new MigrationError(\n `Cannot combine UNIQUE with ${index.type?.toUpperCase()} index \"${index.name}\". ` +\n `MySQL does not support UNIQUE ${index.type?.toUpperCase()} indexes. ` +\n `Either remove 'unique: true' from the index definition, or create a separate unique index.`,\n VibORMErrorCode.MIGRATION_FAILED,\n { meta: { indexName: index.name, indexType: index.type } }\n );\n }\n const unique = index.unique ? \"UNIQUE \" : \"\";\n\n return `CREATE ${unique}${indexPrefix}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} (${cols})`;\n }\n\n generateDropIndex(op: DropIndexOperation): string {\n // MySQL DROP INDEX requires ON tableName syntax\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)} ON ${this.escapeIdentifier(op.tableName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n _context?: DDLContext\n ): string {\n const { tableName, fk } = op;\n const cols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n\n let sql = `ALTER TABLE ${this.escapeIdentifier(tableName)} `;\n sql += `ADD CONSTRAINT ${this.escapeIdentifier(fk.name)} `;\n sql += `FOREIGN KEY (${cols}) `;\n sql += `REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})`;\n\n if (fk.onDelete && fk.onDelete !== \"noAction\") {\n sql += ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`;\n }\n if (fk.onUpdate && fk.onUpdate !== \"noAction\") {\n sql += ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`;\n }\n\n return sql;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n _context?: DDLContext\n ): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP FOREIGN KEY ${this.escapeIdentifier(op.fkName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(op: AddUniqueConstraintOperation): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.escapeIdentifier(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(op: DropUniqueConstraintOperation): string {\n // MySQL uses DROP INDEX for unique constraints\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP INDEX ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n _context?: DDLContext\n ): string {\n const { tableName, primaryKey } = op;\n const cols = primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.escapeIdentifier(tableName)} ADD PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n _context?: DDLContext\n ): string {\n // MySQL doesn't name primary keys in DROP\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP PRIMARY KEY`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // MySQL doesn't have standalone enum types - they're part of column defs\n // ===========================================================================\n\n generateCreateEnum(_op: CreateEnumOperation, _context?: DDLContext): string {\n // MySQL enums are inline with column definitions\n return \"-- MySQL: ENUM type is part of column definition\";\n }\n\n generateDropEnum(_op: DropEnumOperation, _context?: DDLContext): string {\n // No standalone enum to drop\n return \"-- MySQL: ENUM type is part of column definition\";\n }\n\n generateAlterEnum(op: AlterEnumOperation, context?: DDLContext): string {\n // To alter an enum in MySQL, we need to MODIFY COLUMN for each dependent column\n const { enumName, newValues, dependentColumns } = op;\n\n if (!newValues || newValues.length === 0) {\n return `-- MySQL: no new values provided for enum \"${enumName}\"`;\n }\n\n if (!dependentColumns || dependentColumns.length === 0) {\n return `-- MySQL: no dependent columns found for enum \"${enumName}\"`;\n }\n\n const statements: string[] = [];\n const enumType = this.getEnumColumnType(\"\", \"\", newValues);\n\n for (const dep of dependentColumns) {\n const currentTable = context?.currentSchema?.tables.find(\n (t) => t.name === dep.tableName\n );\n const column = currentTable?.columns.find(\n (c) => c.name === dep.columnName\n );\n\n if (!column) {\n statements.push(\n `-- MySQL: column \"${dep.columnName}\" not found in table \"${dep.tableName}\"`\n );\n continue;\n }\n\n const table = this.escapeIdentifier(dep.tableName);\n const col = this.escapeIdentifier(dep.columnName);\n const nullable = column.nullable ? \"\" : \" NOT NULL\";\n const defaultVal =\n column.default !== undefined ? ` DEFAULT ${column.default}` : \"\";\n\n statements.push(\n `ALTER TABLE ${table} MODIFY COLUMN ${col} ${enumType}${nullable}${defaultVal}`\n );\n }\n\n return statements.join(\";\\n\");\n }\n\n // ===========================================================================\n // MIGRATION TRACKING TABLE\n // ===========================================================================\n\n generateCreateTrackingTable(tableName: string): string {\n const table = this.escapeIdentifier(tableName);\n return `CREATE TABLE IF NOT EXISTS ${table} (\n id INT AUTO_INCREMENT PRIMARY KEY,\n name VARCHAR(255) NOT NULL UNIQUE,\n checksum VARCHAR(64) NOT NULL,\n applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`;\n }\n\n generateInsertMigration(tableName: string): {\n sql: string;\n paramCount: number;\n } {\n const table = this.escapeIdentifier(tableName);\n return {\n sql: `INSERT INTO ${table} (name, checksum) VALUES (?, ?)`,\n paramCount: 2,\n };\n }\n\n generateDeleteMigration(tableName: string): {\n sql: string;\n paramCount: number;\n } {\n const table = this.escapeIdentifier(tableName);\n return {\n sql: `DELETE FROM ${table} WHERE name = ?`,\n paramCount: 1,\n };\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(lockId: number): string | null {\n // MySQL uses GET_LOCK for advisory locking\n // Returns 1 if lock acquired, 0 if timeout, NULL if error\n return `SELECT GET_LOCK('viborm_migration_${lockId}', 30)`;\n }\n\n generateReleaseLock(lockId: number): string | null {\n return `SELECT RELEASE_LOCK('viborm_migration_${lockId}')`;\n }\n\n generateResetSQL(): string[] {\n // MySQL requires disabling foreign key checks to drop tables\n return [\n \"SET FOREIGN_KEY_CHECKS = 0\",\n // Tables will be dropped programmatically\n \"SET FOREIGN_KEY_CHECKS = 1\",\n ];\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateListTables(): string {\n return `SELECT TABLE_NAME AS name FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = 'BASE TABLE' ORDER BY TABLE_NAME`;\n }\n\n generateListEnums(): string | null {\n // MySQL doesn't have standalone enum types\n return null;\n }\n}\n\n// Export singleton instance\nexport const mysqlMigrationDriver = new MySQLMigrationDriver();\n","/**\n * PostgreSQL Schema Introspection\n *\n * Reads the current database schema from PostgreSQL's information_schema\n * and system catalogs, returning a normalized SchemaSnapshot.\n */\n\nimport type {\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"../../types\";\nimport { groupBy, groupByNested } from \"../utils\";\nimport type {\n PgColumn,\n PgEnum,\n PgForeignKey,\n PgIndex,\n PgPrimaryKey,\n PgTable,\n PgUniqueConstraint,\n} from \"./types\";\n\n// Regex for cleaning up PostgreSQL type casting (e.g., 'value'::text -> 'value')\nconst TYPE_CAST_REGEX = /::\\w+(\\[\\])?$/;\n\n// =============================================================================\n// SQL QUERIES\n// =============================================================================\n\nconst TABLES_QUERY = `\nSELECT table_name\nFROM information_schema.tables\nWHERE table_schema = 'public'\n AND table_type = 'BASE TABLE'\nORDER BY table_name;\n`;\n\nconst COLUMNS_QUERY = `\nSELECT\n c.table_name,\n c.column_name,\n c.data_type,\n c.udt_name,\n c.is_nullable,\n c.column_default,\n c.character_maximum_length,\n c.numeric_precision,\n c.numeric_scale\nFROM information_schema.columns c\nJOIN information_schema.tables t\n ON c.table_name = t.table_name\n AND c.table_schema = t.table_schema\nWHERE c.table_schema = 'public'\n AND t.table_type = 'BASE TABLE'\nORDER BY c.table_name, c.ordinal_position;\n`;\n\nconst PRIMARY_KEYS_QUERY = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nWHERE tc.table_schema = 'public'\n AND tc.constraint_type = 'PRIMARY KEY'\nORDER BY tc.table_name, kcu.ordinal_position;\n`;\n\nconst INDEXES_QUERY = `\nSELECT\n t.relname AS table_name,\n i.relname AS index_name,\n a.attname AS column_name,\n ix.indisunique AS is_unique,\n am.amname AS index_type,\n pg_get_expr(ix.indpred, ix.indrelid) AS filter_condition,\n array_position(ix.indkey, a.attnum) AS ordinal_position\nFROM pg_index ix\nJOIN pg_class t ON t.oid = ix.indrelid\nJOIN pg_class i ON i.oid = ix.indexrelid\nJOIN pg_am am ON am.oid = i.relam\nJOIN pg_namespace n ON n.oid = t.relnamespace\nJOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(ix.indkey)\nWHERE n.nspname = 'public'\n AND NOT ix.indisprimary\n AND t.relkind = 'r'\nORDER BY t.relname, i.relname, array_position(ix.indkey, a.attnum);\n`;\n\nconst FOREIGN_KEYS_QUERY = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n ccu.table_name AS foreign_table_name,\n ccu.column_name AS foreign_column_name,\n rc.delete_rule,\n rc.update_rule,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nJOIN information_schema.constraint_column_usage ccu\n ON ccu.constraint_name = tc.constraint_name\n AND ccu.table_schema = tc.table_schema\nJOIN information_schema.referential_constraints rc\n ON rc.constraint_name = tc.constraint_name\n AND rc.constraint_schema = tc.table_schema\nWHERE tc.table_schema = 'public'\n AND tc.constraint_type = 'FOREIGN KEY'\nORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position;\n`;\n\nconst UNIQUE_CONSTRAINTS_QUERY = `\nSELECT\n tc.table_name,\n tc.constraint_name,\n kcu.column_name,\n kcu.ordinal_position\nFROM information_schema.table_constraints tc\nJOIN information_schema.key_column_usage kcu\n ON tc.constraint_name = kcu.constraint_name\n AND tc.table_schema = kcu.table_schema\nWHERE tc.table_schema = 'public'\n AND tc.constraint_type = 'UNIQUE'\nORDER BY tc.table_name, tc.constraint_name, kcu.ordinal_position;\n`;\n\nconst ENUMS_QUERY = `\nSELECT\n t.typname AS enum_name,\n e.enumlabel AS enum_value,\n e.enumsortorder AS sort_order\nFROM pg_type t\nJOIN pg_enum e ON t.oid = e.enumtypid\nJOIN pg_namespace n ON n.oid = t.typnamespace\nWHERE n.nspname = 'public'\nORDER BY t.typname, e.enumsortorder;\n`;\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction mapReferentialAction(rule: string): ReferentialAction {\n switch (rule) {\n case \"CASCADE\":\n return \"cascade\";\n case \"SET NULL\":\n return \"setNull\";\n case \"RESTRICT\":\n return \"restrict\";\n case \"SET DEFAULT\":\n return \"setDefault\";\n default:\n return \"noAction\";\n }\n}\n\nfunction formatColumnType(col: PgColumn): string {\n const baseType = col.udt_name.startsWith(\"_\")\n ? `${col.udt_name.slice(1)}[]`\n : col.udt_name;\n\n // Handle special types with precision\n if (col.data_type === \"character varying\" && col.character_maximum_length) {\n return `varchar(${col.character_maximum_length})`;\n }\n if (col.data_type === \"character\" && col.character_maximum_length) {\n return `char(${col.character_maximum_length})`;\n }\n if (col.data_type === \"numeric\" && col.numeric_precision) {\n if (col.numeric_scale !== null && col.numeric_scale !== undefined) {\n return `numeric(${col.numeric_precision},${col.numeric_scale})`;\n }\n return `numeric(${col.numeric_precision})`;\n }\n\n return baseType;\n}\n\nfunction isAutoIncrement(columnDefault: string | null): boolean {\n if (!columnDefault) return false;\n return (\n columnDefault.includes(\"nextval(\") ||\n columnDefault.includes(\"_seq'::regclass)\")\n );\n}\n\nfunction cleanDefault(columnDefault: string | null): string | undefined {\n if (!columnDefault) return undefined;\n\n // Skip auto-increment defaults\n if (isAutoIncrement(columnDefault)) return undefined;\n\n // Clean up type casting (e.g., 'value'::text -> 'value')\n const cleaned = columnDefault.replace(TYPE_CAST_REGEX, \"\").trim();\n return cleaned;\n}\n\n// =============================================================================\n// INTROSPECTION\n// =============================================================================\n\nexport async function introspect(\n executeRaw: <T>(sql: string, params?: unknown[]) => Promise<{ rows: T[] }>\n): Promise<SchemaSnapshot> {\n // Execute all queries in parallel\n const [\n tablesResult,\n columnsResult,\n primaryKeysResult,\n indexesResult,\n foreignKeysResult,\n uniqueConstraintsResult,\n enumsResult,\n ] = await Promise.all([\n executeRaw<PgTable>(TABLES_QUERY),\n executeRaw<PgColumn>(COLUMNS_QUERY),\n executeRaw<PgPrimaryKey>(PRIMARY_KEYS_QUERY),\n executeRaw<PgIndex>(INDEXES_QUERY),\n executeRaw<PgForeignKey>(FOREIGN_KEYS_QUERY),\n executeRaw<PgUniqueConstraint>(UNIQUE_CONSTRAINTS_QUERY),\n executeRaw<PgEnum>(ENUMS_QUERY),\n ]);\n\n // Group results using helper functions\n const columnsByTable = groupBy(columnsResult.rows, (col) => col.table_name);\n const pkByTable = groupBy(primaryKeysResult.rows, (pk) => pk.table_name);\n const indexesByTable = groupByNested(\n indexesResult.rows,\n (idx) => idx.table_name,\n (idx) => idx.index_name\n );\n const fkByTable = groupByNested(\n foreignKeysResult.rows,\n (fk) => fk.table_name,\n (fk) => fk.constraint_name\n );\n const uniqueByTable = groupByNested(\n uniqueConstraintsResult.rows,\n (uq) => uq.table_name,\n (uq) => uq.constraint_name\n );\n const enumsByName = groupBy(enumsResult.rows, (e) => e.enum_name);\n\n // Build tables\n const tables: TableDef[] = [];\n\n for (const table of tablesResult.rows) {\n const tableName = table.table_name;\n\n // Build columns\n const columns = (columnsByTable.get(tableName) || []).map((col) => ({\n name: col.column_name,\n type: formatColumnType(col),\n nullable: col.is_nullable === \"YES\",\n default: cleanDefault(col.column_default),\n autoIncrement: isAutoIncrement(col.column_default),\n }));\n\n // Build primary key\n let primaryKey: PrimaryKeyDef | undefined;\n const pkCols = pkByTable.get(tableName);\n if (pkCols && pkCols.length > 0) {\n pkCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstPk = pkCols[0];\n if (firstPk) {\n primaryKey = {\n columns: pkCols.map((pk) => pk.column_name),\n name: firstPk.constraint_name,\n };\n }\n }\n\n // Build indexes\n const indexes: IndexDef[] = [];\n const tableIndexes = indexesByTable.get(tableName);\n if (tableIndexes) {\n for (const [indexName, indexCols] of tableIndexes) {\n indexCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstCol = indexCols[0];\n if (firstCol) {\n indexes.push({\n name: indexName,\n columns: indexCols.map((idx) => idx.column_name),\n unique: firstCol.is_unique,\n type: firstCol.index_type as \"btree\" | \"hash\" | \"gin\" | \"gist\",\n where: firstCol.filter_condition || undefined,\n });\n }\n }\n }\n\n // Build foreign keys\n const foreignKeys: ForeignKeyDef[] = [];\n const tableFks = fkByTable.get(tableName);\n if (tableFks) {\n for (const [constraintName, fkCols] of tableFks) {\n fkCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n const firstFk = fkCols[0];\n if (firstFk) {\n foreignKeys.push({\n name: constraintName,\n columns: fkCols.map((fk) => fk.column_name),\n referencedTable: firstFk.foreign_table_name,\n referencedColumns: fkCols.map((fk) => fk.foreign_column_name),\n onDelete: mapReferentialAction(firstFk.delete_rule),\n onUpdate: mapReferentialAction(firstFk.update_rule),\n });\n }\n }\n }\n\n // Build unique constraints\n const uniqueConstraints: UniqueConstraintDef[] = [];\n const tableUniques = uniqueByTable.get(tableName);\n if (tableUniques) {\n for (const [constraintName, uqCols] of tableUniques) {\n uqCols.sort((a, b) => a.ordinal_position - b.ordinal_position);\n uniqueConstraints.push({\n name: constraintName,\n columns: uqCols.map((uq) => uq.column_name),\n });\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // Build enums\n const enums: EnumDef[] = [];\n for (const [enumName, enumVals] of enumsByName) {\n enumVals.sort((a, b) => a.sort_order - b.sort_order);\n enums.push({\n name: enumName,\n values: enumVals.map((e) => e.enum_value),\n });\n }\n\n return {\n tables,\n enums: enums.length > 0 ? enums : undefined,\n };\n}\n","/**\n * PostgreSQL Migration Driver\n *\n * Implements the MigrationDriver interface for PostgreSQL databases.\n * Supports all DDL operations natively.\n */\n\nimport type { Field, FieldState } from \"@schema/fields\";\nimport { MigrationError, VibORMErrorCode } from \"../../../errors\";\nimport type { ColumnDef } from \"../../types\";\nimport {\n type AddColumnOperation,\n type AddForeignKeyOperation,\n type AddPrimaryKeyOperation,\n type AddUniqueConstraintOperation,\n type AlterColumnOperation,\n type AlterEnumOperation,\n type CreateEnumOperation,\n type CreateIndexOperation,\n type CreateTableOperation,\n type DDLContext,\n type DropColumnOperation,\n type DropEnumOperation,\n type DropForeignKeyOperation,\n type DropIndexOperation,\n type DropPrimaryKeyOperation,\n type DropTableOperation,\n type DropUniqueConstraintOperation,\n MigrationDriver,\n type RenameColumnOperation,\n type RenameTableOperation,\n} from \"../base\";\nimport { getPostgresType } from \"../type-mapping\";\nimport type { MigrationCapabilities } from \"../types\";\nimport { introspect } from \"./introspect\";\n\nexport class PostgresMigrationDriver extends MigrationDriver {\n readonly dialect = \"postgresql\" as const;\n readonly driverName = \"postgresql\";\n\n readonly capabilities: MigrationCapabilities = {\n supportsNativeEnums: true,\n supportsAddEnumValueInTransaction: false,\n supportsIndexTypes: [\"btree\", \"hash\", \"gin\", \"gist\"],\n supportsNativeArrays: true,\n };\n\n // ===========================================================================\n // INTROSPECTION\n // ===========================================================================\n\n introspect = introspect;\n\n // ===========================================================================\n // TYPE MAPPING\n // ===========================================================================\n\n mapFieldType(field: Field, fieldState: FieldState): string {\n const nativeType = field[\"~\"].nativeType;\n\n // If a native type is specified and it's for PostgreSQL, use it\n if (nativeType && nativeType.db === \"pg\") {\n return fieldState.array ? `${nativeType.type}[]` : nativeType.type;\n }\n\n // Use centralized type mapping\n return getPostgresType({\n type: fieldState.type,\n array: fieldState.array,\n withTimezone: fieldState.withTimezone,\n });\n }\n\n // getDefaultExpression is inherited from base class\n // PostgreSQL uses \"true\"/\"false\" for booleans which is the base default\n\n /**\n * PostgreSQL supports native UUID generation via gen_random_uuid().\n * This is more efficient than generating UUIDs at the application level.\n */\n protected override getAutoGenerateExpression(\n autoGenerate: import(\"@schema/fields\").FieldState[\"autoGenerate\"]\n ): string | undefined {\n switch (autoGenerate) {\n case \"uuid\":\n // gen_random_uuid() is available in PostgreSQL 13+ (pgcrypto extension in older versions)\n return \"gen_random_uuid()\";\n case \"now\":\n // Use database-level NOW() for consistent timestamps\n return \"NOW()\";\n default:\n // Other types (ulid, nanoid, cuid, increment, updatedAt) handled elsewhere\n return undefined;\n }\n }\n\n getEnumColumnType(\n tableName: string,\n columnName: string,\n _values: string[]\n ): string {\n return `${tableName}_${columnName}_enum`;\n }\n\n // ===========================================================================\n // OVERRIDES: Column Definition Helpers\n // ===========================================================================\n\n /**\n * PostgreSQL integer types that support SERIAL auto-increment.\n */\n private static readonly SERIAL_TYPE_MAP: Record<string, string> = {\n integer: \"SERIAL\",\n int4: \"SERIAL\",\n int: \"SERIAL\",\n bigint: \"BIGSERIAL\",\n int8: \"BIGSERIAL\",\n smallint: \"SMALLSERIAL\",\n int2: \"SMALLSERIAL\",\n };\n\n /**\n * Formats the column type for PostgreSQL.\n * Handles SERIAL types for auto-increment and enum type escaping.\n */\n protected override formatColumnType(column: ColumnDef): string {\n // Handle auto-increment with SERIAL types\n if (column.autoIncrement) {\n const normalizedType = column.type.toLowerCase();\n const serialType =\n PostgresMigrationDriver.SERIAL_TYPE_MAP[normalizedType];\n\n if (!serialType) {\n throw new MigrationError(\n \"PostgreSQL auto-increment (SERIAL) requires an integer type (INTEGER, BIGINT, SMALLINT). \" +\n `Column \"${column.name}\" has type \"${column.type}\" which is not compatible with auto-increment.`,\n VibORMErrorCode.INVALID_INPUT,\n {\n meta: {\n column: column.name,\n type: column.type,\n autoIncrement: true,\n },\n }\n );\n }\n\n return serialType;\n }\n\n // Handle enum types (need to be escaped as identifiers)\n if (column.type.endsWith(\"_enum\")) {\n return this.escapeIdentifier(column.type);\n }\n\n // Handle array of enum types\n if (column.type.endsWith(\"[]\")) {\n const baseType = column.type.slice(0, -2);\n if (baseType.endsWith(\"_enum\")) {\n return `${this.escapeIdentifier(baseType)}[]`;\n }\n }\n\n return column.type;\n }\n\n // ===========================================================================\n // DDL GENERATION - Table Operations\n // ===========================================================================\n\n generateCreateTable(op: CreateTableOperation): string {\n const { table } = op;\n const columnDefs = table.columns.map((col) => this.generateColumnDef(col));\n\n if (table.primaryKey) {\n const pkCols = table.primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const pkName = table.primaryKey.name\n ? `CONSTRAINT ${this.escapeIdentifier(table.primaryKey.name)} `\n : \"\";\n columnDefs.push(`${pkName}PRIMARY KEY (${pkCols})`);\n }\n\n for (const uq of table.uniqueConstraints) {\n const uqCols = uq.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n columnDefs.push(\n `CONSTRAINT ${this.escapeIdentifier(uq.name)} UNIQUE (${uqCols})`\n );\n }\n\n const sql = `CREATE TABLE ${this.escapeIdentifier(table.name)} (\\n ${columnDefs.join(\",\\n \")}\\n)`;\n\n const statements = [sql];\n\n for (const idx of table.indexes) {\n statements.push(\n this.generateCreateIndex({\n type: \"createIndex\",\n tableName: table.name,\n index: idx,\n })\n );\n }\n\n for (const fk of table.foreignKeys) {\n statements.push(\n this.generateAddForeignKey({\n type: \"addForeignKey\",\n tableName: table.name,\n fk,\n })\n );\n }\n\n return statements.join(\";\\n\");\n }\n\n generateDropTable(op: DropTableOperation): string {\n return `DROP TABLE ${this.escapeIdentifier(op.tableName)} CASCADE`;\n }\n\n generateRenameTable(op: RenameTableOperation): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.from)} RENAME TO ${this.escapeIdentifier(op.to)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Column Operations\n // ===========================================================================\n\n generateAddColumn(op: AddColumnOperation): string {\n const colDef = this.generateColumnDef(op.column);\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} ADD COLUMN ${colDef}`;\n }\n\n generateDropColumn(op: DropColumnOperation): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP COLUMN ${this.escapeIdentifier(op.columnName)}`;\n }\n\n generateRenameColumn(op: RenameColumnOperation): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} RENAME COLUMN ${this.escapeIdentifier(op.from)} TO ${this.escapeIdentifier(op.to)}`;\n }\n\n generateAlterColumn(op: AlterColumnOperation, _context?: DDLContext): string {\n const { tableName, columnName, from, to } = op;\n const statements: string[] = [];\n const table = this.escapeIdentifier(tableName);\n const col = this.escapeIdentifier(columnName);\n\n if (from.type !== to.type) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} TYPE ${to.type} USING ${col}::${to.type}`\n );\n }\n\n if (from.nullable !== to.nullable) {\n if (to.nullable) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP NOT NULL`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET NOT NULL`\n );\n }\n }\n\n if (from.default !== to.default) {\n if (to.default === undefined) {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} DROP DEFAULT`\n );\n } else {\n statements.push(\n `ALTER TABLE ${table} ALTER COLUMN ${col} SET DEFAULT ${to.default}`\n );\n }\n }\n\n return statements.join(\";\\n\");\n }\n\n // ===========================================================================\n // DDL GENERATION - Index Operations\n // ===========================================================================\n\n generateCreateIndex(op: CreateIndexOperation): string {\n const { tableName, index } = op;\n\n // Validate index type against capabilities\n this.validateIndexType(index.type, index.name);\n\n const unique = index.unique ? \"UNIQUE \" : \"\";\n const indexType = index.type ? `USING ${index.type} ` : \"\";\n const cols = index.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const where = index.where ? ` WHERE ${index.where}` : \"\";\n return `CREATE ${unique}INDEX ${this.escapeIdentifier(index.name)} ON ${this.escapeIdentifier(tableName)} ${indexType}(${cols})${where}`;\n }\n\n generateDropIndex(op: DropIndexOperation): string {\n return `DROP INDEX ${this.escapeIdentifier(op.indexName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Foreign Key Operations\n // ===========================================================================\n\n generateAddForeignKey(\n op: AddForeignKeyOperation,\n _context?: DDLContext\n ): string {\n const { tableName, fk } = op;\n const cols = fk.columns.map((c) => this.escapeIdentifier(c)).join(\", \");\n const refCols = fk.referencedColumns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const onDelete = fk.onDelete\n ? ` ON DELETE ${this.formatReferentialAction(fk.onDelete)}`\n : \"\";\n const onUpdate = fk.onUpdate\n ? ` ON UPDATE ${this.formatReferentialAction(fk.onUpdate)}`\n : \"\";\n return `ALTER TABLE ${this.escapeIdentifier(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(fk.name)} FOREIGN KEY (${cols}) REFERENCES ${this.escapeIdentifier(fk.referencedTable)} (${refCols})${onDelete}${onUpdate}`;\n }\n\n generateDropForeignKey(\n op: DropForeignKeyOperation,\n _context?: DDLContext\n ): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.fkName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Unique Constraint Operations\n // ===========================================================================\n\n generateAddUniqueConstraint(op: AddUniqueConstraintOperation): string {\n const { tableName, constraint } = op;\n const cols = constraint.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n return `ALTER TABLE ${this.escapeIdentifier(tableName)} ADD CONSTRAINT ${this.escapeIdentifier(constraint.name)} UNIQUE (${cols})`;\n }\n\n generateDropUniqueConstraint(op: DropUniqueConstraintOperation): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Primary Key Operations\n // ===========================================================================\n\n generateAddPrimaryKey(\n op: AddPrimaryKeyOperation,\n _context?: DDLContext\n ): string {\n const { tableName, primaryKey } = op;\n const cols = primaryKey.columns\n .map((c) => this.escapeIdentifier(c))\n .join(\", \");\n const name = primaryKey.name\n ? this.escapeIdentifier(primaryKey.name)\n : this.escapeIdentifier(`${tableName}_pkey`);\n return `ALTER TABLE ${this.escapeIdentifier(tableName)} ADD CONSTRAINT ${name} PRIMARY KEY (${cols})`;\n }\n\n generateDropPrimaryKey(\n op: DropPrimaryKeyOperation,\n _context?: DDLContext\n ): string {\n return `ALTER TABLE ${this.escapeIdentifier(op.tableName)} DROP CONSTRAINT ${this.escapeIdentifier(op.constraintName)}`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateCreateEnum(op: CreateEnumOperation, _context?: DDLContext): string {\n const { enumDef } = op;\n const values = enumDef.values.map((v) => this.escapeValue(v)).join(\", \");\n return `CREATE TYPE ${this.escapeIdentifier(enumDef.name)} AS ENUM (${values})`;\n }\n\n generateDropEnum(op: DropEnumOperation, _context?: DDLContext): string {\n return `DROP TYPE ${this.escapeIdentifier(op.enumName)}`;\n }\n\n // ===========================================================================\n // MIGRATION TRACKING TABLE\n // ===========================================================================\n\n generateCreateTrackingTable(tableName: string): string {\n const table = this.escapeIdentifier(tableName);\n return `CREATE TABLE IF NOT EXISTS ${table} (\n id SERIAL PRIMARY KEY,\n name VARCHAR(255) NOT NULL UNIQUE,\n checksum VARCHAR(64) NOT NULL,\n applied_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP\n)`;\n }\n\n generateInsertMigration(tableName: string): {\n sql: string;\n paramCount: number;\n } {\n const table = this.escapeIdentifier(tableName);\n return {\n sql: `INSERT INTO ${table} (name, checksum) VALUES ($1, $2)`,\n paramCount: 2,\n };\n }\n\n generateDeleteMigration(tableName: string): {\n sql: string;\n paramCount: number;\n } {\n const table = this.escapeIdentifier(tableName);\n return {\n sql: `DELETE FROM ${table} WHERE name = $1`,\n paramCount: 1,\n };\n }\n\n // ===========================================================================\n // MIGRATION LOCKING\n // ===========================================================================\n\n generateAcquireLock(lockId: number): string | null {\n return `SELECT pg_advisory_lock(${lockId})`;\n }\n\n generateReleaseLock(lockId: number): string | null {\n return `SELECT pg_advisory_unlock(${lockId})`;\n }\n\n generateResetSQL(): string[] {\n return [\n // Drop all tables in public schema\n `DO $$ DECLARE\n r RECORD;\n BEGIN\n FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP\n EXECUTE 'DROP TABLE IF EXISTS \"' || r.tablename || '\" CASCADE';\n END LOOP;\n END $$`,\n // Drop all enum types in public schema\n `DO $$ DECLARE\n r RECORD;\n BEGIN\n FOR r IN (SELECT typname FROM pg_type t JOIN pg_namespace n ON t.typnamespace = n.oid WHERE n.nspname = 'public' AND t.typtype = 'e') LOOP\n EXECUTE 'DROP TYPE IF EXISTS \"' || r.typname || '\" CASCADE';\n END LOOP;\n END $$`,\n ];\n }\n\n // ===========================================================================\n // SCHEMA INTROSPECTION HELPERS\n // ===========================================================================\n\n generateListTables(): string {\n return `SELECT tablename AS name FROM pg_tables WHERE schemaname = 'public' ORDER BY tablename`;\n }\n\n generateListEnums(): string | null {\n return `SELECT t.typname AS name\n FROM pg_type t\n JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n WHERE t.typtype = 'e' AND n.nspname = 'public'\n ORDER BY t.typname`;\n }\n\n override generateDropEnumSQL(enumName: string): string | null {\n return `DROP TYPE IF EXISTS ${this.escapeIdentifier(enumName)} CASCADE`;\n }\n\n // ===========================================================================\n // DDL GENERATION - Enum Operations\n // ===========================================================================\n\n generateAlterEnum(op: AlterEnumOperation, _context?: DDLContext): string {\n const {\n enumName,\n addValues,\n removeValues,\n newValues,\n dependentColumns,\n valueReplacements,\n } = op;\n const statements: string[] = [];\n\n // Simple case: only adding values\n if (addValues && (!removeValues || removeValues.length === 0)) {\n for (const value of addValues) {\n statements.push(\n `ALTER TYPE ${this.escapeIdentifier(enumName)} ADD VALUE ${this.escapeValue(value)}`\n );\n }\n return statements.join(\";\\n\");\n }\n\n // Complex case: removing values requires enum recreation\n if (removeValues && removeValues.length > 0) {\n if (!newValues || newValues.length === 0) {\n throw new Error(\n `Cannot alter enum \"${enumName}\": newValues required when removing values`\n );\n }\n\n // Step 1: Convert dependent columns to text\n if (dependentColumns && dependentColumns.length > 0) {\n for (const { tableName, columnName } of dependentColumns) {\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)} TYPE text`\n );\n }\n }\n\n // Step 2: Migrate data for removed values\n if (dependentColumns && dependentColumns.length > 0) {\n for (const removedValue of removeValues) {\n let replacement: string | null | undefined;\n if (valueReplacements && removedValue in valueReplacements) {\n replacement = valueReplacements[removedValue];\n } else if (op.defaultReplacement !== undefined) {\n replacement = op.defaultReplacement;\n }\n\n if (replacement !== undefined) {\n for (const { tableName, columnName } of dependentColumns) {\n const newValue =\n replacement === null ? \"NULL\" : this.escapeValue(replacement);\n statements.push(\n `UPDATE ${this.escapeIdentifier(tableName)} SET ${this.escapeIdentifier(columnName)} = ${newValue} WHERE ${this.escapeIdentifier(columnName)} = ${this.escapeValue(removedValue)}`\n );\n }\n }\n }\n }\n\n // Step 3: Drop old enum\n statements.push(`DROP TYPE ${this.escapeIdentifier(enumName)}`);\n\n // Step 4: Create new enum\n const values = newValues.map((v) => this.escapeValue(v)).join(\", \");\n statements.push(\n `CREATE TYPE ${this.escapeIdentifier(enumName)} AS ENUM (${values})`\n );\n\n // Step 5: Convert columns back to enum\n const unreplacedValues = removeValues.filter((v) => {\n const hasExplicit = valueReplacements && v in valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unreplacedValues.length > 0 && dependentColumns?.length) {\n const valuesList = unreplacedValues.map((v) => `'${v}'`).join(\", \");\n statements.push(\n `-- WARNING: The following removed values have no replacement: ${valuesList}\\n` +\n \"-- If rows exist with these values, the migration will fail.\\n\" +\n \"-- To fix this, do one of the following:\\n\" +\n `-- 1. Add valueReplacements: { \"${unreplacedValues[0]}\": \"newValue\" }\\n` +\n \"-- 2. Set defaultReplacement to your field's default value\"\n );\n }\n\n if (dependentColumns && dependentColumns.length > 0) {\n for (const { tableName, columnName } of dependentColumns) {\n statements.push(\n `ALTER TABLE ${this.escapeIdentifier(tableName)} ALTER COLUMN ${this.escapeIdentifier(columnName)} TYPE ${this.escapeIdentifier(enumName)} USING ${this.escapeIdentifier(columnName)}::${this.escapeIdentifier(enumName)}`\n );\n }\n }\n }\n\n return statements.join(\";\\n\");\n }\n}\n\n// Export singleton instance\nexport const postgresMigrationDriver = new PostgresMigrationDriver();\n","/**\n * Migration Driver Registry\n *\n * Central registry for migration drivers. Drivers are registered by their\n * driver name and can be looked up by driver name or dialect.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport type { MigrationDriver } from \"./base\";\nimport type { Dialect } from \"./types\";\n\nexport type {\n AddColumnOperation,\n AddForeignKeyOperation,\n AddPrimaryKeyOperation,\n AddUniqueConstraintOperation,\n AlterColumnOperation,\n AlterEnumOperation,\n CreateEnumOperation,\n CreateIndexOperation,\n CreateTableOperation,\n DDLContext,\n DropColumnOperation,\n DropEnumOperation,\n DropForeignKeyOperation,\n DropIndexOperation,\n DropPrimaryKeyOperation,\n DropTableOperation,\n DropUniqueConstraintOperation,\n RenameColumnOperation,\n RenameTableOperation,\n} from \"./base\";\n// Export base class and types\nexport { MigrationDriver } from \"./base\";\nexport type { Dialect, MigrationCapabilities } from \"./types\";\n\n// =============================================================================\n// REGISTRY\n// =============================================================================\n\n/**\n * Registry of migration drivers by driver name.\n */\nconst driverRegistry = new Map<string, MigrationDriver>();\n\n/**\n * Map of dialects to their default driver names.\n */\nconst dialectDefaults = new Map<Dialect, string>([\n [\"postgresql\", \"postgresql\"],\n [\"sqlite\", \"sqlite3\"],\n [\"mysql\", \"mysql\"],\n]);\n\n/**\n * Registers a migration driver.\n *\n * @param driver - The migration driver to register\n */\nexport function registerMigrationDriver(driver: MigrationDriver): void {\n driverRegistry.set(driver.driverName, driver);\n}\n\n/**\n * Gets a migration driver by driver name or dialect.\n *\n * Lookup order:\n * 1. Exact match by driver name\n * 2. Fallback to dialect default\n *\n * @param driverName - The driver name (e.g., \"pg\", \"pglite\", \"sqlite3\", \"libsql\")\n * @param dialect - The dialect to use as fallback\n * @returns The migration driver\n * @throws MigrationError if no driver found\n */\nexport function getMigrationDriver(\n driverName: string,\n dialect: Dialect\n): MigrationDriver {\n // Try exact driver name match\n let driver = driverRegistry.get(driverName);\n if (driver) return driver;\n\n // Try dialect default\n const defaultDriverName = dialectDefaults.get(dialect);\n if (defaultDriverName) {\n driver = driverRegistry.get(defaultDriverName);\n if (driver) return driver;\n }\n\n throw new MigrationError(\n `No migration driver registered for \"${driverName}\" (dialect: ${dialect}). ` +\n `Available drivers: ${[...driverRegistry.keys()].join(\", \") || \"none\"}`,\n VibORMErrorCode.DRIVER_NOT_SUPPORTED\n );\n}\n\n/**\n * Lists all registered migration drivers.\n */\nexport function listMigrationDrivers(): MigrationDriver[] {\n return [...driverRegistry.values()];\n}\n\n/**\n * Checks if a migration driver is registered.\n */\nexport function hasMigrationDriver(driverName: string): boolean {\n return driverRegistry.has(driverName);\n}\n\n// =============================================================================\n// AUTO-REGISTRATION\n// =============================================================================\n\n// Import and register built-in drivers\nimport { libsqlMigrationDriver } from \"./libsql\";\nimport { mysqlMigrationDriver } from \"./mysql\";\nimport { postgresMigrationDriver } from \"./postgres\";\nimport { sqlite3MigrationDriver } from \"./sqlite\";\n\nregisterMigrationDriver(postgresMigrationDriver);\nregisterMigrationDriver(sqlite3MigrationDriver);\nregisterMigrationDriver(libsqlMigrationDriver);\nregisterMigrationDriver(mysqlMigrationDriver);\n","/**\n * Migration Utilities\n *\n * Shared utilities for migration operations. Consolidates duplicated code\n * from push.ts, generate/index.ts, and apply/index.ts.\n */\n\nimport { relative, resolve } from \"node:path\";\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport type {\n Dialect,\n DiffOperation,\n EnumValueRemoval,\n EnumValueResolver,\n MigrationEntry,\n} from \"./types\";\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nexport const DEFAULT_MIGRATIONS_DIR = \"./migrations\";\nexport const DEFAULT_TABLE_NAME = \"_viborm_migrations\";\n\n// =============================================================================\n// DIALECT UTILITIES\n// =============================================================================\n\n/**\n * Validates and normalizes the database dialect for migrations.\n * Throws if the dialect is not supported.\n */\nexport function normalizeDialect(dialect: string): Dialect {\n if (dialect === \"postgresql\" || dialect === \"postgres\") {\n return \"postgresql\";\n }\n if (dialect === \"sqlite\") {\n return \"sqlite\";\n }\n if (dialect === \"mysql\") {\n return \"mysql\";\n }\n throw new MigrationError(\n `Unsupported dialect for migrations: \"${dialect}\". ` +\n \"Supported dialects: postgresql, sqlite, mysql.\",\n VibORMErrorCode.MIGRATION_DIALECT_MISMATCH,\n { meta: { dialect } }\n );\n}\n\n// =============================================================================\n// PATH UTILITIES\n// =============================================================================\n\n/**\n * Validates and resolves the migrations directory path.\n * Ensures the path doesn't escape the project root (security).\n */\nexport function validateMigrationsDir(dir: string): string {\n const cwd = process.cwd();\n const resolved = resolve(cwd, dir);\n const rel = relative(cwd, resolved);\n\n // Ensure path doesn't escape project root\n if (rel.startsWith(\"..\") || resolve(rel) === rel) {\n throw new MigrationError(\n `Invalid migrations directory: \"${dir}\". Path must be within project root.`,\n VibORMErrorCode.INVALID_INPUT,\n { meta: { migrationsDir: dir } }\n );\n }\n\n return resolved;\n}\n\n// =============================================================================\n// TABLE NAME UTILITIES\n// =============================================================================\n\n/**\n * Validates the migration table name to prevent SQL injection.\n * Only allows alphanumeric characters and underscores.\n */\nexport function validateTableName(tableName: string): string {\n if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(tableName)) {\n throw new MigrationError(\n `Invalid migration table name: \"${tableName}\". ` +\n \"Only alphanumeric characters and underscores are allowed.\",\n VibORMErrorCode.INVALID_INPUT,\n { meta: { table: tableName } }\n );\n }\n return tableName;\n}\n\n// =============================================================================\n// QUERY EXECUTOR\n// =============================================================================\n\n/**\n * Type for executing SQL queries and returning rows.\n */\nexport type QueryExecutor = (\n sql: string,\n params?: unknown[]\n) => Promise<unknown[]>;\n\n/**\n * Creates a query executor from a driver.\n * Extracts rows from the QueryResult.\n */\nexport function createQueryExecutor(driver: AnyDriver): QueryExecutor {\n return async (sql: string, params?: unknown[]) => {\n const result = await driver._executeRaw<Record<string, unknown>>(\n sql,\n params\n );\n return result.rows;\n };\n}\n\n// =============================================================================\n// OPERATION UTILITIES\n// =============================================================================\n\n/**\n * Operation execution order priorities.\n * Lower numbers execute first.\n */\nconst OPERATION_PRIORITY: Record<DiffOperation[\"type\"], number> = {\n createEnum: 1,\n dropForeignKey: 2,\n dropIndex: 3,\n dropUniqueConstraint: 4,\n dropPrimaryKey: 5,\n dropColumn: 6,\n dropTable: 7,\n createTable: 8,\n addColumn: 9,\n alterColumn: 10,\n renameTable: 11,\n renameColumn: 12,\n addPrimaryKey: 13,\n addUniqueConstraint: 14,\n createIndex: 15,\n addForeignKey: 16,\n alterEnum: 17,\n dropEnum: 18,\n};\n\n/**\n * Sorts operations for proper execution order:\n * 1. Create enums (before tables that use them)\n * 2. Drop foreign keys (before dropping tables/columns)\n * 3. Drop indexes, constraints, columns\n * 4. Drop tables\n * 5. Create tables\n * 6. Add columns, constraints\n * 7. Create indexes\n * 8. Add foreign keys (after tables/columns exist)\n */\nexport function sortOperations(operations: DiffOperation[]): DiffOperation[] {\n return [...operations].sort(\n (a, b) => OPERATION_PRIORITY[a.type] - OPERATION_PRIORITY[b.type]\n );\n}\n\n// =============================================================================\n// ENUM VALUE RESOLUTION\n// =============================================================================\n\n/**\n * Resolves enum value removals by calling the resolver callback (if provided)\n * and merging the resolutions into the operations.\n */\nexport async function resolveEnumValueRemovals(\n operations: DiffOperation[],\n resolver?: EnumValueResolver\n): Promise<DiffOperation[]> {\n // Find alterEnum operations with removeValues that need resolution\n const removals: EnumValueRemoval[] = [];\n\n for (const op of operations) {\n if (\n op.type === \"alterEnum\" &&\n op.removeValues &&\n op.removeValues.length > 0\n ) {\n // Check if any removed values lack replacements\n const unresolvedValues = op.removeValues.filter((v) => {\n const hasExplicit = op.valueReplacements && v in op.valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unresolvedValues.length > 0) {\n removals.push({\n enumName: op.enumName,\n removedValues: unresolvedValues,\n newValues: op.newValues || [],\n dependentColumns: op.dependentColumns || [],\n });\n }\n }\n }\n\n // If no unresolved removals or no resolver, return operations unchanged\n if (removals.length === 0 || !resolver) {\n return operations;\n }\n\n // Call the resolver\n const resolutions = await resolver(removals);\n\n // Merge resolutions into operations\n return operations.map((op) => {\n if (op.type !== \"alterEnum\" || !op.removeValues) {\n return op;\n }\n\n const resolution = resolutions.get(op.enumName);\n if (!resolution) {\n return op;\n }\n\n // Merge the resolution into the operation\n return {\n ...op,\n valueReplacements: {\n ...op.valueReplacements,\n ...resolution.valueReplacements,\n },\n defaultReplacement:\n resolution.defaultReplacement ?? op.defaultReplacement,\n };\n });\n}\n\n// =============================================================================\n// MIGRATION FILE UTILITIES\n// =============================================================================\n\n/**\n * Formats a migration filename from entry.\n * Example: 0000_initial.sql, 0001_add-users.sql\n */\nexport function formatMigrationFilename(entry: MigrationEntry): string {\n const paddedIdx = String(entry.idx).padStart(4, \"0\");\n return `${paddedIdx}_${entry.name}.sql`;\n}\n\n/**\n * Generate a migration name based on the operations.\n */\nexport function generateMigrationName(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"empty\";\n }\n\n const primaryOp = operations[0];\n if (!primaryOp) {\n return \"migration\";\n }\n\n switch (primaryOp.type) {\n case \"createTable\":\n return operations.length === 1\n ? `create-${primaryOp.table.name}`\n : \"initial\";\n case \"dropTable\":\n return `drop-${primaryOp.tableName}`;\n case \"addColumn\":\n return `add-${primaryOp.column.name}-to-${primaryOp.tableName}`;\n case \"dropColumn\":\n return `drop-${primaryOp.columnName}-from-${primaryOp.tableName}`;\n case \"renameTable\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"renameColumn\":\n return `rename-${primaryOp.from}-to-${primaryOp.to}`;\n case \"createIndex\":\n return `add-index-${primaryOp.index.name}`;\n case \"dropIndex\":\n return `drop-index-${primaryOp.indexName}`;\n case \"addForeignKey\":\n return `add-fk-${primaryOp.fk.name}`;\n case \"dropForeignKey\":\n return `drop-fk-${primaryOp.fkName}`;\n case \"createEnum\":\n return `create-enum-${primaryOp.enumDef.name}`;\n case \"dropEnum\":\n return `drop-enum-${primaryOp.enumName}`;\n case \"alterEnum\":\n return `alter-enum-${primaryOp.enumName}`;\n default:\n return \"migration\";\n }\n}\n","/**\n * Migration Context\n *\n * Encapsulates all migration configuration and provides shared operations\n * like locking, tracking, and query execution.\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { getMigrationDriver, type MigrationDriver } from \"./drivers\";\nimport type { MigrationClient } from \"./push\";\nimport type { MigrationStorageDriver } from \"./storage\";\nimport type { AppliedMigration, Dialect, MigrationEntry } from \"./types\";\nimport {\n createQueryExecutor,\n DEFAULT_MIGRATIONS_DIR,\n DEFAULT_TABLE_NAME,\n normalizeDialect,\n type QueryExecutor,\n validateMigrationsDir,\n validateTableName,\n} from \"./utils\";\n\n// =============================================================================\n// TYPES\n// =============================================================================\n\nexport interface MigrationContextOptions {\n /** Migrations directory (default: ./migrations) */\n dir?: string;\n /** Migration tracking table name (default: _viborm_migrations) */\n tableName?: string;\n /** Storage driver for migration files (required) */\n storageDriver: MigrationStorageDriver;\n}\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\n/**\n * Lock ID for PostgreSQL advisory locks.\n * Hash of \"viborm_migrations\" to avoid collisions.\n */\nconst MIGRATION_LOCK_ID = 0x76_69_62_6f_72_6d; // \"viborm\" in hex, truncated\n\n// =============================================================================\n// MIGRATION CONTEXT\n// =============================================================================\n\n/**\n * Migration context that encapsulates configuration and provides\n * shared operations for migration commands.\n */\nexport class MigrationContext {\n readonly driver: AnyDriver;\n readonly dialect: Dialect;\n readonly migrationsDir: string;\n readonly tableName: string;\n readonly executor: QueryExecutor;\n readonly migrationDriver: MigrationDriver;\n readonly storage: MigrationStorageDriver;\n\n private _hasLock = false;\n\n constructor(client: MigrationClient, options: MigrationContextOptions) {\n const {\n dir = DEFAULT_MIGRATIONS_DIR,\n tableName = DEFAULT_TABLE_NAME,\n storageDriver,\n } = options;\n\n this.driver = client.$driver;\n this.dialect = normalizeDialect(this.driver.dialect);\n this.migrationsDir = validateMigrationsDir(dir);\n this.tableName = validateTableName(tableName);\n this.executor = createQueryExecutor(this.driver);\n this.migrationDriver = getMigrationDriver(\n this.driver.driverName,\n this.dialect\n );\n this.storage = storageDriver;\n }\n\n // ===========================================================================\n // MIGRATION TRACKING TABLE\n // ===========================================================================\n\n /**\n * Ensures the migrations tracking table exists.\n */\n async ensureTrackingTable(): Promise<void> {\n const ddl = this.migrationDriver.generateCreateTrackingTable(\n this.tableName\n );\n await this.driver._executeRaw(ddl);\n }\n\n // ===========================================================================\n // APPLIED MIGRATIONS\n // ===========================================================================\n\n /**\n * Get all applied migrations from the database.\n */\n async getAppliedMigrations(): Promise<AppliedMigration[]> {\n await this.ensureTrackingTable();\n\n const sqlStr = this.migrationDriver.generateSelectAppliedMigrations(\n this.tableName\n );\n\n const rows = (await this.executor(sqlStr)) as Array<{\n name: string;\n checksum: string;\n applied_at: string | Date;\n }>;\n\n return rows.map((row) => ({\n name: row.name,\n checksum: row.checksum,\n appliedAt:\n row.applied_at instanceof Date\n ? row.applied_at\n : new Date(row.applied_at),\n }));\n }\n\n /**\n * Mark a migration as applied in the database.\n */\n async markMigrationApplied(entry: MigrationEntry): Promise<void> {\n const { sql } = this.migrationDriver.generateInsertMigration(\n this.tableName\n );\n await this.executor(sql, [entry.name, entry.checksum]);\n }\n\n /**\n * Mark a migration as rolled back (remove from tracking table).\n */\n async markMigrationRolledBack(name: string): Promise<void> {\n const { sql } = this.migrationDriver.generateDeleteMigration(\n this.tableName\n );\n await this.executor(sql, [name]);\n }\n\n /**\n * Delete a migration from the tracking table by name.\n * Alias for markMigrationRolledBack, used by squash.\n */\n async deleteMigration(name: string): Promise<void> {\n await this.markMigrationRolledBack(name);\n }\n\n // ===========================================================================\n // LOCKING (Concurrent Protection)\n // ===========================================================================\n\n /**\n * Acquires a migration lock to prevent concurrent migrations.\n * Uses PostgreSQL advisory locks or SQLite exclusive transactions.\n */\n async acquireLock(): Promise<void> {\n if (this._hasLock) {\n return; // Already have the lock\n }\n\n const lockSql = this.migrationDriver.generateAcquireLock(MIGRATION_LOCK_ID);\n if (lockSql) {\n try {\n await this.driver._executeRaw(lockSql);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new MigrationError(\n `Failed to acquire migration lock: ${message}`,\n VibORMErrorCode.MIGRATION_LOCK_FAILED,\n { cause: err instanceof Error ? err : undefined }\n );\n }\n }\n // Only set after successful execution (or if no lock needed for SQLite)\n this._hasLock = true;\n }\n\n /**\n * Releases the migration lock.\n */\n async releaseLock(): Promise<void> {\n if (!this._hasLock) {\n return; // Don't have the lock\n }\n\n // Clear the flag first to avoid retrying on error\n this._hasLock = false;\n\n const unlockSql =\n this.migrationDriver.generateReleaseLock(MIGRATION_LOCK_ID);\n if (unlockSql) {\n try {\n await this.driver._executeRaw(unlockSql);\n } catch {\n // Ignore errors when releasing lock - it will be released when connection closes\n }\n }\n }\n\n /**\n * Execute a function while holding the migration lock.\n */\n async withLock<T>(fn: () => Promise<T>): Promise<T> {\n await this.acquireLock();\n try {\n return await fn();\n } finally {\n await this.releaseLock();\n }\n }\n\n // ===========================================================================\n // UTILITIES\n // ===========================================================================\n\n /**\n * Execute a function within a transaction.\n * The callback receives a transaction-bound context.\n */\n async transaction<T>(\n fn: (txCtx: MigrationContext) => Promise<T>\n ): Promise<T> {\n return this.driver.withTransaction((txDriver) => {\n // Create a transaction-bound context\n const txCtx = Object.create(this) as MigrationContext;\n (txCtx as { driver: AnyDriver }).driver = txDriver;\n // Recreate executor bound to transaction driver\n (txCtx as { executor: QueryExecutor }).executor =\n createQueryExecutor(txDriver);\n return fn(txCtx);\n });\n }\n\n /**\n * Execute raw SQL.\n */\n async executeRaw(sqlStr: string, params?: unknown[]): Promise<void> {\n await this.driver._executeRaw(sqlStr, params);\n }\n\n // ===========================================================================\n // STATEMENT EXECUTION\n // ===========================================================================\n\n /**\n * Executes parsed SQL statements from a migration file.\n * Filters out empty lines and comments, ensures semicolons.\n *\n * Uses the following priority for atomicity:\n * 1. Native batch (if driver.supportsBatch) - D1, D1-HTTP, Neon-HTTP\n * 2. Transaction wrapper (if driver.supportsTransactions) - most drivers\n * 3. Sequential execution with warning (no atomicity)\n *\n * @param statements - Array of SQL statements to execute\n */\n async executeMigrationStatements(statements: string[]): Promise<void> {\n // Filter and normalize statements\n const queries = statements\n .map((stmt) => stmt.trim())\n .filter((stmt) => stmt && !stmt.startsWith(\"--\"))\n .map((stmt) => ({\n sql: stmt.endsWith(\";\") ? stmt : `${stmt};`,\n params: [],\n }));\n\n if (queries.length === 0) {\n return;\n }\n\n // Use driver's _executeBatch which handles priority automatically:\n // 1. Native batch if supportsBatch\n // 2. Transaction wrapper if supportsTransactions\n // 3. Sequential execution (with warning in _executeBatch)\n await this.driver._executeBatch(queries);\n }\n}\n","import {\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { Dialect, MigrationEntry } from \"../types\";\nimport { ensureMigrationsDirs, getMetaDir } from \"./journal\";\n\nconst STATEMENT_BREAKPOINT = \"--> statement-breakpoint\";\n\n/**\n * Format a migration filename from index and name\n * Example: 0000_initial.sql, 0001_add-users.sql\n */\nexport function formatMigrationFilename(idx: number, name: string): string {\n const paddedIdx = String(idx).padStart(4, \"0\");\n return `${paddedIdx}_${name}.sql`;\n}\n\n/**\n * Get the full path to a migration file\n */\nexport function getMigrationFilePath(\n migrationsDir: string,\n entry: MigrationEntry\n): string {\n const filename = formatMigrationFilename(entry.idx, entry.name);\n return join(migrationsDir, filename);\n}\n\n/**\n * Add statement breakpoints between SQL statements\n * This helps with parsing and applying migrations statement by statement\n */\nexport function addStatementBreakpoints(\n statements: string[],\n _dialect: Dialect\n): string {\n if (statements.length === 0) {\n return \"\";\n }\n\n // Join statements with breakpoint markers\n return statements\n .map((stmt) => stmt.trim())\n .filter((stmt) => stmt.length > 0)\n .join(`\\n${STATEMENT_BREAKPOINT}\\n`);\n}\n\n/**\n * Parse a migration file content back into individual statements.\n * Removes header comments (lines starting with --) and empty lines.\n */\nexport function parseStatements(content: string): string[] {\n if (!content.trim()) {\n return [];\n }\n\n // First split by breakpoint marker\n const segments = content.split(STATEMENT_BREAKPOINT);\n\n const statements: string[] = [];\n\n for (const segment of segments) {\n // Remove comment lines from each segment\n const lines = segment.split(\"\\n\");\n const filteredLines: string[] = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n // Skip comment-only lines\n if (trimmed.startsWith(\"--\")) continue;\n // Keep the line (even if empty, to preserve formatting within statements)\n filteredLines.push(line);\n }\n\n const stmt = filteredLines.join(\"\\n\").trim();\n if (stmt.length > 0) {\n statements.push(stmt);\n }\n }\n\n return statements;\n}\n\n/**\n * Write a migration file to disk\n */\nexport function writeMigrationFile(\n migrationsDir: string,\n entry: MigrationEntry,\n content: string\n): string {\n ensureMigrationsDirs(migrationsDir);\n const filePath = getMigrationFilePath(migrationsDir, entry);\n writeFileSync(filePath, content, \"utf-8\");\n return filePath;\n}\n\n/**\n * Read a migration file from disk\n */\nexport function readMigrationFile(\n migrationsDir: string,\n entry: MigrationEntry\n): string | null {\n const filePath = getMigrationFilePath(migrationsDir, entry);\n\n if (!existsSync(filePath)) {\n return null;\n }\n\n return readFileSync(filePath, \"utf-8\");\n}\n\n/**\n * Check if a migration file exists\n */\nexport function migrationFileExists(\n migrationsDir: string,\n entry: MigrationEntry\n): boolean {\n const filePath = getMigrationFilePath(migrationsDir, entry);\n return existsSync(filePath);\n}\n\n/**\n * Generate a header comment for the migration file\n */\nexport function generateMigrationHeader(entry: MigrationEntry): string {\n const date = new Date(entry.when).toISOString();\n return `-- Migration: ${entry.name}\n-- Generated: ${date}\n-- Checksum: ${entry.checksum}\n`;\n}\n\n/**\n * Format complete migration file content with header and statements\n */\nexport function formatMigrationContent(\n entry: MigrationEntry,\n statements: string[],\n dialect: Dialect\n): string {\n const header = generateMigrationHeader(entry);\n const body = addStatementBreakpoints(statements, dialect);\n return `${header}\\n${body}\\n`;\n}\n\n// =============================================================================\n// BACKUP & CLEANUP\n// =============================================================================\n\nconst BACKUP_DIR = \"_backup\";\n\n/**\n * Get the path to the backup directory\n */\nexport function getBackupDir(migrationsDir: string): string {\n return join(getMetaDir(migrationsDir), BACKUP_DIR);\n}\n\n/**\n * Ensure the backup directory exists\n */\nexport function ensureBackupDir(migrationsDir: string): void {\n const backupDir = getBackupDir(migrationsDir);\n if (!existsSync(backupDir)) {\n mkdirSync(backupDir, { recursive: true });\n }\n}\n\n/**\n * Backup a migration file before modification or deletion.\n * Creates a timestamped copy in meta/_backup/\n *\n * @param migrationsDir - The migrations directory\n * @param entry - The migration entry to backup\n * @returns The backup file path, or null if the original file doesn't exist\n */\nexport function backupMigrationFile(\n migrationsDir: string,\n entry: MigrationEntry\n): string | null {\n const sourcePath = getMigrationFilePath(migrationsDir, entry);\n\n if (!existsSync(sourcePath)) {\n return null;\n }\n\n ensureBackupDir(migrationsDir);\n const backupDir = getBackupDir(migrationsDir);\n\n // Create timestamped backup filename\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const originalFilename = formatMigrationFilename(entry.idx, entry.name);\n const backupFilename = `${timestamp}_${originalFilename}`;\n const backupPath = join(backupDir, backupFilename);\n\n // Copy the file to backup\n const content = readFileSync(sourcePath, \"utf-8\");\n writeFileSync(backupPath, content, \"utf-8\");\n\n return backupPath;\n}\n\n/**\n * Delete a migration file from disk.\n *\n * @param migrationsDir - The migrations directory\n * @param entry - The migration entry to delete\n * @param backup - Whether to backup before deletion (default: true)\n * @returns Object with deleted flag and optional backup path\n */\nexport function deleteMigrationFile(\n migrationsDir: string,\n entry: MigrationEntry,\n backup = true\n): { deleted: boolean; backupPath: string | null } {\n const filePath = getMigrationFilePath(migrationsDir, entry);\n\n if (!existsSync(filePath)) {\n return { deleted: false, backupPath: null };\n }\n\n let backupPath: string | null = null;\n if (backup) {\n backupPath = backupMigrationFile(migrationsDir, entry);\n }\n\n unlinkSync(filePath);\n return { deleted: true, backupPath };\n}\n\n/**\n * Move a migration file to the backup directory.\n * Useful for squash cleanup where we want to preserve but not keep in main dir.\n *\n * @param migrationsDir - The migrations directory\n * @param entry - The migration entry to move\n * @returns The new backup path, or null if the original file doesn't exist\n */\nexport function archiveMigrationFile(\n migrationsDir: string,\n entry: MigrationEntry\n): string | null {\n const sourcePath = getMigrationFilePath(migrationsDir, entry);\n\n if (!existsSync(sourcePath)) {\n return null;\n }\n\n ensureBackupDir(migrationsDir);\n const backupDir = getBackupDir(migrationsDir);\n\n // Create timestamped archive filename\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const originalFilename = formatMigrationFilename(entry.idx, entry.name);\n const archiveFilename = `${timestamp}_${originalFilename}`;\n const archivePath = join(backupDir, archiveFilename);\n\n // Move the file\n renameSync(sourcePath, archivePath);\n\n return archivePath;\n}\n","/**\n * Migration Storage Driver\n *\n * Abstract base class for migration file storage.\n * Concrete implementations handle filesystem, S3, database, etc.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type {\n Dialect,\n MigrationEntry,\n MigrationJournal,\n SchemaSnapshot,\n} from \"../types\";\n\n// =============================================================================\n// CONSTANTS\n// =============================================================================\n\nconst JOURNAL_VERSION = \"1\";\nconst JOURNAL_PATH = \"meta/_journal.json\";\nconst SNAPSHOT_PATH = \"meta/_snapshot.json\";\nconst BACKUP_PREFIX = \"meta/_backup/\";\n\n// =============================================================================\n// ABSTRACT STORAGE DRIVER\n// =============================================================================\n\n/**\n * Abstract base class for migration storage drivers.\n * Provides high-level operations for managing migration files.\n *\n * Concrete drivers must implement:\n * - `get(path)`: Read file content\n * - `put(path, content)`: Write file content\n * - `delete(path)`: Delete file\n */\nexport abstract class MigrationStorageDriver {\n readonly driverName: string;\n\n constructor(driverName: string) {\n this.driverName = driverName;\n }\n\n // ===========================================================================\n // ABSTRACT METHODS - Concrete drivers implement these\n // ===========================================================================\n\n /**\n * Read file content.\n * @param path - Relative path (e.g., \"0000_initial.sql\", \"meta/_journal.json\")\n * @returns File content as string, or null if file doesn't exist\n */\n abstract get(path: string): Promise<string | null>;\n\n /**\n * Write file content. Creates directories as needed.\n * @param path - Relative path\n * @param content - Content to write\n */\n abstract put(path: string, content: string): Promise<void>;\n\n /**\n * Delete a file. No-op if file doesn't exist.\n * @param path - Relative path\n */\n abstract delete(path: string): Promise<void>;\n\n // ===========================================================================\n // JOURNAL\n // ===========================================================================\n\n /**\n * Read the migration journal.\n * Returns null if no journal exists.\n */\n async readJournal(): Promise<MigrationJournal | null> {\n const content = await this.get(JOURNAL_PATH);\n if (!content) {\n return null;\n }\n return JSON.parse(content) as MigrationJournal;\n }\n\n /**\n * Write the migration journal.\n */\n async writeJournal(journal: MigrationJournal): Promise<void> {\n await this.put(JOURNAL_PATH, JSON.stringify(journal, null, 2));\n }\n\n /**\n * Get or create a journal for the given dialect.\n */\n async getOrCreateJournal(dialect: Dialect): Promise<MigrationJournal> {\n const existing = await this.readJournal();\n if (existing) {\n if (existing.dialect !== dialect) {\n throw new Error(\n `Journal dialect mismatch: expected \"${dialect}\", found \"${existing.dialect}\". ` +\n \"Cannot mix migrations from different database dialects.\"\n );\n }\n return existing;\n }\n return createEmptyJournal(dialect);\n }\n\n // ===========================================================================\n // SNAPSHOT\n // ===========================================================================\n\n /**\n * Read the schema snapshot.\n * Returns null if no snapshot exists.\n */\n async readSnapshot(): Promise<SchemaSnapshot | null> {\n const content = await this.get(SNAPSHOT_PATH);\n if (!content) {\n return null;\n }\n return JSON.parse(content) as SchemaSnapshot;\n }\n\n /**\n * Write the schema snapshot.\n */\n async writeSnapshot(snapshot: SchemaSnapshot): Promise<void> {\n await this.put(SNAPSHOT_PATH, JSON.stringify(snapshot, null, 2));\n }\n\n /**\n * Get the snapshot or return an empty one.\n */\n async getSnapshotOrEmpty(): Promise<SchemaSnapshot> {\n return (await this.readSnapshot()) ?? createEmptySnapshot();\n }\n\n // ===========================================================================\n // MIGRATION FILES\n // ===========================================================================\n\n /**\n * Read a migration file content.\n */\n async readMigration(entry: MigrationEntry): Promise<string | null> {\n const path = formatMigrationPath(entry);\n return this.get(path);\n }\n\n /**\n * Write a migration file.\n */\n async writeMigration(entry: MigrationEntry, content: string): Promise<void> {\n const path = formatMigrationPath(entry);\n await this.put(path, content);\n }\n\n /**\n * Delete a migration file.\n */\n async deleteMigration(entry: MigrationEntry): Promise<void> {\n const path = formatMigrationPath(entry);\n await this.delete(path);\n }\n\n /**\n * Check if a migration file exists.\n */\n async migrationExists(entry: MigrationEntry): Promise<boolean> {\n const content = await this.readMigration(entry);\n return content !== null;\n }\n\n // ===========================================================================\n // DOWN MIGRATIONS\n // ===========================================================================\n\n /**\n * Read a down migration file if it exists.\n */\n async readDownMigration(entry: MigrationEntry): Promise<string | null> {\n const path = `meta/_down/${formatMigrationFilename(entry)}`;\n return this.get(path);\n }\n\n /**\n * Write a down migration file.\n */\n async writeDownMigration(\n entry: MigrationEntry,\n content: string\n ): Promise<void> {\n const path = `meta/_down/${formatMigrationFilename(entry)}`;\n await this.put(path, content);\n }\n\n // ===========================================================================\n // BACKUP\n // ===========================================================================\n\n /**\n * Backup a migration file to the backup directory.\n * Returns the backup path, or null if the file doesn't exist.\n */\n async backupMigration(entry: MigrationEntry): Promise<string | null> {\n const content = await this.readMigration(entry);\n if (!content) {\n return null;\n }\n\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const backupPath = `${BACKUP_PREFIX}${timestamp}_${formatMigrationFilename(entry)}`;\n await this.put(backupPath, content);\n return backupPath;\n }\n\n /**\n * Archive a migration (backup and delete).\n * Returns the backup path, or null if the file doesn't exist.\n */\n async archiveMigration(entry: MigrationEntry): Promise<string | null> {\n const backupPath = await this.backupMigration(entry);\n if (backupPath) {\n await this.deleteMigration(entry);\n }\n return backupPath;\n }\n}\n\n// =============================================================================\n// HELPERS\n// =============================================================================\n\n/**\n * Format migration filename from entry.\n */\nexport function formatMigrationFilename(entry: MigrationEntry): string {\n const paddedIdx = String(entry.idx).padStart(4, \"0\");\n return `${paddedIdx}_${entry.name}.sql`;\n}\n\n/**\n * Format migration path from entry.\n */\nexport function formatMigrationPath(entry: MigrationEntry): string {\n return formatMigrationFilename(entry);\n}\n\n/**\n * Create an empty journal.\n */\nexport function createEmptyJournal(dialect: Dialect): MigrationJournal {\n return {\n version: JOURNAL_VERSION,\n dialect,\n entries: [],\n };\n}\n\n/**\n * Create an empty snapshot.\n */\nexport function createEmptySnapshot(): SchemaSnapshot {\n return {\n tables: [],\n enums: [],\n };\n}\n\n/**\n * Get the next migration index.\n */\nexport function getNextMigrationIndex(\n journal: MigrationJournal | null\n): number {\n if (!journal || journal.entries.length === 0) {\n return 0;\n }\n const lastEntry = journal.entries[journal.entries.length - 1];\n return lastEntry ? lastEntry.idx + 1 : 0;\n}\n\n/**\n * Generate a timestamp version string (YYYYMMDDHHmmss).\n */\nexport function generateVersion(): 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/**\n * Calculate SHA256 checksum.\n */\nexport function calculateChecksum(content: string): string {\n return createHash(\"sha256\").update(content, \"utf-8\").digest(\"hex\");\n}\n\n/**\n * Convert a name to kebab-case.\n */\nexport function toKebabCase(name: string): string {\n return name\n .replace(/([a-z])([A-Z])/g, \"$1-$2\")\n .replace(/[\\s_]+/g, \"-\")\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\n/**\n * Create a migration entry.\n */\nexport function createMigrationEntry(\n idx: number,\n name: string,\n sqlContent: string,\n tag?: string\n): MigrationEntry {\n const kebabName = toKebabCase(name);\n const version = generateVersion();\n const checksum = calculateChecksum(sqlContent);\n\n return {\n idx,\n version,\n name: kebabName,\n when: Date.now(),\n checksum,\n ...(tag ? { tag } : {}),\n };\n}\n\n/**\n * Add an entry to the journal.\n */\nexport function addJournalEntry(\n journal: MigrationJournal,\n entry: MigrationEntry\n): MigrationJournal {\n return {\n ...journal,\n entries: [...journal.entries, entry],\n };\n}\n\n/**\n * Validate journal dialect.\n */\nexport function validateJournalDialect(\n journal: MigrationJournal,\n expectedDialect: Dialect\n): void {\n if (journal.dialect !== expectedDialect) {\n throw new Error(\n `Journal dialect mismatch: expected \"${expectedDialect}\", found \"${journal.dialect}\". ` +\n \"Cannot apply migrations from a different database dialect.\"\n );\n }\n}\n","/**\n * Migration Apply\n *\n * Applies pending migrations to the database.\n * Similar to `drizzle-kit push` or `prisma migrate deploy`.\n */\n\nimport { MigrationError, VibORMErrorCode } from \"../../errors\";\nimport { MigrationContext } from \"../context\";\nimport { parseStatements } from \"../generate/file-writer\";\nimport type { MigrationClient } from \"../push\";\nimport {\n type MigrationStorageDriver,\n validateJournalDialect,\n} from \"../storage\";\nimport type {\n AppliedMigration,\n ApplyOptions,\n MigrationEntry,\n MigrationStatus,\n} from \"../types\";\n\nexport interface ApplyFullOptions extends ApplyOptions {\n /** Migrations directory */\n dir?: string;\n /** Name of the migrations tracking table */\n tableName?: string;\n /** Storage driver for migration files */\n storageDriver: MigrationStorageDriver;\n}\n\n/**\n * Result of applying migrations.\n * Throws MigrationError on failure instead of returning error object.\n */\nexport interface ApplyResult {\n /** Migrations that were applied */\n applied: MigrationEntry[];\n /** Migrations that are still pending */\n pending: MigrationEntry[];\n}\n\n/**\n * Applies pending migrations to the database.\n * Throws MigrationError on failure.\n *\n * @param client - VibORM client with driver\n * @param options - Apply options\n * @returns Apply result with applied and pending migrations\n * @throws MigrationError if migration fails\n */\nexport async function apply(\n client: MigrationClient,\n options: ApplyFullOptions\n): Promise<ApplyResult> {\n const { to, dryRun = false, dir, tableName, storageDriver } = options;\n\n // Use MigrationContext for proper driver delegation\n const ctx = new MigrationContext(client, { dir, tableName, storageDriver });\n\n // 1. Ensure migrations tracking table exists\n if (!dryRun) {\n await ctx.ensureTrackingTable();\n }\n\n // 2. Read migration journal\n const journal = await ctx.storage.readJournal();\n\n if (!journal) {\n return {\n applied: [],\n pending: [],\n };\n }\n\n // Validate dialect matches\n validateJournalDialect(journal, ctx.dialect);\n\n // 3. Get applied migrations from database\n const appliedMigrations = dryRun ? [] : await ctx.getAppliedMigrations();\n\n const appliedNames = new Set(appliedMigrations.map((m) => m.name));\n\n // 4. Determine which migrations to apply\n let entriesToApply = journal.entries.filter(\n (entry) => !appliedNames.has(entry.name)\n );\n\n // If `to` is specified, limit to migrations up to that index\n if (to !== undefined) {\n entriesToApply = entriesToApply.filter((entry) => entry.idx <= to);\n }\n\n // 5. Verify checksums for already-applied migrations\n for (const appliedMigration of appliedMigrations) {\n const journalEntry = journal.entries.find(\n (e) => e.name === appliedMigration.name\n );\n if (journalEntry && journalEntry.checksum !== appliedMigration.checksum) {\n throw new MigrationError(\n `Migration \"${appliedMigration.name}\" has been modified after being applied. ` +\n `Database has checksum ${appliedMigration.checksum}, ` +\n `but file has checksum ${journalEntry.checksum}. ` +\n \"Migrations should not be modified after being applied.\",\n VibORMErrorCode.MIGRATION_CHECKSUM_MISMATCH,\n {\n meta: {\n migrationName: appliedMigration.name,\n expectedChecksum: appliedMigration.checksum,\n actualChecksum: journalEntry.checksum,\n },\n }\n );\n }\n }\n\n // 6. Apply pending migrations\n const applied: MigrationEntry[] = [];\n\n if (dryRun) {\n // For dry run, just return what would be applied\n return {\n applied: [],\n pending: entriesToApply,\n };\n }\n\n for (const entry of entriesToApply) {\n // Read migration file\n const content = await ctx.storage.readMigration(entry);\n if (!content) {\n throw new MigrationError(\n `Migration file not found for \"${entry.name}\"`,\n VibORMErrorCode.MIGRATION_FILE_NOT_FOUND,\n { meta: { migrationName: entry.name } }\n );\n }\n\n // Parse statements\n const statements = parseStatements(content);\n\n try {\n // Execute migration in a transaction\n await ctx.transaction(async (txCtx) => {\n await txCtx.executeMigrationStatements(statements);\n await txCtx.markMigrationApplied(entry);\n });\n\n applied.push(entry);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new MigrationError(\n `Failed to apply migration \"${entry.name}\": ${message}`,\n VibORMErrorCode.MIGRATION_FAILED,\n {\n cause: err instanceof Error ? err : undefined,\n meta: { migrationName: entry.name },\n }\n );\n }\n }\n\n return {\n applied,\n pending: [],\n };\n}\n\n/**\n * Get the status of all migrations (applied vs pending).\n */\nexport async function status(\n client: MigrationClient,\n options: {\n dir?: string;\n tableName?: string;\n storageDriver: MigrationStorageDriver;\n }\n): Promise<MigrationStatus[]> {\n const { dir, tableName, storageDriver } = options;\n\n // Use MigrationContext for proper driver delegation\n const ctx = new MigrationContext(client, { dir, tableName, storageDriver });\n\n // Read journal\n const journal = await ctx.storage.readJournal();\n\n if (!journal) {\n return [];\n }\n\n // Get applied migrations\n let appliedMigrations: AppliedMigration[];\n try {\n appliedMigrations = await ctx.getAppliedMigrations();\n } catch {\n // Table doesn't exist yet, no migrations applied\n appliedMigrations = [];\n }\n\n const appliedMap = new Map(appliedMigrations.map((m) => [m.name, m]));\n\n // Build status list\n return journal.entries.map((entry) => {\n const appliedMigration = appliedMap.get(entry.name);\n return {\n entry,\n applied: !!appliedMigration,\n appliedAt: appliedMigration?.appliedAt,\n };\n });\n}\n\n/**\n * Get pending migrations that haven't been applied yet.\n */\nexport async function pending(\n client: MigrationClient,\n options: {\n dir?: string;\n tableName?: string;\n storageDriver: MigrationStorageDriver;\n }\n): Promise<MigrationEntry[]> {\n const statuses = await status(client, options);\n return statuses.filter((s) => !s.applied).map((s) => s.entry);\n}\n\n/**\n * Rollback the last N migrations (marks them as not applied).\n * Note: This does NOT run down migrations - it only removes from tracking table.\n */\nexport async function rollback(\n client: MigrationClient,\n options: {\n count?: number;\n dir?: string;\n tableName?: string;\n storageDriver: MigrationStorageDriver;\n }\n): Promise<MigrationEntry[]> {\n const { count = 1, dir, tableName, storageDriver } = options;\n\n // Use MigrationContext for proper driver delegation\n const ctx = new MigrationContext(client, { dir, tableName, storageDriver });\n\n // Read journal\n const journal = await ctx.storage.readJournal();\n\n if (!journal) {\n return [];\n }\n\n // Get applied migrations\n const appliedMigrations = await ctx.getAppliedMigrations();\n\n // Get the last N applied migrations\n const toRollback = appliedMigrations.slice(-count).reverse();\n\n // Remove from tracking table\n const rolledBack: MigrationEntry[] = [];\n\n for (const applied of toRollback) {\n const entry = journal.entries.find((e) => e.name === applied.name);\n if (!entry) continue;\n\n await ctx.markMigrationRolledBack(applied.name);\n rolledBack.push(entry);\n }\n\n return rolledBack;\n}\n","/**\n * Schema Differ\n *\n * Compares two SchemaSnapshots and produces a list of DiffOperations,\n * detecting ambiguous changes that require user input.\n */\n\nimport type {\n AmbiguousChange,\n ColumnDef,\n DiffOperation,\n DiffResult,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\nfunction columnsEqual(a: ColumnDef, b: ColumnDef): boolean {\n return (\n a.name === b.name &&\n normalizeType(a.type) === normalizeType(b.type) &&\n a.nullable === b.nullable &&\n normalizeDefault(a.default) === normalizeDefault(b.default)\n );\n}\n\nfunction normalizeType(type: string): string {\n // Normalize type names for comparison\n const normalized = type.toLowerCase().trim();\n\n // Handle common aliases\n const aliases: Record<string, string> = {\n int4: \"integer\",\n int8: \"bigint\",\n int2: \"smallint\",\n float4: \"real\",\n float8: \"double precision\",\n bool: \"boolean\",\n timestamptz: \"timestamp with time zone\",\n timetz: \"time with time zone\",\n };\n\n return aliases[normalized] || normalized;\n}\n\nfunction normalizeDefault(defaultVal: string | undefined): string | undefined {\n if (defaultVal === undefined) return undefined;\n\n // Normalize common default expressions\n const normalized = defaultVal.trim().toLowerCase();\n\n // Handle NULL\n if (normalized === \"null\") return \"null\";\n\n // Handle boolean values\n if (normalized === \"true\" || normalized === \"'t'\" || normalized === \"1\")\n return \"true\";\n if (normalized === \"false\" || normalized === \"'f'\" || normalized === \"0\")\n return \"false\";\n\n return defaultVal;\n}\n\nfunction indexesEqual(a: IndexDef, b: IndexDef): boolean {\n return (\n a.name === b.name &&\n a.unique === b.unique &&\n arraysEqual(a.columns, b.columns) &&\n a.type === b.type &&\n a.where === b.where\n );\n}\n\nfunction foreignKeysEqual(a: ForeignKeyDef, b: ForeignKeyDef): boolean {\n return (\n a.name === b.name &&\n arraysEqual(a.columns, b.columns) &&\n a.referencedTable === b.referencedTable &&\n arraysEqual(a.referencedColumns, b.referencedColumns) &&\n a.onDelete === b.onDelete &&\n a.onUpdate === b.onUpdate\n );\n}\n\nfunction uniqueConstraintsEqual(\n a: UniqueConstraintDef,\n b: UniqueConstraintDef\n): boolean {\n return a.name === b.name && arraysEqual(a.columns, b.columns);\n}\n\nfunction arraysEqual<T>(a: T[], b: T[]): boolean {\n if (a.length !== b.length) return false;\n return a.every((val, idx) => val === b[idx]);\n}\n\nfunction enumsEqual(a: EnumDef, b: EnumDef): boolean {\n return a.name === b.name && arraysEqual(a.values, b.values);\n}\n\n// =============================================================================\n// TABLE DIFFER\n// =============================================================================\n\ninterface TableDiffResult {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n}\n\nfunction diffTable(\n tableName: string,\n current: TableDef,\n desired: TableDef\n): TableDiffResult {\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n // Build column maps\n const currentColumns = new Map(current.columns.map((c) => [c.name, c]));\n const desiredColumns = new Map(desired.columns.map((c) => [c.name, c]));\n\n // Find dropped and added columns\n const droppedColumns: ColumnDef[] = [];\n const addedColumns: ColumnDef[] = [];\n\n for (const [name, col] of currentColumns) {\n if (!desiredColumns.has(name)) {\n droppedColumns.push(col);\n }\n }\n\n for (const [name, col] of desiredColumns) {\n if (!currentColumns.has(name)) {\n addedColumns.push(col);\n }\n }\n\n // Detect potential column renames (ambiguous changes)\n // A rename is suspected when a column is dropped and another is added\n // with compatible types\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n for (const dropped of droppedColumns) {\n for (const added of addedColumns) {\n if (usedDropped.has(dropped.name) || usedAdded.has(added.name)) continue;\n\n // Check if types are compatible (could be a rename)\n const droppedType = normalizeType(dropped.type);\n const addedType = normalizeType(added.type);\n\n if (droppedType === addedType) {\n // This could be a rename - mark as ambiguous\n ambiguousChanges.push({\n type: \"ambiguousColumn\",\n tableName,\n droppedColumn: dropped,\n addedColumn: added,\n });\n usedDropped.add(dropped.name);\n usedAdded.add(added.name);\n }\n }\n }\n\n // Add operations for non-ambiguous drops and adds\n for (const dropped of droppedColumns) {\n if (!usedDropped.has(dropped.name)) {\n operations.push({\n type: \"dropColumn\",\n tableName,\n columnName: dropped.name,\n });\n }\n }\n\n for (const added of addedColumns) {\n if (!usedAdded.has(added.name)) {\n operations.push({\n type: \"addColumn\",\n tableName,\n column: added,\n });\n }\n }\n\n // Check for column modifications (same name, different properties)\n for (const [name, desiredCol] of desiredColumns) {\n const currentCol = currentColumns.get(name);\n if (currentCol && !columnsEqual(currentCol, desiredCol)) {\n operations.push({\n type: \"alterColumn\",\n tableName,\n columnName: name,\n from: currentCol,\n to: desiredCol,\n });\n }\n }\n\n // Diff indexes\n const currentIndexes = new Map(current.indexes.map((i) => [i.name, i]));\n const desiredIndexes = new Map(desired.indexes.map((i) => [i.name, i]));\n\n for (const [name, idx] of currentIndexes) {\n const desiredIdx = desiredIndexes.get(name);\n if (!desiredIdx) {\n operations.push({ type: \"dropIndex\", tableName, indexName: name });\n } else if (!indexesEqual(idx, desiredIdx)) {\n // Index changed - drop and recreate\n operations.push({ type: \"dropIndex\", tableName, indexName: name });\n operations.push({ type: \"createIndex\", tableName, index: desiredIdx });\n }\n }\n\n for (const [name, idx] of desiredIndexes) {\n if (!currentIndexes.has(name)) {\n operations.push({ type: \"createIndex\", tableName, index: idx });\n }\n }\n\n // Diff foreign keys\n const currentFks = new Map(current.foreignKeys.map((fk) => [fk.name, fk]));\n const desiredFks = new Map(desired.foreignKeys.map((fk) => [fk.name, fk]));\n\n for (const [name, fk] of currentFks) {\n const desiredFk = desiredFks.get(name);\n if (!desiredFk) {\n operations.push({ type: \"dropForeignKey\", tableName, fkName: name });\n } else if (!foreignKeysEqual(fk, desiredFk)) {\n // FK changed - drop and recreate\n operations.push({ type: \"dropForeignKey\", tableName, fkName: name });\n operations.push({ type: \"addForeignKey\", tableName, fk: desiredFk });\n }\n }\n\n for (const [name, fk] of desiredFks) {\n if (!currentFks.has(name)) {\n operations.push({ type: \"addForeignKey\", tableName, fk });\n }\n }\n\n // Diff unique constraints\n const currentUniques = new Map(\n current.uniqueConstraints.map((u) => [u.name, u])\n );\n const desiredUniques = new Map(\n desired.uniqueConstraints.map((u) => [u.name, u])\n );\n\n for (const [name, uq] of currentUniques) {\n const desiredUq = desiredUniques.get(name);\n if (!desiredUq) {\n operations.push({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: name,\n });\n } else if (!uniqueConstraintsEqual(uq, desiredUq)) {\n operations.push({\n type: \"dropUniqueConstraint\",\n tableName,\n constraintName: name,\n });\n operations.push({\n type: \"addUniqueConstraint\",\n tableName,\n constraint: desiredUq,\n });\n }\n }\n\n for (const [name, uq] of desiredUniques) {\n if (!currentUniques.has(name)) {\n operations.push({\n type: \"addUniqueConstraint\",\n tableName,\n constraint: uq,\n });\n }\n }\n\n // Diff primary key\n const currentPk = current.primaryKey;\n const desiredPk = desired.primaryKey;\n\n if (currentPk && !desiredPk) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n } else if (!currentPk && desiredPk) {\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n } else if (\n currentPk &&\n desiredPk &&\n !arraysEqual(currentPk.columns, desiredPk.columns)\n ) {\n operations.push({\n type: \"dropPrimaryKey\",\n tableName,\n constraintName: currentPk.name || `${tableName}_pkey`,\n });\n operations.push({\n type: \"addPrimaryKey\",\n tableName,\n primaryKey: desiredPk,\n });\n }\n\n return { operations, ambiguousChanges };\n}\n\n// =============================================================================\n// MAIN DIFFER\n// =============================================================================\n\n/**\n * Compares two schema snapshots and returns the operations needed to\n * transform the current schema into the desired schema.\n */\nexport function diff(\n current: SchemaSnapshot,\n desired: SchemaSnapshot\n): DiffResult {\n const operations: DiffOperation[] = [];\n const ambiguousChanges: AmbiguousChange[] = [];\n\n // Build table maps\n const currentTables = new Map(current.tables.map((t) => [t.name, t]));\n const desiredTables = new Map(desired.tables.map((t) => [t.name, t]));\n\n // Find dropped and added tables\n const droppedTables: string[] = [];\n const addedTables: string[] = [];\n\n for (const [name] of currentTables) {\n if (!desiredTables.has(name)) {\n droppedTables.push(name);\n }\n }\n\n for (const [name] of desiredTables) {\n if (!currentTables.has(name)) {\n addedTables.push(name);\n }\n }\n\n // Detect potential table renames (ambiguous changes)\n const usedDropped = new Set<string>();\n const usedAdded = new Set<string>();\n\n // For table renames, we check if the structure is similar\n for (const droppedName of droppedTables) {\n const droppedTable = currentTables.get(droppedName)!;\n\n for (const addedName of addedTables) {\n if (usedDropped.has(droppedName) || usedAdded.has(addedName)) continue;\n\n const addedTable = desiredTables.get(addedName)!;\n\n // Check if tables have similar structure (same column names)\n const droppedColNames = new Set(droppedTable.columns.map((c) => c.name));\n const addedColNames = new Set(addedTable.columns.map((c) => c.name));\n\n // Calculate similarity (Jaccard index)\n const intersection = [...droppedColNames].filter((n) =>\n addedColNames.has(n)\n );\n const union = new Set([...droppedColNames, ...addedColNames]);\n const similarity = intersection.length / union.size;\n\n // If tables are very similar (>= 70% column overlap), suggest rename\n if (similarity >= 0.7) {\n ambiguousChanges.push({\n type: \"ambiguousTable\",\n droppedTable: droppedName,\n addedTable: addedName,\n });\n usedDropped.add(droppedName);\n usedAdded.add(addedName);\n }\n }\n }\n\n // Add operations for non-ambiguous table drops and creates\n for (const name of droppedTables) {\n if (!usedDropped.has(name)) {\n operations.push({ type: \"dropTable\", tableName: name });\n }\n }\n\n for (const name of addedTables) {\n if (!usedAdded.has(name)) {\n const table = desiredTables.get(name)!;\n operations.push({ type: \"createTable\", table });\n }\n }\n\n // Diff existing tables\n for (const [name, desiredTable] of desiredTables) {\n const currentTable = currentTables.get(name);\n if (currentTable) {\n const tableDiff = diffTable(name, currentTable, desiredTable);\n operations.push(...tableDiff.operations);\n ambiguousChanges.push(...tableDiff.ambiguousChanges);\n }\n }\n\n // Diff enums (PostgreSQL specific)\n if (current.enums || desired.enums) {\n const currentEnums = new Map((current.enums || []).map((e) => [e.name, e]));\n const desiredEnums = new Map((desired.enums || []).map((e) => [e.name, e]));\n\n // Dropped enums\n for (const [name] of currentEnums) {\n if (!desiredEnums.has(name)) {\n // Find all columns that depend on this enum\n const dependentColumns: Array<{\n tableName: string;\n columnName: string;\n }> = [];\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n operations.push({\n type: \"dropEnum\",\n enumName: name,\n dependentColumns:\n dependentColumns.length > 0 ? dependentColumns : undefined,\n });\n }\n }\n\n // Added enums\n for (const [name, enumDef] of desiredEnums) {\n if (!currentEnums.has(name)) {\n operations.push({ type: \"createEnum\", enumDef });\n }\n }\n\n // Modified enums\n for (const [name, desiredEnum] of desiredEnums) {\n const currentEnum = currentEnums.get(name);\n if (currentEnum && !enumsEqual(currentEnum, desiredEnum)) {\n const addValues = desiredEnum.values.filter(\n (v) => !currentEnum.values.includes(v)\n );\n const removeValues = currentEnum.values.filter(\n (v) => !desiredEnum.values.includes(v)\n );\n\n if (addValues.length > 0 || removeValues.length > 0) {\n // When removing values, we need to find all columns that use this enum\n // so we can temporarily convert them to text during the recreation\n let dependentColumns:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n\n if (removeValues.length > 0) {\n dependentColumns = [];\n // Search through all tables (current schema) for columns using this enum\n for (const table of current.tables) {\n for (const column of table.columns) {\n if (column.type === name) {\n dependentColumns.push({\n tableName: table.name,\n columnName: column.name,\n });\n }\n }\n }\n }\n\n operations.push({\n type: \"alterEnum\",\n enumName: name,\n addValues: addValues.length > 0 ? addValues : undefined,\n removeValues: removeValues.length > 0 ? removeValues : undefined,\n newValues: removeValues.length > 0 ? desiredEnum.values : undefined,\n dependentColumns:\n dependentColumns && dependentColumns.length > 0\n ? dependentColumns\n : undefined,\n });\n }\n }\n }\n }\n\n // Sort operations for proper execution order\n return {\n operations: sortOperations(operations),\n ambiguousChanges,\n };\n}\n\n// =============================================================================\n// DESTRUCTIVE OPERATION CHECKS\n// =============================================================================\n\n/**\n * Checks if any operations are destructive (could cause data loss)\n */\nexport function hasDestructiveOperations(operations: DiffOperation[]): boolean {\n return operations.some(\n (op) =>\n op.type === \"dropTable\" ||\n op.type === \"dropColumn\" ||\n (op.type === \"alterColumn\" &&\n // Type changes or making non-nullable are potentially destructive\n (normalizeType(op.from.type) !== normalizeType(op.to.type) ||\n (op.from.nullable && !op.to.nullable)))\n );\n}\n\n/**\n * Gets a human-readable description of destructive operations\n */\nexport function getDestructiveOperationDescriptions(\n operations: DiffOperation[]\n): string[] {\n const descriptions: string[] = [];\n\n for (const op of operations) {\n if (op.type === \"dropTable\") {\n descriptions.push(`Drop table \"${op.tableName}\" (all data will be lost)`);\n } else if (op.type === \"dropColumn\") {\n descriptions.push(\n `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`\n );\n } else if (op.type === \"alterColumn\") {\n if (normalizeType(op.from.type) !== normalizeType(op.to.type)) {\n descriptions.push(\n `Change type of \"${op.tableName}\".\"${op.columnName}\" from ${op.from.type} to ${op.to.type} (may cause data loss)`\n );\n }\n if (op.from.nullable && !op.to.nullable) {\n descriptions.push(\n `Make \"${op.tableName}\".\"${op.columnName}\" NOT NULL (may fail if column contains NULL values)`\n );\n }\n }\n }\n\n return descriptions;\n}\n","/**\n * Resolver System\n *\n * Handles ambiguous changes that require user input to resolve.\n * Provides utilities for converting user resolutions into concrete operations.\n */\n\nimport type {\n AmbiguousChange,\n ChangeResolution,\n DiffOperation,\n DiffResult,\n ResolveCallback,\n ResolveChange,\n Resolver,\n SchemaSnapshot,\n} from \"./types\";\nimport { sortOperations } from \"./utils\";\n\n// =============================================================================\n// RESOLUTION APPLICATION\n// =============================================================================\n\n/**\n * Converts resolved ambiguous changes into concrete diff operations\n */\nexport function applyResolutions(\n changes: AmbiguousChange[],\n resolutions: Map<AmbiguousChange, ChangeResolution>\n): DiffOperation[] {\n const operations: DiffOperation[] = [];\n\n for (const change of changes) {\n const resolution = resolutions.get(change);\n if (!resolution) {\n // If no resolution provided, default to add+drop (safer)\n if (change.type === \"ambiguousColumn\") {\n operations.push(\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n }\n );\n } else if (change.type === \"ambiguousTable\") {\n operations.push(\n { type: \"dropTable\", tableName: change.droppedTable },\n {\n type: \"createTable\",\n table: {\n name: change.addedTable,\n columns: [],\n indexes: [],\n foreignKeys: [],\n uniqueConstraints: [],\n },\n }\n );\n }\n continue;\n }\n\n if (change.type === \"ambiguousColumn\") {\n if (resolution.type === \"rename\") {\n operations.push({\n type: \"renameColumn\",\n tableName: change.tableName,\n from: change.droppedColumn.name,\n to: change.addedColumn.name,\n });\n\n // If the column properties differ (other than name), also alter it\n if (\n change.droppedColumn.nullable !== change.addedColumn.nullable ||\n change.droppedColumn.default !== change.addedColumn.default\n ) {\n operations.push({\n type: \"alterColumn\",\n tableName: change.tableName,\n columnName: change.addedColumn.name,\n from: { ...change.droppedColumn, name: change.addedColumn.name },\n to: change.addedColumn,\n });\n }\n } else {\n // addAndDrop\n operations.push(\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n }\n );\n }\n } else if (change.type === \"ambiguousTable\") {\n if (resolution.type === \"rename\") {\n operations.push({\n type: \"renameTable\",\n from: change.droppedTable,\n to: change.addedTable,\n });\n } else {\n // addAndDrop - the actual table definition will need to come from the desired schema\n operations.push({ type: \"dropTable\", tableName: change.droppedTable });\n // Note: The createTable operation should be added by the caller with full table definition\n }\n }\n }\n\n return operations;\n}\n\n/**\n * Resolves ambiguous changes and returns the final operations list.\n * Handles both rename and addAndDrop resolutions, including adding\n * createTable operations for table renames resolved as addAndDrop.\n *\n * @param diffResult - The result from the differ containing operations and ambiguous changes\n * @param desiredSnapshot - The desired schema snapshot (used for table definitions)\n * @param resolver - The resolver function to use for ambiguous changes\n * @returns Sorted list of final operations\n */\nexport async function resolveAmbiguousChanges(\n diffResult: DiffResult,\n desiredSnapshot: SchemaSnapshot,\n resolver: Resolver\n): Promise<DiffOperation[]> {\n const finalOperations = [...diffResult.operations];\n\n if (diffResult.ambiguousChanges.length === 0) {\n return finalOperations;\n }\n\n const resolutions = await resolver(diffResult.ambiguousChanges);\n const resolvedOps = applyResolutions(\n diffResult.ambiguousChanges,\n resolutions\n );\n finalOperations.push(...resolvedOps);\n\n // For table renames resolved as addAndDrop, add the createTable\n for (const change of diffResult.ambiguousChanges) {\n if (change.type === \"ambiguousTable\") {\n const resolution = resolutions.get(change);\n if (resolution?.type === \"addAndDrop\") {\n const newTable = desiredSnapshot.tables.find(\n (t) => t.name === change.addedTable\n );\n if (newTable) {\n finalOperations.push({ type: \"createTable\", table: newTable });\n }\n }\n }\n }\n\n return sortOperations(finalOperations);\n}\n\n// =============================================================================\n// DEFAULT RESOLVERS\n// =============================================================================\n\n/**\n * Resolver that always chooses \"rename\" for all ambiguous changes.\n * Useful for preserving data when the intent is clear.\n */\nexport const alwaysRenameResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"rename\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that always chooses \"addAndDrop\" for all ambiguous changes.\n * Useful for clean slate scenarios where data loss is acceptable.\n */\nexport const alwaysAddDropResolver: Resolver = async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n resolutions.set(change, { type: \"addAndDrop\" });\n }\n return resolutions;\n};\n\n/**\n * Resolver that throws an error if any ambiguous changes are detected.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const strictResolver: Resolver = async (changes) => {\n if (changes.length > 0) {\n const descriptions = changes.map((change) => {\n if (change.type === \"ambiguousColumn\") {\n return `Column \"${change.droppedColumn.name}\" was removed and \"${change.addedColumn.name}\" was added in table \"${change.tableName}\"`;\n }\n return `Table \"${change.droppedTable}\" was removed and \"${change.addedTable}\" was added`;\n });\n\n throw new Error(\n `Ambiguous changes detected that require resolution:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Use a custom resolver or the CLI interactive mode to resolve these changes.\"\n );\n }\n return new Map();\n};\n\n// =============================================================================\n// RESOLVER HELPERS\n// =============================================================================\n\n/**\n * Creates a resolver from a simple decision function\n */\nexport function createResolver(\n decide: (\n change: AmbiguousChange\n ) => \"rename\" | \"addAndDrop\" | Promise<\"rename\" | \"addAndDrop\">\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n for (const change of changes) {\n const decision = await decide(change);\n resolutions.set(change, { type: decision });\n }\n return resolutions;\n };\n}\n\n/**\n * Creates a resolver that uses predefined resolutions\n */\nexport function createPredefinedResolver(\n predefined: Array<{\n type: \"column\" | \"table\";\n from: string;\n to: string;\n tableName?: string;\n resolution: \"rename\" | \"addAndDrop\";\n }>\n): Resolver {\n return async (changes) => {\n const resolutions = new Map<AmbiguousChange, ChangeResolution>();\n\n for (const change of changes) {\n const match = predefined.find((p) => {\n if (change.type === \"ambiguousColumn\" && p.type === \"column\") {\n return (\n p.from === change.droppedColumn.name &&\n p.to === change.addedColumn.name &&\n (!p.tableName || p.tableName === change.tableName)\n );\n }\n if (change.type === \"ambiguousTable\" && p.type === \"table\") {\n return p.from === change.droppedTable && p.to === change.addedTable;\n }\n return false;\n });\n\n if (match) {\n resolutions.set(change, { type: match.resolution });\n }\n // If no match found, the change will be handled by the default (add+drop)\n }\n\n return resolutions;\n };\n}\n\n/**\n * Formats ambiguous changes for display\n */\nexport function formatAmbiguousChange(change: AmbiguousChange): string {\n if (change.type === \"ambiguousColumn\") {\n return (\n `Column rename detected in table \"${change.tableName}\":\\n` +\n ` \"${change.droppedColumn.name}\" (${change.droppedColumn.type}) → \"${change.addedColumn.name}\" (${change.addedColumn.type})`\n );\n }\n return (\n \"Table rename detected:\\n\" +\n ` \"${change.droppedTable}\" → \"${change.addedTable}\"`\n );\n}\n\n/**\n * Formats all ambiguous changes for display\n */\nexport function formatAmbiguousChanges(changes: AmbiguousChange[]): string {\n if (changes.length === 0) {\n return \"No ambiguous changes detected.\";\n }\n\n return changes.map(formatAmbiguousChange).join(\"\\n\\n\");\n}\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACKS\n// =============================================================================\n\n/**\n * Rejects all changes requiring resolution.\n * Useful for CI/CD pipelines where human intervention is not possible.\n */\nexport const rejectAllResolver: ResolveCallback = async (change) =>\n change.reject();\n\n/**\n * Accepts destructive changes, treats ambiguous changes as renames,\n * and maps enum value removals to NULL.\n * Useful for development when you know all changes are intentional renames.\n */\nexport const lenientResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.rename();\n }\n\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Accepts destructive changes, treats ambiguous changes as add+drop,\n * and maps enum value removals to NULL.\n * Useful when you don't care about preserving data in ambiguous scenarios.\n */\nexport const addDropResolver: ResolveCallback = async (change) => {\n if (change.type === \"destructive\") {\n return change.proceed();\n }\n if (change.type === \"ambiguous\") {\n return change.addAndDrop();\n }\n // enumValueRemoval: set all removed values to null\n return change.useNull();\n};\n\n/**\n * Creates a unified resolver from a decision function.\n *\n * @example\n * ```ts\n * const resolver = createUnifiedResolver(async (change) => {\n * if (change.type === \"destructive\") {\n * return confirm(`Accept: ${change.description}?`) ? change.proceed() : change.reject();\n * }\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n * if (change.type === \"enumValueRemoval\") {\n * return change.mapValues({ 'OLD': 'NEW' });\n * }\n * return change.reject();\n * });\n * ```\n */\nexport function createUnifiedResolver(\n decide: (\n change: ResolveChange\n ) => Promise<\"proceed\" | \"reject\" | \"rename\" | \"addAndDrop\" | \"enumMapped\">\n): ResolveCallback {\n return decide;\n}\n","/**\n * Model-to-SchemaSnapshot Serializer\n *\n * Converts VibORM model definitions into a database-agnostic SchemaSnapshot\n * that can be compared with the current database state.\n *\n * Database-specific logic is delegated to the MigrationDriver:\n * - Type mapping (mapFieldType)\n * - Default expressions (getDefaultExpression)\n * - Enum handling (capabilities.supportsNativeEnums, getEnumColumnType)\n */\n\nimport type { Field } from \"../schema/fields/base\";\nimport type { AnyModel } from \"../schema/model\";\nimport type { AnyRelation } from \"../schema/relation\";\nimport {\n getJunctionFieldNames,\n getJunctionTableName,\n} from \"../schema/relation/helpers\";\nimport type { MigrationDriver } from \"./drivers\";\nimport type {\n ColumnDef,\n EnumDef,\n ForeignKeyDef,\n IndexDef,\n PrimaryKeyDef,\n ReferentialAction,\n SchemaSnapshot,\n TableDef,\n UniqueConstraintDef,\n} from \"./types\";\n\n// =============================================================================\n// REFERENTIAL ACTION MAPPING\n// =============================================================================\n\nfunction mapReferentialAction(\n action: \"cascade\" | \"setNull\" | \"restrict\" | \"noAction\" | undefined\n): ReferentialAction {\n switch (action) {\n case \"cascade\":\n return \"cascade\";\n case \"setNull\":\n return \"setNull\";\n case \"restrict\":\n return \"restrict\";\n default:\n return \"noAction\";\n }\n}\n\n// =============================================================================\n// SERIALIZER\n// =============================================================================\n\nexport interface SerializeOptions {\n migrationDriver: MigrationDriver;\n}\n\n/**\n * Serializes a collection of VibORM models into a SchemaSnapshot\n */\nexport function serializeModels(\n models: Record<string, AnyModel>,\n options: SerializeOptions\n): SchemaSnapshot {\n const { migrationDriver } = options;\n const tables: TableDef[] = [];\n const enums: EnumDef[] = [];\n const enumsSet = new Set<string>();\n\n for (const [modelName, model] of Object.entries(models)) {\n const modelState = model[\"~\"].state;\n const tableName =\n model[\"~\"].names.sql || modelState.tableName || modelName.toLowerCase();\n\n const columns: ColumnDef[] = [];\n const indexes: IndexDef[] = [];\n const foreignKeys: ForeignKeyDef[] = [];\n const uniqueConstraints: UniqueConstraintDef[] = [];\n let primaryKey: PrimaryKeyDef | undefined;\n const pkColumns: string[] = [];\n\n // Process scalar fields\n for (const [fieldName, field] of Object.entries(modelState.scalars)) {\n const fieldState = (field as Field)[\"~\"].state;\n // Use model's nameRegistry for column name resolution (supports field reuse)\n const columnName = model[\"~\"].getFieldName(fieldName).sql;\n\n // Handle enum types (only for databases that support native enums)\n let columnType: string;\n if (fieldState.type === \"enum\") {\n const enumField = field as any;\n const enumValues = enumField.enumValues as string[] | undefined;\n\n if (migrationDriver.capabilities.supportsNativeEnums && enumValues) {\n // Use explicit enum name if provided, otherwise auto-generate\n const enumName = fieldState.enumName\n ? fieldState.enumName\n : migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues\n );\n\n if (!enumsSet.has(enumName)) {\n enums.push({\n name: enumName,\n values: enumValues,\n });\n enumsSet.add(enumName);\n }\n columnType = enumName;\n } else {\n // Fall back to driver's default enum column type\n columnType = migrationDriver.getEnumColumnType(\n tableName,\n columnName,\n enumValues || []\n );\n }\n } else {\n columnType = migrationDriver.mapFieldType(field as Field, fieldState);\n }\n\n const columnDef: ColumnDef = {\n name: columnName,\n type: columnType,\n nullable: fieldState.nullable,\n default: migrationDriver.getDefaultExpression(fieldState),\n autoIncrement: fieldState.autoGenerate === \"increment\",\n };\n\n columns.push(columnDef);\n\n // Track primary key columns\n if (fieldState.isId) {\n pkColumns.push(columnName);\n }\n\n // Handle unique constraints on individual fields\n if (fieldState.isUnique && !fieldState.isId) {\n uniqueConstraints.push({\n name: `${tableName}_${columnName}_key`,\n columns: [columnName],\n });\n }\n }\n\n // Handle compound primary key\n if (modelState.compoundId) {\n const compoundIdKeys = Object.keys(modelState.compoundId);\n if (compoundIdKeys.length > 0) {\n // The compound ID name contains the field names\n const firstKey = compoundIdKeys[0]!;\n // Extract field names from the compound ID schema\n const compoundIdSchema = modelState.compoundId[firstKey];\n if (compoundIdSchema?.[\"~\"]) {\n const schemaState = compoundIdSchema[\"~\"];\n if (schemaState.def && typeof schemaState.def === \"object\") {\n pkColumns.push(...Object.keys(schemaState.def));\n }\n }\n }\n }\n\n // Set primary key\n if (pkColumns.length > 0) {\n primaryKey = {\n columns: pkColumns,\n name: `${tableName}_pkey`,\n };\n }\n\n // Handle compound unique constraints\n if (modelState.compoundUniques) {\n for (const [constraintName, schema] of Object.entries(\n modelState.compoundUniques\n )) {\n if (schema?.[\"~\"]) {\n const schemaState = schema[\"~\"];\n if (schemaState.def && typeof schemaState.def === \"object\") {\n uniqueConstraints.push({\n name: `${tableName}_${constraintName}_key`,\n columns: Object.keys(schemaState.def),\n });\n }\n }\n }\n }\n\n // Process indexes from model state\n for (const indexDef of modelState.indexes) {\n const indexName =\n indexDef.options.name ||\n `${tableName}_${indexDef.fields.join(\"_\")}_idx`;\n indexes.push({\n name: indexName,\n columns: indexDef.fields,\n unique: indexDef.options.unique,\n type: indexDef.options.type,\n where: indexDef.options.where,\n });\n }\n\n // Process relations to generate foreign keys\n for (const [relationName, relation] of Object.entries(\n modelState.relations\n )) {\n const relationState = (relation as AnyRelation)[\"~\"].state;\n\n // Only process manyToOne and oneToOne relations that define foreign keys\n if (\n (relationState.type === \"manyToOne\" ||\n relationState.type === \"oneToOne\") &&\n relationState.fields &&\n relationState.references\n ) {\n // Get the target model\n const targetModel = relationState.getter();\n if (targetModel?.[\"~\"]) {\n const targetModelState = targetModel[\"~\"].state;\n const targetTableName =\n targetModel[\"~\"].names.sql ||\n targetModelState.tableName ||\n relationName.toLowerCase();\n\n foreignKeys.push({\n name: `${tableName}_${relationState.fields.join(\"_\")}_fkey`,\n columns: relationState.fields,\n referencedTable: targetTableName,\n referencedColumns: relationState.references,\n onDelete: mapReferentialAction(relationState.onDelete),\n onUpdate: mapReferentialAction(relationState.onUpdate),\n });\n }\n }\n }\n\n tables.push({\n name: tableName,\n columns,\n primaryKey,\n indexes,\n foreignKeys,\n uniqueConstraints,\n });\n }\n\n // ==========================================================================\n // JUNCTION TABLES FOR MANY-TO-MANY RELATIONS\n // ==========================================================================\n const junctionTables = new Map<string, TableDef>();\n\n for (const [modelName, model] of Object.entries(models)) {\n const modelState = model[\"~\"].state;\n const sourceTableName =\n model[\"~\"].names.sql || modelState.tableName || modelName.toLowerCase();\n\n for (const [relationName, relation] of Object.entries(\n modelState.relations\n )) {\n const relState = (relation as AnyRelation)[\"~\"].state;\n if (relState.type !== \"manyToMany\") continue;\n\n const targetModel = relState.getter();\n if (!targetModel?.[\"~\"]) continue;\n\n // Target model must have hydrated names\n const targetModelName = targetModel[\"~\"].names.ts;\n if (!targetModelName) {\n throw new Error(\n `Target model for relation \"${relationName}\" has no name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n\n const targetTableName = targetModel[\"~\"].names.sql;\n if (!targetTableName) {\n throw new Error(\n `Target model \"${targetModelName}\" has no SQL table name. ` +\n \"Schema may not be hydrated. Call hydrateSchemaNames() first.\"\n );\n }\n\n // Get junction table name (from .through() or generated)\n const junctionTableName = getJunctionTableName(\n relation as AnyRelation,\n modelName,\n targetModelName\n );\n\n // Avoid duplicating (post_tag from Post side and from Tag side)\n if (junctionTables.has(junctionTableName)) continue;\n\n // Get junction field names\n const [sourceFieldName, targetFieldName] = getJunctionFieldNames(\n relation as AnyRelation,\n modelName,\n targetModelName\n );\n\n // Get PK types from source and target models\n const sourcePkField = getPrimaryKeyFieldDef(model, migrationDriver);\n const targetPkField = getPrimaryKeyFieldDef(targetModel, migrationDriver);\n\n junctionTables.set(junctionTableName, {\n name: junctionTableName,\n columns: [\n {\n name: sourceFieldName,\n type: sourcePkField.type,\n nullable: false,\n },\n {\n name: targetFieldName,\n type: targetPkField.type,\n nullable: false,\n },\n ],\n primaryKey: { columns: [sourceFieldName, targetFieldName] },\n indexes: [],\n foreignKeys: [\n {\n name: `${junctionTableName}_${sourceFieldName}_fkey`,\n columns: [sourceFieldName],\n referencedTable: sourceTableName,\n referencedColumns: [sourcePkField.name],\n onDelete: mapReferentialAction(relState.onDelete),\n onUpdate: mapReferentialAction(relState.onUpdate),\n },\n {\n name: `${junctionTableName}_${targetFieldName}_fkey`,\n columns: [targetFieldName],\n referencedTable: targetTableName,\n referencedColumns: [targetPkField.name],\n onDelete: mapReferentialAction(relState.onDelete),\n onUpdate: mapReferentialAction(relState.onUpdate),\n },\n ],\n uniqueConstraints: [],\n });\n }\n }\n\n // Append junction tables to the tables array\n tables.push(...junctionTables.values());\n\n return {\n tables,\n enums: enums.length > 0 ? enums : undefined,\n };\n}\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/**\n * Get the primary key field definition for a model.\n * Throws if the model uses compound PK (not supported for M2M junction tables).\n */\nfunction getPrimaryKeyFieldDef(\n model: AnyModel,\n migrationDriver: MigrationDriver\n): { name: string; type: string } {\n const modelState = model[\"~\"].state;\n const modelName = model[\"~\"].names.ts;\n\n // Compound PKs not supported for junction tables\n if (modelState.compoundId && Object.keys(modelState.compoundId).length > 0) {\n throw new Error(\n `Model \"${modelName}\" uses compound primary key. ` +\n \"Many-to-many relations with compound PKs are not supported. \" +\n \"Use a single-field surrogate key (e.g., s.string().id().ulid()) instead.\"\n );\n }\n\n for (const [fieldName, field] of Object.entries(modelState.scalars)) {\n const fieldState = (field as Field)[\"~\"].state;\n if (fieldState.isId) {\n const columnName = model[\"~\"].getFieldName(fieldName).sql;\n const columnType = migrationDriver.mapFieldType(\n field as Field,\n fieldState\n );\n return { name: columnName, type: columnType };\n }\n }\n\n throw new Error(\n `Model \"${modelName}\" has no primary key field. ` +\n \"Schema may not be hydrated.\"\n );\n}\n\n/**\n * Gets the SQL column name for a field using the model's nameRegistry.\n * This supports field reuse across multiple models.\n *\n * @param model - The model containing the field\n * @param fieldName - The field key in the schema\n * @returns The SQL column name\n */\nexport function getColumnName(model: AnyModel, fieldName: string): string {\n return model[\"~\"].getFieldName(fieldName).sql;\n}\n\n/**\n * Gets the SQL table name for a model\n */\nexport function getTableName(model: AnyModel, modelName: string): string {\n return (\n model[\"~\"].names.sql ||\n model[\"~\"].state.tableName ||\n modelName.toLowerCase()\n );\n}\n","/**\n * Migration Generate\n *\n * Generates SQL migration files by comparing schema with previous snapshot.\n * Similar to `drizzle-kit generate` or `prisma migrate dev`.\n */\n\nimport { diff } from \"../differ\";\nimport { getMigrationDriver } from \"../drivers\";\nimport type { MigrationClient } from \"../push\";\nimport { resolveAmbiguousChanges, strictResolver } from \"../resolver\";\nimport { serializeModels } from \"../serializer\";\nimport {\n addJournalEntry,\n createMigrationEntry,\n formatMigrationFilename,\n getNextMigrationIndex,\n} from \"../storage\";\nimport type { GenerateOptions, GenerateResult } from \"../types\";\nimport {\n DEFAULT_MIGRATIONS_DIR,\n generateMigrationName,\n normalizeDialect,\n resolveEnumValueRemovals,\n} from \"../utils\";\nimport { formatMigrationContent } from \"./file-writer\";\n\n/**\n * Generates a new migration file by comparing the schema with the last snapshot.\n *\n * @param client - VibORM client with driver and schema\n * @param options - Generation options\n * @returns Generation result with entry, SQL, and operations\n */\nexport async function generate(\n client: MigrationClient,\n options: GenerateOptions = {}\n): Promise<GenerateResult> {\n const {\n name,\n dir = DEFAULT_MIGRATIONS_DIR,\n storageDriver,\n resolver = strictResolver,\n enumValueResolver,\n dryRun = false,\n } = options;\n\n const driver = client.$driver;\n const models = client.$schema;\n const dialect = normalizeDialect(driver.dialect);\n\n // Storage driver is required (client.ts validates this)\n if (!storageDriver) {\n throw new Error(\n \"Storage driver is required for generate(). \" +\n \"Use createMigrationClient() with a storageDriver option.\"\n );\n }\n const storage = storageDriver;\n\n // Get the migration driver\n const migrationDriver = getMigrationDriver(driver.driverName, driver.dialect);\n\n // 1. Read previous snapshot (or create empty for first migration)\n const previousSnapshot = await storage.getSnapshotOrEmpty();\n\n // 2. Serialize current models to SchemaSnapshot\n const currentSnapshot = serializeModels(models, { migrationDriver });\n\n // 3. Calculate diff between snapshots\n const diffResult = diff(previousSnapshot, currentSnapshot);\n\n // 4. Resolve ambiguous changes\n let finalOperations = await resolveAmbiguousChanges(\n diffResult,\n currentSnapshot,\n resolver\n );\n\n // 5. Resolve enum value removals\n finalOperations = await resolveEnumValueRemovals(\n finalOperations,\n enumValueResolver\n );\n\n // 6. Check if there are any changes\n if (finalOperations.length === 0) {\n return {\n entry: null,\n sql: [],\n content: \"\",\n operations: [],\n written: false,\n message: \"No schema changes detected.\",\n };\n }\n\n // 7. Get or create journal\n const journal = await storage.getOrCreateJournal(dialect);\n\n // 8. Generate DDL statements\n const ddlContext = { currentSchema: previousSnapshot };\n const sql: string[] = [];\n\n for (const op of finalOperations) {\n const ddl = migrationDriver.generateDDL(op, ddlContext);\n // Split multi-statement DDL\n const statements = ddl.split(\";\\n\").filter((s) => s.trim());\n for (const stmt of statements) {\n // Ensure statement ends with semicolon\n const trimmed = stmt.trim();\n sql.push(trimmed.endsWith(\";\") ? trimmed : `${trimmed};`);\n }\n }\n\n // 9. Create migration entry\n const idx = getNextMigrationIndex(journal);\n const migrationName = name || generateMigrationName(finalOperations);\n const content = formatMigrationContent(\n { idx, version: \"\", name: migrationName, when: Date.now(), checksum: \"\" },\n sql,\n dialect\n );\n\n const entry = createMigrationEntry(idx, migrationName, content);\n\n // Re-format content with the actual entry (which has checksum)\n const finalContent = formatMigrationContent(entry, sql, dialect);\n\n // 10. Write files (unless dry run)\n if (!dryRun) {\n // Write migration file\n await storage.writeMigration(entry, finalContent);\n\n // Update journal\n const updatedJournal = addJournalEntry(journal, entry);\n await storage.writeJournal(updatedJournal);\n\n // Update snapshot\n await storage.writeSnapshot(currentSnapshot);\n }\n\n return {\n entry,\n sql,\n content: finalContent,\n operations: finalOperations,\n written: !dryRun,\n message: dryRun\n ? `Would generate migration: ${formatMigrationFilename(entry)}`\n : `Generated migration: ${formatMigrationFilename(entry)}`,\n };\n}\n\n/**\n * Preview what migration would be generated without writing files.\n */\nexport async function preview(\n client: MigrationClient,\n options: Omit<GenerateOptions, \"dryRun\"> = {}\n): Promise<GenerateResult> {\n return generate(client, { ...options, dryRun: true });\n}\n\n// Re-export utilities for convenience\nexport { formatMigrationFilename, getNextMigrationIndex } from \"../storage\";\nexport { generateMigrationName } from \"../utils\";\nexport { getMigrationFilePath, parseStatements } from \"./file-writer\";\nexport { readJournal } from \"./journal\";\nexport { getSnapshotOrEmpty, readSnapshot } from \"./snapshot\";\n","// =============================================================================\n// SCHEMA SNAPSHOT (database-agnostic representation)\n// =============================================================================\n\nexport interface SchemaSnapshot {\n tables: TableDef[];\n enums?: EnumDef[] | undefined;\n}\n\nexport interface TableDef {\n name: string;\n columns: ColumnDef[];\n primaryKey?: PrimaryKeyDef | undefined;\n indexes: IndexDef[];\n foreignKeys: ForeignKeyDef[];\n uniqueConstraints: UniqueConstraintDef[];\n}\n\nexport interface ColumnDef {\n name: string;\n type: string; // Normalized type (e.g., \"varchar(255)\", \"integer\", \"boolean\")\n nullable: boolean;\n default?: string | undefined; // SQL expression for default value\n autoIncrement?: boolean | undefined;\n}\n\nexport interface PrimaryKeyDef {\n columns: string[];\n name?: string | undefined;\n}\n\nexport interface IndexDef {\n name: string;\n columns: string[];\n unique: boolean;\n type?: \"btree\" | \"hash\" | \"gin\" | \"gist\" | \"fulltext\" | \"spatial\" | undefined;\n where?: string | undefined; // For partial indexes\n}\n\nexport interface ForeignKeyDef {\n name: string;\n columns: string[];\n referencedTable: string;\n referencedColumns: string[];\n onDelete?: ReferentialAction | undefined;\n onUpdate?: ReferentialAction | undefined;\n}\n\nexport type ReferentialAction =\n | \"cascade\"\n | \"setNull\"\n | \"restrict\"\n | \"noAction\"\n | \"setDefault\";\n\nexport interface UniqueConstraintDef {\n name: string;\n columns: string[];\n}\n\nexport interface EnumDef {\n name: string;\n values: string[];\n}\n\n// =============================================================================\n// DIFF OPERATIONS (resolved, ready to execute)\n// =============================================================================\n\nexport type DiffOperation =\n | { type: \"createTable\"; table: TableDef }\n | { type: \"dropTable\"; tableName: string }\n | { type: \"renameTable\"; from: string; to: string }\n | { type: \"addColumn\"; tableName: string; column: ColumnDef }\n | { type: \"dropColumn\"; tableName: string; columnName: string }\n | { type: \"renameColumn\"; tableName: string; from: string; to: string }\n | {\n type: \"alterColumn\";\n tableName: string;\n columnName: string;\n from: ColumnDef;\n to: ColumnDef;\n }\n | { type: \"createIndex\"; tableName: string; index: IndexDef }\n | { type: \"dropIndex\"; tableName: string; indexName: string }\n | { type: \"addForeignKey\"; tableName: string; fk: ForeignKeyDef }\n | { type: \"dropForeignKey\"; tableName: string; fkName: string }\n | {\n type: \"addUniqueConstraint\";\n tableName: string;\n constraint: UniqueConstraintDef;\n }\n | { type: \"dropUniqueConstraint\"; tableName: string; constraintName: string }\n | { type: \"addPrimaryKey\"; tableName: string; primaryKey: PrimaryKeyDef }\n | { type: \"dropPrimaryKey\"; tableName: string; constraintName: string }\n | { type: \"createEnum\"; enumDef: EnumDef }\n | {\n type: \"dropEnum\";\n enumName: string;\n /**\n * Columns that depend on this enum.\n * Required for SQLite to know which columns need CHECK constraint removal.\n */\n dependentColumns?: Array<{ tableName: string; columnName: string }>;\n }\n | {\n type: \"alterEnum\";\n enumName: string;\n addValues?: string[] | undefined;\n removeValues?: string[] | undefined;\n /**\n * Full list of desired enum values (required when removing values)\n * Used to recreate the enum type in PostgreSQL\n */\n newValues?: string[] | undefined;\n /**\n * Columns that depend on this enum (required when removing values)\n * Each entry is { tableName, columnName }\n */\n dependentColumns?:\n | Array<{ tableName: string; columnName: string }>\n | undefined;\n /**\n * Global replacement values for removed enum values.\n * Used as fallback when no column-specific mapping exists.\n * Maps old value -> new value for data migration.\n *\n * Example: { \"pending\": \"inactive\" } - rows with \"pending\" become \"inactive\"\n * Use null to set rows to NULL: { \"pending\": null }\n */\n valueReplacements?: Record<string, string | null> | undefined;\n /**\n * Per-column replacement values for removed enum values.\n * Allows different columns to have different mappings.\n * Key is \"tableName.columnName\", value is the replacement map.\n *\n * Example: { \"users.status\": { \"pending\": \"inactive\" }, \"orders.status\": { \"pending\": \"cancelled\" } }\n */\n columnValueReplacements?:\n | Record<string, Record<string, string | null>>\n | undefined;\n /**\n * Default replacement for any removed values without explicit mapping.\n * Useful when the enum field has a default value - use that here.\n * Use null to set rows to NULL.\n *\n * Example: If your field has `.default(\"active\")`, set defaultReplacement: \"active\"\n */\n defaultReplacement?: string | null | undefined;\n };\n\n// =============================================================================\n// AMBIGUOUS CHANGES (require user input to resolve)\n// =============================================================================\n\n/** Detected when columns are added AND dropped in the same table */\nexport type AmbiguousColumnChange = {\n type: \"ambiguousColumn\";\n tableName: string;\n droppedColumn: ColumnDef;\n addedColumn: ColumnDef;\n};\n\n/** Detected when tables are added AND dropped */\nexport type AmbiguousTableChange = {\n type: \"ambiguousTable\";\n droppedTable: string;\n addedTable: string;\n};\n\nexport type AmbiguousChange = AmbiguousColumnChange | AmbiguousTableChange;\n\n/** User's resolution for an ambiguous change */\nexport type ChangeResolution =\n | { type: \"rename\" } // Treat as rename (preserve data)\n | { type: \"addAndDrop\" }; // Treat as separate add + drop (data loss)\n\n// =============================================================================\n// DIFF RESULT (output of differ, before resolution)\n// =============================================================================\n\nexport interface DiffResult {\n /** Operations that are unambiguous and ready to execute */\n operations: DiffOperation[];\n /** Changes that need user input to resolve */\n ambiguousChanges: AmbiguousChange[];\n}\n\n// =============================================================================\n// RESOLVER (handles ambiguous changes)\n// =============================================================================\n\n/** Callback to resolve ambiguous changes (used by CLI or programmatic API) */\nexport type Resolver = (\n changes: AmbiguousChange[]\n) => Promise<Map<AmbiguousChange, ChangeResolution>>;\n\n// =============================================================================\n// UNIFIED RESOLVE CALLBACK\n// =============================================================================\n\n/**\n * Valid resolution results.\n * - \"proceed\": Accept the change (for destructive)\n * - \"reject\": Reject the change and abort\n * - \"rename\": Treat as a rename (for ambiguous)\n * - \"addAndDrop\": Treat as separate add + drop (for ambiguous)\n * - \"enumMapped\": Enum values have been mapped (for enumValueRemoval)\n */\nexport type ResolveResult =\n | \"proceed\"\n | \"reject\"\n | \"rename\"\n | \"addAndDrop\"\n | \"enumMapped\";\n\n/**\n * Base properties shared by destructive and ambiguous changes.\n */\ninterface BaseResolveChange {\n /** The specific operation type */\n operation:\n | \"dropTable\"\n | \"dropColumn\"\n | \"alterColumn\"\n | \"renameTable\"\n | \"renameColumn\";\n\n /** The table involved */\n table: string;\n\n /** The column involved (if applicable) */\n column?: string;\n\n /** Human-readable description of the change */\n description: string;\n\n /** Reject this change and abort the operation */\n reject(): ResolveResult;\n}\n\n/**\n * A destructive change that will cause data loss.\n * Available methods: `proceed()`, `reject()`\n */\nexport interface DestructiveResolveChange extends BaseResolveChange {\n type: \"destructive\";\n\n /** Accept the destructive change (causes data loss) */\n proceed(): ResolveResult;\n}\n\n/**\n * An ambiguous change that could be a rename or add+drop.\n * Available methods: `rename()`, `addAndDrop()`, `reject()`\n */\nexport interface AmbiguousResolveChange extends BaseResolveChange {\n type: \"ambiguous\";\n\n /** The old name (for renames) */\n oldName?: string;\n\n /** The new name (for renames) */\n newName?: string;\n\n /** The old type (for alterColumn) */\n oldType?: string;\n\n /** The new type (for alterColumn) */\n newType?: string;\n\n /** Treat as a rename (preserves data) */\n rename(): ResolveResult;\n\n /** Treat as separate add + drop (causes data loss) */\n addAndDrop(): ResolveResult;\n}\n\n/**\n * An enum value removal that needs replacement mappings for a specific column.\n * Called once per column that uses the enum, allowing different mappings per column.\n * Available methods: `mapValues()`, `useNull()`, `reject()`\n */\nexport interface EnumValueRemovalChange {\n type: \"enumValueRemoval\";\n\n /** The enum name */\n enumName: string;\n\n /** The table containing the column */\n tableName: string;\n\n /** The column using this enum */\n columnName: string;\n\n /** Whether this column is nullable (if true, useNull() is safe) */\n isNullable: boolean;\n\n /** Values being removed */\n removedValues: string[];\n\n /** Available values to map to */\n availableValues: string[];\n\n /** Human-readable description */\n description: string;\n\n /**\n * Map removed values to replacement values.\n * @param replacements - Map of old value → new value (or null for NULL)\n */\n mapValues(replacements: Record<string, string | null>): ResolveResult;\n\n /**\n * Set all removed values to NULL.\n * This is a shorthand for mapValues where all values map to null.\n * Note: Only safe if the column is nullable.\n */\n useNull(): ResolveResult;\n\n /** Reject this change and abort the operation */\n reject(): ResolveResult;\n\n /** Internal: stores the mapping result */\n _mappings?: Record<string, string | null>;\n\n /** Internal: flag indicating to use null as default */\n _useNullDefault?: boolean;\n}\n\n/**\n * A change that requires user resolution.\n * Use the type discriminant to determine which methods are available:\n * - `destructive`: `proceed()`, `reject()`\n * - `ambiguous`: `rename()`, `addAndDrop()`, `reject()`\n * - `enumValueRemoval`: `mapValues()`, `reject()`\n */\nexport type ResolveChange =\n | DestructiveResolveChange\n | AmbiguousResolveChange\n | EnumValueRemovalChange;\n\n/**\n * Unified callback for resolving changes that need user input.\n * Called once per change, allowing granular control over each decision.\n *\n * @param change - The change requiring resolution\n * @returns The resolution decision (call a method on change to get this)\n *\n * @example\n * ```ts\n * resolve: async (change) => {\n * console.log(change.description);\n *\n * if (change.type === \"destructive\") {\n * return confirm(\"Accept data loss?\") ? change.proceed() : change.reject();\n * }\n *\n * if (change.type === \"ambiguous\") {\n * return change.rename();\n * }\n *\n * if (change.type === \"enumValueRemoval\") {\n * // Map removed enum values to new values\n * return change.mapValues({\n * 'PENDING': 'INACTIVE',\n * 'OLD_VALUE': null, // Set to NULL\n * });\n * }\n * }\n * ```\n */\nexport type ResolveCallback = (\n change: ResolveChange\n) =>\n | Promise<ResolveResult | undefined | void>\n | ResolveResult\n | undefined\n | void;\n\n/**\n * Create a destructive change object with resolution methods.\n */\nexport function createDestructiveChange(props: {\n operation: \"dropTable\" | \"dropColumn\" | \"alterColumn\";\n table: string;\n column?: string;\n description: string;\n}): DestructiveResolveChange {\n return {\n type: \"destructive\",\n ...props,\n proceed: () => \"proceed\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an ambiguous change object with resolution methods.\n */\nexport function createAmbiguousChange(props: {\n operation: \"renameTable\" | \"renameColumn\";\n table: string;\n column?: string;\n oldName?: string;\n newName?: string;\n oldType?: string;\n newType?: string;\n description: string;\n}): AmbiguousResolveChange {\n return {\n type: \"ambiguous\",\n ...props,\n rename: () => \"rename\",\n addAndDrop: () => \"addAndDrop\",\n reject: () => \"reject\",\n };\n}\n\n/**\n * Create an enum value removal change object with resolution methods.\n */\nexport function createEnumValueRemovalChange(props: {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n description: string;\n}): EnumValueRemovalChange {\n const change: EnumValueRemovalChange = {\n type: \"enumValueRemoval\",\n ...props,\n mapValues: (replacements: Record<string, string | null>) => {\n change._mappings = replacements;\n return \"enumMapped\";\n },\n useNull: () => {\n change._useNullDefault = true;\n return \"enumMapped\";\n },\n reject: () => \"reject\",\n };\n return change;\n}\n\n/** Information about an enum value removal that needs resolution */\nexport interface EnumValueRemoval {\n enumName: string;\n removedValues: string[];\n newValues: string[];\n dependentColumns: Array<{ tableName: string; columnName: string }>;\n}\n\n/** User's resolution for enum value removal */\nexport interface EnumValueResolution {\n /** Map specific old values to new values */\n valueReplacements?: Record<string, string | null>;\n /** Default replacement for any values not in valueReplacements */\n defaultReplacement?: string | null;\n}\n\n/** Callback to resolve enum value removals (used by CLI or programmatic API) */\nexport type EnumValueResolver = (\n removals: EnumValueRemoval[]\n) => Promise<Map<string, EnumValueResolution>>; // Map<enumName, resolution>\n\n// =============================================================================\n// UNIFIED RESOLVER (handles all resolution types)\n// =============================================================================\n\n/**\n * Resolution request types for the unified resolver.\n */\nexport type ResolutionRequestType = \"ambiguous_change\" | \"enum_value_removal\";\n\n/**\n * Base interface for resolution requests.\n */\nexport interface ResolutionRequestBase<T extends ResolutionRequestType> {\n /** Unique identifier for this request */\n id: string;\n /** The type of resolution needed */\n type: T;\n}\n\n/**\n * Request to resolve an ambiguous schema change (rename vs add+drop).\n */\nexport interface AmbiguousChangeRequest\n extends ResolutionRequestBase<\"ambiguous_change\"> {\n /** The ambiguous change details */\n change: AmbiguousChange;\n}\n\n/**\n * Request to resolve enum value removals.\n */\nexport interface EnumValueRemovalRequest\n extends ResolutionRequestBase<\"enum_value_removal\"> {\n /** The enum value removal details */\n removal: EnumValueRemoval;\n}\n\n/**\n * Union type of all resolution request types.\n */\nexport type ResolutionRequest =\n | AmbiguousChangeRequest\n | EnumValueRemovalRequest;\n\n/**\n * Resolution result for an ambiguous change.\n */\nexport interface AmbiguousChangeResolution {\n type: \"ambiguous_change\";\n resolution: ChangeResolution;\n}\n\n/**\n * Resolution result for an enum value removal.\n */\nexport interface EnumValueRemovalResolution {\n type: \"enum_value_removal\";\n resolution: EnumValueResolution;\n}\n\n/**\n * Union type of all resolution result types.\n */\nexport type ResolutionResult =\n | AmbiguousChangeResolution\n | EnumValueRemovalResolution;\n\n/**\n * Unified resolver callback that handles all types of resolutions.\n *\n * This allows a single resolver to handle both ambiguous changes and\n * enum value removals in one callback, simplifying the API.\n *\n * @param requests - Array of resolution requests\n * @returns Map of request ID to resolution result\n */\nexport type UnifiedResolver = (\n requests: ResolutionRequest[]\n) => Promise<Map<string, ResolutionResult>>;\n\n/**\n * Helper to create an AmbiguousChangeRequest.\n */\nexport function createAmbiguousChangeRequest(\n id: string,\n change: AmbiguousChange\n): AmbiguousChangeRequest {\n return { id, type: \"ambiguous_change\", change };\n}\n\n/**\n * Helper to create an EnumValueRemovalRequest.\n */\nexport function createEnumValueRemovalRequest(\n id: string,\n removal: EnumValueRemoval\n): EnumValueRemovalRequest {\n return { id, type: \"enum_value_removal\", removal };\n}\n\n// =============================================================================\n// PUSH RESULT\n// =============================================================================\n\nexport interface PushResult {\n /** All operations that were applied (or would be applied in dry-run) */\n operations: DiffOperation[];\n /** Whether the operations were actually applied to the database */\n applied: boolean;\n /** Generated SQL statements */\n sql: string[];\n}\n\n// =============================================================================\n// MIGRATION JOURNAL (tracks generated migrations)\n// =============================================================================\n\nexport type Dialect = \"postgresql\" | \"sqlite\" | \"mysql\";\n\nexport interface MigrationJournal {\n /** Schema version for the journal format */\n version: string;\n /** Database dialect */\n dialect: Dialect;\n /** List of migration entries */\n entries: MigrationEntry[];\n}\n\nexport interface MigrationEntry {\n /** Sequential index (0, 1, 2...) */\n idx: number;\n /** Timestamp version (e.g., \"20240118143052\") */\n version: string;\n /** Migration name (e.g., \"add_users_table\") */\n name: string;\n /** Unix timestamp when generated */\n when: number;\n /** SHA256 hash of SQL content for integrity verification */\n checksum: string;\n /** Optional tag for grouping migrations */\n tag?: string;\n}\n\n// =============================================================================\n// GENERATE OPTIONS & RESULT\n// =============================================================================\n\nexport interface GenerateOptions {\n /** Custom migration name (will be kebab-cased) */\n name?: string;\n /** Output directory for migrations (default: ./migrations). Ignored if storageDriver is provided. */\n dir?: string;\n /** Custom storage driver. If not provided, uses filesystem driver with `dir`. */\n storageDriver?: import(\"./storage/driver\").MigrationStorageDriver;\n /** Resolver for ambiguous changes */\n resolver?: Resolver;\n /** Resolver for enum value removals */\n enumValueResolver?: EnumValueResolver;\n /** Don't write files, just return what would be generated */\n dryRun?: boolean;\n}\n\nexport interface GenerateResult {\n /** Generated migration entry (null if no changes) */\n entry: MigrationEntry | null;\n /** Generated SQL statements */\n sql: string[];\n /** Combined SQL content with statement breakpoints */\n content: string;\n /** Operations included in migration */\n operations: DiffOperation[];\n /** Whether files were written */\n written: boolean;\n /** Message describing the result */\n message: string;\n}\n\n// =============================================================================\n// APPLY OPTIONS & RESULT\n// =============================================================================\n\nexport interface ApplyOptions {\n /** Apply up to this migration index (inclusive) */\n to?: number;\n /** Don't apply, just return what would be applied */\n dryRun?: boolean;\n}\n\n/**\n * Result of applying migrations.\n * Throws MigrationError on failure instead of returning error object.\n */\nexport interface ApplyResult {\n /** Migrations that were applied */\n applied: MigrationEntry[];\n /** Migrations that are still pending */\n pending: MigrationEntry[];\n}\n\n// =============================================================================\n// MIGRATION STATUS\n// =============================================================================\n\nexport interface MigrationStatus {\n /** Migration entry from journal */\n entry: MigrationEntry;\n /** Whether this migration has been applied */\n applied: boolean;\n /** When the migration was applied (if applied) */\n appliedAt?: Date;\n}\n\n// =============================================================================\n// APPLIED MIGRATION (from database tracking table)\n// =============================================================================\n\nexport interface AppliedMigration {\n /** Migration name (matches MigrationEntry.name) */\n name: string;\n /** Checksum at time of application */\n checksum: string;\n /** When the migration was applied */\n appliedAt: Date;\n}\n","/**\n * Push Workflow\n *\n * Orchestrates the database schema push operation:\n * 1. Serialize VibORM models to SchemaSnapshot\n * 2. Introspect current database state\n * 3. Calculate diff\n * 4. Resolve ambiguous changes\n * 5. Generate and execute DDL\n */\n\nimport type { AnyDriver } from \"../drivers/driver\";\nimport type { AnyModel } from \"../schema/model\";\n\n/**\n * Minimal client interface required for migrations.\n * This allows push() to work with any object that has $driver and $schema.\n */\nexport interface MigrationClient {\n $driver: AnyDriver;\n $schema: Record<string, AnyModel>;\n}\n\nimport { MigrationError, VibORMErrorCode } from \"../errors\";\nimport { diff } from \"./differ\";\nimport { getMigrationDriver, type MigrationDriver } from \"./drivers\";\nimport { alwaysAddDropResolver, resolveAmbiguousChanges } from \"./resolver\";\nimport { serializeModels } from \"./serializer\";\nimport {\n type AmbiguousChange,\n type ChangeResolution,\n createAmbiguousChange,\n createDestructiveChange,\n createEnumValueRemovalChange,\n type DiffOperation,\n type PushResult,\n type ResolveCallback,\n type ResolveChange,\n type Resolver,\n type SchemaSnapshot,\n} from \"./types\";\n\n// =============================================================================\n// PUSH OPTIONS\n// =============================================================================\n\n// Re-export PushResult from types for convenience\nexport type { PushResult } from \"./types\";\n\nexport interface PushOptions {\n /** Skip confirmations for destructive and ambiguous changes */\n force?: boolean;\n /** Preview SQL without executing */\n dryRun?: boolean;\n /**\n * Drop all tables and enums before pushing schema.\n * If a storage driver is configured, also clears migration tracking.\n * Use with extreme caution - all data will be lost.\n */\n forceReset?: boolean;\n /**\n * Unified callback for resolving changes that require user input.\n * Called once per change, allowing granular control over each decision.\n *\n * Each change has methods for valid resolutions:\n * - Destructive: `change.proceed()`, `change.reject()`\n * - Ambiguous: `change.rename()`, `change.addAndDrop()`, `change.reject()`\n * - Enum value removal: `change.mapValues({...})`, `change.useNull()`, `change.reject()`\n *\n * **Combining with `force`:**\n * When both `resolve` and `force: true` are provided, the resolver takes precedence.\n * If the resolver returns `undefined` (doesn't handle a change), force mode kicks in:\n * - Destructive: auto-accepted\n * - Ambiguous: treated as add+drop\n * - Enum removal: set to NULL\n *\n * This allows patterns like \"accept everything except dropping table X\".\n *\n * @example\n * ```ts\n * // Protect specific tables while auto-accepting everything else\n * await migrations.push({\n * force: true,\n * resolve: async (change) => {\n * if (change.type === \"destructive\" && change.table === \"users\") {\n * return change.reject(); // Protect users table\n * }\n * // Return undefined to let force handle the rest\n * },\n * });\n * ```\n */\n resolve?: ResolveCallback;\n /**\n * Internal: storage driver passed from migration client.\n * Used for forceReset to clear migration tracking if available.\n * @internal\n */\n _storageDriver?: import(\"./storage/driver\").MigrationStorageDriver;\n}\n\nconst MATCH_ALTER_TYPE_ADD_VALUE = /^ALTER\\s+TYPE\\s+.*\\s+ADD\\s+VALUE\\s+/i;\n\n// =============================================================================\n// PUSH FUNCTION\n// =============================================================================\n\n/**\n * Pushes schema changes directly to the database.\n *\n * @param client - VibORM client containing driver and schema\n * @param options - Push options\n * @returns Push result with operations and SQL statements\n */\nexport async function push(\n client: MigrationClient,\n options: PushOptions = {}\n): Promise<PushResult> {\n const { force = false, dryRun = false, forceReset = false } = options;\n\n const driver = client.$driver;\n const models = client.$schema;\n\n // Get the migration driver for this database\n const migrationDriver = getMigrationDriver(driver.driverName, driver.dialect);\n\n // Handle forceReset - drop all tables before push\n if (forceReset && !dryRun) {\n await resetDatabase(driver, migrationDriver, options._storageDriver);\n }\n\n // 1. Serialize VibORM models to SchemaSnapshot\n const desired = serializeModels(models, { migrationDriver });\n\n // 2. Introspect current database state\n const current = await migrationDriver.introspect(async (sql, params) => {\n const result = await driver._executeRaw<any>(sql, params);\n return result;\n });\n\n // Create DDL context for drivers that need schema info (e.g., SQLite table recreation)\n const ddlContext = { currentSchema: current };\n\n // 3. Calculate diff\n const diffResult = diff(current, desired);\n\n // 4. Resolve changes using unified resolve callback\n let finalOperations: DiffOperation[];\n\n // Detect enum value removals that need resolution (per-column)\n const allEnumRemovals = detectEnumValueRemovals(\n diffResult.operations,\n current\n );\n\n // Separate removals: nullable columns can be auto-resolved to NULL\n const autoResolvableRemovals = allEnumRemovals.filter((r) => r.isNullable);\n const enumRemovalsNeedingResolution = allEnumRemovals.filter(\n (r) => !r.isNullable\n );\n\n if (options.resolve) {\n // Resolver provided - use it for all changes\n // If force is also true, unhandled changes (resolver returns undefined) will be auto-accepted\n finalOperations = await resolveWithCallback(\n diffResult,\n desired,\n enumRemovalsNeedingResolution,\n options.resolve,\n force // Pass force flag to auto-accept unhandled changes\n );\n // Auto-resolve nullable column enum removals\n finalOperations = applyForceEnumResolutions(\n finalOperations,\n autoResolvableRemovals\n );\n } else if (force) {\n // Force mode without resolver: auto-accept destructive, treat ambiguous as add+drop\n finalOperations = await resolveAmbiguousChanges(\n diffResult,\n desired,\n alwaysAddDropResolver\n );\n // Auto-resolve ALL enum value removals: set removed values to NULL\n finalOperations = applyForceEnumResolutions(\n finalOperations,\n allEnumRemovals\n );\n } else {\n // No resolve callback and not force: check if resolution is needed\n const destructiveOps = diffResult.operations.filter(isDestructiveOperation);\n const hasAmbiguous = diffResult.ambiguousChanges.length > 0;\n // Only non-nullable columns require resolution\n const hasEnumRemovalsNeedingResolution =\n enumRemovalsNeedingResolution.length > 0;\n\n if (\n destructiveOps.length > 0 ||\n hasAmbiguous ||\n hasEnumRemovalsNeedingResolution\n ) {\n const descriptions: string[] = [];\n\n for (const op of destructiveOps) {\n descriptions.push(formatDestructiveOperation(op));\n }\n\n for (const change of diffResult.ambiguousChanges) {\n descriptions.push(formatAmbiguousChangeDescription(change));\n }\n\n for (const removal of enumRemovalsNeedingResolution) {\n descriptions.push(\n `[enumValueRemoval] \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - removing values: ${removal.removedValues.join(\", \")} (non-nullable)`\n );\n }\n\n throw new MigrationError(\n `Changes requiring resolution detected:\\n${descriptions.join(\"\\n\")}\\n\\n` +\n \"Use --force to auto-accept or provide a resolve callback.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n // Auto-resolve nullable column enum removals (no prompting needed)\n finalOperations = applyForceEnumResolutions(\n [...diffResult.operations],\n autoResolvableRemovals\n );\n }\n\n // 6. Generate DDL statements\n const sql: string[] = [];\n for (const op of finalOperations) {\n const ddl = migrationDriver.generateDDL(op, ddlContext);\n // generateDDL may return multiple statements separated by ;\\n\n const statements = ddl.split(\";\\n\").filter((s) => s.trim());\n sql.push(...statements);\n }\n\n // 7. Execute DDL (unless dry run)\n if (!dryRun && sql.length > 0) {\n // Check if driver supports ADD VALUE in transaction\n const canAddValueInTransaction =\n migrationDriver.capabilities.supportsAddEnumValueInTransaction;\n\n // Separate ALTER TYPE ... ADD VALUE statements if needed\n // (PostgreSQL limitation: ADD VALUE cannot be executed inside a transaction block)\n const addValueStatements: string[] = [];\n const transactionalStatements: string[] = [];\n\n for (const statement of sql) {\n if (\n !canAddValueInTransaction &&\n statement.trim().match(MATCH_ALTER_TYPE_ADD_VALUE)\n ) {\n addValueStatements.push(statement);\n } else {\n transactionalStatements.push(statement);\n }\n }\n\n // Execute ADD VALUE statements outside transaction first\n for (const statement of addValueStatements) {\n await driver._executeRaw(`${statement};`);\n }\n\n // Execute remaining statements in a transaction for atomicity\n if (transactionalStatements.length > 0) {\n await driver.withTransaction(async (txDriver) => {\n for (const statement of transactionalStatements) {\n await txDriver._executeRaw(`${statement};`);\n }\n });\n }\n }\n\n return {\n operations: finalOperations,\n applied: !dryRun && sql.length > 0,\n sql,\n };\n}\n\n// =============================================================================\n// RESET HELPERS\n// =============================================================================\n\n/**\n * Resets the database by dropping all tables and enums.\n * If storage driver is provided, also clears migration tracking.\n */\nasync function resetDatabase(\n driver: AnyDriver,\n migrationDriver: MigrationDriver,\n storageDriver?: import(\"./storage/driver\").MigrationStorageDriver\n): Promise<void> {\n // Get current schema to know what to drop\n const current = await migrationDriver.introspect(async (sql, params) => {\n const result = await driver._executeRaw<any>(sql, params);\n return result;\n });\n\n // Drop all tables in reverse order (for FK dependencies)\n // NOTE: Reverse order helps with simple FK chains but doesn't handle circular dependencies.\n // PostgreSQL uses CASCADE to handle this. SQLite/MySQL may fail on circular FKs.\n const tablesToDrop = [...current.tables].reverse();\n for (const table of tablesToDrop) {\n const dropSql = migrationDriver.generateDropTableSQL(table.name, true);\n await driver._executeRaw(`${dropSql};`);\n }\n\n // Drop all enums (only for databases that support them)\n if (current.enums) {\n for (const enumDef of current.enums) {\n const dropSql = migrationDriver.generateDropEnumSQL(enumDef.name);\n if (dropSql) {\n await driver._executeRaw(`${dropSql};`);\n }\n }\n }\n\n // If storage driver exists, clear the journal and snapshot\n if (storageDriver) {\n // Write empty journal\n await storageDriver.writeJournal({\n version: \"1\",\n dialect: driver.dialect as \"postgresql\" | \"sqlite\",\n entries: [],\n });\n // Clear snapshot\n await storageDriver.writeSnapshot({ tables: [], enums: [] });\n }\n}\n\n// =============================================================================\n// RESOLVE HELPERS\n// =============================================================================\n\n/** Detected enum value removal needing resolution (per-column) */\ninterface EnumRemoval {\n enumName: string;\n tableName: string;\n columnName: string;\n isNullable: boolean;\n removedValues: string[];\n availableValues: string[];\n}\n\n/**\n * Detects enum value removals that need resolution.\n * Returns one removal per column that uses the enum.\n * Nullable columns can be auto-resolved to NULL.\n */\nfunction detectEnumValueRemovals(\n operations: DiffOperation[],\n currentSchema: SchemaSnapshot\n): EnumRemoval[] {\n const removals: EnumRemoval[] = [];\n\n for (const op of operations) {\n if (\n op.type === \"alterEnum\" &&\n op.removeValues &&\n op.removeValues.length > 0\n ) {\n // Check if any removed values lack replacements\n const unresolvedValues = op.removeValues.filter((v) => {\n const hasExplicit = op.valueReplacements && v in op.valueReplacements;\n const hasDefault = op.defaultReplacement !== undefined;\n return !(hasExplicit || hasDefault);\n });\n\n if (unresolvedValues.length > 0) {\n const dependentColumns = op.dependentColumns || [];\n\n // Create one removal per column\n for (const dep of dependentColumns) {\n const table = currentSchema.tables.find(\n (t) => t.name === dep.tableName\n );\n if (!table) {\n throw new MigrationError(\n `Table \"${dep.tableName}\" not found in current schema for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n const column = table.columns.find((c) => c.name === dep.columnName);\n if (!column) {\n throw new MigrationError(\n `Column \"${dep.columnName}\" not found in table \"${dep.tableName}\" for enum \"${op.enumName}\"`,\n VibORMErrorCode.INTERNAL_ERROR\n );\n }\n const isNullable = column.nullable;\n\n removals.push({\n enumName: op.enumName,\n tableName: dep.tableName,\n columnName: dep.columnName,\n isNullable,\n removedValues: unresolvedValues,\n availableValues: op.newValues || [],\n });\n }\n }\n }\n }\n\n return removals;\n}\n\n/**\n * Applies force mode resolutions for enum value removals.\n * Sets all removed values to NULL for each column.\n */\nfunction applyForceEnumResolutions(\n operations: DiffOperation[],\n enumRemovals: EnumRemoval[]\n): DiffOperation[] {\n if (enumRemovals.length === 0) {\n return operations;\n }\n\n // Group removals by enum name\n const removalsByEnum = new Map<string, EnumRemoval[]>();\n for (const removal of enumRemovals) {\n const existing = removalsByEnum.get(removal.enumName) || [];\n existing.push(removal);\n removalsByEnum.set(removal.enumName, existing);\n }\n\n return operations.map((op) => {\n if (op.type !== \"alterEnum\" || !op.removeValues) {\n return op;\n }\n\n const removals = removalsByEnum.get(op.enumName);\n if (!removals || removals.length === 0) {\n return op;\n }\n\n // Build per-column value replacements (all set to null in force mode)\n const columnValueReplacements: Record<\n string,\n Record<string, string | null>\n > = {\n ...op.columnValueReplacements,\n };\n\n for (const removal of removals) {\n const columnKey = `${removal.tableName}.${removal.columnName}`;\n const nullMappings: Record<string, null> = {};\n for (const value of removal.removedValues) {\n nullMappings[value] = null;\n }\n columnValueReplacements[columnKey] = {\n ...columnValueReplacements[columnKey],\n ...nullMappings,\n };\n }\n\n return {\n ...op,\n columnValueReplacements,\n };\n });\n}\n\n/**\n * Resolves changes using the unified resolve callback.\n * Calls the callback once per destructive/ambiguous/enum change.\n * For enum value removals, calls once per column using the enum.\n *\n * @param force - If true, unhandled changes (resolver returns undefined) are auto-accepted\n */\nasync function resolveWithCallback(\n diffResult: {\n operations: DiffOperation[];\n ambiguousChanges: AmbiguousChange[];\n },\n desiredSnapshot: SchemaSnapshot,\n enumRemovals: EnumRemoval[],\n resolve: ResolveCallback,\n force = false\n): Promise<DiffOperation[]> {\n const finalOperations: DiffOperation[] = [];\n const ambiguousResolutions = new Map<AmbiguousChange, ChangeResolution>();\n // Per-column mappings: Map<enumName, Map<\"tableName.columnName\", mappings>>\n const columnMappings = new Map<\n string,\n Map<string, Record<string, string | null>>\n >();\n\n // 1. Process non-destructive, non-enum operations (pass through)\n for (const op of diffResult.operations) {\n if (!isDestructiveOperation(op) && op.type !== \"alterEnum\") {\n finalOperations.push(op);\n }\n }\n\n // 2. Resolve destructive operations\n for (const op of diffResult.operations) {\n if (isDestructiveOperation(op)) {\n const change = operationToResolveChange(op);\n const result = await resolve(change);\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n if (result === undefined) {\n // Resolver didn't handle this change\n if (force) {\n // Force mode: auto-accept\n finalOperations.push(op);\n } else {\n // No force: throw error\n throw new MigrationError(\n `Unresolved destructive change: ${change.description}\\n` +\n \"Return change.proceed() or change.reject() from the resolver, or use force: true.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"proceed\") {\n finalOperations.push(op);\n }\n // \"rename\" and \"addAndDrop\" are invalid for destructive ops, treat as proceed\n if (result === \"rename\" || result === \"addAndDrop\") {\n finalOperations.push(op);\n }\n }\n }\n\n // 3. Resolve ambiguous changes\n for (const change of diffResult.ambiguousChanges) {\n const resolveChange = ambiguousToResolveChange(change);\n const result = await resolve(resolveChange);\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${resolveChange.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n if (result === undefined) {\n // Resolver didn't handle this change\n if (force) {\n // Force mode: treat as addAndDrop\n ambiguousResolutions.set(change, { type: \"addAndDrop\" });\n } else {\n // No force: throw error\n throw new MigrationError(\n `Unresolved ambiguous change: ${resolveChange.description}\\n` +\n \"Return change.rename() or change.addAndDrop() from the resolver, or use force: true.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"rename\") {\n ambiguousResolutions.set(change, { type: \"rename\" });\n } else {\n // \"addAndDrop\" or \"proceed\" (treat proceed as addAndDrop for ambiguous)\n ambiguousResolutions.set(change, { type: \"addAndDrop\" });\n }\n }\n\n // 4. Resolve enum value removals (per-column)\n for (const removal of enumRemovals) {\n const change = createEnumValueRemovalChange({\n enumName: removal.enumName,\n tableName: removal.tableName,\n columnName: removal.columnName,\n isNullable: removal.isNullable,\n removedValues: removal.removedValues,\n availableValues: removal.availableValues,\n description:\n `Column \"${removal.tableName}.${removal.columnName}\" uses enum \"${removal.enumName}\" - ` +\n `removing values: ${removal.removedValues.join(\", \")}. ` +\n `Map to: ${removal.availableValues.join(\", \")} or NULL`,\n });\n\n const result = await resolve(change);\n\n if (result === \"reject\") {\n throw new MigrationError(\n `Change rejected: ${change.description}`,\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n\n const columnKey = `${removal.tableName}.${removal.columnName}`;\n\n if (result === undefined) {\n // Resolver didn't handle this change\n if (force) {\n // Force mode: set all to null\n if (!columnMappings.has(removal.enumName)) {\n columnMappings.set(removal.enumName, new Map());\n }\n const enumColMappings = columnMappings.get(removal.enumName)!;\n const nullMappings: Record<string, null> = {};\n for (const value of removal.removedValues) {\n nullMappings[value] = null;\n }\n enumColMappings.set(columnKey, nullMappings);\n } else {\n // No force: throw error\n throw new MigrationError(\n `Unresolved enum value removal: ${change.description}\\n` +\n \"Return change.mapValues() or change.useNull() from the resolver, or use force: true.\",\n VibORMErrorCode.MIGRATION_DESTRUCTIVE_REJECTED\n );\n }\n continue;\n }\n\n if (result === \"enumMapped\") {\n // Get or create the enum's column mapping\n if (!columnMappings.has(removal.enumName)) {\n columnMappings.set(removal.enumName, new Map());\n }\n const enumColMappings = columnMappings.get(removal.enumName)!;\n\n if (change._mappings) {\n // Explicit mappings provided via mapValues()\n enumColMappings.set(columnKey, change._mappings);\n } else if (change._useNullDefault) {\n // useNull() was called - create mappings with all values -> null\n const nullMappings: Record<string, null> = {};\n for (const value of removal.removedValues) {\n nullMappings[value] = null;\n }\n enumColMappings.set(columnKey, nullMappings);\n }\n }\n // Other results (proceed, rename, addAndDrop) - no mapping, will use null default\n }\n\n // 5. Apply ambiguous resolutions\n if (diffResult.ambiguousChanges.length > 0) {\n const resolvedOps = applyAmbiguousResolutions(\n diffResult.ambiguousChanges,\n ambiguousResolutions,\n desiredSnapshot\n );\n finalOperations.push(...resolvedOps);\n }\n\n // 6. Process alterEnum operations with resolved per-column mappings\n for (const op of diffResult.operations) {\n if (op.type === \"alterEnum\") {\n const enumColMappings = columnMappings.get(op.enumName);\n if (enumColMappings && enumColMappings.size > 0) {\n // Convert Map to Record for columnValueReplacements\n const columnValueReplacements: Record<\n string,\n Record<string, string | null>\n > = {\n ...op.columnValueReplacements,\n };\n for (const [colKey, mappings] of enumColMappings) {\n columnValueReplacements[colKey] = {\n ...columnValueReplacements[colKey],\n ...mappings,\n };\n }\n finalOperations.push({\n ...op,\n columnValueReplacements,\n });\n } else {\n // No mapping provided, use null as default replacement\n finalOperations.push({\n ...op,\n defaultReplacement: op.defaultReplacement ?? null,\n });\n }\n }\n }\n\n return sortOperations(finalOperations);\n}\n\n/**\n * Checks if an operation is destructive (causes data loss).\n */\nfunction isDestructiveOperation(op: DiffOperation): boolean {\n if (op.type === \"dropTable\" || op.type === \"dropColumn\") {\n return true;\n }\n if (op.type === \"alterColumn\") {\n // Type changes or making non-nullable are potentially destructive\n const typeChanged =\n normalizeType(op.from.type) !== normalizeType(op.to.type);\n const madeNonNullable = op.from.nullable && !op.to.nullable;\n return typeChanged || madeNonNullable;\n }\n return false;\n}\n\n/**\n * Normalizes a type string for comparison.\n */\nfunction normalizeType(type: string): string {\n return type.toLowerCase().replace(/\\s+/g, \" \").trim();\n}\n\n/**\n * Converts a destructive operation to a ResolveChange with resolution methods.\n */\nfunction operationToResolveChange(op: DiffOperation): ResolveChange {\n switch (op.type) {\n case \"dropTable\":\n return createDestructiveChange({\n operation: \"dropTable\",\n table: op.tableName,\n description: `Drop table \"${op.tableName}\" (all data will be lost)`,\n });\n case \"dropColumn\":\n return createDestructiveChange({\n operation: \"dropColumn\",\n table: op.tableName,\n column: op.columnName,\n description: `Drop column \"${op.columnName}\" from table \"${op.tableName}\" (data will be lost)`,\n });\n case \"alterColumn\":\n return createDestructiveChange({\n operation: \"alterColumn\",\n table: op.tableName,\n column: op.columnName,\n description: `Alter column \"${op.columnName}\" in \"${op.tableName}\" (${op.from.type} → ${op.to.type})`,\n });\n default:\n throw new Error(`Unexpected operation type: ${(op as any).type}`);\n }\n}\n\n/**\n * Converts an ambiguous change to a ResolveChange with resolution methods.\n */\nfunction ambiguousToResolveChange(change: AmbiguousChange): ResolveChange {\n if (change.type === \"ambiguousColumn\") {\n return createAmbiguousChange({\n operation: \"renameColumn\",\n table: change.tableName,\n column: change.addedColumn.name,\n oldName: change.droppedColumn.name,\n newName: change.addedColumn.name,\n oldType: change.droppedColumn.type,\n newType: change.addedColumn.type,\n description: `Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in table \"${change.tableName}\" (rename or add+drop?)`,\n });\n }\n return createAmbiguousChange({\n operation: \"renameTable\",\n table: change.addedTable,\n oldName: change.droppedTable,\n newName: change.addedTable,\n description: `Table \"${change.droppedTable}\" → \"${change.addedTable}\" (rename or add+drop?)`,\n });\n}\n\n/**\n * Formats a destructive operation for error messages.\n */\nfunction formatDestructiveOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"dropTable\":\n return `[destructive] Drop table \"${op.tableName}\"`;\n case \"dropColumn\":\n return `[destructive] Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"alterColumn\":\n return `[destructive] Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n default:\n return `[destructive] ${(op as any).type}`;\n }\n}\n\n/**\n * Formats an ambiguous change for error messages.\n */\nfunction formatAmbiguousChangeDescription(change: AmbiguousChange): string {\n if (change.type === \"ambiguousColumn\") {\n return `[ambiguous] Column \"${change.droppedColumn.name}\" → \"${change.addedColumn.name}\" in \"${change.tableName}\"`;\n }\n return `[ambiguous] Table \"${change.droppedTable}\" → \"${change.addedTable}\"`;\n}\n\n/**\n * Applies ambiguous resolutions to generate operations.\n */\nfunction applyAmbiguousResolutions(\n changes: AmbiguousChange[],\n resolutions: Map<AmbiguousChange, ChangeResolution>,\n desiredSnapshot: SchemaSnapshot\n): DiffOperation[] {\n const operations: DiffOperation[] = [];\n\n for (const change of changes) {\n const resolution = resolutions.get(change);\n if (!resolution) continue;\n\n if (change.type === \"ambiguousColumn\") {\n if (resolution.type === \"rename\") {\n operations.push({\n type: \"renameColumn\",\n tableName: change.tableName,\n from: change.droppedColumn.name,\n to: change.addedColumn.name,\n });\n\n // If column properties differ, also alter it\n if (\n change.droppedColumn.nullable !== change.addedColumn.nullable ||\n change.droppedColumn.default !== change.addedColumn.default\n ) {\n operations.push({\n type: \"alterColumn\",\n tableName: change.tableName,\n columnName: change.addedColumn.name,\n from: { ...change.droppedColumn, name: change.addedColumn.name },\n to: change.addedColumn,\n });\n }\n } else {\n // addAndDrop\n operations.push(\n {\n type: \"dropColumn\",\n tableName: change.tableName,\n columnName: change.droppedColumn.name,\n },\n {\n type: \"addColumn\",\n tableName: change.tableName,\n column: change.addedColumn,\n }\n );\n }\n } else if (change.type === \"ambiguousTable\") {\n if (resolution.type === \"rename\") {\n operations.push({\n type: \"renameTable\",\n from: change.droppedTable,\n to: change.addedTable,\n });\n } else {\n // addAndDrop\n operations.push({ type: \"dropTable\", tableName: change.droppedTable });\n const newTable = desiredSnapshot.tables.find(\n (t) => t.name === change.addedTable\n );\n if (newTable) {\n operations.push({ type: \"createTable\", table: newTable });\n }\n }\n }\n }\n\n return operations;\n}\n\n/**\n * Sorts operations in the correct execution order.\n */\nfunction sortOperations(operations: DiffOperation[]): DiffOperation[] {\n const priority: Record<string, number> = {\n createEnum: 0,\n alterEnum: 1,\n dropForeignKey: 2,\n dropIndex: 3,\n dropUniqueConstraint: 4,\n dropPrimaryKey: 5,\n dropColumn: 6,\n dropTable: 7,\n createTable: 8,\n renameTable: 9,\n addColumn: 10,\n renameColumn: 11,\n alterColumn: 12,\n addPrimaryKey: 13,\n addUniqueConstraint: 14,\n createIndex: 15,\n addForeignKey: 16,\n dropEnum: 17,\n };\n\n return [...operations].sort((a, b) => {\n const pa = priority[a.type] ?? 100;\n const pb = priority[b.type] ?? 100;\n return pa - pb;\n });\n}\n\n// =============================================================================\n// INTROSPECTION & DDL GENERATION\n// =============================================================================\n\n/**\n * Introspects the current database schema without making any changes.\n * Useful for debugging or displaying current state.\n */\nexport async function introspect(\n client: MigrationClient\n): Promise<SchemaSnapshot> {\n const driver = client.$driver;\n const migrationDriver = getMigrationDriver(driver.driverName, driver.dialect);\n return migrationDriver.introspect(async (sql, params) => {\n const result = await driver._executeRaw<any>(sql, params);\n return result;\n });\n}\n\n/**\n * Generates DDL statements for transforming current schema to desired schema\n * without executing them. Useful for generating migration files.\n */\nexport async function generateDDL(\n client: MigrationClient,\n options: { resolver?: Resolver } = {}\n): Promise<{ operations: DiffOperation[]; sql: string[] }> {\n const result = await push(client, {\n ...options,\n dryRun: true,\n force: true,\n });\n\n return {\n operations: result.operations,\n sql: result.sql,\n };\n}\n\n/**\n * Formats an operation for human-readable display\n */\nexport function formatOperation(op: DiffOperation): string {\n switch (op.type) {\n case \"createTable\":\n return `+ Create table \"${op.table.name}\" with ${op.table.columns.length} columns`;\n case \"dropTable\":\n return `- Drop table \"${op.tableName}\"`;\n case \"renameTable\":\n return `~ Rename table \"${op.from}\" → \"${op.to}\"`;\n case \"addColumn\":\n return `+ Add column \"${op.column.name}\" (${op.column.type}) to \"${op.tableName}\"`;\n case \"dropColumn\":\n return `- Drop column \"${op.columnName}\" from \"${op.tableName}\"`;\n case \"renameColumn\":\n return `~ Rename column \"${op.from}\" → \"${op.to}\" in \"${op.tableName}\"`;\n case \"alterColumn\":\n return `~ Alter column \"${op.columnName}\" in \"${op.tableName}\"`;\n case \"createIndex\":\n return `+ Create index \"${op.index.name}\" on \"${op.tableName}\"`;\n case \"dropIndex\":\n return `- Drop index \"${op.indexName}\"`;\n case \"addForeignKey\":\n return `+ Add foreign key \"${op.fk.name}\" to \"${op.tableName}\"`;\n case \"dropForeignKey\":\n return `- Drop foreign key \"${op.fkName}\" from \"${op.tableName}\"`;\n case \"addUniqueConstraint\":\n return `+ Add unique constraint \"${op.constraint.name}\" to \"${op.tableName}\"`;\n case \"dropUniqueConstraint\":\n return `- Drop unique constraint \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"addPrimaryKey\":\n return `+ Add primary key to \"${op.tableName}\"`;\n case \"dropPrimaryKey\":\n return `- Drop primary key \"${op.constraintName}\" from \"${op.tableName}\"`;\n case \"createEnum\":\n return `+ Create enum \"${op.enumDef.name}\" with values [${op.enumDef.values.join(\", \")}]`;\n case \"dropEnum\":\n return `- Drop enum \"${op.enumName}\"`;\n case \"alterEnum\": {\n const parts: string[] = [];\n if (op.addValues?.length) parts.push(`add: ${op.addValues.join(\", \")}`);\n if (op.removeValues?.length)\n parts.push(`remove: ${op.removeValues.join(\", \")}`);\n return `~ Alter enum \"${op.enumName}\" (${parts.join(\"; \")})`;\n }\n default:\n return `Unknown operation: ${(op as any).type}`;\n }\n}\n\n/**\n * Formats all operations for human-readable display\n */\nexport function formatOperations(operations: DiffOperation[]): string {\n if (operations.length === 0) {\n return \"No changes detected.\";\n }\n\n return operations.map(formatOperation).join(\"\\n\");\n}\n"],"mappings":"mWA8FA,IAAsB,EAAtB,KAAsC,CAsJpC,iBAAiB,EAAsB,CACrC,GAAI,GAAQ,KACV,MAAM,IAAI,EACR,6CACA,EAAgB,cACjB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