@warlock.js/cascade 5.31.0 → 5.32.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 (230) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/cjs/index.cjs +104 -85
  3. package/cjs/index.cjs.map +1 -1
  4. package/esm/context/database-data-source-context.d.mts +2 -3
  5. package/esm/context/database-data-source-context.d.mts.map +1 -1
  6. package/esm/context/database-transaction-context.d.mts +2 -3
  7. package/esm/context/database-transaction-context.d.mts.map +1 -1
  8. package/esm/contracts/database-driver.contract.d.mts +56 -36
  9. package/esm/contracts/database-driver.contract.d.mts.map +1 -1
  10. package/esm/contracts/database-id-generator.contract.d.mts +7 -5
  11. package/esm/contracts/database-id-generator.contract.d.mts.map +1 -1
  12. package/esm/contracts/database-remover.contract.d.mts +3 -5
  13. package/esm/contracts/database-remover.contract.d.mts.map +1 -1
  14. package/esm/contracts/database-restorer.contract.d.mts +6 -6
  15. package/esm/contracts/database-restorer.contract.d.mts.map +1 -1
  16. package/esm/contracts/database-writer.contract.d.mts +4 -6
  17. package/esm/contracts/database-writer.contract.d.mts.map +1 -1
  18. package/esm/contracts/driver-blueprint.contract.d.mts +2 -3
  19. package/esm/contracts/driver-blueprint.contract.d.mts.map +1 -1
  20. package/esm/contracts/index.d.mts +2 -1
  21. package/esm/contracts/migration-driver.contract.d.mts +101 -53
  22. package/esm/contracts/migration-driver.contract.d.mts.map +1 -1
  23. package/esm/contracts/query-builder.contract.d.mts +51 -33
  24. package/esm/contracts/query-builder.contract.d.mts.map +1 -1
  25. package/esm/contracts/sync-adapter.contract.d.mts +25 -14
  26. package/esm/contracts/sync-adapter.contract.d.mts.map +1 -1
  27. package/esm/data-source/data-source-registry.d.mts +4 -5
  28. package/esm/data-source/data-source-registry.d.mts.map +1 -1
  29. package/esm/data-source/data-source.d.mts +8 -5
  30. package/esm/data-source/data-source.d.mts.map +1 -1
  31. package/esm/database-dirty-tracker.d.mts +2 -2
  32. package/esm/database-dirty-tracker.d.mts.map +1 -1
  33. package/esm/database-dirty-tracker.mjs +3 -2
  34. package/esm/database-dirty-tracker.mjs.map +1 -1
  35. package/esm/drivers/mongodb/mongodb-driver.d.mts +3 -4
  36. package/esm/drivers/mongodb/mongodb-driver.d.mts.map +1 -1
  37. package/esm/drivers/mongodb/mongodb-id-generator.d.mts +2 -3
  38. package/esm/drivers/mongodb/mongodb-id-generator.d.mts.map +1 -1
  39. package/esm/drivers/mongodb/mongodb-migration-driver.d.mts +1 -3
  40. package/esm/drivers/mongodb/mongodb-migration-driver.d.mts.map +1 -1
  41. package/esm/drivers/mongodb/mongodb-query-builder.d.mts +2 -3
  42. package/esm/drivers/mongodb/mongodb-query-builder.d.mts.map +1 -1
  43. package/esm/drivers/mongodb/mongodb-query-builder.mjs +8 -5
  44. package/esm/drivers/mongodb/mongodb-query-builder.mjs.map +1 -1
  45. package/esm/drivers/mongodb/mongodb-query-operations.d.mts +1 -3
  46. package/esm/drivers/mongodb/mongodb-query-operations.d.mts.map +1 -1
  47. package/esm/drivers/mongodb/mongodb-query-parser.d.mts +7 -6
  48. package/esm/drivers/mongodb/mongodb-query-parser.d.mts.map +1 -1
  49. package/esm/drivers/mongodb/mongodb-query-parser.mjs +2 -6
  50. package/esm/drivers/mongodb/mongodb-query-parser.mjs.map +1 -1
  51. package/esm/drivers/mongodb/mongodb-sync-adapter.d.mts +1 -3
  52. package/esm/drivers/mongodb/mongodb-sync-adapter.d.mts.map +1 -1
  53. package/esm/drivers/mongodb/types.d.mts +11 -9
  54. package/esm/drivers/mongodb/types.d.mts.map +1 -1
  55. package/esm/drivers/postgres/index.d.mts +2 -1
  56. package/esm/drivers/postgres/index.mjs +1 -1
  57. package/esm/drivers/postgres/naming.mjs +1 -1
  58. package/esm/drivers/postgres/postgres-blueprint.d.mts +1 -3
  59. package/esm/drivers/postgres/postgres-blueprint.d.mts.map +1 -1
  60. package/esm/drivers/postgres/postgres-dialect.d.mts +4 -6
  61. package/esm/drivers/postgres/postgres-dialect.d.mts.map +1 -1
  62. package/esm/drivers/postgres/postgres-driver.d.mts +4 -5
  63. package/esm/drivers/postgres/postgres-driver.d.mts.map +1 -1
  64. package/esm/drivers/postgres/postgres-migration-driver.d.mts +1 -3
  65. package/esm/drivers/postgres/postgres-migration-driver.d.mts.map +1 -1
  66. package/esm/drivers/postgres/postgres-migration-driver.mjs +13 -10
  67. package/esm/drivers/postgres/postgres-migration-driver.mjs.map +1 -1
  68. package/esm/drivers/postgres/postgres-query-builder.d.mts +4 -4
  69. package/esm/drivers/postgres/postgres-query-builder.d.mts.map +1 -1
  70. package/esm/drivers/postgres/postgres-query-builder.mjs +14 -10
  71. package/esm/drivers/postgres/postgres-query-builder.mjs.map +1 -1
  72. package/esm/drivers/postgres/postgres-query-parser.d.mts +16 -11
  73. package/esm/drivers/postgres/postgres-query-parser.d.mts.map +1 -1
  74. package/esm/drivers/postgres/postgres-query-parser.mjs +1 -1
  75. package/esm/drivers/postgres/postgres-query-parser.mjs.map +1 -1
  76. package/esm/drivers/postgres/postgres-sql-serializer.mjs +13 -10
  77. package/esm/drivers/postgres/postgres-sql-serializer.mjs.map +1 -1
  78. package/esm/drivers/postgres/postgres-ttl-purge.mjs +1 -1
  79. package/esm/drivers/postgres/postgres-type-converters.mjs +2 -2
  80. package/esm/drivers/postgres/postgres-type-converters.mjs.map +1 -1
  81. package/esm/drivers/postgres/postgres-update-validator.mjs +1 -1
  82. package/esm/drivers/postgres/postgres-update-validator.mjs.map +1 -1
  83. package/esm/drivers/postgres/types.d.mts +87 -45
  84. package/esm/drivers/postgres/types.d.mts.map +1 -1
  85. package/esm/drivers/sql/sql-dialect.contract.d.mts +1 -3
  86. package/esm/drivers/sql/sql-dialect.contract.d.mts.map +1 -1
  87. package/esm/drivers/sql/sql-types.d.mts +113 -59
  88. package/esm/drivers/sql/sql-types.d.mts.map +1 -1
  89. package/esm/errors/missing-data-source.error.d.mts +1 -2
  90. package/esm/errors/missing-data-source.error.d.mts.map +1 -1
  91. package/esm/errors/transaction-rollback.error.d.mts +1 -2
  92. package/esm/errors/transaction-rollback.error.d.mts.map +1 -1
  93. package/esm/errors/undefined-where-value.error.d.mts +1 -2
  94. package/esm/errors/undefined-where-value.error.d.mts.map +1 -1
  95. package/esm/errors/unsafe-filter.error.d.mts +1 -2
  96. package/esm/errors/unsafe-filter.error.d.mts.map +1 -1
  97. package/esm/errors/unsafe-raw-expression.error.d.mts +1 -2
  98. package/esm/errors/unsafe-raw-expression.error.d.mts.map +1 -1
  99. package/esm/errors/unsupported-lean-operation.error.d.mts +1 -2
  100. package/esm/errors/unsupported-lean-operation.error.d.mts.map +1 -1
  101. package/esm/errors/unsupported-lock-for-update.error.d.mts +1 -2
  102. package/esm/errors/unsupported-lock-for-update.error.d.mts.map +1 -1
  103. package/esm/errors/unsupported-query-operation.error.d.mts +1 -2
  104. package/esm/errors/unsupported-query-operation.error.d.mts.map +1 -1
  105. package/esm/errors/unsupported-update-operation.error.d.mts +1 -2
  106. package/esm/errors/unsupported-update-operation.error.d.mts.map +1 -1
  107. package/esm/events/model-events.d.mts +8 -6
  108. package/esm/events/model-events.d.mts.map +1 -1
  109. package/esm/expressions/aggregate-expressions.d.mts +7 -7
  110. package/esm/expressions/aggregate-expressions.d.mts.map +1 -1
  111. package/esm/expressions/column-expressions.d.mts +11 -11
  112. package/esm/expressions/column-expressions.d.mts.map +1 -1
  113. package/esm/index.d.mts +7 -2
  114. package/esm/index.mjs +1 -1
  115. package/esm/migration/column-builder.d.mts +2 -3
  116. package/esm/migration/column-builder.d.mts.map +1 -1
  117. package/esm/migration/column-helpers.d.mts +49 -50
  118. package/esm/migration/column-helpers.d.mts.map +1 -1
  119. package/esm/migration/column-helpers.mjs +1 -1
  120. package/esm/migration/foreign-key-builder.d.mts +2 -3
  121. package/esm/migration/foreign-key-builder.d.mts.map +1 -1
  122. package/esm/migration/index.d.mts +3 -2
  123. package/esm/migration/index.mjs +2 -2
  124. package/esm/migration/migration-runner.d.mts +7 -6
  125. package/esm/migration/migration-runner.d.mts.map +1 -1
  126. package/esm/migration/migration-runner.mjs +15 -11
  127. package/esm/migration/migration-runner.mjs.map +1 -1
  128. package/esm/migration/migration.d.mts +50 -32
  129. package/esm/migration/migration.d.mts.map +1 -1
  130. package/esm/migration/migration.mjs +1 -3
  131. package/esm/migration/migration.mjs.map +1 -1
  132. package/esm/migration/sql-serializer.d.mts +1 -3
  133. package/esm/migration/sql-serializer.d.mts.map +1 -1
  134. package/esm/migration/types.d.mts +7 -7
  135. package/esm/migration/types.d.mts.map +1 -1
  136. package/esm/model/methods/accessor-methods.mjs +1 -1
  137. package/esm/model/methods/accessor-methods.mjs.map +1 -1
  138. package/esm/model/methods/meta-methods.mjs +4 -2
  139. package/esm/model/methods/meta-methods.mjs.map +1 -1
  140. package/esm/model/methods/query-methods.mjs +1 -1
  141. package/esm/model/methods/write-methods.d.mts +3 -2
  142. package/esm/model/methods/write-methods.d.mts.map +1 -1
  143. package/esm/model/methods/write-methods.mjs +5 -2
  144. package/esm/model/methods/write-methods.mjs.map +1 -1
  145. package/esm/model/model.d.mts +9 -9
  146. package/esm/model/model.d.mts.map +1 -1
  147. package/esm/model/model.types.d.mts +7 -7
  148. package/esm/model/model.types.d.mts.map +1 -1
  149. package/esm/model/register-model.d.mts +13 -15
  150. package/esm/model/register-model.d.mts.map +1 -1
  151. package/esm/model/relation-decorators.d.mts +6 -8
  152. package/esm/model/relation-decorators.d.mts.map +1 -1
  153. package/esm/operations/database.d.mts +13 -8
  154. package/esm/operations/database.d.mts.map +1 -1
  155. package/esm/operations/index.d.mts +2 -1
  156. package/esm/operations/index.mjs +1 -1
  157. package/esm/operations/migrations.d.mts +18 -14
  158. package/esm/operations/migrations.d.mts.map +1 -1
  159. package/esm/query-builder/query-builder.d.mts +2 -4
  160. package/esm/query-builder/query-builder.d.mts.map +1 -1
  161. package/esm/query-builder/query-builder.mjs +12 -11
  162. package/esm/query-builder/query-builder.mjs.map +1 -1
  163. package/esm/relations/index.d.mts +2 -1
  164. package/esm/relations/index.mjs +1 -1
  165. package/esm/relations/key-conventions.mjs +2 -1
  166. package/esm/relations/key-conventions.mjs.map +1 -1
  167. package/esm/relations/pivot-operations.d.mts +3 -5
  168. package/esm/relations/pivot-operations.d.mts.map +1 -1
  169. package/esm/relations/relation-hydrator.d.mts +3 -5
  170. package/esm/relations/relation-hydrator.d.mts.map +1 -1
  171. package/esm/relations/relation-loader.d.mts +2 -4
  172. package/esm/relations/relation-loader.d.mts.map +1 -1
  173. package/esm/relations/relation-loader.mjs +4 -5
  174. package/esm/relations/relation-loader.mjs.map +1 -1
  175. package/esm/relations/types.d.mts +14 -15
  176. package/esm/relations/types.d.mts.map +1 -1
  177. package/esm/remover/database-remover.d.mts +1 -3
  178. package/esm/remover/database-remover.d.mts.map +1 -1
  179. package/esm/restorer/database-restorer.d.mts +1 -3
  180. package/esm/restorer/database-restorer.d.mts.map +1 -1
  181. package/esm/restorer/database-restorer.mjs +2 -1
  182. package/esm/restorer/database-restorer.mjs.map +1 -1
  183. package/esm/sql-database-dirty-tracker.d.mts +1 -3
  184. package/esm/sql-database-dirty-tracker.d.mts.map +1 -1
  185. package/esm/sync/model-events.mjs +1 -1
  186. package/esm/sync/model-sync-operation.d.mts +2 -4
  187. package/esm/sync/model-sync-operation.d.mts.map +1 -1
  188. package/esm/sync/model-sync.d.mts +3 -4
  189. package/esm/sync/model-sync.d.mts.map +1 -1
  190. package/esm/sync/sync-context.d.mts +2 -4
  191. package/esm/sync/sync-context.d.mts.map +1 -1
  192. package/esm/sync/sync-fanout.mjs +1 -1
  193. package/esm/sync/sync-manager.d.mts +2 -4
  194. package/esm/sync/sync-manager.d.mts.map +1 -1
  195. package/esm/sync/types.d.mts +121 -64
  196. package/esm/sync/types.d.mts.map +1 -1
  197. package/esm/transactions/after-commit.d.mts +2 -2
  198. package/esm/transactions/after-commit.d.mts.map +1 -1
  199. package/esm/types.d.mts +7 -8
  200. package/esm/types.d.mts.map +1 -1
  201. package/esm/utils/connect-to-database.d.mts +7 -8
  202. package/esm/utils/connect-to-database.d.mts.map +1 -1
  203. package/esm/utils/database-writer.utils.d.mts +3 -4
  204. package/esm/utils/database-writer.utils.d.mts.map +1 -1
  205. package/esm/utils/define-model.d.mts +3 -5
  206. package/esm/utils/define-model.d.mts.map +1 -1
  207. package/esm/utils/escape-regex.d.mts +3 -4
  208. package/esm/utils/escape-regex.d.mts.map +1 -1
  209. package/esm/utils/once-connected.d.mts +2 -4
  210. package/esm/utils/once-connected.d.mts.map +1 -1
  211. package/esm/utils/sanitize-filter.d.mts +3 -4
  212. package/esm/utils/sanitize-filter.d.mts.map +1 -1
  213. package/esm/validation/database-seal-plugins.d.mts +2 -1
  214. package/esm/validation/database-writer-validation-error.d.mts +1 -3
  215. package/esm/validation/database-writer-validation-error.d.mts.map +1 -1
  216. package/esm/validation/index.d.mts +3 -1
  217. package/esm/validation/index.mjs +1 -1
  218. package/esm/validation/plugins/database-rules-plugin.d.mts +2 -3
  219. package/esm/validation/plugins/database-rules-plugin.d.mts.map +1 -1
  220. package/esm/validation/plugins/embed-validator-plugin.d.mts +4 -3
  221. package/esm/validation/plugins/embed-validator-plugin.d.mts.map +1 -1
  222. package/esm/validation/types.d.mts +14 -10
  223. package/esm/validation/types.d.mts.map +1 -1
  224. package/esm/validation/validators/embed-validator.d.mts +2 -3
  225. package/esm/validation/validators/embed-validator.d.mts.map +1 -1
  226. package/esm/writer/database-writer.d.mts +1 -3
  227. package/esm/writer/database-writer.d.mts.map +1 -1
  228. package/esm/writer/database-writer.mjs +1 -1
  229. package/esm/writer/database-writer.mjs.map +1 -1
  230. package/package.json +5 -5
@@ -11,8 +11,8 @@ import path from "path";
11
11
  /** Name of the lock document Mongo migrations claim inside the migrations collection. */
12
12
  const MIGRATION_LOCK_NAME = "__warlock_migration_lock__";
13
13
  const MIGRATION_LOCK_KEY = "warlock:migrations";
14
- const MIGRATION_LOCK_TTL_MS = 600 * 1e3;
15
- const MIGRATION_LOCK_WAIT_MS = 60 * 1e3;
14
+ const MIGRATION_LOCK_TTL_MS = 6e5;
15
+ const MIGRATION_LOCK_WAIT_MS = 6e4;
16
16
  const MIGRATION_LOCK_RETRY_MS = 1e3;
17
17
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
18
18
  /**
@@ -119,7 +119,7 @@ var MigrationRunner = class {
119
119
  }
120
120
  /** Distinct data sources across the registered migrations (runner's own included). */
121
121
  getSources() {
122
- const sources = new Set([this.getDataSource()]);
122
+ const sources = /* @__PURE__ */ new Set([this.getDataSource()]);
123
123
  for (const MigrationClass of this.migrations) sources.add(this.sourceOf(MigrationClass));
124
124
  return [...sources];
125
125
  }
@@ -689,17 +689,21 @@ var MigrationRunner = class {
689
689
  };
690
690
  if (shouldUseTransaction && databaseDriver.transaction) await databaseDriver.transaction(async () => {
691
691
  await applyMigration();
692
- if (record) if (direction === "up") {
693
- const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
694
- await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
695
- } else await this.removeMigrationRecord(name, dataSource);
692
+ if (record) {
693
+ if (direction === "up") {
694
+ const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
695
+ await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
696
+ } else await this.removeMigrationRecord(name, dataSource);
697
+ }
696
698
  });
697
699
  else {
698
700
  await applyMigration();
699
- if (record) if (direction === "up") {
700
- const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
701
- await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
702
- } else await this.removeMigrationRecord(name, dataSource);
701
+ if (record) {
702
+ if (direction === "up") {
703
+ const batch = options.batch ?? await this.getNextBatchNumber(dataSource);
704
+ await this.recordMigration(name, batch, MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : /* @__PURE__ */ new Date(), dataSource);
705
+ } else await this.removeMigrationRecord(name, dataSource);
706
+ }
703
707
  }
704
708
  }
705
709
  } catch (err) {
@@ -1 +1 @@
1
- {"version":3,"file":"migration-runner.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/migration-runner.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { log } from \"@warlock.js/logger\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { MigrationDriverContract } from \"../contracts/migration-driver.contract\";\nimport type { DataSource } from \"../data-source/data-source\";\nimport { dataSourceRegistry } from \"../data-source/data-source-registry\";\nimport {\n type Migration,\n type MigrationContract,\n type MigrationOrigin,\n type MigrationStep,\n} from \"./migration\";\nimport { sortMigrations, sortMigrationsForRollback } from \"./migration-order\";\nimport { parseCreatedAt } from \"./parse-created-at\";\nimport { SQLGrammar } from \"./sql-grammar\";\nimport type { MigrationRecord, MigrationResult, TaggedSQL } from \"./types\";\n\n/**\n * Migration class type with static name property.\n */\ntype MigrationClass = (new () => Migration) & {\n migrationName: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * What a caller may hand to {@link MigrationRunner.register}.\n *\n * Looser than {@link MigrationClass} in exactly one way: `migrationName` may be\n * absent. That is the documented workflow — the CLI imports a migration file and\n * sets the name from the filename afterwards — and `register()` enforces it at\n * runtime, throwing a message that says so. Once past that check the name IS\n * present, which is why everything stored and read downstream uses the stricter\n * type. Requiring it on the INPUT made the runner reject the very classes the\n * public `MigrationConstructor` describes.\n *\n * It constructs a MigrationContract rather than the abstract Migration class for the\n * same reason: `typeof Migration` is abstract and cannot satisfy `new () => Migration`,\n * and the public MigrationConstructor is declared against the contract. The runner only\n * ever uses contract members on what it registers.\n */\ntype RegisterableMigration = (new () => MigrationContract) & {\n migrationName?: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * Resolved instance data for a single pending migration.\n * @internal\n */\ntype MigrationData = {\n MigrationClass: MigrationClass;\n migration: Migration;\n name: string;\n /** Data source this migration runs against (its own, else the runner's). */\n dataSource: DataSource;\n /** Serialized `up()` statements (empty for direct-execution drivers). */\n statements: string[];\n /** Same as `statements`, with queued data steps kept in authored order. */\n steps: MigrationStep[];\n /** Whether the migration runs inside a transaction. */\n transactional: boolean;\n /** Driver has no SQL dialect (MongoDB): executed through `runMigration`. */\n direct: boolean;\n};\n\n/**\n * Options for migration execution.\n */\ntype ExecuteOptions = {\n /** Run in dry-run mode (no actual changes) */\n readonly dryRun?: boolean;\n /** Record to migrations table (default: true for batch, false for single) */\n readonly record?: boolean;\n /**\n * Rollback only: delete the `_migrations` rows whose migration file is no\n * longer registered, instead of failing on them.\n */\n readonly pruneMissing?: boolean;\n};\n\n/** Name of the lock document Mongo migrations claim inside the migrations collection. */\nconst MIGRATION_LOCK_NAME = \"__warlock_migration_lock__\";\nconst MIGRATION_LOCK_KEY = \"warlock:migrations\";\nconst MIGRATION_LOCK_TTL_MS = 10 * 60 * 1000;\nconst MIGRATION_LOCK_WAIT_MS = 60 * 1000;\nconst MIGRATION_LOCK_RETRY_MS = 1000;\n\n/** Held lock for one data source. `refresh` extends the TTL; `release` frees it. */\ntype MigrationLock = {\n refresh: () => Promise<void>;\n release: () => Promise<void>;\n};\n\ntype PgLockClient = {\n query: (sql: string, params?: unknown[]) => Promise<unknown>;\n release: () => void;\n};\n\n/** Minimal Mongo surface the lock needs (kept structural: no driver import). */\ntype MongoLockDatabase = {\n collection: (name: string) => {\n findOneAndUpdate: (filter: object, update: object, options: object) => Promise<unknown>;\n findOne: (filter: object) => Promise<{ owner?: string; expiresAt?: unknown } | null>;\n deleteOne: (filter: object) => Promise<unknown>;\n };\n};\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Derive a migration name from a file path: drop everything after the first dot\n * and strip a trailing `-migration` / `_migration` suffix. Shared by every CLI\n * so the same file is recorded under the same name.\n */\nexport function inferMigrationName(file: string): string {\n const basename = path.basename(file).split(\".\")[0] ?? \"\";\n\n return basename.replace(/-migration$/, \"\").replace(/_migration$/, \"\");\n}\n\n/**\n * Migration runner that executes migrations.\n *\n * This is a pure executor - it doesn't discover migrations.\n * Discovery is handled by the framework (e.g., @warlock.js/core CLI).\n *\n * The migration name is read from the static `name` property on the class,\n * which should be set by the CLI after importing:\n *\n * @example\n * ```typescript\n * // In CLI after importing:\n * const { default: MigrationClass } = await import(\"./create-users.migration.ts\");\n * MigrationClass.migrationName ??= \"create-users\";\n *\n * // Then register or execute:\n * runner.register(MigrationClass);\n * // or\n * await runner.execute(MigrationClass);\n * ```\n *\n * @example\n * ```typescript\n * // Simple direct execution\n * await runner.execute(CreateUsersTable);\n * await runner.rollback(CreateUsersTable);\n *\n * // Registry pattern for batch operations\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * await runner.runAll();\n * await runner.rollbackAll();\n * ```\n */\nexport class MigrationRunner {\n /** Registered migrations */\n public readonly migrations: MigrationClass[] = [];\n\n /** Data source to use */\n private dataSource?: DataSource;\n\n /** Cached migration drivers, one per data source */\n private readonly migrationDrivers = new Map<DataSource, MigrationDriverContract>();\n\n /** Table name for tracking migrations */\n private readonly migrationsTable: string;\n\n /** Whether to log operations */\n private readonly verbose: boolean;\n\n /**\n * Create a new migration runner.\n *\n * @param options - Runner options\n */\n public constructor(\n options: {\n dataSource?: DataSource;\n migrationsTable?: string;\n verbose?: boolean;\n } = {},\n ) {\n this.dataSource = options.dataSource;\n this.migrationsTable = options.migrationsTable ?? \"_migrations\";\n this.verbose = options.verbose ?? true;\n }\n\n // ============================================================================\n // DATA SOURCE\n // ============================================================================\n\n /**\n * Set the data source.\n */\n public setDataSource(dataSource: DataSource): this {\n this.dataSource = dataSource;\n this.migrationDrivers.clear();\n return this;\n }\n\n /**\n * Get the data source.\n */\n private getDataSource(): DataSource {\n if (!this.dataSource) {\n this.dataSource = dataSourceRegistry.get();\n }\n return this.dataSource;\n }\n\n /**\n * Get the migration driver.\n */\n private getMigrationDriver(\n dataSource: DataSource = this.getDataSource(),\n ): MigrationDriverContract {\n let driver = this.migrationDrivers.get(dataSource);\n if (!driver) {\n driver = dataSource.driver.migrationDriver();\n this.migrationDrivers.set(dataSource, driver);\n }\n return driver;\n }\n\n /**\n * Resolve a migration's declared data source (name or instance).\n * Falls back to the runner's own data source when it declares none.\n */\n private resolveDataSource(declared?: string | DataSource): DataSource {\n if (!declared) return this.getDataSource();\n if (typeof declared === \"string\") return dataSourceRegistry.get(declared);\n return declared;\n }\n\n /** Data source a registered migration class runs against. */\n private sourceOf(MigrationClass: MigrationClass): DataSource {\n return this.resolveDataSource(new MigrationClass().dataSource);\n }\n\n /** Distinct data sources across the registered migrations (runner's own included). */\n private getSources(): DataSource[] {\n const sources = new Set<DataSource>([this.getDataSource()]);\n for (const MigrationClass of this.migrations) {\n sources.add(this.sourceOf(MigrationClass));\n }\n return [...sources];\n }\n\n /**\n * Resolve whether a migration runs in a transaction:\n * 1. migration-level flag (instance, else the static from `Migration.create/alter`)\n * 2. `CONCURRENTLY` statements cannot run in a transaction block\n * 3. data-source config\n * 4. driver default\n */\n private resolveTransactional(\n MigrationClass: MigrationClass,\n migration: Migration,\n dataSource: DataSource,\n statements: string[] = [],\n ): boolean {\n const explicit =\n migration.transactional ?? (MigrationClass as { transactional?: boolean }).transactional;\n\n if (explicit !== undefined) return explicit;\n\n if (statements.some((sql) => /\\bCONCURRENTLY\\b/i.test(sql))) return false;\n\n return (\n dataSource.migrations?.transactional ??\n this.getMigrationDriver(dataSource).getDefaultTransactional()\n );\n }\n\n // ============================================================================\n // LOCKING\n // ============================================================================\n\n /** Locks held by the run in progress (Mongo TTL heartbeat). */\n private activeLocks: MigrationLock[] = [];\n\n /** Extend every held lock's TTL; called between migrations. */\n private async refreshLocks(): Promise<void> {\n for (const lock of this.activeLocks) {\n await lock.refresh();\n }\n }\n\n /**\n * Run `callback` while holding a migration lock on every given data source, so\n * concurrent `migrate` invocations (replicas, init containers) serialize.\n */\n private async withLock<T>(sources: DataSource[], callback: () => Promise<T>): Promise<T> {\n const held: MigrationLock[] = [];\n\n try {\n for (const dataSource of sources) {\n const lock = await this.acquireLock(dataSource);\n if (lock) held.push(lock);\n }\n\n this.activeLocks = held;\n\n return await callback();\n } finally {\n this.activeLocks = [];\n\n for (const lock of held.reverse()) {\n try {\n await lock.release();\n } catch (error) {\n log.warn(\n \"database\",\n \"migration\",\n `Failed to release migration lock: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n }\n\n /** Acquire the lock for one data source; `undefined` when its driver has no lock support. */\n private async acquireLock(dataSource: DataSource): Promise<MigrationLock | undefined> {\n const driver = dataSource.driver as unknown as {\n name: string;\n getClient?: () => { connect?: () => Promise<PgLockClient> };\n getDatabase?: () => MongoLockDatabase;\n };\n\n if (driver.name === \"postgres\" && driver.getClient) {\n // A dedicated client: advisory locks are per-session, not per-pool.\n const client = await driver.getClient().connect?.();\n if (!client) return undefined;\n\n try {\n await client.query(\"SELECT pg_advisory_lock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } catch (error) {\n client.release();\n throw error;\n }\n\n return {\n refresh: async () => {},\n release: async () => {\n try {\n await client.query(\"SELECT pg_advisory_unlock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } finally {\n client.release();\n }\n },\n };\n }\n\n if (driver.getDatabase) {\n // The unique index on `name` (created here) makes the claim below atomic.\n await this.getMigrationDriver(dataSource).ensureMigrationsTable(this.migrationsTable);\n\n const collection = driver.getDatabase().collection(this.migrationsTable);\n const owner = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n const deadline = Date.now() + MIGRATION_LOCK_WAIT_MS;\n\n const claim = async (): Promise<boolean> => {\n const now = new Date();\n\n try {\n await collection.findOneAndUpdate(\n {\n name: MIGRATION_LOCK_NAME,\n $or: [{ expiresAt: { $lt: now } }, { owner }],\n },\n {\n $set: { owner, expiresAt: new Date(now.getTime() + MIGRATION_LOCK_TTL_MS) },\n $setOnInsert: { batch: 0 },\n },\n { upsert: true },\n );\n\n return true;\n } catch (error) {\n // Held by someone else: the upsert collides with the unique `name` index.\n if ((error as { code?: number }).code === 11000) return false;\n throw error;\n }\n };\n\n while (!(await claim())) {\n if (Date.now() >= deadline) {\n const holder = await collection.findOne({ name: MIGRATION_LOCK_NAME });\n throw new Error(\n `Could not acquire the migration lock within ${MIGRATION_LOCK_WAIT_MS / 1000}s; ` +\n `held by \"${holder?.owner ?? \"unknown\"}\" until ${holder?.expiresAt ?? \"unknown\"}.`,\n );\n }\n\n await sleep(MIGRATION_LOCK_RETRY_MS);\n }\n\n return {\n refresh: async () => {\n await claim();\n },\n release: async () => {\n await collection.deleteOne({ name: MIGRATION_LOCK_NAME, owner });\n },\n };\n }\n\n return undefined;\n }\n\n // ============================================================================\n // REGISTRATION\n // ============================================================================\n\n /**\n * Register a migration.\n *\n * The migration name is read from `MigrationClass.migrationName`.\n *\n * @param MigrationClass - Migration class (must have static `name` set)\n * @param origin - Registration source; defaults to `\"app\"` for direct registrations.\n * @returns This runner for chaining\n *\n * @example\n * ```typescript\n * CreateUsersTable.migrationName = \"2024-01-15_create-users\";\n * runner.register(CreateUsersTable);\n * ```\n */\n public register(MigrationClass: RegisterableMigration, origin: MigrationOrigin = \"app\"): this {\n const name = MigrationClass.migrationName;\n if (!name) {\n throw new Error(\n `Migration class must have a static 'migrationName' property set. ` +\n `Set it in CLI after importing: MigrationClass.migrationName = \"filename\";`,\n );\n }\n const existing = this.migrations.find((m) => m.migrationName === name);\n\n if (existing) {\n // Re-registering the same class is idempotent; a DIFFERENT class under the\n // same name would silently never run, so fail loudly.\n if ((existing as unknown) !== MigrationClass) {\n throw new Error(\n `Duplicate migration name \"${name}\": two different migration classes resolve to the same name. ` +\n `Rename one of the files (or set a unique static 'migrationName').`,\n );\n }\n\n return this;\n }\n\n // `name` is proven present by the throw above, so this satisfies the stricter\n // stored type that every reader downstream relies on.\n MigrationClass.origin = origin;\n this.migrations.push(MigrationClass as MigrationClass);\n\n return this;\n }\n\n /**\n * Register multiple migrations.\n *\n * @param migrations - Array of migration classes\n * @returns This runner for chaining\n */\n public registerMany(migrations: RegisterableMigration[]): this {\n for (const MigrationClass of migrations) {\n this.register(MigrationClass);\n }\n return this;\n }\n\n /**\n * Clear all registered migrations.\n */\n public clear(): this {\n this.migrations.length = 0;\n return this;\n }\n\n /**\n * Get all registered migration names.\n */\n public getRegisteredNames(): string[] {\n return this.migrations.map((m) => m.migrationName);\n }\n\n // ============================================================================\n // SINGLE EXECUTION\n // ============================================================================\n\n /**\n * Execute a single migration's up() method.\n *\n * @param MigrationClass - Migration class to execute\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.execute(CreateUsersTable);\n * await runner.execute(AddEmailIndex, { dryRun: true });\n * ```\n */\n public async run(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"up\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n /**\n * Execute a single migration's down() method.\n *\n * @param MigrationClass - Migration class to rollback\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.rollback(CreateUsersTable);\n * ```\n */\n public async rollback(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"down\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n // ============================================================================\n // BATCH EXECUTION (REGISTERED MIGRATIONS)\n // ============================================================================\n\n /**\n * Run all pending registered migrations.\n *\n * Only runs migrations not already in the migrations table.\n *\n * @param options - Execution options\n * @returns Results for each migration\n *\n * @example\n * ```typescript\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * const results = await runner.runAll();\n * ```\n */\n public async runAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // A dry run writes nothing, so it needs no lock.\n if (options.dryRun) return this.runAllUnlocked(options);\n\n // The pending set is computed INSIDE the lock, so a replica that waited sees\n // what the winner already applied.\n return this.withLock(this.getSources(), () => this.runAllUnlocked(options));\n }\n\n private async runAllUnlocked(options: ExecuteOptions): Promise<MigrationResult[]> {\n const { dryRun = false, record = true } = options;\n\n const results: MigrationResult[] = [];\n\n // Get pending migrations (a dry run must not create the migrations table)\n const pending = await this.getPendingMigrations({ readOnly: dryRun });\n\n if (pending.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to migrate.\");\n return results;\n }\n\n // Next batch number per data source: each source has its own migrations table.\n const sources = new Set<DataSource>();\n const migrationsData: MigrationData[] = [];\n\n log.info(\"database\", \"migration\", `Found ${pending.length} pending migration(s).`);\n\n // 1. Resolve each migration's data source and transactional mode, and collect\n // its SQL. Drivers without SQL serialization (MongoDB) are executed\n // directly through the migration driver instead.\n // Extension checks fire concurrently as CREATE EXTENSION statements are met.\n const extensionChecks: Promise<void>[] = [];\n\n for (const MigrationClass of pending) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n const dataSource = this.resolveDataSource(migration.dataSource);\n sources.add(dataSource);\n\n if (dataSource.driver.supportsSqlSerialization === false) {\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements: [],\n steps: [],\n transactional: false,\n direct: true,\n });\n continue;\n }\n\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n // Collection must not run `withConnection` side effects during a dry run.\n migration.setDryRun?.(dryRun);\n\n await migration.up();\n const steps: MigrationStep[] = migration.toSteps?.() ?? migration.toSQL();\n const statements = steps.map((step) =>\n typeof step === \"string\" ? step : \"-- data step (withConnection) skipped\",\n );\n migration.setDryRun?.(false);\n\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements,\n steps,\n transactional:\n !!dataSource.driver.transaction &&\n this.resolveTransactional(MigrationClass, migration, dataSource, statements),\n direct: false,\n });\n\n for (const sql of statements) {\n if (SQLGrammar.classify(sql) === \"CREATE_EXTENSION\") {\n const ext = SQLGrammar.extractExtensionName(sql);\n if (ext) extensionChecks.push(this.informIfExtensionMissing(ext, dataSource));\n }\n }\n }\n\n // 2. Resolve all extension checks before any SQL is executed.\n await Promise.all(extensionChecks);\n\n // 3. Dry run: print statements in migration order (authored order kept; no\n // global phase sort, which would reorder add-column → backfill → NOT NULL).\n if (dryRun) {\n log.info(\"database\", \"migration\", \"Dry run enabled. Would execute the following statements:\");\n for (const data of migrationsData) {\n for (const sql of data.statements) {\n console.log(\n `-- [${SQLGrammar.classify(sql)}] Phase ${SQLGrammar.phase(sql)} [${data.name}]`,\n );\n console.log(sql + \";\\n\");\n }\n }\n return [];\n }\n\n const batches = new Map<DataSource, number>();\n for (const dataSource of sources) {\n batches.set(dataSource, await this.getNextBatchNumber(dataSource));\n }\n\n // 4. Split into runs: consecutive transactional migrations on the same data\n // source share one transaction; every other migration (non-transactional\n // or direct) runs alone.\n const runs: MigrationData[][] = [];\n for (const data of migrationsData) {\n const last = runs[runs.length - 1];\n const lastFirst = last?.[0];\n if (\n data.transactional &&\n last &&\n lastFirst?.transactional &&\n lastFirst.dataSource === data.dataSource\n ) {\n last.push(data);\n } else {\n runs.push([data]);\n }\n }\n\n for (const run of runs) {\n const first = run[0];\n if (!first) continue;\n await this.refreshLocks();\n const dataSource = first.dataSource;\n const nextBatch = batches.get(dataSource)!;\n const startTime = Date.now();\n\n if (first.direct) {\n const result = await this.runMigration(first.MigrationClass, \"up\", {\n dryRun,\n record,\n batch: nextBatch,\n });\n results.push(result);\n if (!result.success) break;\n continue;\n }\n\n const driver = dataSource.driver;\n let failed = false;\n let errorMessage = \"\";\n /** The migration that owns the SQL statement that threw. */\n let failingMigrationName: string | undefined;\n\n const executeRun = async (): Promise<void> => {\n for (const data of run) {\n for (const step of data.steps) {\n try {\n if (typeof step === \"string\") await driver.query(step);\n else await step.data();\n } catch (err) {\n failingMigrationName = data.name;\n throw err;\n }\n }\n\n // A non-transactional migration is recorded right after it applied.\n // Transactional ones are recorded inside the shared transaction.\n if (record) {\n await this.recordMigration(\n data.name,\n nextBatch,\n data.MigrationClass.createdAt\n ? parseCreatedAt(data.MigrationClass.createdAt)\n : new Date(),\n dataSource,\n );\n }\n }\n };\n\n try {\n if (first.transactional && driver.transaction) {\n await driver.transaction(executeRun);\n } else {\n await executeRun();\n }\n } catch (err) {\n failed = true;\n errorMessage = err instanceof Error ? err.message : String(err);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Only the migration that owns the failing statement is marked failed;\n // the rest of its run is reported as rolled back.\n for (const data of run) {\n const isCulprit = failed && data.name === failingMigrationName;\n const wasSkipped = failed && !isCulprit;\n\n results.push({\n name: data.name,\n table: data.migration.table,\n direction: \"up\",\n success: !failed,\n error: isCulprit ? errorMessage : undefined,\n durationMs: Math.round(durationMs / run.length),\n executedAt: new Date(),\n });\n\n if (isCulprit) {\n log.error(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: ✗ Failed: ${errorMessage}`,\n );\n } else if (wasSkipped) {\n log.warn(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: rolled back (batch transaction failed)`,\n );\n } else {\n log.success(\n \"database\",\n \"migration\",\n `Migrated: ${colors.magenta(data.name)} successfully`,\n );\n }\n }\n\n if (failed) {\n log.error(\n \"database\",\n \"migration\",\n `Batch execution failed. Rollback performed if transactional.`,\n );\n throw new Error(\"Migration batch failed: \" + errorMessage);\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Migration execution complete: ${successCount}/${pending.length} migrations processed successfully.`,\n );\n\n return results;\n }\n\n /**\n * Export migrations as phase-ordered SQL files in database/sql/ directory.\n * By default, it exports all registered migrations. Use `pendingOnly: true` to export only pending ones.\n */\n public async exportSQL(\n options: { pendingOnly?: boolean; compact?: boolean } = {},\n ): Promise<void> {\n if (this.getDataSource().driver.supportsSqlSerialization === false) {\n throw new Error(\n \"SQL export is not supported on this data source — its driver has no SQL dialect. \" +\n \"Migrations on this driver execute native commands through the migration driver instead.\",\n );\n }\n\n const migrationsToExport = options.pendingOnly\n ? await this.getPendingMigrations({ readOnly: true })\n : this.migrations;\n\n if (migrationsToExport.length === 0) {\n log.warn(\"database\", \"migration\", \"No migrations to export.\");\n return;\n }\n\n log.info(\n \"database\",\n \"migration\",\n `Exporting ${migrationsToExport.length} ${options.pendingOnly ? \"pending \" : \"\"}migration(s) to SQL files...`,\n );\n\n const upStatements: TaggedSQL[] = [];\n // Down SQL is grouped per migration so only the migration order is reversed,\n // never the statements inside one migration's down().\n const downGroups: { createdAt?: string; index: number; statements: TaggedSQL[] }[] = [];\n\n for (const [index, MigrationClass] of migrationsToExport.entries()) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n\n // Export performs no writes: `withConnection` callbacks are skipped.\n migration.setDryRun?.(true);\n\n // Collect up SQL\n await migration.up();\n for (const sql of migration.toSQL()) {\n upStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n\n // Collect down SQL (reuse same instance — toSQL() cleared pendingOps)\n await migration.down();\n const statements: TaggedSQL[] = [];\n for (const sql of migration.toSQL()) {\n statements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n downGroups.push({ createdAt: MigrationClass.createdAt, index, statements });\n }\n\n const sortedUp = SQLGrammar.sort(upStatements);\n // Down SQL: newest migration first (chronological, registration order breaks\n // ties), each migration's own down() statements keep their order.\n const sortedDown = downGroups\n .sort((a, b) => {\n const byDate = (a.createdAt ?? \"\").localeCompare(b.createdAt ?? \"\");\n return byDate !== 0 ? byDate : a.index - b.index;\n })\n .reverse()\n .flatMap((group) => group.statements);\n\n const upSQLString = this.formatSQLForExport(sortedUp, options.compact);\n const downSQLString = this.formatSQLForExport(sortedDown, options.compact);\n\n const rootPath = process.cwd();\n const sqlDir = path.join(rootPath, \"database\", \"sql\");\n\n if (!fs.existsSync(sqlDir)) {\n fs.mkdirSync(sqlDir, { recursive: true });\n }\n\n const timestamp = new Date().toISOString().replace(/T/, \"_\").replace(/:/g, \"-\").split(\".\")[0];\n const upPath = path.join(sqlDir, `migration_${timestamp}.up.sql`);\n const downPath = path.join(sqlDir, `migration_${timestamp}.down.sql`);\n\n fs.writeFileSync(upPath, upSQLString);\n fs.writeFileSync(downPath, downSQLString);\n\n log.success(\"database\", \"migration\", `Exported to:\\n- ${upPath}\\n- ${downPath}`);\n }\n\n /**\n * Rollback the last batch of migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackLast(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n return this.rollbackBatches(1, options);\n }\n\n /**\n * Rollback N batches of migrations.\n *\n * @param batches - Number of batches to rollback\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackBatches(\n batches: number,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult[]> {\n if (options.dryRun) return this.rollbackBatchesUnlocked(batches, options);\n\n return this.withLock(this.getSources(), () => this.rollbackBatchesUnlocked(batches, options));\n }\n\n private async rollbackBatchesUnlocked(\n batches: number,\n options: ExecuteOptions,\n ): Promise<MigrationResult[]> {\n const dryRun = options.dryRun ?? false;\n const record = options.record ?? true;\n const results: MigrationResult[] = [];\n\n const toRollback = await this.getMigrationsToRollback(batches, {\n pruneMissing: options.pruneMissing,\n readOnly: dryRun,\n });\n\n if (toRollback.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to rollback.\");\n return results;\n }\n\n log.info(\"database\", \"migration\", `Rolling back ${toRollback.length} migration(s).`);\n\n for (const MigrationClass of toRollback) {\n await this.refreshLocks();\n\n const result = await this.runMigration(MigrationClass, \"down\", {\n dryRun,\n record,\n });\n results.push(result);\n\n if (!result.success) {\n break;\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Rollback complete: ${successCount}/${toRollback.length} successful.`,\n );\n\n return results;\n }\n\n /**\n * Rollback all executed migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // Batch numbers are per data source; rolling back \"all\" is every batch of each.\n return this.rollbackBatches(Number.POSITIVE_INFINITY, options);\n }\n\n /**\n * Reset and re-run: rollback all then run all.\n *\n * @param options - Execution options\n * @returns Combined results\n */\n public async fresh(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n const rollbackResults = await this.rollbackAll(options);\n const runResults = await this.runAll(options);\n return [...rollbackResults, ...runResults];\n }\n\n // ============================================================================\n // STATUS\n // ============================================================================\n\n /**\n * Get status of all registered migrations.\n */\n public async status(): Promise<\n Array<{\n name: string;\n table: string;\n executed: boolean;\n batch: number | null;\n }>\n > {\n const executedBySource = new Map<DataSource, Map<string, MigrationRecord>>();\n\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly: true });\n executedBySource.set(dataSource, new Map(executed.map((r) => [r.name, r])));\n }\n\n return this.migrations.map((MigrationClass) => {\n const instance = new MigrationClass();\n const name = MigrationClass.migrationName;\n const record = executedBySource.get(this.sourceOf(MigrationClass))?.get(name);\n return {\n name,\n table: instance.table,\n executed: !!record,\n batch: record?.batch ?? null,\n };\n });\n }\n\n // ============================================================================\n // EXTENSION PRE-FLIGHT\n // ============================================================================\n\n /**\n * Check whether a database extension is available and inform the developer\n * if it is not installed.\n *\n * Does NOT throw — execution proceeds normally. If the extension is truly\n * missing, the database will surface its own error with full context already\n * displayed to the developer.\n *\n * @example\n * await this.informIfExtensionMissing(\"vector\");\n */\n private async informIfExtensionMissing(\n extension: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n try {\n const migrationDriver = this.getMigrationDriver(dataSource);\n const isAvailable = await migrationDriver.isExtensionAvailable(extension);\n\n if (!isAvailable) {\n const hr = \"─\".repeat(60);\n console.log(`\\n${colors.yellow(hr)}`);\n console.log(colors.yellow(` ⚠ Missing Database Extension: ${colors.bold(extension)}`));\n console.log(colors.yellow(hr));\n console.log();\n console.log(` A pending migration requires the ${colors.cyan(extension)} extension,`);\n console.log(` which is not installed on your database server.`);\n console.log();\n console.log(\n ` ${colors.bold(\"This means the physical database server is missing the extension package.\")}`,\n );\n console.log(` You cannot simply run CREATE EXTENSION until the package is installed`);\n console.log(` on the host machine or Docker container.`);\n console.log();\n\n const docsUrl = migrationDriver.getExtensionDocsUrl(extension);\n if (docsUrl) {\n console.log(` ${colors.bold(\"Or follow the installation guide:\")}`);\n console.log(` ${colors.cyan(docsUrl)}`);\n }\n console.log(`\\n${colors.yellow(hr)}\\n`);\n }\n } catch {\n // If the check itself fails, silently skip — don't break the migration.\n }\n }\n\n // ============================================================================\n // PRIVATE HELPERS\n // ============================================================================\n\n /**\n * Run a single migration.\n */\n private async runMigration(\n MigrationClass: MigrationClass,\n direction: \"up\" | \"down\",\n options: {\n dryRun?: boolean;\n record?: boolean;\n batch?: number;\n } = {},\n ): Promise<MigrationResult> {\n const { dryRun = false, record = true } = options;\n const startTime = Date.now();\n let success = true;\n let error: string | undefined;\n\n const migration = new MigrationClass();\n const name = MigrationClass.migrationName;\n\n log.info(\n \"database\",\n \"migration\",\n `${direction === \"up\" ? \"Migrating\" : \"Rolling back\"}: ${colors.magenta(name)}...`,\n );\n\n try {\n if (!dryRun) {\n // The migration runs against its declared data source (default: the runner's)\n // and is recorded in THAT source's migrations table.\n const dataSource = this.resolveDataSource(migration.dataSource);\n const driver = this.getMigrationDriver(dataSource);\n migration.setDriver(driver);\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n\n // ============================================================================\n // TRANSACTION RESOLUTION (3-tier hierarchy)\n // ============================================================================\n // 1. Migration-level explicit override (instance or static)\n // 2. CONCURRENTLY statements (cannot run in a transaction block)\n // 3. Config-level global override\n // 4. Driver default (PostgreSQL: true, MongoDB: false)\n // Resolved below, once the statements are known.\n\n // ============================================================================\n // EXECUTE WITH OR WITHOUT TRANSACTION\n // ============================================================================\n\n // Collect the requested direction's operations\n if (direction === \"up\") {\n await migration.up();\n } else {\n await migration.down();\n }\n\n const databaseDriver = dataSource.driver;\n\n // SQL-capable drivers serialize the queued operations to SQL strings;\n // drivers without SQL serialization (MongoDB) keep them queued and\n // execute them directly through the migration driver.\n const directExecution = databaseDriver.supportsSqlSerialization === false;\n const steps: MigrationStep[] = directExecution\n ? []\n : (migration.toSteps?.() ?? migration.toSQL());\n const sqlStatements = steps.filter((step): step is string => typeof step === \"string\");\n const shouldUseTransaction = this.resolveTransactional(\n MigrationClass,\n migration,\n dataSource,\n sqlStatements,\n );\n\n const applyMigration = async (): Promise<void> => {\n if (directExecution) {\n await migration.execute();\n return;\n }\n\n // Execute generated SQL statements sequentially (no phase-sorting here since it's single execution)\n for (const step of steps) {\n if (typeof step === \"string\") await databaseDriver.query(step);\n else await step.data();\n }\n };\n\n if (shouldUseTransaction && databaseDriver.transaction) {\n // Transactional execution\n await databaseDriver.transaction(async () => {\n await applyMigration();\n\n // Record migration tracking\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n });\n } else {\n // Non-transactional execution\n await applyMigration();\n\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n }\n }\n } catch (err) {\n success = false;\n error = err instanceof Error ? err.message : String(err);\n log.error(\"database\", \"migration\", `${colors.magenta(name)}: ✗ Failed: ${error}`);\n throw err;\n }\n\n const durationMs = Date.now() - startTime;\n\n if (success) {\n log.success(\n \"database\",\n \"migration\",\n `${direction == \"up\" ? \"Migrated\" : \"Rolled back\"}: ${colors.magenta(name)} successfully (${durationMs}ms)`,\n );\n }\n\n return {\n name,\n table: migration.table,\n direction,\n success,\n error,\n durationMs,\n executedAt: new Date(),\n };\n }\n\n /**\n * Create, configure, and return a ready-to-use migration instance.\n *\n * Centralises the repeated \"new + setDriver + setMigrationDefaults\" boilerplate\n * that all batch/single execution paths need.\n *\n * @internal\n */\n private createMigrationInstance(MigrationClass: MigrationClass): Migration {\n const migration = new MigrationClass();\n const dataSource = this.resolveDataSource(migration.dataSource);\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n return migration;\n }\n\n /**\n * Format an ordered array of TaggedSQL into a human-readable SQL file string.\n *\n * Consecutive statements that belong to the same (phase, migration) group share\n * a single block comment at the top, avoiding the noisy per-statement repetition.\n *\n * Example output:\n * ```sql\n * /* Phase 3 [create-users] *\\/\n * ALTER TABLE \"users\" ADD COLUMN \"name\" TEXT NOT NULL;\n * ALTER TABLE \"users\" ADD COLUMN \"email\" TEXT NOT NULL;\n *\n * /* Phase 4 [create-users] *\\/\n * CREATE UNIQUE INDEX ...;\n * ```\n *\n * @internal\n */\n private formatSQLForExport(statements: TaggedSQL[], compact: boolean = false): string {\n const lines: string[] = [];\n\n if (compact) {\n // Just output raw statements, no grouping, no blank lines\n for (const stmt of statements) {\n lines.push(`${stmt.sql};`);\n }\n return lines.join(\"\\n\");\n }\n\n // Group statements by their phase and migration name\n const grouped = new Map<string, string[]>();\n\n for (const stmt of statements) {\n const groupKey = `Phase ${stmt.phase} [${stmt.migrationName}]`;\n if (!grouped.has(groupKey)) {\n grouped.set(groupKey, []);\n }\n grouped.get(groupKey)!.push(stmt.sql);\n }\n\n // Format each group\n for (const [groupKey, sqls] of grouped.entries()) {\n if (lines.length > 0) lines.push(\"\"); // blank line between groups\n lines.push(`/* ${groupKey} */`);\n for (const sql of sqls) {\n lines.push(`${sql};`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Get pending (not executed) registered migrations, in the order they would\n * execute.\n *\n * ⚠️ \"Registered\" is load-bearing. This filters `this.migrations`, which is\n * populated only by `register()` / `registerMany()`. A caller that has not\n * registered anything gets `[]` — indistinguishable from a database with\n * nothing pending. Anything reporting this set to a human MUST register\n * migrations first, or it will print a confident all-clear over an unknown.\n *\n * @see listPendingMigrations\n */\n public async getPendingMigrations(\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n // \"Executed\" is judged in each migration's own data source's migrations table.\n const executedNames = new Map<DataSource, Set<string>>();\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, options);\n executedNames.set(dataSource, new Set(executed.map((r) => r.name)));\n }\n\n const migrations = this.migrations.filter(\n (m) => !executedNames.get(this.sourceOf(m))?.has(m.migrationName),\n );\n\n return migrations.sort(sortMigrations);\n }\n\n /**\n * Get migrations to rollback, newest-first.\n *\n * A rollback must undo migrations in the exact inverse of the order `up`\n * applied them, or a `down()` will hit schema its predecessor already\n * removed — dropping a table before dropping the column added to it, say.\n *\n * The sort has to be explicitly **descending**. Reversing the executed list\n * is not enough: `getExecutedMigrations` orders by `batch, name`, so the\n * input is alphabetical rather than chronological, and reversing it only\n * yields reverse-alphabetical order. (Sorting *ascending* here — which is\n * what this method used to do after a `.reverse()` — silently restored the\n * forward `up` order and made the reverse dead code.)\n */\n private async getMigrationsToRollback(\n batches: number,\n options: { pruneMissing?: boolean; readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n const migrations: MigrationClass[] = [];\n const batchOf = new Map<MigrationClass, number>();\n const orphans: Array<{ name: string; dataSource: DataSource }> = [];\n\n // Batches are numbered per data source (each has its own migrations table).\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, {\n readOnly: options.readOnly,\n });\n if (executed.length === 0) continue;\n\n const batchNumbers = [...new Set(executed.map((r) => r.batch))]\n .sort((a, b) => b - a)\n .slice(0, batches);\n\n for (const record of executed) {\n if (!batchNumbers.includes(record.batch)) continue;\n\n const MigrationClass = this.migrations.find(\n (m) => m.migrationName === record.name && this.sourceOf(m) === dataSource,\n );\n if (MigrationClass) {\n migrations.push(MigrationClass);\n batchOf.set(MigrationClass, record.batch);\n } else {\n orphans.push({ name: record.name, dataSource });\n }\n }\n }\n\n if (orphans.length > 0) {\n if (!options.pruneMissing) {\n throw new Error(\n `Cannot roll back: ${orphans.length} executed migration(s) have no registered file: ` +\n `${orphans.map((o) => o.name).join(\", \")}. ` +\n `They were renamed, deleted, or not matched by the migration pattern. ` +\n `Restore the file(s), or pass pruneMissing (--prune-missing) to delete those records.`,\n );\n }\n\n if (!options.readOnly) {\n for (const orphan of orphans) {\n await this.removeMigrationRecord(orphan.name, orphan.dataSource);\n log.warn(\"database\", \"migration\", `Pruned orphaned migration record: ${orphan.name}`);\n }\n }\n }\n\n // Newest batch first, then newest migration first within a batch.\n return migrations.sort(\n (a, b) => (batchOf.get(b) ?? 0) - (batchOf.get(a) ?? 0) || sortMigrationsForRollback(a, b),\n );\n }\n\n /**\n * Get executed migration records.\n */\n public async getExecutedMigrations(\n dataSource: DataSource = this.getDataSource(),\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationRecord[]> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n if (options.readOnly) {\n // Dry runs and listings must not create the migrations table.\n if (!(await migrationDriver.tableExists(this.migrationsTable))) return [];\n } else {\n // A missing table is created here; every other error (connection,\n // permission…) propagates instead of looking like \"nothing executed\".\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n }\n\n const queryBuilder = driver.queryBuilder<MigrationRecord>(this.migrationsTable);\n const records = await queryBuilder.orderBy(\"batch\", \"asc\").orderBy(\"name\", \"asc\").get();\n\n // The Mongo lock document lives in this collection; it is not a migration.\n return records.filter((record) => record.name !== MIGRATION_LOCK_NAME);\n }\n\n /**\n * Record a migration.\n */\n private async recordMigration(\n name: string,\n batch: number,\n createdAt?: Date,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n // Ensure migrations table exists\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n\n await driver.insert(this.migrationsTable, {\n name,\n batch,\n executedAt: new Date(),\n createdAt,\n });\n }\n\n /**\n * Remove a migration record.\n */\n private async removeMigrationRecord(\n name: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n await driver.delete(this.migrationsTable, { name });\n }\n\n /**\n * Get next batch number.\n */\n private async getNextBatchNumber(\n dataSource: DataSource = this.getDataSource(),\n readOnly = false,\n ): Promise<number> {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly });\n if (executed.length === 0) return 1;\n return Math.max(...executed.map((r) => r.batch)) + 1;\n }\n}\n\nexport const migrationRunner = new MigrationRunner();\n"],"mappings":";;;;;;;;;;;AAqFA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB,MAAU;AACxC,MAAM,yBAAyB,KAAK;AACpC,MAAM,0BAA0B;AAsBhC,MAAM,SAAS,OAAe,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAOpF,SAAgB,mBAAmB,MAAsB;CAGvD,QAFiB,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAEvC,CAAC,QAAQ,eAAe,EAAE,CAAC,CAAC,QAAQ,eAAe,EAAE;AACtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,kBAAb,MAA6B;;CAE3B,AAAgB,aAA+B,CAAC;;CAGhD,AAAQ;;CAGR,AAAiB,mCAAmB,IAAI,IAAyC;;CAGjF,AAAiB;;CAGjB,AAAiB;;;;;;CAOjB,AAAO,YACL,UAII,CAAC,GACL;EACA,KAAK,aAAa,QAAQ;EAC1B,KAAK,kBAAkB,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W,OACM;EACjB,MAAM,WAAW,MAAM,KAAK,sBAAsB,YAAY,EAAE,SAAS,CAAC;EAC1E,IAAI,SAAS,WAAW,GAAG,OAAO;EAClC,OAAO,KAAK,IAAI,GAAG,SAAS,KAAK,MAAM,EAAE,KAAK,CAAC,IAAI;CACrD;AACF;AAEA,MAAa,kBAAkB,IAAI,gBAAgB"}
1
+ {"version":3,"file":"migration-runner.mjs","names":[],"sources":["../../../../../../../../packages/cascade/src/migration/migration-runner.ts"],"sourcesContent":["import { colors } from \"@mongez/copper\";\nimport { log } from \"@warlock.js/logger\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport type { MigrationDriverContract } from \"../contracts/migration-driver.contract\";\nimport type { DataSource } from \"../data-source/data-source\";\nimport { dataSourceRegistry } from \"../data-source/data-source-registry\";\nimport {\n type Migration,\n type MigrationContract,\n type MigrationOrigin,\n type MigrationStep,\n} from \"./migration\";\nimport { sortMigrations, sortMigrationsForRollback } from \"./migration-order\";\nimport { parseCreatedAt } from \"./parse-created-at\";\nimport { SQLGrammar } from \"./sql-grammar\";\nimport type { MigrationRecord, MigrationResult, TaggedSQL } from \"./types\";\n\n/**\n * Migration class type with static name property.\n */\ntype MigrationClass = (new () => Migration) & {\n migrationName: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * What a caller may hand to {@link MigrationRunner.register}.\n *\n * Looser than {@link MigrationClass} in exactly one way: `migrationName` may be\n * absent. That is the documented workflow — the CLI imports a migration file and\n * sets the name from the filename afterwards — and `register()` enforces it at\n * runtime, throwing a message that says so. Once past that check the name IS\n * present, which is why everything stored and read downstream uses the stricter\n * type. Requiring it on the INPUT made the runner reject the very classes the\n * public `MigrationConstructor` describes.\n *\n * It constructs a MigrationContract rather than the abstract Migration class for the\n * same reason: `typeof Migration` is abstract and cannot satisfy `new () => Migration`,\n * and the public MigrationConstructor is declared against the contract. The runner only\n * ever uses contract members on what it registers.\n */\ntype RegisterableMigration = (new () => MigrationContract) & {\n migrationName?: string;\n createdAt?: string;\n origin?: MigrationOrigin;\n};\n\n/**\n * Resolved instance data for a single pending migration.\n * @internal\n */\ntype MigrationData = {\n MigrationClass: MigrationClass;\n migration: Migration;\n name: string;\n /** Data source this migration runs against (its own, else the runner's). */\n dataSource: DataSource;\n /** Serialized `up()` statements (empty for direct-execution drivers). */\n statements: string[];\n /** Same as `statements`, with queued data steps kept in authored order. */\n steps: MigrationStep[];\n /** Whether the migration runs inside a transaction. */\n transactional: boolean;\n /** Driver has no SQL dialect (MongoDB): executed through `runMigration`. */\n direct: boolean;\n};\n\n/**\n * Options for migration execution.\n */\ntype ExecuteOptions = {\n /** Run in dry-run mode (no actual changes) */\n readonly dryRun?: boolean;\n /** Record to migrations table (default: true for batch, false for single) */\n readonly record?: boolean;\n /**\n * Rollback only: delete the `_migrations` rows whose migration file is no\n * longer registered, instead of failing on them.\n */\n readonly pruneMissing?: boolean;\n};\n\n/** Name of the lock document Mongo migrations claim inside the migrations collection. */\nconst MIGRATION_LOCK_NAME = \"__warlock_migration_lock__\";\nconst MIGRATION_LOCK_KEY = \"warlock:migrations\";\nconst MIGRATION_LOCK_TTL_MS = 10 * 60 * 1000;\nconst MIGRATION_LOCK_WAIT_MS = 60 * 1000;\nconst MIGRATION_LOCK_RETRY_MS = 1000;\n\n/** Held lock for one data source. `refresh` extends the TTL; `release` frees it. */\ntype MigrationLock = {\n refresh: () => Promise<void>;\n release: () => Promise<void>;\n};\n\ntype PgLockClient = {\n query: (sql: string, params?: unknown[]) => Promise<unknown>;\n release: () => void;\n};\n\n/** Minimal Mongo surface the lock needs (kept structural: no driver import). */\ntype MongoLockDatabase = {\n collection: (name: string) => {\n findOneAndUpdate: (filter: object, update: object, options: object) => Promise<unknown>;\n findOne: (filter: object) => Promise<{ owner?: string; expiresAt?: unknown } | null>;\n deleteOne: (filter: object) => Promise<unknown>;\n };\n};\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Derive a migration name from a file path: drop everything after the first dot\n * and strip a trailing `-migration` / `_migration` suffix. Shared by every CLI\n * so the same file is recorded under the same name.\n */\nexport function inferMigrationName(file: string): string {\n const basename = path.basename(file).split(\".\")[0] ?? \"\";\n\n return basename.replace(/-migration$/, \"\").replace(/_migration$/, \"\");\n}\n\n/**\n * Migration runner that executes migrations.\n *\n * This is a pure executor - it doesn't discover migrations.\n * Discovery is handled by the framework (e.g., @warlock.js/core CLI).\n *\n * The migration name is read from the static `name` property on the class,\n * which should be set by the CLI after importing:\n *\n * @example\n * ```typescript\n * // In CLI after importing:\n * const { default: MigrationClass } = await import(\"./create-users.migration.ts\");\n * MigrationClass.migrationName ??= \"create-users\";\n *\n * // Then register or execute:\n * runner.register(MigrationClass);\n * // or\n * await runner.execute(MigrationClass);\n * ```\n *\n * @example\n * ```typescript\n * // Simple direct execution\n * await runner.execute(CreateUsersTable);\n * await runner.rollback(CreateUsersTable);\n *\n * // Registry pattern for batch operations\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * await runner.runAll();\n * await runner.rollbackAll();\n * ```\n */\nexport class MigrationRunner {\n /** Registered migrations */\n public readonly migrations: MigrationClass[] = [];\n\n /** Data source to use */\n private dataSource?: DataSource;\n\n /** Cached migration drivers, one per data source */\n private readonly migrationDrivers = new Map<DataSource, MigrationDriverContract>();\n\n /** Table name for tracking migrations */\n private readonly migrationsTable: string;\n\n /** Whether to log operations */\n private readonly verbose: boolean;\n\n /**\n * Create a new migration runner.\n *\n * @param options - Runner options\n */\n public constructor(\n options: {\n dataSource?: DataSource;\n migrationsTable?: string;\n verbose?: boolean;\n } = {},\n ) {\n this.dataSource = options.dataSource;\n this.migrationsTable = options.migrationsTable ?? \"_migrations\";\n this.verbose = options.verbose ?? true;\n }\n\n // ============================================================================\n // DATA SOURCE\n // ============================================================================\n\n /**\n * Set the data source.\n */\n public setDataSource(dataSource: DataSource): this {\n this.dataSource = dataSource;\n this.migrationDrivers.clear();\n return this;\n }\n\n /**\n * Get the data source.\n */\n private getDataSource(): DataSource {\n if (!this.dataSource) {\n this.dataSource = dataSourceRegistry.get();\n }\n return this.dataSource;\n }\n\n /**\n * Get the migration driver.\n */\n private getMigrationDriver(\n dataSource: DataSource = this.getDataSource(),\n ): MigrationDriverContract {\n let driver = this.migrationDrivers.get(dataSource);\n if (!driver) {\n driver = dataSource.driver.migrationDriver();\n this.migrationDrivers.set(dataSource, driver);\n }\n return driver;\n }\n\n /**\n * Resolve a migration's declared data source (name or instance).\n * Falls back to the runner's own data source when it declares none.\n */\n private resolveDataSource(declared?: string | DataSource): DataSource {\n if (!declared) return this.getDataSource();\n if (typeof declared === \"string\") return dataSourceRegistry.get(declared);\n return declared;\n }\n\n /** Data source a registered migration class runs against. */\n private sourceOf(MigrationClass: MigrationClass): DataSource {\n return this.resolveDataSource(new MigrationClass().dataSource);\n }\n\n /** Distinct data sources across the registered migrations (runner's own included). */\n private getSources(): DataSource[] {\n const sources = new Set<DataSource>([this.getDataSource()]);\n for (const MigrationClass of this.migrations) {\n sources.add(this.sourceOf(MigrationClass));\n }\n return [...sources];\n }\n\n /**\n * Resolve whether a migration runs in a transaction:\n * 1. migration-level flag (instance, else the static from `Migration.create/alter`)\n * 2. `CONCURRENTLY` statements cannot run in a transaction block\n * 3. data-source config\n * 4. driver default\n */\n private resolveTransactional(\n MigrationClass: MigrationClass,\n migration: Migration,\n dataSource: DataSource,\n statements: string[] = [],\n ): boolean {\n const explicit =\n migration.transactional ?? (MigrationClass as { transactional?: boolean }).transactional;\n\n if (explicit !== undefined) return explicit;\n\n if (statements.some((sql) => /\\bCONCURRENTLY\\b/i.test(sql))) return false;\n\n return (\n dataSource.migrations?.transactional ??\n this.getMigrationDriver(dataSource).getDefaultTransactional()\n );\n }\n\n // ============================================================================\n // LOCKING\n // ============================================================================\n\n /** Locks held by the run in progress (Mongo TTL heartbeat). */\n private activeLocks: MigrationLock[] = [];\n\n /** Extend every held lock's TTL; called between migrations. */\n private async refreshLocks(): Promise<void> {\n for (const lock of this.activeLocks) {\n await lock.refresh();\n }\n }\n\n /**\n * Run `callback` while holding a migration lock on every given data source, so\n * concurrent `migrate` invocations (replicas, init containers) serialize.\n */\n private async withLock<T>(sources: DataSource[], callback: () => Promise<T>): Promise<T> {\n const held: MigrationLock[] = [];\n\n try {\n for (const dataSource of sources) {\n const lock = await this.acquireLock(dataSource);\n if (lock) held.push(lock);\n }\n\n this.activeLocks = held;\n\n return await callback();\n } finally {\n this.activeLocks = [];\n\n for (const lock of held.reverse()) {\n try {\n await lock.release();\n } catch (error) {\n log.warn(\n \"database\",\n \"migration\",\n `Failed to release migration lock: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n }\n }\n\n /** Acquire the lock for one data source; `undefined` when its driver has no lock support. */\n private async acquireLock(dataSource: DataSource): Promise<MigrationLock | undefined> {\n const driver = dataSource.driver as unknown as {\n name: string;\n getClient?: () => { connect?: () => Promise<PgLockClient> };\n getDatabase?: () => MongoLockDatabase;\n };\n\n if (driver.name === \"postgres\" && driver.getClient) {\n // A dedicated client: advisory locks are per-session, not per-pool.\n const client = await driver.getClient().connect?.();\n if (!client) return undefined;\n\n try {\n await client.query(\"SELECT pg_advisory_lock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } catch (error) {\n client.release();\n throw error;\n }\n\n return {\n refresh: async () => {},\n release: async () => {\n try {\n await client.query(\"SELECT pg_advisory_unlock(hashtext($1))\", [MIGRATION_LOCK_KEY]);\n } finally {\n client.release();\n }\n },\n };\n }\n\n if (driver.getDatabase) {\n // The unique index on `name` (created here) makes the claim below atomic.\n await this.getMigrationDriver(dataSource).ensureMigrationsTable(this.migrationsTable);\n\n const collection = driver.getDatabase().collection(this.migrationsTable);\n const owner = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n const deadline = Date.now() + MIGRATION_LOCK_WAIT_MS;\n\n const claim = async (): Promise<boolean> => {\n const now = new Date();\n\n try {\n await collection.findOneAndUpdate(\n {\n name: MIGRATION_LOCK_NAME,\n $or: [{ expiresAt: { $lt: now } }, { owner }],\n },\n {\n $set: { owner, expiresAt: new Date(now.getTime() + MIGRATION_LOCK_TTL_MS) },\n $setOnInsert: { batch: 0 },\n },\n { upsert: true },\n );\n\n return true;\n } catch (error) {\n // Held by someone else: the upsert collides with the unique `name` index.\n if ((error as { code?: number }).code === 11000) return false;\n throw error;\n }\n };\n\n while (!(await claim())) {\n if (Date.now() >= deadline) {\n const holder = await collection.findOne({ name: MIGRATION_LOCK_NAME });\n throw new Error(\n `Could not acquire the migration lock within ${MIGRATION_LOCK_WAIT_MS / 1000}s; ` +\n `held by \"${holder?.owner ?? \"unknown\"}\" until ${holder?.expiresAt ?? \"unknown\"}.`,\n );\n }\n\n await sleep(MIGRATION_LOCK_RETRY_MS);\n }\n\n return {\n refresh: async () => {\n await claim();\n },\n release: async () => {\n await collection.deleteOne({ name: MIGRATION_LOCK_NAME, owner });\n },\n };\n }\n\n return undefined;\n }\n\n // ============================================================================\n // REGISTRATION\n // ============================================================================\n\n /**\n * Register a migration.\n *\n * The migration name is read from `MigrationClass.migrationName`.\n *\n * @param MigrationClass - Migration class (must have static `name` set)\n * @param origin - Registration source; defaults to `\"app\"` for direct registrations.\n * @returns This runner for chaining\n *\n * @example\n * ```typescript\n * CreateUsersTable.migrationName = \"2024-01-15_create-users\";\n * runner.register(CreateUsersTable);\n * ```\n */\n public register(MigrationClass: RegisterableMigration, origin: MigrationOrigin = \"app\"): this {\n const name = MigrationClass.migrationName;\n if (!name) {\n throw new Error(\n `Migration class must have a static 'migrationName' property set. ` +\n `Set it in CLI after importing: MigrationClass.migrationName = \"filename\";`,\n );\n }\n const existing = this.migrations.find((m) => m.migrationName === name);\n\n if (existing) {\n // Re-registering the same class is idempotent; a DIFFERENT class under the\n // same name would silently never run, so fail loudly.\n if ((existing as unknown) !== MigrationClass) {\n throw new Error(\n `Duplicate migration name \"${name}\": two different migration classes resolve to the same name. ` +\n `Rename one of the files (or set a unique static 'migrationName').`,\n );\n }\n\n return this;\n }\n\n // `name` is proven present by the throw above, so this satisfies the stricter\n // stored type that every reader downstream relies on.\n MigrationClass.origin = origin;\n this.migrations.push(MigrationClass as MigrationClass);\n\n return this;\n }\n\n /**\n * Register multiple migrations.\n *\n * @param migrations - Array of migration classes\n * @returns This runner for chaining\n */\n public registerMany(migrations: RegisterableMigration[]): this {\n for (const MigrationClass of migrations) {\n this.register(MigrationClass);\n }\n return this;\n }\n\n /**\n * Clear all registered migrations.\n */\n public clear(): this {\n this.migrations.length = 0;\n return this;\n }\n\n /**\n * Get all registered migration names.\n */\n public getRegisteredNames(): string[] {\n return this.migrations.map((m) => m.migrationName);\n }\n\n // ============================================================================\n // SINGLE EXECUTION\n // ============================================================================\n\n /**\n * Execute a single migration's up() method.\n *\n * @param MigrationClass - Migration class to execute\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.execute(CreateUsersTable);\n * await runner.execute(AddEmailIndex, { dryRun: true });\n * ```\n */\n public async run(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"up\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n /**\n * Execute a single migration's down() method.\n *\n * @param MigrationClass - Migration class to rollback\n * @param options - Execution options\n * @returns Migration result\n *\n * @example\n * ```typescript\n * await runner.rollback(CreateUsersTable);\n * ```\n */\n public async rollback(\n MigrationClass: MigrationClass,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult> {\n return this.runMigration(MigrationClass, \"down\", {\n dryRun: options.dryRun,\n record: options.record ?? false,\n });\n }\n\n // ============================================================================\n // BATCH EXECUTION (REGISTERED MIGRATIONS)\n // ============================================================================\n\n /**\n * Run all pending registered migrations.\n *\n * Only runs migrations not already in the migrations table.\n *\n * @param options - Execution options\n * @returns Results for each migration\n *\n * @example\n * ```typescript\n * runner.register(CreateUsersTable);\n * runner.register(AddEmailIndex);\n * const results = await runner.runAll();\n * ```\n */\n public async runAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // A dry run writes nothing, so it needs no lock.\n if (options.dryRun) return this.runAllUnlocked(options);\n\n // The pending set is computed INSIDE the lock, so a replica that waited sees\n // what the winner already applied.\n return this.withLock(this.getSources(), () => this.runAllUnlocked(options));\n }\n\n private async runAllUnlocked(options: ExecuteOptions): Promise<MigrationResult[]> {\n const { dryRun = false, record = true } = options;\n\n const results: MigrationResult[] = [];\n\n // Get pending migrations (a dry run must not create the migrations table)\n const pending = await this.getPendingMigrations({ readOnly: dryRun });\n\n if (pending.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to migrate.\");\n return results;\n }\n\n // Next batch number per data source: each source has its own migrations table.\n const sources = new Set<DataSource>();\n const migrationsData: MigrationData[] = [];\n\n log.info(\"database\", \"migration\", `Found ${pending.length} pending migration(s).`);\n\n // 1. Resolve each migration's data source and transactional mode, and collect\n // its SQL. Drivers without SQL serialization (MongoDB) are executed\n // directly through the migration driver instead.\n // Extension checks fire concurrently as CREATE EXTENSION statements are met.\n const extensionChecks: Promise<void>[] = [];\n\n for (const MigrationClass of pending) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n const dataSource = this.resolveDataSource(migration.dataSource);\n sources.add(dataSource);\n\n if (dataSource.driver.supportsSqlSerialization === false) {\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements: [],\n steps: [],\n transactional: false,\n direct: true,\n });\n continue;\n }\n\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n // Collection must not run `withConnection` side effects during a dry run.\n migration.setDryRun?.(dryRun);\n\n await migration.up();\n const steps: MigrationStep[] = migration.toSteps?.() ?? migration.toSQL();\n const statements = steps.map((step) =>\n typeof step === \"string\" ? step : \"-- data step (withConnection) skipped\",\n );\n migration.setDryRun?.(false);\n\n migrationsData.push({\n MigrationClass,\n migration,\n name,\n dataSource,\n statements,\n steps,\n transactional:\n !!dataSource.driver.transaction &&\n this.resolveTransactional(MigrationClass, migration, dataSource, statements),\n direct: false,\n });\n\n for (const sql of statements) {\n if (SQLGrammar.classify(sql) === \"CREATE_EXTENSION\") {\n const ext = SQLGrammar.extractExtensionName(sql);\n if (ext) extensionChecks.push(this.informIfExtensionMissing(ext, dataSource));\n }\n }\n }\n\n // 2. Resolve all extension checks before any SQL is executed.\n await Promise.all(extensionChecks);\n\n // 3. Dry run: print statements in migration order (authored order kept; no\n // global phase sort, which would reorder add-column → backfill → NOT NULL).\n if (dryRun) {\n log.info(\"database\", \"migration\", \"Dry run enabled. Would execute the following statements:\");\n for (const data of migrationsData) {\n for (const sql of data.statements) {\n console.log(\n `-- [${SQLGrammar.classify(sql)}] Phase ${SQLGrammar.phase(sql)} [${data.name}]`,\n );\n console.log(sql + \";\\n\");\n }\n }\n return [];\n }\n\n const batches = new Map<DataSource, number>();\n for (const dataSource of sources) {\n batches.set(dataSource, await this.getNextBatchNumber(dataSource));\n }\n\n // 4. Split into runs: consecutive transactional migrations on the same data\n // source share one transaction; every other migration (non-transactional\n // or direct) runs alone.\n const runs: MigrationData[][] = [];\n for (const data of migrationsData) {\n const last = runs[runs.length - 1];\n const lastFirst = last?.[0];\n if (\n data.transactional &&\n last &&\n lastFirst?.transactional &&\n lastFirst.dataSource === data.dataSource\n ) {\n last.push(data);\n } else {\n runs.push([data]);\n }\n }\n\n for (const run of runs) {\n const first = run[0];\n if (!first) continue;\n await this.refreshLocks();\n const dataSource = first.dataSource;\n const nextBatch = batches.get(dataSource)!;\n const startTime = Date.now();\n\n if (first.direct) {\n const result = await this.runMigration(first.MigrationClass, \"up\", {\n dryRun,\n record,\n batch: nextBatch,\n });\n results.push(result);\n if (!result.success) break;\n continue;\n }\n\n const driver = dataSource.driver;\n let failed = false;\n let errorMessage = \"\";\n /** The migration that owns the SQL statement that threw. */\n let failingMigrationName: string | undefined;\n\n const executeRun = async (): Promise<void> => {\n for (const data of run) {\n for (const step of data.steps) {\n try {\n if (typeof step === \"string\") await driver.query(step);\n else await step.data();\n } catch (err) {\n failingMigrationName = data.name;\n throw err;\n }\n }\n\n // A non-transactional migration is recorded right after it applied.\n // Transactional ones are recorded inside the shared transaction.\n if (record) {\n await this.recordMigration(\n data.name,\n nextBatch,\n data.MigrationClass.createdAt\n ? parseCreatedAt(data.MigrationClass.createdAt)\n : new Date(),\n dataSource,\n );\n }\n }\n };\n\n try {\n if (first.transactional && driver.transaction) {\n await driver.transaction(executeRun);\n } else {\n await executeRun();\n }\n } catch (err) {\n failed = true;\n errorMessage = err instanceof Error ? err.message : String(err);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Only the migration that owns the failing statement is marked failed;\n // the rest of its run is reported as rolled back.\n for (const data of run) {\n const isCulprit = failed && data.name === failingMigrationName;\n const wasSkipped = failed && !isCulprit;\n\n results.push({\n name: data.name,\n table: data.migration.table,\n direction: \"up\",\n success: !failed,\n error: isCulprit ? errorMessage : undefined,\n durationMs: Math.round(durationMs / run.length),\n executedAt: new Date(),\n });\n\n if (isCulprit) {\n log.error(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: ✗ Failed: ${errorMessage}`,\n );\n } else if (wasSkipped) {\n log.warn(\n \"database\",\n \"migration\",\n `${colors.magenta(data.name)}: rolled back (batch transaction failed)`,\n );\n } else {\n log.success(\n \"database\",\n \"migration\",\n `Migrated: ${colors.magenta(data.name)} successfully`,\n );\n }\n }\n\n if (failed) {\n log.error(\n \"database\",\n \"migration\",\n `Batch execution failed. Rollback performed if transactional.`,\n );\n throw new Error(\"Migration batch failed: \" + errorMessage);\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Migration execution complete: ${successCount}/${pending.length} migrations processed successfully.`,\n );\n\n return results;\n }\n\n /**\n * Export migrations as phase-ordered SQL files in database/sql/ directory.\n * By default, it exports all registered migrations. Use `pendingOnly: true` to export only pending ones.\n */\n public async exportSQL(\n options: { pendingOnly?: boolean; compact?: boolean } = {},\n ): Promise<void> {\n if (this.getDataSource().driver.supportsSqlSerialization === false) {\n throw new Error(\n \"SQL export is not supported on this data source — its driver has no SQL dialect. \" +\n \"Migrations on this driver execute native commands through the migration driver instead.\",\n );\n }\n\n const migrationsToExport = options.pendingOnly\n ? await this.getPendingMigrations({ readOnly: true })\n : this.migrations;\n\n if (migrationsToExport.length === 0) {\n log.warn(\"database\", \"migration\", \"No migrations to export.\");\n return;\n }\n\n log.info(\n \"database\",\n \"migration\",\n `Exporting ${migrationsToExport.length} ${options.pendingOnly ? \"pending \" : \"\"}migration(s) to SQL files...`,\n );\n\n const upStatements: TaggedSQL[] = [];\n // Down SQL is grouped per migration so only the migration order is reversed,\n // never the statements inside one migration's down().\n const downGroups: { createdAt?: string; index: number; statements: TaggedSQL[] }[] = [];\n\n for (const [index, MigrationClass] of migrationsToExport.entries()) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n\n // Export performs no writes: `withConnection` callbacks are skipped.\n migration.setDryRun?.(true);\n\n // Collect up SQL\n await migration.up();\n for (const sql of migration.toSQL()) {\n upStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n\n // Collect down SQL (reuse same instance — toSQL() cleared pendingOps)\n await migration.down();\n const statements: TaggedSQL[] = [];\n for (const sql of migration.toSQL()) {\n statements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n downGroups.push({ createdAt: MigrationClass.createdAt, index, statements });\n }\n\n const sortedUp = SQLGrammar.sort(upStatements);\n // Down SQL: newest migration first (chronological, registration order breaks\n // ties), each migration's own down() statements keep their order.\n const sortedDown = downGroups\n .sort((a, b) => {\n const byDate = (a.createdAt ?? \"\").localeCompare(b.createdAt ?? \"\");\n return byDate !== 0 ? byDate : a.index - b.index;\n })\n .reverse()\n .flatMap((group) => group.statements);\n\n const upSQLString = this.formatSQLForExport(sortedUp, options.compact);\n const downSQLString = this.formatSQLForExport(sortedDown, options.compact);\n\n const rootPath = process.cwd();\n const sqlDir = path.join(rootPath, \"database\", \"sql\");\n\n if (!fs.existsSync(sqlDir)) {\n fs.mkdirSync(sqlDir, { recursive: true });\n }\n\n const timestamp = new Date().toISOString().replace(/T/, \"_\").replace(/:/g, \"-\").split(\".\")[0];\n const upPath = path.join(sqlDir, `migration_${timestamp}.up.sql`);\n const downPath = path.join(sqlDir, `migration_${timestamp}.down.sql`);\n\n fs.writeFileSync(upPath, upSQLString);\n fs.writeFileSync(downPath, downSQLString);\n\n log.success(\"database\", \"migration\", `Exported to:\\n- ${upPath}\\n- ${downPath}`);\n }\n\n /**\n * Rollback the last batch of migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackLast(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n return this.rollbackBatches(1, options);\n }\n\n /**\n * Rollback N batches of migrations.\n *\n * @param batches - Number of batches to rollback\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackBatches(\n batches: number,\n options: ExecuteOptions = {},\n ): Promise<MigrationResult[]> {\n if (options.dryRun) return this.rollbackBatchesUnlocked(batches, options);\n\n return this.withLock(this.getSources(), () => this.rollbackBatchesUnlocked(batches, options));\n }\n\n private async rollbackBatchesUnlocked(\n batches: number,\n options: ExecuteOptions,\n ): Promise<MigrationResult[]> {\n const dryRun = options.dryRun ?? false;\n const record = options.record ?? true;\n const results: MigrationResult[] = [];\n\n const toRollback = await this.getMigrationsToRollback(batches, {\n pruneMissing: options.pruneMissing,\n readOnly: dryRun,\n });\n\n if (toRollback.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to rollback.\");\n return results;\n }\n\n log.info(\"database\", \"migration\", `Rolling back ${toRollback.length} migration(s).`);\n\n for (const MigrationClass of toRollback) {\n await this.refreshLocks();\n\n const result = await this.runMigration(MigrationClass, \"down\", {\n dryRun,\n record,\n });\n results.push(result);\n\n if (!result.success) {\n break;\n }\n }\n\n const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Rollback complete: ${successCount}/${toRollback.length} successful.`,\n );\n\n return results;\n }\n\n /**\n * Rollback all executed migrations.\n *\n * @param options - Execution options\n * @returns Results for each migration\n */\n public async rollbackAll(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n // Batch numbers are per data source; rolling back \"all\" is every batch of each.\n return this.rollbackBatches(Number.POSITIVE_INFINITY, options);\n }\n\n /**\n * Reset and re-run: rollback all then run all.\n *\n * @param options - Execution options\n * @returns Combined results\n */\n public async fresh(options: ExecuteOptions = {}): Promise<MigrationResult[]> {\n const rollbackResults = await this.rollbackAll(options);\n const runResults = await this.runAll(options);\n return [...rollbackResults, ...runResults];\n }\n\n // ============================================================================\n // STATUS\n // ============================================================================\n\n /**\n * Get status of all registered migrations.\n */\n public async status(): Promise<\n Array<{\n name: string;\n table: string;\n executed: boolean;\n batch: number | null;\n }>\n > {\n const executedBySource = new Map<DataSource, Map<string, MigrationRecord>>();\n\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly: true });\n executedBySource.set(dataSource, new Map(executed.map((r) => [r.name, r])));\n }\n\n return this.migrations.map((MigrationClass) => {\n const instance = new MigrationClass();\n const name = MigrationClass.migrationName;\n const record = executedBySource.get(this.sourceOf(MigrationClass))?.get(name);\n return {\n name,\n table: instance.table,\n executed: !!record,\n batch: record?.batch ?? null,\n };\n });\n }\n\n // ============================================================================\n // EXTENSION PRE-FLIGHT\n // ============================================================================\n\n /**\n * Check whether a database extension is available and inform the developer\n * if it is not installed.\n *\n * Does NOT throw — execution proceeds normally. If the extension is truly\n * missing, the database will surface its own error with full context already\n * displayed to the developer.\n *\n * @example\n * await this.informIfExtensionMissing(\"vector\");\n */\n private async informIfExtensionMissing(\n extension: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n try {\n const migrationDriver = this.getMigrationDriver(dataSource);\n const isAvailable = await migrationDriver.isExtensionAvailable(extension);\n\n if (!isAvailable) {\n const hr = \"─\".repeat(60);\n console.log(`\\n${colors.yellow(hr)}`);\n console.log(colors.yellow(` ⚠ Missing Database Extension: ${colors.bold(extension)}`));\n console.log(colors.yellow(hr));\n console.log();\n console.log(` A pending migration requires the ${colors.cyan(extension)} extension,`);\n console.log(` which is not installed on your database server.`);\n console.log();\n console.log(\n ` ${colors.bold(\"This means the physical database server is missing the extension package.\")}`,\n );\n console.log(` You cannot simply run CREATE EXTENSION until the package is installed`);\n console.log(` on the host machine or Docker container.`);\n console.log();\n\n const docsUrl = migrationDriver.getExtensionDocsUrl(extension);\n if (docsUrl) {\n console.log(` ${colors.bold(\"Or follow the installation guide:\")}`);\n console.log(` ${colors.cyan(docsUrl)}`);\n }\n console.log(`\\n${colors.yellow(hr)}\\n`);\n }\n } catch {\n // If the check itself fails, silently skip — don't break the migration.\n }\n }\n\n // ============================================================================\n // PRIVATE HELPERS\n // ============================================================================\n\n /**\n * Run a single migration.\n */\n private async runMigration(\n MigrationClass: MigrationClass,\n direction: \"up\" | \"down\",\n options: {\n dryRun?: boolean;\n record?: boolean;\n batch?: number;\n } = {},\n ): Promise<MigrationResult> {\n const { dryRun = false, record = true } = options;\n const startTime = Date.now();\n let success = true;\n let error: string | undefined;\n\n const migration = new MigrationClass();\n const name = MigrationClass.migrationName;\n\n log.info(\n \"database\",\n \"migration\",\n `${direction === \"up\" ? \"Migrating\" : \"Rolling back\"}: ${colors.magenta(name)}...`,\n );\n\n try {\n if (!dryRun) {\n // The migration runs against its declared data source (default: the runner's)\n // and is recorded in THAT source's migrations table.\n const dataSource = this.resolveDataSource(migration.dataSource);\n const driver = this.getMigrationDriver(dataSource);\n migration.setDriver(driver);\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n\n // ============================================================================\n // TRANSACTION RESOLUTION (3-tier hierarchy)\n // ============================================================================\n // 1. Migration-level explicit override (instance or static)\n // 2. CONCURRENTLY statements (cannot run in a transaction block)\n // 3. Config-level global override\n // 4. Driver default (PostgreSQL: true, MongoDB: false)\n // Resolved below, once the statements are known.\n\n // ============================================================================\n // EXECUTE WITH OR WITHOUT TRANSACTION\n // ============================================================================\n\n // Collect the requested direction's operations\n if (direction === \"up\") {\n await migration.up();\n } else {\n await migration.down();\n }\n\n const databaseDriver = dataSource.driver;\n\n // SQL-capable drivers serialize the queued operations to SQL strings;\n // drivers without SQL serialization (MongoDB) keep them queued and\n // execute them directly through the migration driver.\n const directExecution = databaseDriver.supportsSqlSerialization === false;\n const steps: MigrationStep[] = directExecution\n ? []\n : (migration.toSteps?.() ?? migration.toSQL());\n const sqlStatements = steps.filter((step): step is string => typeof step === \"string\");\n const shouldUseTransaction = this.resolveTransactional(\n MigrationClass,\n migration,\n dataSource,\n sqlStatements,\n );\n\n const applyMigration = async (): Promise<void> => {\n if (directExecution) {\n await migration.execute();\n return;\n }\n\n // Execute generated SQL statements sequentially (no phase-sorting here since it's single execution)\n for (const step of steps) {\n if (typeof step === \"string\") await databaseDriver.query(step);\n else await step.data();\n }\n };\n\n if (shouldUseTransaction && databaseDriver.transaction) {\n // Transactional execution\n await databaseDriver.transaction(async () => {\n await applyMigration();\n\n // Record migration tracking\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n });\n } else {\n // Non-transactional execution\n await applyMigration();\n\n if (record) {\n if (direction === \"up\") {\n const batch = options.batch ?? (await this.getNextBatchNumber(dataSource));\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n dataSource,\n );\n } else {\n await this.removeMigrationRecord(name, dataSource);\n }\n }\n }\n }\n } catch (err) {\n success = false;\n error = err instanceof Error ? err.message : String(err);\n log.error(\"database\", \"migration\", `${colors.magenta(name)}: ✗ Failed: ${error}`);\n throw err;\n }\n\n const durationMs = Date.now() - startTime;\n\n if (success) {\n log.success(\n \"database\",\n \"migration\",\n `${direction == \"up\" ? \"Migrated\" : \"Rolled back\"}: ${colors.magenta(name)} successfully (${durationMs}ms)`,\n );\n }\n\n return {\n name,\n table: migration.table,\n direction,\n success,\n error,\n durationMs,\n executedAt: new Date(),\n };\n }\n\n /**\n * Create, configure, and return a ready-to-use migration instance.\n *\n * Centralises the repeated \"new + setDriver + setMigrationDefaults\" boilerplate\n * that all batch/single execution paths need.\n *\n * @internal\n */\n private createMigrationInstance(MigrationClass: MigrationClass): Migration {\n const migration = new MigrationClass();\n const dataSource = this.resolveDataSource(migration.dataSource);\n migration.setDriver(this.getMigrationDriver(dataSource));\n migration.setMigrationDefaults(dataSource.migrationDefaults);\n return migration;\n }\n\n /**\n * Format an ordered array of TaggedSQL into a human-readable SQL file string.\n *\n * Consecutive statements that belong to the same (phase, migration) group share\n * a single block comment at the top, avoiding the noisy per-statement repetition.\n *\n * Example output:\n * ```sql\n * /* Phase 3 [create-users] *\\/\n * ALTER TABLE \"users\" ADD COLUMN \"name\" TEXT NOT NULL;\n * ALTER TABLE \"users\" ADD COLUMN \"email\" TEXT NOT NULL;\n *\n * /* Phase 4 [create-users] *\\/\n * CREATE UNIQUE INDEX ...;\n * ```\n *\n * @internal\n */\n private formatSQLForExport(statements: TaggedSQL[], compact: boolean = false): string {\n const lines: string[] = [];\n\n if (compact) {\n // Just output raw statements, no grouping, no blank lines\n for (const stmt of statements) {\n lines.push(`${stmt.sql};`);\n }\n return lines.join(\"\\n\");\n }\n\n // Group statements by their phase and migration name\n const grouped = new Map<string, string[]>();\n\n for (const stmt of statements) {\n const groupKey = `Phase ${stmt.phase} [${stmt.migrationName}]`;\n if (!grouped.has(groupKey)) {\n grouped.set(groupKey, []);\n }\n grouped.get(groupKey)!.push(stmt.sql);\n }\n\n // Format each group\n for (const [groupKey, sqls] of grouped.entries()) {\n if (lines.length > 0) lines.push(\"\"); // blank line between groups\n lines.push(`/* ${groupKey} */`);\n for (const sql of sqls) {\n lines.push(`${sql};`);\n }\n }\n\n return lines.join(\"\\n\");\n }\n\n /**\n * Get pending (not executed) registered migrations, in the order they would\n * execute.\n *\n * ⚠️ \"Registered\" is load-bearing. This filters `this.migrations`, which is\n * populated only by `register()` / `registerMany()`. A caller that has not\n * registered anything gets `[]` — indistinguishable from a database with\n * nothing pending. Anything reporting this set to a human MUST register\n * migrations first, or it will print a confident all-clear over an unknown.\n *\n * @see listPendingMigrations\n */\n public async getPendingMigrations(\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n // \"Executed\" is judged in each migration's own data source's migrations table.\n const executedNames = new Map<DataSource, Set<string>>();\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, options);\n executedNames.set(dataSource, new Set(executed.map((r) => r.name)));\n }\n\n const migrations = this.migrations.filter(\n (m) => !executedNames.get(this.sourceOf(m))?.has(m.migrationName),\n );\n\n return migrations.sort(sortMigrations);\n }\n\n /**\n * Get migrations to rollback, newest-first.\n *\n * A rollback must undo migrations in the exact inverse of the order `up`\n * applied them, or a `down()` will hit schema its predecessor already\n * removed — dropping a table before dropping the column added to it, say.\n *\n * The sort has to be explicitly **descending**. Reversing the executed list\n * is not enough: `getExecutedMigrations` orders by `batch, name`, so the\n * input is alphabetical rather than chronological, and reversing it only\n * yields reverse-alphabetical order. (Sorting *ascending* here — which is\n * what this method used to do after a `.reverse()` — silently restored the\n * forward `up` order and made the reverse dead code.)\n */\n private async getMigrationsToRollback(\n batches: number,\n options: { pruneMissing?: boolean; readOnly?: boolean } = {},\n ): Promise<MigrationClass[]> {\n const migrations: MigrationClass[] = [];\n const batchOf = new Map<MigrationClass, number>();\n const orphans: Array<{ name: string; dataSource: DataSource }> = [];\n\n // Batches are numbered per data source (each has its own migrations table).\n for (const dataSource of this.getSources()) {\n const executed = await this.getExecutedMigrations(dataSource, {\n readOnly: options.readOnly,\n });\n if (executed.length === 0) continue;\n\n const batchNumbers = [...new Set(executed.map((r) => r.batch))]\n .sort((a, b) => b - a)\n .slice(0, batches);\n\n for (const record of executed) {\n if (!batchNumbers.includes(record.batch)) continue;\n\n const MigrationClass = this.migrations.find(\n (m) => m.migrationName === record.name && this.sourceOf(m) === dataSource,\n );\n if (MigrationClass) {\n migrations.push(MigrationClass);\n batchOf.set(MigrationClass, record.batch);\n } else {\n orphans.push({ name: record.name, dataSource });\n }\n }\n }\n\n if (orphans.length > 0) {\n if (!options.pruneMissing) {\n throw new Error(\n `Cannot roll back: ${orphans.length} executed migration(s) have no registered file: ` +\n `${orphans.map((o) => o.name).join(\", \")}. ` +\n `They were renamed, deleted, or not matched by the migration pattern. ` +\n `Restore the file(s), or pass pruneMissing (--prune-missing) to delete those records.`,\n );\n }\n\n if (!options.readOnly) {\n for (const orphan of orphans) {\n await this.removeMigrationRecord(orphan.name, orphan.dataSource);\n log.warn(\"database\", \"migration\", `Pruned orphaned migration record: ${orphan.name}`);\n }\n }\n }\n\n // Newest batch first, then newest migration first within a batch.\n return migrations.sort(\n (a, b) => (batchOf.get(b) ?? 0) - (batchOf.get(a) ?? 0) || sortMigrationsForRollback(a, b),\n );\n }\n\n /**\n * Get executed migration records.\n */\n public async getExecutedMigrations(\n dataSource: DataSource = this.getDataSource(),\n options: { readOnly?: boolean } = {},\n ): Promise<MigrationRecord[]> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n if (options.readOnly) {\n // Dry runs and listings must not create the migrations table.\n if (!(await migrationDriver.tableExists(this.migrationsTable))) return [];\n } else {\n // A missing table is created here; every other error (connection,\n // permission…) propagates instead of looking like \"nothing executed\".\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n }\n\n const queryBuilder = driver.queryBuilder<MigrationRecord>(this.migrationsTable);\n const records = await queryBuilder.orderBy(\"batch\", \"asc\").orderBy(\"name\", \"asc\").get();\n\n // The Mongo lock document lives in this collection; it is not a migration.\n return records.filter((record) => record.name !== MIGRATION_LOCK_NAME);\n }\n\n /**\n * Record a migration.\n */\n private async recordMigration(\n name: string,\n batch: number,\n createdAt?: Date,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n const migrationDriver = this.getMigrationDriver(dataSource);\n\n // Ensure migrations table exists\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n\n await driver.insert(this.migrationsTable, {\n name,\n batch,\n executedAt: new Date(),\n createdAt,\n });\n }\n\n /**\n * Remove a migration record.\n */\n private async removeMigrationRecord(\n name: string,\n dataSource: DataSource = this.getDataSource(),\n ): Promise<void> {\n const driver = dataSource.driver;\n await driver.delete(this.migrationsTable, { name });\n }\n\n /**\n * Get next batch number.\n */\n private async getNextBatchNumber(\n dataSource: DataSource = this.getDataSource(),\n readOnly = false,\n ): Promise<number> {\n const executed = await this.getExecutedMigrations(dataSource, { readOnly });\n if (executed.length === 0) return 1;\n return Math.max(...executed.map((r) => r.batch)) + 1;\n }\n}\n\nexport const migrationRunner = new MigrationRunner();\n"],"mappings":";;;;;;;;;;;AAqFA,MAAM,sBAAsB;AAC5B,MAAM,qBAAqB;AAC3B,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;AAC/B,MAAM,0BAA0B;AAsBhC,MAAM,SAAS,OAAe,IAAI,SAAe,YAAY,WAAW,SAAS,EAAE,CAAC;;;;;;AAOpF,SAAgB,mBAAmB,MAAsB;CAGvD,QAFiB,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,MAAM,GAEvC,CAAC,QAAQ,eAAe,EAAE,CAAC,CAAC,QAAQ,eAAe,EAAE;AACtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,kBAAb,MAA6B;;CAE3B,AAAgB,aAA+B,CAAC;;CAGhD,AAAQ;;CAGR,AAAiB,mCAAmB,IAAI,IAAyC;;CAGjF,AAAiB;;CAGjB,AAAiB;;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AAW,OACb,OAAO,KAAK,iBAAiB,EAAE,KAAK,CAAC;CACpD;;;;CAKA,MAAc,mBACZ,aAAyB,KAAK,cAAc,GAC5C,WAAW,OACM;EACjB,MAAM,WAAW,MAAM,KAAK,sBAAsB,YAAY,EAAE,SAAS,CAAC;EAC1E,IAAI,SAAS,WAAW,GAAG,OAAO;EAClC,OAAO,KAAK,IAAI,GAAG,SAAS,KAAK,MAAM,EAAE,KAAK,CAAC,IAAI;CACrD;AACF;AAEA,MAAa,kBAAkB,IAAI,gBAAgB"}
@@ -8,30 +8,29 @@ import { Model } from "../model/model.mjs";
8
8
  import { DatabaseDriver } from "../utils/connect-to-database.mjs";
9
9
  import { ForeignKeyBuilder } from "./foreign-key-builder.mjs";
10
10
  import { DataSource } from "../data-source/data-source.mjs";
11
-
12
11
  //#region ../../packages/cascade/src/migration/migration.d.ts
13
12
  /**
14
13
  * Pending operation types supported by migrations.
15
14
  */
16
- type OperationType = "addColumn" | "dropColumn" | "dropColumns" | "renameColumn" | "modifyColumn" | "createIndex" | "dropIndex" | "createUniqueIndex" | "dropUniqueIndex" | "createFullTextIndex" | "dropFullTextIndex" | "createGeoIndex" | "dropGeoIndex" | "createVectorIndex" | "dropVectorIndex" | "createTTLIndex" | "dropTTLIndex" | "addForeignKey" | "dropForeignKey" | "addPrimaryKey" | "dropPrimaryKey" | "addCheck" | "dropCheck" | "createTable" | "createTableIfNotExists" | "dropTable" | "dropTableIfExists" | "renameTable" | "truncateTable" | "createTimestamps" | "rawStatement" | "dataStep" | "setSchemaValidation" | "removeSchemaValidation";
15
+ export type OperationType = "addColumn" | "dropColumn" | "dropColumns" | "renameColumn" | "modifyColumn" | "createIndex" | "dropIndex" | "createUniqueIndex" | "dropUniqueIndex" | "createFullTextIndex" | "dropFullTextIndex" | "createGeoIndex" | "dropGeoIndex" | "createVectorIndex" | "dropVectorIndex" | "createTTLIndex" | "dropTTLIndex" | "addForeignKey" | "dropForeignKey" | "addPrimaryKey" | "dropPrimaryKey" | "addCheck" | "dropCheck" | "createTable" | "createTableIfNotExists" | "dropTable" | "dropTableIfExists" | "renameTable" | "truncateTable" | "createTimestamps" | "rawStatement" | "dataStep" | "setSchemaValidation" | "removeSchemaValidation";
17
16
  /**
18
17
  * One executable step of a migration, in authored order: a serialized SQL
19
18
  * statement, or a queued data step (`withConnection` callback).
20
19
  */
21
- type MigrationStep = string | {
20
+ export type MigrationStep = string | {
22
21
  readonly data: () => Promise<unknown>;
23
22
  };
24
23
  /**
25
24
  * Pending operation to be executed when migration runs.
26
25
  */
27
- type PendingOperation = {
26
+ export type PendingOperation = {
28
27
  readonly type: OperationType;
29
28
  readonly payload: unknown;
30
29
  };
31
30
  /**
32
31
  * Contract for a migration class.
33
32
  */
34
- interface MigrationContract {
33
+ export interface MigrationContract {
35
34
  /**
36
35
  * Table/collection name for this migration.
37
36
  */
@@ -489,11 +488,11 @@ interface MigrationContract {
489
488
  vector(column: string, dimensions: number): ColumnBuilder;
490
489
  }
491
490
  /** The source that registered a migration with a runner. */
492
- type MigrationOrigin = "package" | "app";
491
+ export type MigrationOrigin = "package" | "app";
493
492
  /**
494
493
  * Constructor for the migration class.
495
494
  */
496
- interface MigrationConstructor {
495
+ export interface MigrationConstructor {
497
496
  new (): MigrationContract;
498
497
  migrationName?: string;
499
498
  createdAt?: string;
@@ -549,7 +548,7 @@ interface MigrationConstructor {
549
548
  * }
550
549
  * ```
551
550
  */
552
- declare abstract class Migration implements MigrationContract {
551
+ export declare abstract class Migration implements MigrationContract {
553
552
  /**
554
553
  * Migration name that will be labeled with
555
554
  * If record is enabled in migration, it will be stored as migration name
@@ -1742,7 +1741,7 @@ declare abstract class Migration implements MigrationContract {
1742
1741
  */
1743
1742
  static alter: (model: ChildModel<Model<any>>, schema: AlterSchema, options?: MigrationAlterOptions) => MigrationConstructor;
1744
1743
  }
1745
- declare function migrate(model: ChildModel<Model<any>>, options?: {
1744
+ export declare function migrate(model: ChildModel<Model<any>>, options?: {
1746
1745
  createdAt?: string;
1747
1746
  name?: string;
1748
1747
  up?: (this: MigrationContract) => void | Promise<void>;
@@ -1764,15 +1763,19 @@ declare function migrate(model: ChildModel<Model<any>>, options?: {
1764
1763
  * { columns: ["embedding"], using: "ivfflat" }
1765
1764
  * ```
1766
1765
  */
1767
- type IndexEntry = {
1768
- /** Column(s) to include in the index. */columns: string | string[]; /** Optional explicit index name. Auto-generated when omitted. */
1766
+ export type IndexEntry = {
1767
+ /** Column(s) to include in the index. */
1768
+ columns: string | string[];
1769
+ /** Optional explicit index name. Auto-generated when omitted. */
1769
1770
  name?: string;
1770
1771
  /**
1771
1772
  * Index access method (PostgreSQL).
1772
1773
  * Defaults to `"btree"` when omitted.
1773
1774
  */
1774
- using?: "btree" | "hash" | "gin" | "gist" | "brin" | "ivfflat" | "hnsw" | (string & {}); /** Extra columns to include in a covering index (PostgreSQL `INCLUDE`). */
1775
- include?: string[]; /** Build the index without locking the table (PostgreSQL). */
1775
+ using?: "btree" | "hash" | "gin" | "gist" | "brin" | "ivfflat" | "hnsw" | (string & {});
1776
+ /** Extra columns to include in a covering index (PostgreSQL `INCLUDE`). */
1777
+ include?: string[];
1778
+ /** Build the index without locking the table (PostgreSQL). */
1776
1779
  concurrently?: boolean;
1777
1780
  };
1778
1781
  /**
@@ -1787,16 +1790,20 @@ type IndexEntry = {
1787
1790
  * { columns: ["org_id", "content_id", "lang"], name: "uq_summary_idempotency" }
1788
1791
  * ```
1789
1792
  */
1790
- type UniqueEntry = {
1791
- /** Column(s) that must be unique together. */columns: string | string[]; /** Optional explicit constraint name. Auto-generated when omitted. */
1792
- name?: string; /** Extra columns to include (PostgreSQL covering unique index). */
1793
- include?: string[]; /** Build the constraint without locking the table (PostgreSQL). */
1793
+ export type UniqueEntry = {
1794
+ /** Column(s) that must be unique together. */
1795
+ columns: string | string[];
1796
+ /** Optional explicit constraint name. Auto-generated when omitted. */
1797
+ name?: string;
1798
+ /** Extra columns to include (PostgreSQL covering unique index). */
1799
+ include?: string[];
1800
+ /** Build the constraint without locking the table (PostgreSQL). */
1794
1801
  concurrently?: boolean;
1795
1802
  };
1796
1803
  /**
1797
1804
  * Options accepted by `Migration.create()`.
1798
1805
  */
1799
- type MigrationCreateOptions = {
1806
+ export type MigrationCreateOptions = {
1800
1807
  /**
1801
1808
  * Sort order override.
1802
1809
  * @default 0
@@ -1902,13 +1909,16 @@ type MigrationCreateOptions = {
1902
1909
  * Keys become the column names; values are `DetachedColumnBuilder` instances
1903
1910
  * produced by the standalone column helpers (`uuid()`, `text()`, etc.).
1904
1911
  */
1905
- type ColumnMap = Record<string, DetachedColumnBuilder>;
1912
+ export type ColumnMap = Record<string, DetachedColumnBuilder>;
1906
1913
  /**
1907
1914
  * Options accepted by `Migration.alter()`.
1908
1915
  */
1909
- type MigrationAlterOptions = {
1910
- /** Sort order override. */order?: number; /** ISO timestamp override. */
1911
- createdAt?: string; /** Whether to wrap in a transaction. */
1916
+ export type MigrationAlterOptions = {
1917
+ /** Sort order override. */
1918
+ order?: number;
1919
+ /** ISO timestamp override. */
1920
+ createdAt?: string;
1921
+ /** Whether to wrap in a transaction. */
1912
1922
  transactional?: boolean;
1913
1923
  /**
1914
1924
  * Custom logic to execute after the declarative definitions.
@@ -1944,10 +1954,14 @@ type MigrationAlterOptions = {
1944
1954
  * });
1945
1955
  * ```
1946
1956
  */
1947
- type AlterSchema = {
1948
- /** Columns to add. Keys become column names. */add?: ColumnMap; /** Column names to drop. */
1949
- drop?: string[]; /** Rename map: `{ oldName: newName }`. */
1950
- rename?: Record<string, string>; /** Columns to modify. Keys become column names. */
1957
+ export type AlterSchema = {
1958
+ /** Columns to add. Keys become column names. */
1959
+ add?: ColumnMap;
1960
+ /** Column names to drop. */
1961
+ drop?: string[];
1962
+ /** Rename map: `{ oldName: newName }`. */
1963
+ rename?: Record<string, string>;
1964
+ /** Columns to modify. Keys become column names. */
1951
1965
  modify?: ColumnMap;
1952
1966
  /**
1953
1967
  * Regular indexes to add.
@@ -2031,7 +2045,8 @@ type AlterSchema = {
2031
2045
  addFullText?: Array<{
2032
2046
  columns: string | string[];
2033
2047
  options?: FullTextIndexOptions;
2034
- }>; /** Full-text indexes to drop (by name). */
2048
+ }>;
2049
+ /** Full-text indexes to drop (by name). */
2035
2050
  dropFullText?: string[];
2036
2051
  /**
2037
2052
  * Geo-spatial indexes to add.
@@ -2044,7 +2059,8 @@ type AlterSchema = {
2044
2059
  addGeoIndex?: Array<{
2045
2060
  column: string;
2046
2061
  options?: GeoIndexOptions;
2047
- }>; /** Geo indexes to drop (by column name). */
2062
+ }>;
2063
+ /** Geo indexes to drop (by column name). */
2048
2064
  dropGeoIndex?: string[];
2049
2065
  /**
2050
2066
  * Vector search indexes to add.
@@ -2057,7 +2073,8 @@ type AlterSchema = {
2057
2073
  addVectorIndex?: Array<{
2058
2074
  column: string;
2059
2075
  options: VectorIndexOptions;
2060
- }>; /** Vector indexes to drop (by column name). */
2076
+ }>;
2077
+ /** Vector indexes to drop (by column name). */
2061
2078
  dropVectorIndex?: string[];
2062
2079
  /**
2063
2080
  * TTL indexes to add (MongoDB-primary).
@@ -2070,7 +2087,8 @@ type AlterSchema = {
2070
2087
  addTTLIndex?: Array<{
2071
2088
  column: string;
2072
2089
  expireAfterSeconds: number;
2073
- }>; /** TTL indexes to drop (by column name). */
2090
+ }>;
2091
+ /** TTL indexes to drop (by column name). */
2074
2092
  dropTTLIndex?: string[];
2075
2093
  /**
2076
2094
  * Foreign keys to add to existing columns.
@@ -2116,7 +2134,8 @@ type AlterSchema = {
2116
2134
  addCheck?: Array<{
2117
2135
  name: string;
2118
2136
  expression: string;
2119
- }>; /** CHECK constraints to drop (by name). */
2137
+ }>;
2138
+ /** CHECK constraints to drop (by name). */
2120
2139
  dropCheck?: string[];
2121
2140
  /**
2122
2141
  * Raw SQL queries to execute as part of this alter operation.
@@ -2124,5 +2143,4 @@ type AlterSchema = {
2124
2143
  raw?: string | string[];
2125
2144
  };
2126
2145
  //#endregion
2127
- export { AlterSchema, ColumnMap, IndexEntry, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationOrigin, MigrationStep, OperationType, PendingOperation, UniqueEntry, migrate };
2128
2146
  //# sourceMappingURL=migration.d.mts.map