diff --git a/documentation/components/bridges/symfony-postgresql-bundle.md b/documentation/components/bridges/symfony-postgresql-bundle.md index 0d70d36322..9171402ef4 100644 --- a/documentation/components/bridges/symfony-postgresql-bundle.md +++ b/documentation/components/bridges/symfony-postgresql-bundle.md @@ -231,8 +231,18 @@ flow_postgresql: all_or_nothing: false # Wrap all migrations in a single transaction generate_rollback: true # Generate rollback files automatically drop_if_exists: false # Emit IF EXISTS on diff-generated DROP statements + mode: all_pending # Which pending migrations migrate runs: all_pending or strict_order ``` +#### `mode` + +When two branches each add a migration and the older version deploys second, that pending migration is older than +the latest executed migration. + +- `all_pending` (default): `flow:migrations:migrate` runs every pending migration up to the target, in version order. +- `strict_order`: `flow:migrations:migrate` stops with an error and exit code 1. It runs no migration. Run the older + version with `flow:migrations:execute`, or set the mode to `all_pending`. + #### `drop_if_exists` To add `IF EXISTS` to every `DROP` that the diff generates, set `drop_if_exists: true`. Use it for convergence diff --git a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Command/MigrateCommand.php b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Command/MigrateCommand.php index e0084e7144..c58d0b204f 100644 --- a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Command/MigrateCommand.php +++ b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Command/MigrateCommand.php @@ -6,6 +6,7 @@ use Flow\PostgreSql\Migrations\Configuration as MigrationsConfiguration; use Flow\PostgreSql\Migrations\Direction; +use Flow\PostgreSql\Migrations\Exception\MigrationException; use Flow\PostgreSql\Migrations\MigrationState; use Flow\PostgreSql\Migrations\Migrator; use Flow\PostgreSql\Migrations\VersionResolver; @@ -94,7 +95,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::SUCCESS; } - $results = $this->migrator->migrate($version, $dryRun, $allOrNothing); + try { + $results = $this->migrator->migrate($version, $dryRun, $allOrNothing); + } catch (MigrationException $exception) { + $io->error($exception->getMessage()); + + return Command::FAILURE; + } if (count($results) === 0) { $io->success('Already up to date.'); diff --git a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/FlowPostgreSqlBundle.php b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/FlowPostgreSqlBundle.php index c35785ed1a..0c5360525f 100644 --- a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/FlowPostgreSqlBundle.php +++ b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/FlowPostgreSqlBundle.php @@ -36,6 +36,7 @@ use Flow\PostgreSql\Migrations\Executor\MigrationExecutor; use Flow\PostgreSql\Migrations\Generator\DiffMigrationGenerator; use Flow\PostgreSql\Migrations\Generator\MigrationGenerator; +use Flow\PostgreSql\Migrations\MigrationMode; use Flow\PostgreSql\Migrations\MigrationsFactory; use Flow\PostgreSql\Migrations\Migrator; use Flow\PostgreSql\Migrations\Repository\MigrationRepository; @@ -415,6 +416,11 @@ public function configure(DefinitionConfigurator $definition): void ->defaultFalse() ->info('Emit IF EXISTS on diff-generated DROP statements (default: false)') ->end() + ->enumNode('mode') + ->info('Which pending migrations migrate runs: "all_pending" (every pending migration up to the target, in version order) or "strict_order" (fail before any migration runs when a pending migration is older than the latest executed one)') + ->values(['all_pending', 'strict_order']) + ->defaultValue('all_pending') + ->end() ->arrayNode('context') ->info( 'Extra attributes merged into the migration context alongside the service container (available under FlowPostgreSqlBundle::SERVICE_CONTAINER). Read them in a migration via MigrationContext::attribute(). Values can be literals, @service_id references (@@ escapes a literal @), %parameter% placeholders, or %env(VAR)% expressions. Useful for handing private services or resolved config to a migration without making them public.', @@ -528,7 +534,7 @@ public function configure(DefinitionConfigurator $definition): void } /** - * @param array{connections: array, session_settings: array, test_transaction_rollback: bool, lazy: bool, context?: array, telemetry?: array{service_id: string, clock_service_id: ?string, trace_queries: bool, transaction_spans: 'grouped'|'per_operation'|'off', collect_metrics: bool, log_queries: bool, max_query_length: int, include_parameters: bool, max_parameters: int, max_parameter_length: int}, profiler?: bool}>, messenger: array{enabled: bool, table_name: string, schema: string}, cache: array{pools?: array}, session: array{enabled: bool, connection: ?string, table_name: string, schema: string, id_col: string, data_col: string, lifetime_col: string, time_col: string, lock_mode: string, ttl: ?int, share_connection: bool}, migrations: array{enabled: bool, connection: ?string, directory: string, namespace: string, table_name: string, table_schema: string, migration_file_name: string, rollback_file_name: string, all_or_nothing: bool, generate_rollback: bool, drop_if_exists: bool, context?: array, exclude?: list}, catalog_providers: list}>, profiler?: array{enabled?: bool|null, include_parameters?: bool, max_queries?: int, max_retained_parameters?: int, max_query_length?: int, migrations?: bool}} $config + * @param array{connections: array, session_settings: array, test_transaction_rollback: bool, lazy: bool, context?: array, telemetry?: array{service_id: string, clock_service_id: ?string, trace_queries: bool, transaction_spans: 'grouped'|'per_operation'|'off', collect_metrics: bool, log_queries: bool, max_query_length: int, include_parameters: bool, max_parameters: int, max_parameter_length: int}, profiler?: bool}>, messenger: array{enabled: bool, table_name: string, schema: string}, cache: array{pools?: array}, session: array{enabled: bool, connection: ?string, table_name: string, schema: string, id_col: string, data_col: string, lifetime_col: string, time_col: string, lock_mode: string, ttl: ?int, share_connection: bool}, migrations: array{enabled: bool, connection: ?string, directory: string, namespace: string, table_name: string, table_schema: string, migration_file_name: string, rollback_file_name: string, all_or_nothing: bool, generate_rollback: bool, drop_if_exists: bool, mode: 'all_pending'|'strict_order', context?: array, exclude?: list}, catalog_providers: list}>, profiler?: array{enabled?: bool|null, include_parameters?: bool, max_queries?: int, max_retained_parameters?: int, max_query_length?: int, migrations?: bool}} $config */ #[Override] public function loadExtension(array $config, ContainerConfigurator $configurator, ContainerBuilder $container): void @@ -922,7 +928,7 @@ private function registerMessenger( } /** - * @param array{enabled: bool, connection: ?string, directory: string, namespace: string, table_name: string, table_schema: string, migration_file_name: string, rollback_file_name: string, all_or_nothing: bool, generate_rollback: bool, drop_if_exists: bool, context?: array, exclude?: list} $mc + * @param array{enabled: bool, connection: ?string, directory: string, namespace: string, table_name: string, table_schema: string, migration_file_name: string, rollback_file_name: string, all_or_nothing: bool, generate_rollback: bool, drop_if_exists: bool, mode: 'all_pending'|'strict_order', context?: array, exclude?: list} $mc */ private function registerMigrations(string $connection, array $mc, ContainerBuilder $container): void { @@ -942,6 +948,7 @@ private function registerMigrations(string $connection, array $mc, ContainerBuil $this->buildExclusionPolicy($mc['exclude'] ?? []), $mc['drop_if_exists'], $this->buildMigrationContextAttributes($mc['context'] ?? []), + MigrationMode::from($mc['mode']), ]); $configDef->setPublic(true); $container->setDefinition("flow.postgresql.migrations.configuration", $configDef); diff --git a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Profiler/FlowMigrationsDataCollector.php b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Profiler/FlowMigrationsDataCollector.php index 681a2fdc1c..b6b696fd90 100644 --- a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Profiler/FlowMigrationsDataCollector.php +++ b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Profiler/FlowMigrationsDataCollector.php @@ -16,7 +16,7 @@ /** * @type MigrationRow = array{version: string, name: string, state: string, executedAt: null|string, executionTimeMs: null|int} - * @type ConfigurationData = array{tableName: string, tableSchema: string, directory: string, namespace: string, allOrNothing: bool} + * @type ConfigurationData = array{tableName: string, tableSchema: string, directory: string, namespace: string, allOrNothing: bool, mode: string} */ final class FlowMigrationsDataCollector extends DataCollector { @@ -154,6 +154,7 @@ private function describeConfiguration(): array 'directory' => $this->configuration->migrationsDirectory, 'namespace' => $this->configuration->migrationsNamespace, 'allOrNothing' => $this->configuration->allOrNothing, + 'mode' => $this->configuration->mode->value, ]; } } diff --git a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Resources/views/Collector/migrations.html.twig b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Resources/views/Collector/migrations.html.twig index 4e2d7530a5..3a11a2c394 100644 --- a/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Resources/views/Collector/migrations.html.twig +++ b/src/bridge/symfony/postgresql-bundle/src/Flow/Bridge/Symfony/PostgreSqlBundle/Resources/views/Collector/migrations.html.twig @@ -120,6 +120,7 @@ Directory{{ collector.configuration.directory }} Namespace{{ collector.configuration.namespace }} All or nothing{{ collector.configuration.allOrNothing ? 'true' : 'false' }} + Mode{{ collector.configuration.mode }} {% endif %} diff --git a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/CommandTestContext.php b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/CommandTestContext.php index 562ce6ec18..1c6e58248b 100644 --- a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/CommandTestContext.php +++ b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/CommandTestContext.php @@ -11,6 +11,7 @@ use Flow\Filesystem\Path\Filter\KeepAll; use Flow\PostgreSql\Client\DsnParser; use Flow\PostgreSql\Client\Infrastructure\PgSql\PgSqlClient; +use Flow\PostgreSql\Migrations\MigrationMode; use LogicException; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Tester\CommandTester; @@ -69,10 +70,10 @@ public function bootForDatabaseManagement(string $targetDatabase): void ]); } - public function bootWithMigrations(): void + public function bootWithMigrations(MigrationMode $mode = MigrationMode::ALL_PENDING): void { $this->symfonyContext->bootKernel([ - 'config' => function (TestKernel $kernel): void { + 'config' => function (TestKernel $kernel) use ($mode): void { $kernel->addTestContainerConfigurator(static function (ContainerBuilder $container): void { $container->register('test.catalog_provider', SimpleTestCatalogProvider::class)->setPublic(true); }); @@ -87,6 +88,7 @@ public function bootWithMigrations(): void 'directory' => $this->migrationsDir, 'namespace' => 'FlowTest\\Migrations', 'table_name' => 'flow_migrations_test', + 'mode' => $mode->value, ], 'catalog_providers' => [ ['catalog_provider_id' => 'test.catalog_provider'], @@ -201,6 +203,22 @@ public function generateDiffMigration(): string return $matches[1]; } + public function generateMigrationOlderThanAnyExecuted(): void + { + (new CommandTester($this->command('flow.postgresql.command.generate')))->execute(['name' => 'older']); + + $this->filesystem->mv( + path((string) $this->migrationDirs('*_older')[0]), + path($this->migrationsDir . '/20000101000000_older'), + ); + } + + public function isUpToDate(): bool + { + return (new CommandTester($this->command('flow.postgresql.command.up_to_date')))->execute([]) + === Command::SUCCESS; + } + public function migrationDirs(string $pattern): array { $dirs = []; diff --git a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/MigrateCommandTest.php b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/MigrateCommandTest.php index c689a58a90..9765aaf3f3 100644 --- a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/MigrateCommandTest.php +++ b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/Command/MigrateCommandTest.php @@ -4,6 +4,7 @@ namespace Flow\Bridge\Symfony\PostgreSqlBundle\Tests\Integration\Command; +use Flow\PostgreSql\Migrations\MigrationMode; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Tester\CommandTester; @@ -39,6 +40,37 @@ public function test_migrate_dry_run_does_not_apply_changes(): void static::assertFalse($this->context->tableExists('test_users')); } + public function test_migrate_executes_pending_migration_older_than_latest_executed(): void + { + $this->context->generateDiffMigration(); + $this->context->runMigrate(); + $this->context->generateMigrationOlderThanAnyExecuted(); + + $tester = new CommandTester($this->context->command('flow.postgresql.command.migrate')); + $tester->execute([], ['interactive' => false]); + + static::assertSame(Command::SUCCESS, $tester->getStatusCode()); + static::assertStringNotContainsString('Already up to date', $tester->getDisplay()); + static::assertStringContainsString('1 migration(s) executed', $tester->getDisplay()); + static::assertTrue($this->context->isUpToDate()); + } + + public function test_migrate_in_strict_order_fails_on_pending_migration_older_than_latest_executed(): void + { + $this->context->bootWithMigrations(MigrationMode::STRICT_ORDER); + $this->context->generateDiffMigration(); + $this->context->runMigrate(); + $this->context->generateMigrationOlderThanAnyExecuted(); + + $tester = new CommandTester($this->context->command('flow.postgresql.command.migrate')); + $tester->execute([], ['interactive' => false]); + + static::assertSame(Command::FAILURE, $tester->getStatusCode()); + static::assertStringNotContainsString('Already up to date', $tester->getDisplay()); + static::assertStringContainsString('Pending migrations "20000101000000" are older', $tester->getDisplay()); + static::assertFalse($this->context->isUpToDate()); + } + public function test_migrate_first_rolls_back_to_first_version(): void { $this->context->generateDiffMigration(); diff --git a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/FlowPostgreSqlExtensionTest.php b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/FlowPostgreSqlExtensionTest.php index 6ba99120cb..53ab55ed6b 100644 --- a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/FlowPostgreSqlExtensionTest.php +++ b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Integration/FlowPostgreSqlExtensionTest.php @@ -30,6 +30,7 @@ use Flow\PostgreSql\Migrations\Executor\MigrationExecutor; use Flow\PostgreSql\Migrations\Generator\DiffMigrationGenerator; use Flow\PostgreSql\Migrations\Generator\MigrationGenerator; +use Flow\PostgreSql\Migrations\MigrationMode; use Flow\PostgreSql\Migrations\MigrationsFactory; use Flow\PostgreSql\Migrations\Migrator; use Flow\PostgreSql\Migrations\Repository\MigrationRepository; @@ -461,6 +462,37 @@ public function test_class_aliases_for_migration_services(): void static::assertTrue($this->getContainer()->has(DiffMigrationGenerator::class)); } + public function test_migrations_configuration_receives_mode(): void + { + $this->bootKernel([ + 'config' => static function (TestKernel $kernel): void { + $kernel->addTestContainerConfigurator(static function (ContainerBuilder $container): void { + $container->register('flow.postgresql.default.client', SpyClient::class)->setPublic(true); + }); + $kernel->addTestExtensionConfig('flow_postgresql', [ + 'connections' => [ + 'default' => [ + 'dsn' => 'postgresql://postgres:postgres@localhost:5432/postgres', + ], + ], + 'migrations' => [ + 'enabled' => true, + 'directory' => '/tmp/test_migrations', + 'namespace' => 'App\\Migrations', + 'mode' => 'strict_order', + ], + 'catalog_providers' => [ + ['catalog' => ['schemas' => []]], + ], + ]); + }, + ]); + + $configuration = $this->getContainer()->get('flow.postgresql.migrations.configuration'); + static::assertInstanceOf(MigrationsConfiguration::class, $configuration); + static::assertSame(MigrationMode::STRICT_ORDER, $configuration->mode); + } + public function test_migrations_configuration_injects_service_container_attribute(): void { $this->bootKernel([ diff --git a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php index a5b596ebc5..5cbf5a3a2f 100644 --- a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php +++ b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/DependencyInjection/ConfigurationTest.php @@ -482,6 +482,22 @@ public function test_migrations_default_values(): void static::assertFalse($config['migrations']['all_or_nothing']); static::assertTrue($config['migrations']['generate_rollback']); static::assertFalse($config['migrations']['drop_if_exists']); + static::assertSame('all_pending', $config['migrations']['mode']); + } + + public function test_migrations_mode_can_be_strict_order(): void + { + $config = $this->context->processConfig([ + 'connections' => [ + 'default' => ['dsn' => 'postgresql://user:pass@localhost:5432/db'], + ], + 'migrations' => [ + 'enabled' => true, + 'mode' => 'strict_order', + ], + ]); + + static::assertSame('strict_order', $config['migrations']['mode']); } public function test_migrations_drop_if_exists_can_be_enabled(): void diff --git a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/Profiler/FlowMigrationsDataCollectorTest.php b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/Profiler/FlowMigrationsDataCollectorTest.php index d1ba542cee..b88edd13ee 100644 --- a/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/Profiler/FlowMigrationsDataCollectorTest.php +++ b/src/bridge/symfony/postgresql-bundle/tests/Flow/Bridge/Symfony/PostgreSqlBundle/Tests/Unit/Profiler/FlowMigrationsDataCollectorTest.php @@ -92,6 +92,7 @@ public function test_collects_executed_and_pending_with_execution_time(): void $configurationData = $collector->getConfiguration(); static::assertIsArray($configurationData); static::assertSame('flow_migrations', $configurationData['tableName']); + static::assertSame('all_pending', $configurationData['mode']); $executed = $collector->getMigrations()[0]; static::assertSame('20260401120000', $executed['version']); diff --git a/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Configuration.php b/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Configuration.php index 2bde78f978..81d11a53ff 100644 --- a/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Configuration.php +++ b/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Configuration.php @@ -27,5 +27,6 @@ public function __construct( public ?ExclusionPolicy $exclusionPolicy = null, public bool $dropIfExists = false, public array $attributes = [], + public MigrationMode $mode = MigrationMode::ALL_PENDING, ) {} } diff --git a/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Exception/MigrationException.php b/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Exception/MigrationException.php index 5a387857cc..e4aa2319cd 100644 --- a/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Exception/MigrationException.php +++ b/src/lib/postgresql/src/Flow/PostgreSql/Migrations/Exception/MigrationException.php @@ -8,6 +8,8 @@ use RuntimeException; use Throwable; +use function array_map; +use function implode; use function sprintf; class MigrationException extends RuntimeException @@ -69,6 +71,15 @@ public static function noChangesDetected(): self return new self('No changes detected between source and target catalog.'); } + public static function outOfOrder(Version $latestExecuted, Version ...$pending): self + { + return new self(sprintf( + 'Pending migrations "%s" are older than the latest executed migration "%s". Switch the migration mode to "all_pending" (MigrationMode::ALL_PENDING) to run them, or execute each version explicitly.', + implode('", "', array_map(static fn(Version $version): string => (string) $version, $pending)), + $latestExecuted, + )); + } + public static function versionNotFound(Version $version): self { return new self(sprintf('Migration version "%s" not found.', $version)); diff --git a/src/lib/postgresql/src/Flow/PostgreSql/Migrations/MigrationMode.php b/src/lib/postgresql/src/Flow/PostgreSql/Migrations/MigrationMode.php new file mode 100644 index 0000000000..78f502250e --- /dev/null +++ b/src/lib/postgresql/src/Flow/PostgreSql/Migrations/MigrationMode.php @@ -0,0 +1,11 @@ +version->equals($target)) { - return []; - } - $plans = []; - if ($latestExecuted === null || $target->isAfter($latestExecuted->version)) { - $pending = $latestExecuted === null - ? $available->upTo($target) - : $available->after($latestExecuted->version)->upTo($target); + if ($latestExecuted === null || !$latestExecuted->version->isAfter($target)) { + foreach ($available->upTo($target) as $migration) { + if (!$executed->has($migration->version)) { + $plans[] = new MigrationPlan( + $migration->version, + $migration->migration, + $migration->rollback, + Direction::UP, + ); + } + } - foreach ($pending as $migration) { - $plans[] = new MigrationPlan( - $migration->version, - $migration->migration, - $migration->rollback, - Direction::UP, - ); + if ($latestExecuted !== null && $this->configuration->mode === MigrationMode::STRICT_ORDER) { + $outOfOrder = array_filter($plans, static fn( + MigrationPlan $plan, + ): bool => $latestExecuted->version->isAfter($plan->version)); + + if ($outOfOrder !== []) { + throw MigrationException::outOfOrder( + $latestExecuted->version, + ...array_map(static fn(MigrationPlan $plan): Version => $plan->version, $outOfOrder), + ); + } } - } elseif ($latestExecuted->version->isAfter($target)) { + } else { $toRollback = []; foreach ($executed as $em) { diff --git a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Integration/MigratorTest.php b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Integration/MigratorTest.php index 5759d3ed51..bd017a5271 100644 --- a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Integration/MigratorTest.php +++ b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Integration/MigratorTest.php @@ -132,6 +132,27 @@ public function test_migrate_down_to_specific_version(): void static::assertCount(1, $this->store->executedMigrations()); } + public function test_migrate_executes_pending_migration_older_than_latest_executed(): void + { + $migrator = new Migrator( + $this->fixtureRepository(), + $this->store, + new DefaultMigrationExecutor(), + $this->context->client, + $this->configuration, + ); + + $migrator->executeVersion(Version::fromString('20260401120000'), Direction::UP); + $migrator->executeVersion(Version::fromString('20260403090000'), Direction::UP); + + $results = $migrator->migrate(); + + static::assertCount(1, $results); + static::assertTrue($results[0]->isSuccessful()); + static::assertTrue($results[0]->version->equals(Version::fromString('20260402100000'))); + static::assertCount(0, $migrator->status()->pending()); + } + public function test_migrate_up_from_empty_state(): void { $migrator = new Migrator( diff --git a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/ConfigurationTest.php b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/ConfigurationTest.php index 7af80633da..74cfb841fd 100644 --- a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/ConfigurationTest.php +++ b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/ConfigurationTest.php @@ -5,6 +5,7 @@ namespace Flow\PostgreSql\Migrations\Tests\Unit; use Flow\PostgreSql\Migrations\Configuration; +use Flow\PostgreSql\Migrations\MigrationMode; use Flow\PostgreSql\Migrations\Tests\Double\FakeCatalogProvider; use Flow\PostgreSql\Migrations\Tests\Double\SpyClient; use Flow\PostgreSql\Schema\Catalog; @@ -68,5 +69,6 @@ public function test_default_values(): void static::assertFalse($config->allOrNothing); static::assertTrue($config->generateRollback); static::assertSame([], $config->attributes); + static::assertSame(MigrationMode::ALL_PENDING, $config->mode); } } diff --git a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/Exception/MigrationExceptionTest.php b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/Exception/MigrationExceptionTest.php index 9765153ab0..bcac2b1cf6 100644 --- a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/Exception/MigrationExceptionTest.php +++ b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/Exception/MigrationExceptionTest.php @@ -97,6 +97,18 @@ public function test_no_changes_detected(): void static::assertSame('No changes detected between source and target catalog.', $exception->getMessage()); } + public function test_out_of_order(): void + { + static::assertSame( + 'Pending migrations "20260101000000", "20260102000000" are older than the latest executed migration "20260103000000". Switch the migration mode to "all_pending" (MigrationMode::ALL_PENDING) to run them, or execute each version explicitly.', + MigrationException::outOfOrder( + Version::fromString('20260103000000'), + Version::fromString('20260101000000'), + Version::fromString('20260102000000'), + )->getMessage(), + ); + } + public function test_version_not_found(): void { $exception = MigrationException::versionNotFound(Version::fromString('20260403120000')); diff --git a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/MigratorTest.php b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/MigratorTest.php index adf38087b8..79fd1dc34a 100644 --- a/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/MigratorTest.php +++ b/src/lib/postgresql/tests/Flow/PostgreSql/Migrations/Tests/Unit/MigratorTest.php @@ -6,6 +6,8 @@ use Flow\PostgreSql\Migrations\Configuration; use Flow\PostgreSql\Migrations\Direction; +use Flow\PostgreSql\Migrations\Exception\MigrationException; +use Flow\PostgreSql\Migrations\MigrationMode; use Flow\PostgreSql\Migrations\MigrationState; use Flow\PostgreSql\Migrations\Migrator; use Flow\PostgreSql\Migrations\Repository\AvailableMigration; @@ -127,6 +129,218 @@ public function test_migrate_executes_pending_migrations(): void } } + public function test_migrate_executes_pending_migration_older_than_latest_executed(): void + { + $store = new FakeMigrationStore(); + $store->complete(Version::fromString('20260402120000'), 100); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'older', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260402120000'), 'newer', new SpyMigration(), null), + ), + $store, + new SpyMigrationExecutor(), + $client, + new Configuration($client, new FakeCatalogProvider(new Catalog([])), '/tmp', 'App\\Migrations'), + ); + + $results = $migrator->migrate(); + + static::assertCount(1, $results); + static::assertSame(Direction::UP, $results[0]->direction); + static::assertTrue($results[0]->version->equals(Version::fromString('20260401120000'))); + static::assertCount(0, $migrator->status()->pending()); + } + + public function test_migrate_executes_pending_migrations_around_latest_executed_in_version_order(): void + { + $store = new FakeMigrationStore(); + $store->complete(Version::fromString('20260402120000'), 100); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'older', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260402120000'), 'executed', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260403120000'), 'newer', new SpyMigration(), null), + ), + $store, + new SpyMigrationExecutor(), + $client, + new Configuration($client, new FakeCatalogProvider(new Catalog([])), '/tmp', 'App\\Migrations'), + ); + + $results = $migrator->migrate(); + + static::assertCount(2, $results); + static::assertTrue($results[0]->version->equals(Version::fromString('20260401120000'))); + static::assertTrue($results[1]->version->equals(Version::fromString('20260403120000'))); + static::assertCount(0, $migrator->status()->pending()); + } + + public function test_migrate_to_latest_executed_version_executes_older_pending_migration_only(): void + { + $store = new FakeMigrationStore(); + $store->complete(Version::fromString('20260402120000'), 100); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'older', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260402120000'), 'executed', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260403120000'), 'newer', new SpyMigration(), null), + ), + $store, + new SpyMigrationExecutor(), + $client, + new Configuration($client, new FakeCatalogProvider(new Catalog([])), '/tmp', 'App\\Migrations'), + ); + + $results = $migrator->migrate(Version::fromString('20260402120000')); + + static::assertCount(1, $results); + static::assertSame(Direction::UP, $results[0]->direction); + static::assertTrue($results[0]->version->equals(Version::fromString('20260401120000'))); + static::assertFalse($store->executedMigrations()->has(Version::fromString('20260403120000'))); + } + + public function test_migrate_in_strict_order_executes_all_migrations_when_nothing_is_executed(): void + { + $store = new FakeMigrationStore(); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'first', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260402120000'), 'second', new SpyMigration(), null), + ), + $store, + new SpyMigrationExecutor(), + $client, + new Configuration( + $client, + new FakeCatalogProvider(new Catalog([])), + '/tmp', + 'App\\Migrations', + mode: MigrationMode::STRICT_ORDER, + ), + ); + + static::assertCount(2, $migrator->migrate()); + static::assertCount(2, $store->executedMigrations()); + } + + public function test_migrate_in_strict_order_fails_on_pending_migrations_older_than_latest_executed(): void + { + $store = new FakeMigrationStore(); + $store->complete(Version::fromString('20260403120000'), 100); + $executor = new SpyMigrationExecutor(); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'oldest', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260402120000'), 'older', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260403120000'), 'executed', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260404120000'), 'newer', new SpyMigration(), null), + ), + $store, + $executor, + $client, + new Configuration( + $client, + new FakeCatalogProvider(new Catalog([])), + '/tmp', + 'App\\Migrations', + mode: MigrationMode::STRICT_ORDER, + ), + ); + + try { + $migrator->migrate(); + static::fail('Expected MigrationException'); + } catch (MigrationException $exception) { + static::assertStringContainsString( + '"20260401120000", "20260402120000" are older than the latest executed migration "20260403120000"', + $exception->getMessage(), + ); + } + + static::assertSame([], $executor->executedPlans); + static::assertCount(1, $store->executedMigrations()); + } + + public function test_migrate_in_strict_order_executes_pending_migrations_newer_than_latest_executed(): void + { + $store = new FakeMigrationStore(); + $store->complete(Version::fromString('20260401120000'), 100); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'executed', new SpyMigration(), null), + new AvailableMigration(Version::fromString('20260402120000'), 'newer', new SpyMigration(), null), + ), + $store, + new SpyMigrationExecutor(), + $client, + new Configuration( + $client, + new FakeCatalogProvider(new Catalog([])), + '/tmp', + 'App\\Migrations', + mode: MigrationMode::STRICT_ORDER, + ), + ); + + static::assertCount(1, $migrator->migrate()); + static::assertCount(2, $store->executedMigrations()); + } + + public function test_migrate_in_strict_order_rolls_back_when_older_migration_is_pending(): void + { + $store = new FakeMigrationStore(); + $store->complete(Version::fromString('20260402120000'), 100); + $store->complete(Version::fromString('20260403120000'), 100); + $client = new SpyClient(); + + $migrator = new Migrator( + new FakeMigrationRepository( + new AvailableMigration(Version::fromString('20260401120000'), 'older', new SpyMigration(), null), + new AvailableMigration( + Version::fromString('20260402120000'), + 'target', + new SpyMigration(), + new SpyRollback(), + ), + new AvailableMigration( + Version::fromString('20260403120000'), + 'latest', + new SpyMigration(), + new SpyRollback(), + ), + ), + $store, + new SpyMigrationExecutor(), + $client, + new Configuration( + $client, + new FakeCatalogProvider(new Catalog([])), + '/tmp', + 'App\\Migrations', + mode: MigrationMode::STRICT_ORDER, + ), + ); + + $results = $migrator->migrate(Version::fromString('20260402120000')); + + static::assertCount(1, $results); + static::assertSame(Direction::DOWN, $results[0]->direction); + static::assertTrue($results[0]->version->equals(Version::fromString('20260403120000'))); + } + public function test_migrate_propagates_configuration_attributes_to_context(): void { $attribute = new stdClass();