Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions documentation/components/bridges/symfony-postgresql-bundle.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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.',
Expand Down Expand Up @@ -528,7 +534,7 @@ public function configure(DefinitionConfigurator $definition): void
}

/**
* @param array{connections: array<string, array{dsn: string, dbname: ?string, host: ?string, port: ?int, user: ?string, password: ?string, dbname_suffix: string, options: array<string, bool|float|int|string|null>, session_settings: array<string, bool|float|int|string|null>, test_transaction_rollback: bool, lazy: bool, context?: array<string, mixed>, 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<string, array{connection: ?string, table_name: string, schema: string, id_col: string, data_col: string, lifetime_col: string, time_col: string, namespace: string, default_lifetime: int, marshaller_service_id: ?string, share_connection: bool}>}, 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<string, mixed>, exclude?: list<array{schema: ?string, table: ?string, exact: ?string, starts_with: ?string, ends_with: ?string, pattern: ?string, policy_id: ?string, type: ?string, for_schema: ?string}>}, catalog_providers: list<array{catalog_provider_id: ?string, catalog: ?array<string, mixed>}>, 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<string, array{dsn: string, dbname: ?string, host: ?string, port: ?int, user: ?string, password: ?string, dbname_suffix: string, options: array<string, bool|float|int|string|null>, session_settings: array<string, bool|float|int|string|null>, test_transaction_rollback: bool, lazy: bool, context?: array<string, mixed>, 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<string, array{connection: ?string, table_name: string, schema: string, id_col: string, data_col: string, lifetime_col: string, time_col: string, namespace: string, default_lifetime: int, marshaller_service_id: ?string, share_connection: bool}>}, 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<string, mixed>, exclude?: list<array{schema: ?string, table: ?string, exact: ?string, starts_with: ?string, ends_with: ?string, pattern: ?string, policy_id: ?string, type: ?string, for_schema: ?string}>}, catalog_providers: list<array{catalog_provider_id: ?string, catalog: ?array<string, mixed>}>, 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
Expand Down Expand Up @@ -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<string, mixed>, exclude?: list<array{schema: ?string, table: ?string, exact: ?string, starts_with: ?string, ends_with: ?string, pattern: ?string, policy_id: ?string, type: ?string, for_schema: ?string}>} $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<string, mixed>, exclude?: list<array{schema: ?string, table: ?string, exact: ?string, starts_with: ?string, ends_with: ?string, pattern: ?string, policy_id: ?string, type: ?string, for_schema: ?string}>} $mc
*/
private function registerMigrations(string $connection, array $mc, ContainerBuilder $container): void
{
Expand All @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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,
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@
<tr><th>Directory</th><td>{{ collector.configuration.directory }}</td></tr>
<tr><th>Namespace</th><td>{{ collector.configuration.namespace }}</td></tr>
<tr><th>All or nothing</th><td>{{ collector.configuration.allOrNothing ? 'true' : 'false' }}</td></tr>
<tr><th>Mode</th><td>{{ collector.configuration.mode }}</td></tr>
</tbody>
</table>
{% endif %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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);
});
Expand All @@ -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'],
Expand Down Expand Up @@ -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 = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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([
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,6 @@ public function __construct(
public ?ExclusionPolicy $exclusionPolicy = null,
public bool $dropIfExists = false,
public array $attributes = [],
public MigrationMode $mode = MigrationMode::ALL_PENDING,
) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
use RuntimeException;
use Throwable;

use function array_map;
use function implode;
use function sprintf;

class MigrationException extends RuntimeException
Expand Down Expand Up @@ -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));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace Flow\PostgreSql\Migrations;

enum MigrationMode: string
{
case ALL_PENDING = 'all_pending';
case STRICT_ORDER = 'strict_order';
}
Loading