@warlock.js/cascade 4.11.0 → 4.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.d.mts CHANGED
@@ -49,10 +49,10 @@ import { SyncManager } from "./sync/sync-manager.mjs";
49
49
  import { ModelTransformCallback, useModelTransformer } from "./utils/database-writer.utils.mjs";
50
50
  import { DefineModelOptions, ModelType, defineModel } from "./utils/define-model.mjs";
51
51
  import { onceConnected, onceDisconnected } from "./utils/once-connected.mjs";
52
- import { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, PendingMigration, RollbackOptions, RunMigrationsOptions } from "./migration/types.mjs";
52
+ import { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, RollbackOptions, RunMigrationsOptions } from "./migration/types.mjs";
53
53
  import { MigrationRunner, migrationRunner } from "./migration/migration-runner.mjs";
54
54
  import { CreateDatabaseResult, DropAllTablesResult, createDatabase, dropAllTables } from "./operations/database.mjs";
55
- import { ExportMigrationsSQLOptions, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
55
+ import { ExportMigrationsSQLOptions, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
56
56
  import { MongoMigrationDriver } from "./drivers/mongodb/mongodb-migration-driver.mjs";
57
57
  import { SqlDialectContract } from "./drivers/sql/sql-dialect.contract.mjs";
58
58
  import { SqlAggregateFunction, SqlDeleteOperation, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType } from "./drivers/sql/sql-types.mjs";
@@ -65,6 +65,6 @@ import { PostgresQueryBuilder } from "./drivers/postgres/postgres-query-builder.
65
65
  import { PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresQueryParser } from "./drivers/postgres/postgres-query-parser.mjs";
66
66
  import { PostgresSyncAdapter } from "./drivers/postgres/postgres-sync-adapter.mjs";
67
67
  import { MongoClientOptions, TransactionOptions } from "mongodb";
68
- export { $agg, $expr, AggregateExpression, AggregateFunction, AlterSchema, ArithmeticExpression, type BaseQueryRuleOptions, type BaseUniqueRuleOptions, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToOptions, BuildUpdateOperationsResult, type ChildModel, ChunkCallback, ColumnBuilder, ColumnDefinition, ColumnExpression, ColumnExpressionInput, ColumnExpressionType, ColumnMap, ColumnRefExpression, ColumnType, ConnectionOptions, CreateDatabaseOptions, CreateDatabaseResult, CursorPaginationOptions, CursorPaginationResult, DEFAULT_MAX_SYNC_DEPTH, DataSource, DataSourceOptions, DataSourceRegistryEvent, DataSourceRegistryListener, DatabaseDirtyTracker, DatabaseDriver, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DefineModelOptions, DeleteStrategy, DetachedColumnBuilder, DriverContract, DriverEvent, DriverEventListener, DriverQuery, DriverTransactionContract, DropAllTablesResult, DropDatabaseOptions, type EmbedKey, type ExistsRuleOptions, ExportMigrationsSQLOptions, ForeignKeyBuilder, ForeignKeyDefinition, FullTextIndexOptions, GenerateIdOptions, GeoIndexOptions, type GlobalScopeDefinition, type GlobalScopeOptions, GroupByInput, HasMany, type HasManyOptions, HasOne, type HasOneOptions, HavingInput, IdGeneratorContract, IndexDefinition, IndexEntry, InsertResult, JoinOptions, LiteralExpression, type LoadedRelationResult, type LoadedRelationsMap, type LocalScopeCallback, LockForUpdateOptions, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationDefaults, MigrationDriverContract, MigrationDriverFactory, type MigrationRecord, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, MissingDataSourceError, Model, ModelDefaultConfig, ModelDefaults, ModelEventListener, ModelEventName, ModelEvents, ModelRef, type ModelSchema, type ModelSnapshot, type ModelSyncConfig, type ModelSyncContract, ModelSyncOperation, type ModelSyncOperationContract, ModelTransformCallback, ModelType, type MongoClientOptions, MongoDbDriver, MongoDriverOptions, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, NamingConvention, OnDeletedEventContext, Operation, OperationType, OrderDirection, PaginationOptions, PaginationResult, type PendingMigration, PendingOperation, PipelineStage, type PivotData, type PivotIds, PivotOperations, PostgresBlueprint, PostgresConnectionConfig, PostgresCopyOptions, PostgresDialect, PostgresDriver, PostgresIsolationLevel, PostgresMigrationDriver, PostgresNotification, PostgresOperation, PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresPoolConfig, PostgresQueryBuilder, PostgresQueryParser, PostgresQueryResult, PostgresSyncAdapter, PostgresTransactionOptions, PostgresWhereClause, QueryBuilderContract, RELATION_METADATA_KEY, RawColumnExpression, RawExpression, RawQueryResult, RegisterModel, RegisterModelOptions, type RelationConstraintCallback, type RelationConstraints, RelationDefaults, type RelationDefinition, type RelationDefinitions, RelationHydrator, RelationLoader, type RelationType, RemoverContract, RemoverOptions, RemoverResult, RestorerContract, RestorerOptions, RestorerResult, RollbackMigrationsOptions, type RollbackOptions, type RunMigrationsOptions, type ScopeTiming, type SerializedRelation, SqlAggregateFunction, SqlDeleteOperation, SqlDialectContract, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType, StrictMode, SyncAdapterContract, type SyncConfig, type SyncContext, SyncContextManager, type SyncEventPayload, SyncInstruction, type SyncInstructionOptions, SyncManager, type SyncResult, type TableIndexInformation, TransactionContext, type TransactionOptions, TransactionRollbackError, UniqueEntry, type UniqueRuleOptions, UpdateOperations, UpdateResult, UuidStrategy, VectorIndexOptions, WhereCallback, WhereObject, WhereOperator, WriterContract, WriterOptions, WriterResult, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, lineString, listExecutedMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
68
+ export { $agg, $expr, AggregateExpression, AggregateFunction, AlterSchema, ArithmeticExpression, type BaseQueryRuleOptions, type BaseUniqueRuleOptions, BelongsTo, BelongsToMany, type BelongsToManyOptions, type BelongsToOptions, BuildUpdateOperationsResult, type ChildModel, ChunkCallback, ColumnBuilder, ColumnDefinition, ColumnExpression, ColumnExpressionInput, ColumnExpressionType, ColumnMap, ColumnRefExpression, ColumnType, ConnectionOptions, CreateDatabaseOptions, CreateDatabaseResult, CursorPaginationOptions, CursorPaginationResult, DEFAULT_MAX_SYNC_DEPTH, DataSource, DataSourceOptions, DataSourceRegistryEvent, DataSourceRegistryListener, DatabaseDirtyTracker, DatabaseDriver, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DefineModelOptions, DeleteStrategy, DetachedColumnBuilder, DriverContract, DriverEvent, DriverEventListener, DriverQuery, DriverTransactionContract, DropAllTablesResult, DropDatabaseOptions, type EmbedKey, type ExistsRuleOptions, ExportMigrationsSQLOptions, ForeignKeyBuilder, ForeignKeyDefinition, FullTextIndexOptions, GenerateIdOptions, GeoIndexOptions, type GlobalScopeDefinition, type GlobalScopeOptions, GroupByInput, HasMany, type HasManyOptions, HasOne, type HasOneOptions, HavingInput, IdGeneratorContract, IndexDefinition, IndexEntry, InsertResult, JoinOptions, LiteralExpression, type LoadedRelationResult, type LoadedRelationsMap, type LocalScopeCallback, LockForUpdateOptions, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, MigrationDefaults, MigrationDriverContract, MigrationDriverFactory, type MigrationRecord, type MigrationResult, MigrationRunner, type MigrationRunnerOptions, type MigrationStatus, MissingDataSourceError, Model, ModelDefaultConfig, ModelDefaults, ModelEventListener, ModelEventName, ModelEvents, ModelRef, type ModelSchema, type ModelSnapshot, type ModelSyncConfig, type ModelSyncContract, ModelSyncOperation, type ModelSyncOperationContract, ModelTransformCallback, ModelType, type MongoClientOptions, MongoDbDriver, MongoDriverOptions, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, NamingConvention, OnDeletedEventContext, Operation, OperationType, OrderDirection, PaginationOptions, PaginationResult, PendingOperation, PipelineStage, type PivotData, type PivotIds, PivotOperations, PostgresBlueprint, PostgresConnectionConfig, PostgresCopyOptions, PostgresDialect, PostgresDriver, PostgresIsolationLevel, PostgresMigrationDriver, PostgresNotification, PostgresOperation, PostgresOperationType, PostgresParserOperation, PostgresParserOptions, PostgresPoolConfig, PostgresQueryBuilder, PostgresQueryParser, PostgresQueryResult, PostgresSyncAdapter, PostgresTransactionOptions, PostgresWhereClause, QueryBuilderContract, RELATION_METADATA_KEY, RawColumnExpression, RawExpression, RawQueryResult, RegisterModel, RegisterModelOptions, type RelationConstraintCallback, type RelationConstraints, RelationDefaults, type RelationDefinition, type RelationDefinitions, RelationHydrator, RelationLoader, type RelationType, RemoverContract, RemoverOptions, RemoverResult, RestorerContract, RestorerOptions, RestorerResult, RollbackMigrationsOptions, type RollbackOptions, type RunMigrationsOptions, type ScopeTiming, type SerializedRelation, SqlAggregateFunction, SqlDeleteOperation, SqlDialectContract, SqlGroupClause, SqlHavingClause, SqlInsertOperation, SqlJoinClause, SqlJoinType, SqlOrderClause, SqlQueryConfig, SqlQueryResult, SqlSelectClause, SqlUpdateOperation, SqlWhereOperation, SqlWhereType, StrictMode, SyncAdapterContract, type SyncConfig, type SyncContext, SyncContextManager, type SyncEventPayload, SyncInstruction, type SyncInstructionOptions, SyncManager, type SyncResult, type TableIndexInformation, TransactionContext, type TransactionOptions, TransactionRollbackError, UniqueEntry, type UniqueRuleOptions, UpdateOperations, UpdateResult, UuidStrategy, VectorIndexOptions, WhereCallback, WhereObject, WhereOperator, WriterContract, WriterOptions, WriterResult, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
69
69
  import "./validation/plugins/database-rules-plugin.mjs";
70
70
  import "./validation/plugins/embed-validator-plugin.mjs";
package/esm/index.mjs CHANGED
@@ -48,7 +48,7 @@ import { Migration, migrate } from "./migration/migration.mjs";
48
48
  import { MigrationRunner, migrationRunner } from "./migration/migration-runner.mjs";
49
49
  import "./migration/index.mjs";
50
50
  import { createDatabase, dropAllTables } from "./operations/database.mjs";
51
- import { exportMigrationsSQL, freshMigrate, listExecutedMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
51
+ import { exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./operations/migrations.mjs";
52
52
  import "./operations/index.mjs";
53
53
 
54
- export { $agg, $expr, BelongsTo, BelongsToMany, ColumnBuilder, DEFAULT_MAX_SYNC_DEPTH, DataSource, DatabaseDirtyTracker, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DetachedColumnBuilder, ForeignKeyBuilder, HasMany, HasOne, Migration, MigrationRunner, MissingDataSourceError, Model, ModelEvents, ModelSyncOperation, MongoDbDriver, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, PivotOperations, PostgresBlueprint, PostgresDialect, PostgresDriver, PostgresMigrationDriver, PostgresQueryBuilder, PostgresQueryParser, PostgresSyncAdapter, RELATION_METADATA_KEY, RegisterModel, RelationHydrator, RelationLoader, SyncContextManager, SyncManager, TransactionRollbackError, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, lineString, listExecutedMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
54
+ export { $agg, $expr, BelongsTo, BelongsToMany, ColumnBuilder, DEFAULT_MAX_SYNC_DEPTH, DataSource, DatabaseDirtyTracker, DatabaseRemover, DatabaseRestorer, DatabaseWriter, DatabaseWriterValidationError, DetachedColumnBuilder, ForeignKeyBuilder, HasMany, HasOne, Migration, MigrationRunner, MissingDataSourceError, Model, ModelEvents, ModelSyncOperation, MongoDbDriver, MongoIdGenerator, MongoMigrationDriver, MongoQueryBuilder, MongoSyncAdapter, PivotOperations, PostgresBlueprint, PostgresDialect, PostgresDriver, PostgresMigrationDriver, PostgresQueryBuilder, PostgresQueryParser, PostgresSyncAdapter, RELATION_METADATA_KEY, RegisterModel, RelationHydrator, RelationLoader, SyncContextManager, SyncManager, TransactionRollbackError, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol as bool, boolCol, char, cleanupModelsRegistery, connectToDatabase, createDatabase, createPivotOperations, dataSourceRegistry, databaseDataSourceContext, databaseTransactionContext, date, dateTime, decimal, defineModel, double, dropAllTables, enumCol, exportMigrationsSQL, float, freshMigrate, geometry, getAllModelsFromRegistry, getDatabaseDriver, getModelFromRegistry, globalModelEvents, int, integer, ipAddress, isAggregateExpression, isColumnExpression, isMongoDBDriverLoaded, json, lineString, listExecutedMigrations, listPendingMigrations, longText, macAddress, mediumText, migrate, migrationRunner, modelSync, objectCol, onceConnected, onceDisconnected, point, polygon, registerModelInRegistry, removeModelFromRegistery, resolveModelClass, resolveModelName, rollbackMigrations, runMigrations, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, toColumnExpression, transaction, tryResolveModelClass, ulid, useModelTransformer, uuid, vector, verifyRegisteredRelations, year };
@@ -2,5 +2,5 @@ import { ColumnBuilder } from "./column-builder.mjs";
2
2
  import { DetachedColumnBuilder, arrayBigInt, arrayBoolean, arrayDate, arrayDecimal, arrayFloat, arrayInt, arrayJson, arrayText, arrayTimestamp, arrayUuid, bigInt, bigInteger, binary, blobCol, boolCol, char, date, dateTime, decimal, double, enumCol, float, geometry, int, integer, ipAddress, json, lineString, longText, macAddress, mediumText, objectCol, point, polygon, setCol, smallInt, smallInteger, string, text, time, timestamp, tinyInt, tinyInteger, ulid, uuid, vector, year } from "./column-helpers.mjs";
3
3
  import { ForeignKeyBuilder } from "./foreign-key-builder.mjs";
4
4
  import { AlterSchema, ColumnMap, IndexEntry, Migration, MigrationAlterOptions, MigrationConstructor, MigrationContract, MigrationCreateOptions, OperationType, PendingOperation, UniqueEntry, migrate } from "./migration.mjs";
5
- import { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, PendingMigration, RollbackOptions, RunMigrationsOptions } from "./types.mjs";
5
+ import { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, RollbackOptions, RunMigrationsOptions } from "./types.mjs";
6
6
  import { MigrationRunner, migrationRunner } from "./migration-runner.mjs";
@@ -249,9 +249,18 @@ declare class MigrationRunner {
249
249
  */
250
250
  private formatSQLForExport;
251
251
  /**
252
- * Get pending (not executed) registered migrations.
252
+ * Get pending (not executed) registered migrations, in the order they would
253
+ * execute.
254
+ *
255
+ * ⚠️ "Registered" is load-bearing. This filters `this.migrations`, which is
256
+ * populated only by `register()` / `registerMany()`. A caller that has not
257
+ * registered anything gets `[]` — indistinguishable from a database with
258
+ * nothing pending. Anything reporting this set to a human MUST register
259
+ * migrations first, or it will print a confident all-clear over an unknown.
260
+ *
261
+ * @see listPendingMigrations
253
262
  */
254
- private getPendingMigrations;
263
+ getPendingMigrations(): Promise<MigrationClass[]>;
255
264
  /**
256
265
  * Get migrations to rollback, newest-first.
257
266
  *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,cAOH,eAAA,EAAe,eAAwB"}
@@ -574,7 +574,16 @@ var MigrationRunner = class {
574
574
  return lines.join("\n");
575
575
  }
576
576
  /**
577
- * Get pending (not executed) registered migrations.
577
+ * Get pending (not executed) registered migrations, in the order they would
578
+ * execute.
579
+ *
580
+ * ⚠️ "Registered" is load-bearing. This filters `this.migrations`, which is
581
+ * populated only by `register()` / `registerMany()`. A caller that has not
582
+ * registered anything gets `[]` — indistinguishable from a database with
583
+ * nothing pending. Anything reporting this set to a human MUST register
584
+ * migrations first, or it will print a confident all-clear over an unknown.
585
+ *
586
+ * @see listPendingMigrations
578
587
  */
579
588
  async getPendingMigrations() {
580
589
  const executed = await this.getExecutedMigrations();
@@ -1 +1 @@
1
- {"version":3,"file":"migration-runner.mjs","names":[],"sources":["../../../../../../../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 { type Migration } 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};\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};\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\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 driver */\n private cachedMigrationDriver?: 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.cachedMigrationDriver = undefined;\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(): MigrationDriverContract {\n if (!this.cachedMigrationDriver) {\n this.cachedMigrationDriver = this.getDataSource().driver.migrationDriver();\n }\n return this.cachedMigrationDriver;\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 createdAt - Optional timestamp for ordering\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: MigrationClass): 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 // Avoid duplicates\n if (!this.migrations.some((m) => m.migrationName === name)) {\n this.migrations.push(MigrationClass);\n }\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: MigrationClass[]): 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 const { dryRun = false, record = true } = options;\n\n const results: MigrationResult[] = [];\n\n // Get pending migrations\n const pending = await this.getPendingMigrations();\n\n if (pending.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to migrate.\");\n return results;\n }\n\n // Drivers without SQL serialization (MongoDB) execute each migration's\n // pending operations directly through the migration driver — there is no\n // SQL pool to collect or phase-sort.\n if (this.getDataSource().driver.supportsSqlSerialization === false) {\n const batch = await this.getNextBatchNumber();\n for (const MigrationClass of pending) {\n const result = await this.runMigration(MigrationClass, \"up\", { dryRun, record, batch });\n results.push(result);\n\n if (!result.success) {\n break;\n }\n }\n return results;\n }\n\n log.info(\n \"database\",\n \"migration\",\n `Found ${pending.length} pending migration(s). Generating SQL pool...`,\n );\n const nextBatch = await this.getNextBatchNumber();\n\n const taggedStatements: TaggedSQL[] = [];\n const migrationsData: MigrationData[] = [];\n\n // 1. Collect SQL from each pending migration.\n // Fire extension checks concurrently as we encounter CREATE EXTENSION\n // statements — they resolve before execution begins.\n const extensionChecks: Promise<void>[] = [];\n\n for (const MigrationClass of pending) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n\n await migration.up();\n const upStatements = migration.toSQL();\n\n migrationsData.push({ MigrationClass, migration, name });\n\n for (const sql of upStatements) {\n const statementType = SQLGrammar.classify(sql);\n\n if (statementType === \"CREATE_EXTENSION\") {\n const ext = SQLGrammar.extractExtensionName(sql);\n if (ext) extensionChecks.push(this.informIfExtensionMissing(ext));\n }\n\n taggedStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType,\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n }\n\n // 2. Resolve all extension checks before any SQL is executed.\n // Each check displays a rich message if the extension is missing\n // but does not throw — execution continues and Postgres will\n // surface its own error with full context already shown.\n await Promise.all(extensionChecks);\n\n // 3. Sort all SQL statements globally across all pending migrations\n const sortedStatements = SQLGrammar.sort(taggedStatements);\n\n // 4. Execute in a single batch\n if (dryRun) {\n log.info(\"database\", \"migration\", \"Dry run enabled. Would execute the following statements:\");\n for (const statement of sortedStatements) {\n console.log(\n `-- [${statement.statementType}] Phase ${statement.phase} [${statement.migrationName}]`,\n );\n console.log(statement.sql + \";\\n\");\n }\n return [];\n }\n\n const driver = this.getDataSource().driver;\n\n let transactionFailed = false;\n let errorMessage = \"\";\n /** The migration name that owns the SQL statement that threw. */\n let failingMigrationName: string | undefined;\n\n const startTime = Date.now();\n\n /**\n * Execute all sorted statements, capturing which migration owns the\n * statement that throws — so we report a precise culprit instead of\n * blaming every migration in the batch.\n */\n const executeStatements = async (): Promise<void> => {\n for (const statement of sortedStatements) {\n try {\n await driver.query(statement.sql);\n } catch (err) {\n failingMigrationName = statement.migrationName;\n throw err;\n }\n }\n\n if (record) {\n for (const data of migrationsData) {\n await this.recordMigration(\n data.name,\n nextBatch,\n data.MigrationClass.createdAt\n ? parseCreatedAt(data.MigrationClass.createdAt)\n : new Date(),\n );\n }\n }\n };\n\n try {\n if (driver.transaction) {\n await driver.transaction(executeStatements);\n } else {\n await executeStatements();\n }\n } catch (err) {\n transactionFailed = true;\n errorMessage = err instanceof Error ? err.message : String(err);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Report results per-migration.\n // Only the migration that owns the failing statement is marked as failed;\n // all others are reported as rolled back / not reached.\n for (const data of migrationsData) {\n const isCulprit = transactionFailed && data.name === failingMigrationName;\n const wasSkipped = transactionFailed && !isCulprit;\n\n results.push({\n name: data.name,\n table: data.migration.table,\n direction: \"up\",\n success: !transactionFailed,\n error: isCulprit ? errorMessage : undefined,\n durationMs: Math.round(durationMs / migrationsData.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(\"database\", \"migration\", `Migrated: ${colors.magenta(data.name)} successfully`);\n }\n }\n\n if (transactionFailed) {\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 const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Migration bulk phase 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(options: { pendingOnly?: boolean; compact?: boolean } = {}): 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()\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 const downStatements: TaggedSQL[] = [];\n\n for (const MigrationClass of migrationsToExport) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\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 for (const sql of migration.toSQL()) {\n downStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n }\n\n const sortedUp = SQLGrammar.sort(upStatements);\n // Down SQL: reverse order (undo in reverse dependency order)\n const sortedDown = downStatements.reverse();\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 const dryRun = options.dryRun ?? false;\n const record = options.record ?? true;\n const results: MigrationResult[] = [];\n\n const toRollback = await this.getMigrationsToRollback(batches);\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 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 const executed = await this.getExecutedMigrations();\n if (executed.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to rollback.\");\n return [];\n }\n\n const maxBatch = Math.max(...executed.map((r) => r.batch));\n return this.rollbackBatches(maxBatch, 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 executed = await this.getExecutedMigrations();\n const executedMap = new Map(executed.map((r) => [r.name, r]));\n\n return this.migrations.map((MigrationClass) => {\n const instance = new MigrationClass();\n const name = MigrationClass.migrationName;\n const record = executedMap.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(extension: string): Promise<void> {\n try {\n const migrationDriver = this.getMigrationDriver();\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 const driver = this.getMigrationDriver();\n migration.setDriver(driver);\n migration.setMigrationDefaults(this.getDataSource().migrationDefaults);\n\n // ============================================================================\n // TRANSACTION RESOLUTION (3-tier hierarchy)\n // ============================================================================\n // 1. Migration-level explicit override\n // 2. Config-level global override\n // 3. Driver default (PostgreSQL: true, MongoDB: false)\n const shouldUseTransaction =\n migration.transactional ??\n this.getDataSource().migrations?.transactional ??\n driver.getDefaultTransactional();\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 = this.getDataSource().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 sqlStatements = directExecution ? [] : migration.toSQL();\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 sql of sqlStatements) {\n await databaseDriver.query(sql);\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());\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n );\n } else {\n await this.removeMigrationRecord(name);\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());\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n );\n } else {\n await this.removeMigrationRecord(name);\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 migration.setDriver(this.getMigrationDriver());\n migration.setMigrationDefaults(this.getDataSource().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.\n */\n private async getPendingMigrations(): Promise<MigrationClass[]> {\n const executed = await this.getExecutedMigrations();\n const executedNames = new Set(executed.map((r) => r.name));\n const migrations = this.migrations.filter((m) => !executedNames.has(m.migrationName));\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(batches: number): Promise<MigrationClass[]> {\n const executed = await this.getExecutedMigrations();\n if (executed.length === 0) return [];\n\n const batchNumbers = [...new Set(executed.map((r) => r.batch))]\n .sort((a, b) => b - a)\n .slice(0, batches);\n\n const migrations = executed\n .filter((r) => batchNumbers.includes(r.batch))\n .map((r) => this.migrations.find((m) => m.migrationName === r.name))\n .filter((m): m is MigrationClass => !!m);\n\n return migrations.sort(sortMigrationsForRollback);\n }\n\n /**\n * Get executed migration records.\n */\n public async getExecutedMigrations(): Promise<MigrationRecord[]> {\n const driver = this.getDataSource().driver;\n\n try {\n const migrationDriver = this.getMigrationDriver();\n\n // Ensure migrations table exists\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n\n const queryBuilder = driver.queryBuilder<MigrationRecord>(this.migrationsTable);\n return await queryBuilder.orderBy(\"batch\", \"asc\").orderBy(\"name\", \"asc\").get();\n } catch {\n return [];\n }\n }\n\n /**\n * Record a migration.\n */\n private async recordMigration(name: string, batch: number, createdAt?: Date): Promise<void> {\n const driver = this.getDataSource().driver;\n const migrationDriver = this.getMigrationDriver();\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(name: string): Promise<void> {\n const driver = this.getDataSource().driver;\n await driver.delete(this.migrationsTable, { name });\n }\n\n /**\n * Get next batch number.\n */\n private async getNextBatchNumber(): Promise<number> {\n const executed = await this.getExecutedMigrations();\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,IAAa,kBAAb,MAA6B;;CAE3B,AAAgB,aAA+B,CAAC;;CAGhD,AAAQ;;CAGR,AAAQ;;CAGR,AAAiB;;CAGjB,AAAiB;;;;;;CAOjB,AAAO,YACL,UAII,CAAC,GACL;EACA,KAAK,aAAa,QAAQ;EAC1B,KAAK,kBAAkB,QAAQ,mBAAmB;EAClD,KAAK,UAAU,QAAQ,WAAW;CACpC;;;;CASA,AAAO,cAAc,YAA8B;EACjD,KAAK,aAAa;EAClB,KAAK,wBAAwB;EAC7B,OAAO;CACT;;;;CAKA,AAAQ,gBAA4B;EAClC,IAAI,CAAC,KAAK,YACR,KAAK,aAAa,mBAAmB,IAAI;EAE3C,OAAO,KAAK;CACd;;;;CAKA,AAAQ,qBAA8C;EACpD,IAAI,CAAC,KAAK,uBACR,KAAK,wBAAwB,KAAK,cAAc,CAAC,CAAC,OAAO,gBAAgB;EAE3E,OAAO,KAAK;CACd;;;;;;;;;;;;;;;;CAqBA,AAAO,SAAS,gBAAsC;EACpD,MAAM,OAAO,eAAe;EAC5B,IAAI,CAAC,MACH,MAAM,IAAI,MACR,8IAEF;EAGF,IAAI,CAAC,KAAK,WAAW,MAAM,MAAM,EAAE,kBAAkB,IAAI,GACvD,KAAK,WAAW,KAAK,cAAc;EAGrC,OAAO;CACT;;;;;;;CAQA,AAAO,aAAa,YAAoC;EACtD,KAAK,MAAM,kBAAkB,YAC3B,KAAK,SAAS,cAAc;E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AAC,CAAC;EAEpC,IAAI;GAIF,MAHwB,KAAK,mBAGT,CAAC,CAAC,sBAAsB,KAAK,eAAe;GAGhE,OAAO,MADc,OAAO,aAA8B,KAAK,eACvC,CAAC,CAAC,QAAQ,SAAS,KAAK,CAAC,CAAC,QAAQ,QAAQ,KAAK,CAAC,CAAC,IAAI;EAC/E,QAAQ;GACN,OAAO,CAAC;EACV;CACF;;;;CAKA,MAAc,gBAAgB,MAAc,OAAe,WAAiC;EAC1F,MAAM,SAAS,KAAK,cAAc,CAAC,CAAC;EAIpC,MAHwB,KAAK,mBAGT,CAAC,CAAC,sBAAsB,KAAK,eAAe;EAEhE,MAAM,OAAO,OAAO,KAAK,iBAAiB;GACxC;GACA;GACA,4BAAY,IAAI,KAAK;GACrB;EACF,CAAC;CACH;;;;CAKA,MAAc,sBAAsB,MAA6B;EAE/D,MADe,KAAK,cAAc,CAAC,CAAC,OACvB,OAAO,KAAK,iBAAiB,EAAE,KAAK,CAAC;CACpD;;;;CAKA,MAAc,qBAAsC;EAClD,MAAM,WAAW,MAAM,KAAK,sBAAsB;EAClD,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":["../../../../../../../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 { type Migration } 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};\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};\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\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 driver */\n private cachedMigrationDriver?: 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.cachedMigrationDriver = undefined;\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(): MigrationDriverContract {\n if (!this.cachedMigrationDriver) {\n this.cachedMigrationDriver = this.getDataSource().driver.migrationDriver();\n }\n return this.cachedMigrationDriver;\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 createdAt - Optional timestamp for ordering\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: MigrationClass): 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 // Avoid duplicates\n if (!this.migrations.some((m) => m.migrationName === name)) {\n this.migrations.push(MigrationClass);\n }\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: MigrationClass[]): 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 const { dryRun = false, record = true } = options;\n\n const results: MigrationResult[] = [];\n\n // Get pending migrations\n const pending = await this.getPendingMigrations();\n\n if (pending.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to migrate.\");\n return results;\n }\n\n // Drivers without SQL serialization (MongoDB) execute each migration's\n // pending operations directly through the migration driver — there is no\n // SQL pool to collect or phase-sort.\n if (this.getDataSource().driver.supportsSqlSerialization === false) {\n const batch = await this.getNextBatchNumber();\n for (const MigrationClass of pending) {\n const result = await this.runMigration(MigrationClass, \"up\", { dryRun, record, batch });\n results.push(result);\n\n if (!result.success) {\n break;\n }\n }\n return results;\n }\n\n log.info(\n \"database\",\n \"migration\",\n `Found ${pending.length} pending migration(s). Generating SQL pool...`,\n );\n const nextBatch = await this.getNextBatchNumber();\n\n const taggedStatements: TaggedSQL[] = [];\n const migrationsData: MigrationData[] = [];\n\n // 1. Collect SQL from each pending migration.\n // Fire extension checks concurrently as we encounter CREATE EXTENSION\n // statements — they resolve before execution begins.\n const extensionChecks: Promise<void>[] = [];\n\n for (const MigrationClass of pending) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\n\n await migration.up();\n const upStatements = migration.toSQL();\n\n migrationsData.push({ MigrationClass, migration, name });\n\n for (const sql of upStatements) {\n const statementType = SQLGrammar.classify(sql);\n\n if (statementType === \"CREATE_EXTENSION\") {\n const ext = SQLGrammar.extractExtensionName(sql);\n if (ext) extensionChecks.push(this.informIfExtensionMissing(ext));\n }\n\n taggedStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType,\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n }\n\n // 2. Resolve all extension checks before any SQL is executed.\n // Each check displays a rich message if the extension is missing\n // but does not throw — execution continues and Postgres will\n // surface its own error with full context already shown.\n await Promise.all(extensionChecks);\n\n // 3. Sort all SQL statements globally across all pending migrations\n const sortedStatements = SQLGrammar.sort(taggedStatements);\n\n // 4. Execute in a single batch\n if (dryRun) {\n log.info(\"database\", \"migration\", \"Dry run enabled. Would execute the following statements:\");\n for (const statement of sortedStatements) {\n console.log(\n `-- [${statement.statementType}] Phase ${statement.phase} [${statement.migrationName}]`,\n );\n console.log(statement.sql + \";\\n\");\n }\n return [];\n }\n\n const driver = this.getDataSource().driver;\n\n let transactionFailed = false;\n let errorMessage = \"\";\n /** The migration name that owns the SQL statement that threw. */\n let failingMigrationName: string | undefined;\n\n const startTime = Date.now();\n\n /**\n * Execute all sorted statements, capturing which migration owns the\n * statement that throws — so we report a precise culprit instead of\n * blaming every migration in the batch.\n */\n const executeStatements = async (): Promise<void> => {\n for (const statement of sortedStatements) {\n try {\n await driver.query(statement.sql);\n } catch (err) {\n failingMigrationName = statement.migrationName;\n throw err;\n }\n }\n\n if (record) {\n for (const data of migrationsData) {\n await this.recordMigration(\n data.name,\n nextBatch,\n data.MigrationClass.createdAt\n ? parseCreatedAt(data.MigrationClass.createdAt)\n : new Date(),\n );\n }\n }\n };\n\n try {\n if (driver.transaction) {\n await driver.transaction(executeStatements);\n } else {\n await executeStatements();\n }\n } catch (err) {\n transactionFailed = true;\n errorMessage = err instanceof Error ? err.message : String(err);\n }\n\n const durationMs = Date.now() - startTime;\n\n // Report results per-migration.\n // Only the migration that owns the failing statement is marked as failed;\n // all others are reported as rolled back / not reached.\n for (const data of migrationsData) {\n const isCulprit = transactionFailed && data.name === failingMigrationName;\n const wasSkipped = transactionFailed && !isCulprit;\n\n results.push({\n name: data.name,\n table: data.migration.table,\n direction: \"up\",\n success: !transactionFailed,\n error: isCulprit ? errorMessage : undefined,\n durationMs: Math.round(durationMs / migrationsData.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(\"database\", \"migration\", `Migrated: ${colors.magenta(data.name)} successfully`);\n }\n }\n\n if (transactionFailed) {\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 const successCount = results.filter((r) => r.success).length;\n log.success(\n \"database\",\n \"migration\",\n `Migration bulk phase 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(options: { pendingOnly?: boolean; compact?: boolean } = {}): 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()\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 const downStatements: TaggedSQL[] = [];\n\n for (const MigrationClass of migrationsToExport) {\n const migration = this.createMigrationInstance(MigrationClass);\n const name = MigrationClass.migrationName;\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 for (const sql of migration.toSQL()) {\n downStatements.push({\n sql,\n phase: SQLGrammar.phase(sql),\n statementType: SQLGrammar.classify(sql),\n createdAt: MigrationClass.createdAt,\n migrationName: name,\n });\n }\n }\n\n const sortedUp = SQLGrammar.sort(upStatements);\n // Down SQL: reverse order (undo in reverse dependency order)\n const sortedDown = downStatements.reverse();\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 const dryRun = options.dryRun ?? false;\n const record = options.record ?? true;\n const results: MigrationResult[] = [];\n\n const toRollback = await this.getMigrationsToRollback(batches);\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 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 const executed = await this.getExecutedMigrations();\n if (executed.length === 0) {\n log.warn(\"database\", \"migration\", \"Nothing to rollback.\");\n return [];\n }\n\n const maxBatch = Math.max(...executed.map((r) => r.batch));\n return this.rollbackBatches(maxBatch, 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 executed = await this.getExecutedMigrations();\n const executedMap = new Map(executed.map((r) => [r.name, r]));\n\n return this.migrations.map((MigrationClass) => {\n const instance = new MigrationClass();\n const name = MigrationClass.migrationName;\n const record = executedMap.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(extension: string): Promise<void> {\n try {\n const migrationDriver = this.getMigrationDriver();\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 const driver = this.getMigrationDriver();\n migration.setDriver(driver);\n migration.setMigrationDefaults(this.getDataSource().migrationDefaults);\n\n // ============================================================================\n // TRANSACTION RESOLUTION (3-tier hierarchy)\n // ============================================================================\n // 1. Migration-level explicit override\n // 2. Config-level global override\n // 3. Driver default (PostgreSQL: true, MongoDB: false)\n const shouldUseTransaction =\n migration.transactional ??\n this.getDataSource().migrations?.transactional ??\n driver.getDefaultTransactional();\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 = this.getDataSource().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 sqlStatements = directExecution ? [] : migration.toSQL();\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 sql of sqlStatements) {\n await databaseDriver.query(sql);\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());\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n );\n } else {\n await this.removeMigrationRecord(name);\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());\n await this.recordMigration(\n name,\n batch,\n MigrationClass.createdAt ? parseCreatedAt(MigrationClass.createdAt) : new Date(),\n );\n } else {\n await this.removeMigrationRecord(name);\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 migration.setDriver(this.getMigrationDriver());\n migration.setMigrationDefaults(this.getDataSource().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(): Promise<MigrationClass[]> {\n const executed = await this.getExecutedMigrations();\n const executedNames = new Set(executed.map((r) => r.name));\n const migrations = this.migrations.filter((m) => !executedNames.has(m.migrationName));\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(batches: number): Promise<MigrationClass[]> {\n const executed = await this.getExecutedMigrations();\n if (executed.length === 0) return [];\n\n const batchNumbers = [...new Set(executed.map((r) => r.batch))]\n .sort((a, b) => b - a)\n .slice(0, batches);\n\n const migrations = executed\n .filter((r) => batchNumbers.includes(r.batch))\n .map((r) => this.migrations.find((m) => m.migrationName === r.name))\n .filter((m): m is MigrationClass => !!m);\n\n return migrations.sort(sortMigrationsForRollback);\n }\n\n /**\n * Get executed migration records.\n */\n public async getExecutedMigrations(): Promise<MigrationRecord[]> {\n const driver = this.getDataSource().driver;\n\n try {\n const migrationDriver = this.getMigrationDriver();\n\n // Ensure migrations table exists\n await migrationDriver.ensureMigrationsTable(this.migrationsTable);\n\n const queryBuilder = driver.queryBuilder<MigrationRecord>(this.migrationsTable);\n return await queryBuilder.orderBy(\"batch\", \"asc\").orderBy(\"name\", \"asc\").get();\n } catch {\n return [];\n }\n }\n\n /**\n * Record a migration.\n */\n private async recordMigration(name: string, batch: number, createdAt?: Date): Promise<void> {\n const driver = this.getDataSource().driver;\n const migrationDriver = this.getMigrationDriver();\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(name: string): Promise<void> {\n const driver = this.getDataSource().driver;\n await driver.delete(this.migrationsTable, { name });\n }\n\n /**\n * Get next batch number.\n */\n private async getNextBatchNumber(): Promise<number> {\n const executed = await this.getExecutedMigrations();\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2EA,IAAa,kBAAb,MAA6B;;CAE3B,AAAgB,aAA+B,CAAC;;CAGhD,AAAQ;;CAGR,AAAQ;;CAGR,AAAiB;;CAGjB,AAAiB;;;;;;CAOjB,AAAO,YACL,UAII,CAAC,GACL;EACA,KAAK,aAAa,QAAQ;EAC1B,KAAK,kBAAkB,QAAQ,mBAAmB;EAClD,KAAK,UAAU,QAAQ,WAAW;CACpC;;;;CASA,AAAO,cAAc,YAA8B;EACjD,KAAK,aAAa;EAClB,KA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MAAM,WAAW,MAAM,KAAK,sBAAsB;EAClD,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,5 +1,3 @@
1
- import { Migration } from "./migration.mjs";
2
-
3
1
  //#region ../cascade/src/migration/types.d.ts
4
2
  /**
5
3
  * Result of a single migration execution.
@@ -37,21 +35,6 @@ interface MigrationStatus {
37
35
  /** File path of the migration */
38
36
  readonly filePath: string;
39
37
  }
40
- /**
41
- * Pending migration ready to be executed.
42
- */
43
- interface PendingMigration {
44
- /** Migration name/identifier */
45
- readonly name: string;
46
- /** Table/collection affected */
47
- readonly table: string;
48
- /** Migration instance */
49
- readonly migration: Migration;
50
- /** File path of the migration */
51
- readonly filePath: string;
52
- /** Parsed createdAt timestamp */
53
- readonly createdAt: Date;
54
- }
55
38
  /**
56
39
  * Record stored in the migrations table.
57
40
  */
@@ -132,5 +115,5 @@ interface RollbackOptions {
132
115
  readonly dryRun?: boolean;
133
116
  }
134
117
  //#endregion
135
- export { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, PendingMigration, RollbackOptions, RunMigrationsOptions };
118
+ export { MigrationRecord, MigrationResult, MigrationRunnerOptions, MigrationStatus, RollbackOptions, RunMigrationsOptions };
136
119
  //# sourceMappingURL=types.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":[],"sources":["../../../../../../../cascade/src/migration/types.ts"],"mappings":";;;;;AAKA;UAAiB,eAAA;;WAEN,IAAA;EAAA;EAAA,SAEA,KAAA;EAEA;EAAA,SAAA,SAAA;EAIA;EAAA,SAFA,OAAA;EAMA;EAAA,SAJA,KAAA;EAIgB;EAAA,SAFhB,UAAA;EAQM;EAAA,SANN,UAAA,EAAY,IAAI;AAAA;;;;UAMV,eAAA;EAQN;EAAA,SANA,IAAA;EAQY;EAAA,S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UAAA,EAAY,IAAA;EAoEH;EAlET,SAAA,EAAW,IAAI;AAAA;;AA4EA;;UAtEA,sBAAA;;;;;;WAMN,OAAA;;;;WAKA,SAAA;;;;;;WAOA,eAAA;;;;;;WAOA,MAAA;;;;;;WAOA,OAAA;AAAA;;;;UAMM,oBAAA;;;;;WAKN,IAAA;;;;WAKA,MAAM;AAAA;;;;UAMA,eAAA;;;;;;WAMN,OAAA;;;;WAKA,IAAA;;;;WAKA,MAAA;AAAA"}
@@ -1,2 +1,2 @@
1
1
  import { CreateDatabaseResult, DropAllTablesResult, createDatabase, dropAllTables } from "./database.mjs";
2
- import { ExportMigrationsSQLOptions, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, rollbackMigrations, runMigrations } from "./migrations.mjs";
2
+ import { ExportMigrationsSQLOptions, PendingMigration, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./migrations.mjs";
@@ -1,4 +1,4 @@
1
1
  import { createDatabase, dropAllTables } from "./database.mjs";
2
- import { exportMigrationsSQL, freshMigrate, listExecutedMigrations, rollbackMigrations, runMigrations } from "./migrations.mjs";
2
+ import { exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations } from "./migrations.mjs";
3
3
 
4
4
  export { };
@@ -66,6 +66,30 @@ declare function exportMigrationsSQL(options?: ExportMigrationsSQLOptions): Prom
66
66
  * console.log(executed.map((record) => record.name));
67
67
  */
68
68
  declare function listExecutedMigrations(): Promise<MigrationRecord[]>;
69
+ /**
70
+ * A registered migration that has not yet been executed against the configured
71
+ * data source.
72
+ */
73
+ type PendingMigration = {
74
+ /** Migration name/identifier, as it will be recorded once executed. */readonly name: string; /** Creation timestamp, when the migration carries one. */
75
+ readonly createdAt?: string;
76
+ };
77
+ /**
78
+ * Return the registered migrations that have NOT been executed, **in the order
79
+ * they will execute**. The order is the point: it makes the result a dry run
80
+ * rather than a set.
81
+ *
82
+ * ⚠️ Only registered migrations can be pending. Register them first — via
83
+ * `migrationRunner.register()` / `registerMany()`, or whatever the host
84
+ * framework's loader does — or this returns `[]`, which reads as "nothing
85
+ * pending" and is not the same thing.
86
+ *
87
+ * @example
88
+ * migrationRunner.registerMany([CreateUsersTable, AddEmailIndex]);
89
+ * const pending = await listPendingMigrations();
90
+ * console.log(pending.map((migration) => migration.name));
91
+ */
92
+ declare function listPendingMigrations(): Promise<PendingMigration[]>;
69
93
  //#endregion
70
- export { ExportMigrationsSQLOptions, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, rollbackMigrations, runMigrations };
94
+ export { ExportMigrationsSQLOptions, PendingMigration, RollbackMigrationsOptions, exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations };
71
95
  //# sourceMappingURL=migrations.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.d.mts","names":[],"sources":["../../../../../../../cascade/src/operations/migrations.ts"],"mappings":";;;;;AAMA;KAAY,0BAAA;0FAED,WAAA,YAEO;EAAA,SAAP,OAAO;AAAA;;;AAUA;KAJN,yBAAA;EAkBuB,kFAhBxB,GAAA,YAgB4B;EAAA,SAd5B,OAAO;AAAA;;;;;;;;;;;;iBAcI,aAAA,IAAiB,OAAO,CAAC,eAAA;AAgBrB;AAkB1B;;;;AAA6D;AAY7D;;;;AA9B0B,iBAFJ,kBAAA,CACpB,OAAA,GAAS,yBAAA,GACR,OAAA,CAAQ,eAAA;;;;AAgCD;AAaV;;;;iBA3BsB,YAAA,IAAgB,OAAO,CAAC,eAAA;;;;;;;;;iBAYxB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;;;;;;;;;;iBAaY,sBAAA,IAA0B,OAAO,CAAC,eAAA"}
1
+ {"version":3,"file":"migrations.d.mts","names":[],"sources":["../../../../../../../cascade/src/operations/migrations.ts"],"mappings":";;;;;AAMA;KAAY,0BAAA;0FAED,WAAA,YAEO;EAAA,SAAP,OAAO;AAAA;;;AAUA;KAJN,yBAAA;EAkBuB,kFAhBxB,GAAA,YAgB4B;EAAA,SAd5B,OAAO;AAAA;;;;;;;;;;;;iBAcI,aAAA,IAAiB,OAAO,CAAC,eAAA;AAgBrB;AAkB1B;;;;AAA6D;AAY7D;;;;AA9B0B,iBAFJ,kBAAA,CACpB,OAAA,GAAS,yBAAA,GACR,OAAA,CAAQ,eAAA;;;;AAgCD;AAaV;;;;iBA3BsB,YAAA,IAAgB,OAAO,CAAC,eAAA;AAmC9C;;;;AAIoB;AAkBpB;;;AAtBA,iBAvBsB,mBAAA,CACpB,OAAA,GAAS,0BAAA,GACR,OAAO;AA2C6D;;;;;;;;;AAAA,iBA9BjD,sBAAA,IAA0B,OAAO,CAAC,eAAA;;;;;KAQ5C,gBAAA;kFAED,IAAA;WAEA,SAAS;AAAA;;;;;;;;;;;;;;;;iBAkBE,qBAAA,IAAyB,OAAO,CAAC,gBAAA"}
@@ -64,7 +64,28 @@ async function exportMigrationsSQL(options = {}) {
64
64
  async function listExecutedMigrations() {
65
65
  return migrationRunner.getExecutedMigrations();
66
66
  }
67
+ /**
68
+ * Return the registered migrations that have NOT been executed, **in the order
69
+ * they will execute**. The order is the point: it makes the result a dry run
70
+ * rather than a set.
71
+ *
72
+ * ⚠️ Only registered migrations can be pending. Register them first — via
73
+ * `migrationRunner.register()` / `registerMany()`, or whatever the host
74
+ * framework's loader does — or this returns `[]`, which reads as "nothing
75
+ * pending" and is not the same thing.
76
+ *
77
+ * @example
78
+ * migrationRunner.registerMany([CreateUsersTable, AddEmailIndex]);
79
+ * const pending = await listPendingMigrations();
80
+ * console.log(pending.map((migration) => migration.name));
81
+ */
82
+ async function listPendingMigrations() {
83
+ return (await migrationRunner.getPendingMigrations()).map((MigrationClass) => ({
84
+ name: MigrationClass.migrationName,
85
+ createdAt: MigrationClass.createdAt
86
+ }));
87
+ }
67
88
 
68
89
  //#endregion
69
- export { exportMigrationsSQL, freshMigrate, listExecutedMigrations, rollbackMigrations, runMigrations };
90
+ export { exportMigrationsSQL, freshMigrate, listExecutedMigrations, listPendingMigrations, rollbackMigrations, runMigrations };
70
91
  //# sourceMappingURL=migrations.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"migrations.mjs","names":[],"sources":["../../../../../../../cascade/src/operations/migrations.ts"],"sourcesContent":["import { migrationRunner } from \"../migration/migration-runner\";\nimport type { MigrationRecord, MigrationResult } from \"../migration/types\";\n\n/**\n * Options for exporting migrations as SQL files.\n */\nexport type ExportMigrationsSQLOptions = {\n /** Export only pending migrations. Default: false (exports all registered). */\n readonly pendingOnly?: boolean;\n /** Strip generated block comments and blank lines from the output. */\n readonly compact?: boolean;\n};\n\n/**\n * Options for rolling back migrations.\n */\nexport type RollbackMigrationsOptions = {\n /** Roll back every executed migration. Overrides `batches` when true. */\n readonly all?: boolean;\n /** Number of batches to roll back when `all` is not set. Default: 1. */\n readonly batches?: number;\n};\n\n/**\n * Run every pending migration registered on the migration runner.\n *\n * Caller is responsible for registering migration classes first via\n * `migrationRunner.register()` / `migrationRunner.registerMany()`. Returns one\n * result entry per executed migration.\n *\n * @example\n * migrationRunner.registerMany([CreateUsersTable, AddEmailIndex]);\n * const results = await runMigrations();\n */\nexport async function runMigrations(): Promise<MigrationResult[]> {\n return migrationRunner.runAll();\n}\n\n/**\n * Roll back executed migrations. By default rolls back the most recent batch;\n * pass `all: true` to undo every executed migration, or `batches: N` to undo\n * the last N batches.\n *\n * @example\n * await rollbackMigrations(); // last batch\n * await rollbackMigrations({ batches: 3 }); // last three batches\n * await rollbackMigrations({ all: true }); // everything\n */\nexport async function rollbackMigrations(\n options: RollbackMigrationsOptions = {},\n): Promise<MigrationResult[]> {\n if (options.all) {\n return migrationRunner.rollbackAll();\n }\n\n const batches = options.batches ?? 1;\n\n return migrationRunner.rollbackBatches(batches);\n}\n\n/**\n * Roll back every executed migration, then run every registered migration.\n * Equivalent to `rollbackMigrations({ all: true })` followed by\n * `runMigrations()`.\n *\n * @example\n * await freshMigrate();\n */\nexport async function freshMigrate(): Promise<MigrationResult[]> {\n return migrationRunner.fresh();\n}\n\n/**\n * Export registered migrations as phase-ordered `.up.sql` and `.down.sql`\n * files under `<cwd>/database/sql/`.\n *\n * @example\n * await exportMigrationsSQL();\n * await exportMigrationsSQL({ pendingOnly: true, compact: true });\n */\nexport async function exportMigrationsSQL(\n options: ExportMigrationsSQLOptions = {},\n): Promise<void> {\n return migrationRunner.exportSQL(options);\n}\n\n/**\n * Return the migration records persisted in the migrations table — one entry\n * per migration that has ever been executed against the configured data\n * source.\n *\n * @example\n * const executed = await listExecutedMigrations();\n * console.log(executed.map((record) => record.name));\n */\nexport async function listExecutedMigrations(): Promise<MigrationRecord[]> {\n return migrationRunner.getExecutedMigrations();\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,eAAsB,gBAA4C;CAChE,OAAO,gBAAgB,OAAO;AAChC;;;;;;;;;;;AAYA,eAAsB,mBACpB,UAAqC,CAAC,GACV;CAC5B,IAAI,QAAQ,KACV,OAAO,gBAAgB,YAAY;CAGrC,MAAM,UAAU,QAAQ,WAAW;CAEnC,OAAO,gBAAgB,gBAAgB,OAAO;AAChD;;;;;;;;;AAUA,eAAsB,eAA2C;CAC/D,OAAO,gBAAgB,MAAM;AAC/B;;;;;;;;;AAUA,eAAsB,oBACpB,UAAsC,CAAC,GACxB;CACf,OAAO,gBAAgB,UAAU,OAAO;AAC1C;;;;;;;;;;AAWA,eAAsB,yBAAqD;CACzE,OAAO,gBAAgB,sBAAsB;AAC/C"}
1
+ {"version":3,"file":"migrations.mjs","names":[],"sources":["../../../../../../../cascade/src/operations/migrations.ts"],"sourcesContent":["import { migrationRunner } from \"../migration/migration-runner\";\nimport type { MigrationRecord, MigrationResult } from \"../migration/types\";\n\n/**\n * Options for exporting migrations as SQL files.\n */\nexport type ExportMigrationsSQLOptions = {\n /** Export only pending migrations. Default: false (exports all registered). */\n readonly pendingOnly?: boolean;\n /** Strip generated block comments and blank lines from the output. */\n readonly compact?: boolean;\n};\n\n/**\n * Options for rolling back migrations.\n */\nexport type RollbackMigrationsOptions = {\n /** Roll back every executed migration. Overrides `batches` when true. */\n readonly all?: boolean;\n /** Number of batches to roll back when `all` is not set. Default: 1. */\n readonly batches?: number;\n};\n\n/**\n * Run every pending migration registered on the migration runner.\n *\n * Caller is responsible for registering migration classes first via\n * `migrationRunner.register()` / `migrationRunner.registerMany()`. Returns one\n * result entry per executed migration.\n *\n * @example\n * migrationRunner.registerMany([CreateUsersTable, AddEmailIndex]);\n * const results = await runMigrations();\n */\nexport async function runMigrations(): Promise<MigrationResult[]> {\n return migrationRunner.runAll();\n}\n\n/**\n * Roll back executed migrations. By default rolls back the most recent batch;\n * pass `all: true` to undo every executed migration, or `batches: N` to undo\n * the last N batches.\n *\n * @example\n * await rollbackMigrations(); // last batch\n * await rollbackMigrations({ batches: 3 }); // last three batches\n * await rollbackMigrations({ all: true }); // everything\n */\nexport async function rollbackMigrations(\n options: RollbackMigrationsOptions = {},\n): Promise<MigrationResult[]> {\n if (options.all) {\n return migrationRunner.rollbackAll();\n }\n\n const batches = options.batches ?? 1;\n\n return migrationRunner.rollbackBatches(batches);\n}\n\n/**\n * Roll back every executed migration, then run every registered migration.\n * Equivalent to `rollbackMigrations({ all: true })` followed by\n * `runMigrations()`.\n *\n * @example\n * await freshMigrate();\n */\nexport async function freshMigrate(): Promise<MigrationResult[]> {\n return migrationRunner.fresh();\n}\n\n/**\n * Export registered migrations as phase-ordered `.up.sql` and `.down.sql`\n * files under `<cwd>/database/sql/`.\n *\n * @example\n * await exportMigrationsSQL();\n * await exportMigrationsSQL({ pendingOnly: true, compact: true });\n */\nexport async function exportMigrationsSQL(\n options: ExportMigrationsSQLOptions = {},\n): Promise<void> {\n return migrationRunner.exportSQL(options);\n}\n\n/**\n * Return the migration records persisted in the migrations table — one entry\n * per migration that has ever been executed against the configured data\n * source.\n *\n * @example\n * const executed = await listExecutedMigrations();\n * console.log(executed.map((record) => record.name));\n */\nexport async function listExecutedMigrations(): Promise<MigrationRecord[]> {\n return migrationRunner.getExecutedMigrations();\n}\n\n/**\n * A registered migration that has not yet been executed against the configured\n * data source.\n */\nexport type PendingMigration = {\n /** Migration name/identifier, as it will be recorded once executed. */\n readonly name: string;\n /** Creation timestamp, when the migration carries one. */\n readonly createdAt?: string;\n};\n\n/**\n * Return the registered migrations that have NOT been executed, **in the order\n * they will execute**. The order is the point: it makes the result a dry run\n * rather than a set.\n *\n * ⚠️ Only registered migrations can be pending. Register them first — via\n * `migrationRunner.register()` / `registerMany()`, or whatever the host\n * framework's loader does — or this returns `[]`, which reads as \"nothing\n * pending\" and is not the same thing.\n *\n * @example\n * migrationRunner.registerMany([CreateUsersTable, AddEmailIndex]);\n * const pending = await listPendingMigrations();\n * console.log(pending.map((migration) => migration.name));\n */\nexport async function listPendingMigrations(): Promise<PendingMigration[]> {\n const pending = await migrationRunner.getPendingMigrations();\n\n return pending.map((MigrationClass) => ({\n name: MigrationClass.migrationName,\n createdAt: MigrationClass.createdAt,\n }));\n}\n"],"mappings":";;;;;;;;;;;;;;AAkCA,eAAsB,gBAA4C;CAChE,OAAO,gBAAgB,OAAO;AAChC;;;;;;;;;;;AAYA,eAAsB,mBACpB,UAAqC,CAAC,GACV;CAC5B,IAAI,QAAQ,KACV,OAAO,gBAAgB,YAAY;CAGrC,MAAM,UAAU,QAAQ,WAAW;CAEnC,OAAO,gBAAgB,gBAAgB,OAAO;AAChD;;;;;;;;;AAUA,eAAsB,eAA2C;CAC/D,OAAO,gBAAgB,MAAM;AAC/B;;;;;;;;;AAUA,eAAsB,oBACpB,UAAsC,CAAC,GACxB;CACf,OAAO,gBAAgB,UAAU,OAAO;AAC1C;;;;;;;;;;AAWA,eAAsB,yBAAqD;CACzE,OAAO,gBAAgB,sBAAsB;AAC/C;;;;;;;;;;;;;;;;AA4BA,eAAsB,wBAAqD;CAGzE,QAAO,MAFe,gBAAgB,qBAAqB,EAE7C,CAAC,KAAK,oBAAoB;EACtC,MAAM,eAAe;EACrB,WAAW,eAAe;CAC5B,EAAE;AACJ"}
package/package.json CHANGED
@@ -23,13 +23,13 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@mongez/copper": "^2.1.2",
26
- "@mongez/dotenv": "^1.2.4",
26
+ "@mongez/dotenv": "^1.3.1",
27
27
  "@mongez/events": "^2.2.6",
28
28
  "@mongez/reinforcements": "^3.3.0",
29
29
  "@mongez/supportive-is": "^2.1.3",
30
- "@warlock.js/context": "4.11.0",
31
- "@warlock.js/logger": "4.11.0",
32
- "@warlock.js/seal": "4.11.0",
30
+ "@warlock.js/context": "4.12.0",
31
+ "@warlock.js/logger": "4.12.0",
32
+ "@warlock.js/seal": "4.12.0",
33
33
  "citty": "^0.2.2",
34
34
  "fast-glob": "^3.3.3"
35
35
  },
@@ -40,7 +40,7 @@
40
40
  "bin": {
41
41
  "cascade": "bin/cascade.js"
42
42
  },
43
- "version": "4.11.0",
43
+ "version": "4.12.0",
44
44
  "main": "./cjs/index.cjs",
45
45
  "module": "./esm/index.mjs",
46
46
  "types": "./esm/index.d.mts",