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
18 changes: 16 additions & 2 deletions .github/workflows/database.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,31 @@ permissions:

jobs:
database:
name: Database (${{ matrix.engine }})
strategy:
fail-fast: false
matrix:
include:
- engine: MariaDB 11.8
image: mariadb:11.8@sha256:79d59758afc91b89b120b0a8904d637f5a3b3e1c4900f29b740d6d46c72fef68
health: healthcheck.sh --connect --innodb_initialized
- engine: MySQL 8.4
image: mysql:8.4@sha256:80f4933e3835f9dc4d35a28ec500d7986cb4414e6c6821c5461239cb7beb8995
health: mysqladmin ping -h 127.0.0.1 --silent
runs-on: ubuntu-24.04
timeout-minutes: 15
services:
database:
image: mariadb:11.8@sha256:79d59758afc91b89b120b0a8904d637f5a3b3e1c4900f29b740d6d46c72fef68
image: ${{ matrix.image }}
env:
MARIADB_ROOT_PASSWORD: sympress-database-test-only
MARIADB_DATABASE: sympress_review_migration
MYSQL_ROOT_PASSWORD: sympress-database-test-only
MYSQL_DATABASE: sympress_review_migration
MYSQL_ROOT_HOST: '%'
ports: ['3306:3306']
options: >-
--health-cmd="healthcheck.sh --connect --innodb_initialized"
--health-cmd="${{ matrix.health }}"
--health-interval=10s --health-timeout=5s --health-retries=10
env:
CI: 'true'
Expand Down
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html)
where applicable.

## 1.0.7 — 2026-10-02

- Continue other plugins after a failed migration, then return a failing aggregate CLI result.
- Add administrator-only `wp migration adopt` for an explicitly confirmed exact legacy identity/version; retain the recorded version and append-only history without migration SQL.
- Run real database contracts against pinned MySQL 8.4 and MariaDB 11.8 services.

## 1.0.6 — 2026-10-02

- Document the two narrowly scoped WordPress Plugin Check exceptions for the private temporary CSV-formatting stream; WordPress file-operation checks remain enabled elsewhere.
Expand Down
23 changes: 23 additions & 0 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,29 @@ incomplete tests and runs on pull requests, main and the weekly schedule.

## Identity, deployment and table scoping

`wp migration migrate` with no plugin catches failures per plugin, continues the
remaining registrations and returns a nonzero aggregate result. Each individual
plugin still stops at its first failed migration; no failed migration is marked
applied. Failure diagnostics contain the plugin slug without SQL/credential data.

An administrator can adopt one reviewed anonymous legacy record explicitly:

```sh
wp --user=<administrator> migration adopt <plugin> orm-schema:<manager> \
--legacy-base64=<base64-of-exact-stored-identity> \
--expected-version=<exact-recorded-version> --yes
```

Base64 transports PHP's NUL-separated identity unchanged. The target must be an
exact registered stable key. Adoption validates the recorded version and any
existing target under the operation lock, preserves that version/date, retires
only the specified legacy current-state entry and appends `adopt` history.
Historical entries remain unchanged. It runs no migration `up()` SQL and does not
claim that a newer intended schema is applied; changed schema remains pending.
Unknown/conflicting state fails. `manage_options` and explicit `--yes` are required
by the CLI before metadata is touched. The lower-level manager method is available
to trusted deployment tooling after equivalent operator authorization.

Named migration classes keep their class identity unless they declare a stable
`getMigrationKey(): string`. Anonymous migrations **require** that method;
basename/line and release-directory heuristics cannot establish unique identity.
Expand Down
2 changes: 1 addition & 1 deletion migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/**
* Plugin Name: Database Migration System
* Description: Standalone MU plugin for versioned WordPress database migrations.
* Version: 1.0.6
* Version: 1.0.7
* Requires at least: 6.9
* Requires PHP: 8.5
* Author: Brian Schaeffner
Expand Down
27 changes: 27 additions & 0 deletions src/Application/MigrationLifecycle.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,33 @@ public function markMigrated(PluginSlug $pluginSlug, MigrationContract $migratio
return $this->runOperation($pluginSlug, [], fn (): bool => $this->markMigratedUnlocked($pluginSlug, $migration));
}

public function adoptLegacyMigration(PluginSlug $pluginSlug, MigrationContract $migration, string $legacyKey, string $expectedVersion): bool
{
$key = MigrationKey::forMigration($migration);
if (!str_contains($legacyKey, '@anonymous') || $legacyKey === $key || $expectedVersion === '') {
throw new \InvalidArgumentException(
'Adoption requires an exact anonymous legacy identity and its recorded version.',
);
}
return $this->runOperation($pluginSlug, [], function () use ($pluginSlug, $key, $legacyKey, $expectedVersion): bool {
$legacy = $this->store->findRecord($pluginSlug->value, $legacyKey);
$current = $this->store->findRecord($pluginSlug->value, $key);
if (
$legacy === null || $legacy->version !== $expectedVersion
|| ($current !== null && $current->version !== $expectedVersion)
) {
throw new \RuntimeException(
'Legacy state does not match the reviewed version or conflicts with the stable identity.',
);
}
$record = new MigrationRecord($pluginSlug->value, $key, $legacy->version, $legacy->migratedAt);
if (!$this->store->saveRecord($record) || !$this->store->deleteRecord($pluginSlug->value, $legacyKey)) {
return false;
}
return $this->store->appendHistory($this->createExecution($record, 'adopt', $this->currentTimestamp()));
});
}

private function markMigratedUnlocked(PluginSlug $pluginSlug, MigrationContract $migration): bool
{
$existingRecord = $this->recordForMigration($pluginSlug, $migration);
Expand Down
44 changes: 43 additions & 1 deletion src/Cli/MigrationCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
private MigrationCommandReporter $reporter;

public function __construct(
?MigrationRegistry $registry = null,
private ?MigrationRegistry $registry = null,
?SymfonyConsoleRunner $consoleRunner = null,
) {

Expand Down Expand Up @@ -127,6 +127,48 @@ public function version(array $args, array $assocArgs): void
$this->executor->version($args, $assocArgs);
}

/**
* Adopt one reviewed legacy identity without running migration SQL.
*
* ## OPTIONS
*
* <plugin>
* : Registered plugin slug.
* <migration>
* : Exact registered stable migration key.
* --legacy-base64=<identity>
* : Base64 encoded exact old identity, including binary bytes.
* --expected-version=<version>
* : Exact version already recorded for the old identity.
* --yes
* : Confirm the reviewed metadata adoption.
*
* @param list<string> $args
* @param array<string, scalar|null> $assocArgs
*/
public function adopt(array $args, array $assocArgs): void
{
if (!function_exists('current_user_can') || !current_user_can('manage_options')) {
\WP_CLI::error('Adoption requires a loaded WordPress administrator; select one with --user.');
}
if (($assocArgs['yes'] ?? false) !== true) {
\WP_CLI::error('Adoption requires explicit --yes confirmation after reviewing the legacy state.');
}
$encoded = $assocArgs['legacy-base64'] ?? null;
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- Exact binary identity transport, no executable payload.
$legacy = is_string($encoded) ? base64_decode($encoded, true) : false;
$version = $assocArgs['expected-version'] ?? null;
if ($legacy === false || $legacy === '' || !is_string($version) || $version === '') {
\WP_CLI::error('Provide the exact --legacy-base64 identity and --expected-version.');
}
$context = new MigrationCommandContext($this->registry);
$manager = $context->managerOrFail($context->requirePluginSlug($args, 'adopt'));
if (!$manager->adoptLegacyMigration($context->requireMigrationClass($args, 'adopt'), $legacy, $version)) {
\WP_CLI::error('Legacy adoption failed; reconcile metadata before retrying.');
}
\WP_CLI::success('Legacy identity adopted; recorded version and existing history retained.');
}

/**
* Show migration status.
*
Expand Down
32 changes: 21 additions & 11 deletions src/Cli/MigrationCommandExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,21 +171,31 @@ private function migrateAllPlugins(): void
}

$processed = 0;
$failed = 0;

foreach ($managers as $slug => $manager) {
if (!$manager->hasPendingMigrations()) {
continue;
}

$processed++;
WP_CLI::log(sprintf('Running pending migrations for "%s"...', $slug));

if ($manager->runMigrations()) {
WP_CLI::success(sprintf('Completed migrations for "%s".', $slug));
continue;
try {
if (!$manager->hasPendingMigrations()) {
continue;
}
$processed++;
WP_CLI::log(sprintf('Running pending migrations for "%s"...', $slug));
if ($manager->runMigrations()) {
WP_CLI::success(sprintf('Completed migrations for "%s".', $slug));
continue;
}
} catch (\Throwable) {
// Keep SQL, credentials and exception messages out of the CLI diagnostic.
}
$failed++;
WP_CLI::warning(sprintf('Migration failed for "%s"; reconcile its state before retrying.', $slug));
}

WP_CLI::error(sprintf('Migration failed for "%s".', $slug));
if ($failed > 0) {
WP_CLI::error(sprintf(
'Migrations failed for %d plugin(s); other registered plugins were processed.',
$failed,
));
}

if ($processed === 0) {
Expand Down
17 changes: 17 additions & 0 deletions src/Domain/MigrationManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,23 @@ public function markMigration(string $migrationClass, string $direction): bool
return false;
}

public function adoptLegacyMigration(string $migrationKey, string $legacyKey, string $expectedVersion): bool
{
$migration = $this->getMigration($migrationKey);
if ($migration === null || MigrationKey::forMigration($migration) !== $migrationKey) {
throw new \InvalidArgumentException('Adoption requires the exact registered stable migration key.');
}
foreach ($this->migrations->all() as $other) {
if ($other !== $migration && in_array($legacyKey, MigrationKey::identities($other), true)) {
throw new \InvalidArgumentException('Legacy identity already belongs to another registered migration.');
}
}
if (!$this->lifecycle->ensureStorageIsReady()) {
return false;
}
return $this->lifecycle->adoptLegacyMigration($this->pluginSlug, $migration, $legacyKey, $expectedVersion);
}

public function needsUpdate(string $migrationClass): bool
{
$migration = $this->getMigration($migrationClass);
Expand Down
9 changes: 9 additions & 0 deletions tests/Support/TestEnvironment.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ final class WordPressState

public static string $currentTime = '2026-03-27 12:00:00';
public static string $environmentType = 'development';
public static bool $administrator = false;

public static function reset(): void
{
Expand All @@ -41,6 +42,7 @@ public static function reset(): void
];
self::$currentTime = '2026-03-27 12:00:00';
self::$environmentType = 'development';
self::$administrator = false;
}
}
}
Expand All @@ -49,6 +51,13 @@ public static function reset(): void

use SymPress\WordPress\Migration\Tests\Support\WordPressState;

if (!function_exists('current_user_can')) {
function current_user_can(string $capability): bool
{
return $capability === 'manage_options' && WordPressState::$administrator;
}
}

if (!function_exists('wp_get_environment_type')) {
function wp_get_environment_type(): string
{
Expand Down
64 changes: 64 additions & 0 deletions tests/Unit/Cli/MigrationCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,70 @@ public function test_run_executes_pending_migrations(): void
);
}

public function testAllPluginsContinuesAfterThrownAndReturnedFailuresAndReportsFailure(): void
{
$registry = MigrationRegistry::getInstance();
$registry->clear();
foreach (['throws', 'returns-false'] as $slug) {
$failed = new class ($slug, $this->database) extends MigrationManager {
public function __construct(private string $mode, \wpdb $database)
{
parent::__construct(\SymPress\WordPress\Migration\Value\PluginSlug::fromString($mode), new \SymPress\WordPress\Migration\Application\MigrationLifecycle(new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($database), new \SymPress\WordPress\Migration\Infrastructure\WordPressSqlExecutor($database)));
}
public function hasPendingMigrations(): bool { return true; }
public function runMigrations(): bool
{
if ($this->mode === 'throws') { throw new \RuntimeException('credentialSentinel'); }
return false;
}
};
$registry->set($slug, $failed);
}
$registry->set('my-plugin', $this->manager);
try {
$this->command->migrate([]);
self::fail('Aggregate failure must return a failing CLI result.');
} catch (\RuntimeException $exception) {
self::assertStringContainsString('2 plugin(s)', $exception->getMessage());
}
self::assertFalse($this->manager->hasPendingMigrations());
self::assertCount(2, WordPressState::$cliCalls['warning']);
self::assertStringNotContainsString('credentialSentinel', json_encode(WordPressState::$cliCalls, JSON_THROW_ON_ERROR));
}

public function testAdoptionRequiresAdministratorAndExplicitConfirmationBeforeStorageMutation(): void
{
foreach ([false, true] as $administrator) {
WordPressState::$administrator = $administrator;
try {
$this->command->adopt(['my-plugin', 'stable'], []);
self::fail('Unconfirmed or unprivileged adoption accepted.');
} catch (\RuntimeException) {
self::assertSame([], $this->manager->getMigratedVersions());
}
}
self::assertFalse($this->database->hasTable('wp_migrations'));
}

public function testAdministratorCanAdoptTheExactBinaryLegacyIdentityWithoutExecutingSql(): void
{
$legacy = "Migration@anonymous\0/old/release.php:40";
$tracker = new \SymPress\WordPress\Migration\Infrastructure\MigrationTracker($this->database);
self::assertTrue($tracker->record('my-plugin', $legacy, '0.9.0'));
WordPressState::$administrator = true;
$this->command->adopt(['my-plugin', CreateCustomersTableMigration::class], [
'legacy-base64' => base64_encode($legacy),
'expected-version' => '0.9.0',
'yes' => true,
]);
self::assertNull($tracker->getVersion('my-plugin', $legacy));
self::assertSame('0.9.0', $tracker->getVersion('my-plugin', CreateCustomersTableMigration::class));
self::assertFalse($this->database->hasTable('wp_customers'));
self::assertTrue($this->manager->hasPendingMigrations());
self::assertSame('adopt', $this->manager->getMigrationHistory()[0]['direction']);
self::assertCount(1, WordPressState::$cliCalls['success']);
}

public function test_migrate_can_target_a_specific_version(): void
{
$this->command->migrate(['my-plugin', '1.0.0']);
Expand Down
Loading
Loading