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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ where applicable.
- Share advisory locks across all migration scopes in a database, configure the timeout, and verify connection/lock ownership before SQL and metadata writes.
- Continue other plugins only after typed operational failures; propagate PHP/programming errors immediately.

## 1.0.10 — 2026-11-16

- Detect a failed `dbDelta()` query that a later successful query would have masked, so the migration is no longer recorded as applied with missing columns or indexes.
- Restrict `wp migration version --delete` to local/development environments like `rollback` and `execute --down`, because it makes the next `migrate` run `up()` again.
- Pin the shared `sympress/workflows` CI workflows to v1.3.2.

## 1.0.9 — 2026-11-06

- Use the Symfony 8.1.11 security patches released on November 4.
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ wp migration migrate
wp migration migrate orders-plugin
wp migration migrate orders-plugin 1.0.0
wp migration run orders-plugin
# Rollbacks require WordPress local/development; staging/production are blocked.
# Rollbacks, execute --down and version --delete require WordPress local/development;
# staging/production are blocked.
wp migration rollback orders-plugin
wp migration rollback orders-plugin --migration=CreateOrdersTableMigration
wp migration execute orders-plugin CreateOrdersTableMigration --up
Expand Down
4 changes: 3 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ status check that could become stale. Concurrent forward work cannot turn this
call into a rollback. The library default remains `allowRollback: true` for
explicitly reviewed inverse migrations; direct library calls do not infer a
WordPress environment. Metadata-only `version --add/--delete` remains an
explicit reconciliation operation and does not execute migration SQL.
explicit reconciliation operation and does not execute migration SQL. Because
`--delete` makes the next `migrate` run `up()` again, it shares the CLI rollback
restriction to local/development environments.

## State model

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.9
* Version: 1.0.10
* Requires at least: 6.9
* Requires PHP: 8.5
* Author: Brian Schaeffner
Expand Down
2 changes: 1 addition & 1 deletion src/Cli/MigrationCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public function execute(array $args, array $assocArgs): void
* : Mark the version as migrated.
*
* --delete
* : Mark the version as rolled back.
* : Mark the version as rolled back. Local/development environments only.
*
* @param list<string> $args
* @param array<string, scalar|null> $assocArgs
Expand Down
4 changes: 4 additions & 0 deletions src/Cli/MigrationCommandExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ public function version(array $args, array $assocArgs): void
$pluginSlug = $this->context->requirePluginSlug($args, 'version');
$migrationClass = $this->context->requireMigrationClass($args, 'version');
$direction = $this->resolveVersionDirection($assocArgs);
if ($direction === 'down') {
// Unmarking re-runs a non-idempotent up() on the next migrate, like a rollback.
$this->context->requireRollbackEnvironment();
}
$manager = $this->context->managerOrFail($pluginSlug);

if (!$manager->markMigration($migrationClass, $direction)) {
Expand Down
34 changes: 27 additions & 7 deletions src/Infrastructure/WordPressSqlExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,10 @@ private function executeStatement(string $statement): bool
MigrationDatabaseGuard::assertDatabaseOwnership($this->database);
if ($this->shouldUseDbDelta($statement)) {
$this->loadWordPressUpgradeLibrary();
$this->resetLastError();

dbDelta($statement);
$succeeded = $this->runDbDelta($statement);
MigrationDatabaseGuard::assertDatabaseOwnership($this->database);

return $this->lastErrorIsEmpty();
return $succeeded;
}

// @phpstan-ignore sympress.preparedSql (Reviewed Migration::up/down raw SQL contract, including DDL; metadata uses prepared SQL.)
Expand Down Expand Up @@ -206,13 +204,35 @@ private function loadWordPressUpgradeLibrary(): void
require_once $absolutePath . 'wp-admin/includes/upgrade.php';
}

private function resetLastError(): void
/**
* dbDelta() runs several queries and each one resets last_error, so a failed ALTER
* would be masked by a later successful one. Check the error before every next query.
*/
private function runDbDelta(string $statement): bool
{
$this->database->last_error = '';
$failed = false;
$previous = '';
$inspect = function (string $query) use (&$failed, &$previous): string {
$failed = $failed || $this->previousQueryFailed($previous);
$previous = $query;

return $query;
};

add_filter('query', $inspect);
try {
dbDelta($statement);
} finally {
remove_filter('query', $inspect);
}

return !$failed && !$this->previousQueryFailed($previous);
}

private function lastErrorIsEmpty(): bool
private function previousQueryFailed(string $previous): bool
{
return $this->database->last_error === '';
// dbDelta() probes for missing tables with DESCRIBE on purpose; that error is expected.
return $this->database->last_error !== '' && preg_match('/^\s*DESCRIBE\b/i', $previous) !== 1;
}
}
23 changes: 23 additions & 0 deletions tests/Database/WordPressDatabaseProbeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,29 @@ public function test_it_executes_migration_sql_against_wordpress_and_mariadb():
));
}

public function testDbDeltaReportsAFailedAlterFollowedByASuccessfulOne(): void
{
$executor = new WordPressSqlExecutor($this->database);
self::assertTrue($executor->execute("CREATE TABLE {$this->table} (id bigint NOT NULL, dup int NOT NULL, other int NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB"));
self::assertTrue($executor->execute("INSERT INTO {$this->table} (id, dup, other) VALUES (1, 7, 1), (2, 7, 2)"));
$this->database->suppress_errors(true);
try {
// The UNIQUE KEY fails on duplicate data; the later KEY succeeds and resets last_error.
self::assertFalse($executor->execute("CREATE TABLE {$this->table} (
id bigint NOT NULL,
dup int NOT NULL,
other int NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY dup (dup),
KEY other (other)
) ENGINE=InnoDB"));
} finally {
$this->database->suppress_errors(false);
}
self::assertSame('other', $this->database->get_var($this->database->prepare('SHOW INDEX FROM %i WHERE Key_name = %s', $this->table, 'other'), 2));
self::assertNull($this->database->get_var($this->database->prepare('SHOW INDEX FROM %i WHERE Key_name = %s', $this->table, 'dup'), 2));
}

public function test_it_persists_current_state_and_append_only_history(): void
{
$tracker = new MigrationTracker($this->database);
Expand Down
48 changes: 46 additions & 2 deletions tests/Support/TestEnvironment.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ final class WordPressState
/** @var list<string> */
public static array $dbDelta = [];

/** @var array<string, list<string>> Queries the dbDelta() stub runs for a statement, e.g. generated ALTERs. */
public static array $dbDeltaQueries = [];

/**
* @var array{
* commands: list<array{name: string, class: string}>,
Expand All @@ -32,6 +35,7 @@ public static function reset(): void
{
self::$hooks = [];
self::$dbDelta = [];
self::$dbDeltaQueries = [];
self::$cliCalls = [
'commands' => [],
'log' => [],
Expand Down Expand Up @@ -402,7 +406,7 @@ public function delete(string $table, array $where, array $whereFormats = []): i

public function query(string $query): int|false
{
$statement = $this->normalizeStatement($query);
$statement = $this->normalizeStatement((string) apply_filters('query', $query));
$this->executedStatements[] = $statement;

if (in_array($statement, $this->failedStatements, true)) {
Expand Down Expand Up @@ -590,6 +594,44 @@ function do_action(string $hook, mixed ...$args): void
}
}

if (!function_exists('add_filter')) {
function add_filter(string $hook, callable $callback, int $priority = 10, int $acceptedArgs = 1): bool
{
add_action($hook, $callback, $priority, $acceptedArgs);

return true;
}
}

if (!function_exists('remove_filter')) {
function remove_filter(string $hook, callable $callback, int $priority = 10): bool
{
$callbacks = WordPressState::$hooks[$hook][$priority] ?? [];
WordPressState::$hooks[$hook][$priority] = array_values(array_filter(
$callbacks,
static fn (array $registered): bool => $registered['callback'] !== $callback,
));

return count($callbacks) !== count(WordPressState::$hooks[$hook][$priority]);
}
}

if (!function_exists('apply_filters')) {
function apply_filters(string $hook, mixed $value, mixed ...$args): mixed
{
$callbacksByPriority = WordPressState::$hooks[$hook] ?? [];
ksort($callbacksByPriority);

foreach ($callbacksByPriority as $callbacks) {
foreach ($callbacks as $callback) {
$value = ($callback['callback'])(...array_slice([$value, ...$args], 0, $callback['accepted_args']));
}
}

return $value;
}
}

if (!function_exists('current_time')) {
function current_time(string $type = 'mysql', bool $gmt = false): string
{
Expand All @@ -605,7 +647,9 @@ function dbDelta(string $sql): array
$database = $GLOBALS['wpdb'] ?? null;

if ($database instanceof wpdb) {
$database->query($sql);
foreach (WordPressState::$dbDeltaQueries[$sql] ?? [$sql] as $query) {
$database->query($query);
}
}

return [$sql];
Expand Down
4 changes: 4 additions & 0 deletions tests/Unit/Cli/MigrationRollbackPolicyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public function testRestrictedEnvironmentsRejectEveryCliRollbackBeforeDownOrStat
fn () => $command->migrate(['my-plugin', '1.0.0']),
fn () => $command->migrate(['my-plugin', CreateCustomersTableMigration::class]),
fn () => $command->run(['my-plugin', 'CreateCustomersTableMigration']),
fn () => $command->version(['my-plugin', 'AddCustomersEmailIndexMigration'], ['delete' => true]),
] as $operation) {
$database->executedStatements = [];
try {
Expand Down Expand Up @@ -90,6 +91,9 @@ public function testLocalCliRollbacksRemainAvailable(string $environment): void
$command->execute(['my-plugin', 'CreateCustomersTableMigration'], ['down' => true]);
self::assertSame([], $manager->getMigratedVersions());
$command->execute(['my-plugin', 'CreateCustomersTableMigration'], ['up' => true]);
$command->version(['my-plugin', 'CreateCustomersTableMigration'], ['delete' => true]);
self::assertSame([], $manager->getMigratedVersions());
$command->version(['my-plugin', 'CreateCustomersTableMigration'], ['add' => true]);
$command->rollback(['my-plugin'], ['migration' => 'CreateCustomersTableMigration']);
self::assertSame([], $manager->getMigratedVersions());
$command->migrate(['my-plugin']);
Expand Down
24 changes: 24 additions & 0 deletions tests/Unit/Migration/WordPressSqlExecutorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,30 @@ public function test_it_routes_create_table_through_db_delta_and_other_sql_throu
], $this->database->executedStatements);
}

public function test_it_reports_a_failed_db_delta_alter_masked_by_a_later_success(): void
{
$create = 'CREATE TABLE wp_orders (id bigint unsigned NOT NULL, sku varchar(64) NOT NULL, UNIQUE KEY sku (sku))';
$failed = 'ALTER TABLE wp_orders ADD UNIQUE KEY `sku` (`sku`)';
WordPressState::$dbDeltaQueries[$create] = [
'DESCRIBE wp_orders;',
$failed,
'ALTER TABLE wp_orders CHANGE COLUMN `sku` sku varchar(64) NOT NULL',
];
$this->database->failedStatements[] = $failed;

self::assertFalse($this->executor->execute($create));
self::assertSame([], WordPressState::$hooks['query'][10] ?? []);
}

public function test_it_ignores_the_describe_probe_dbdelta_runs_for_a_new_table(): void
{
$create = 'CREATE TABLE wp_orders (id bigint unsigned NOT NULL)';
WordPressState::$dbDeltaQueries[$create] = ['DESCRIBE wp_orders;', $create];
$this->database->failedStatements[] = 'DESCRIBE wp_orders;';

self::assertTrue($this->executor->execute($create));
}

public function test_it_stops_after_the_first_database_error(): void
{
$failed = 'ALTER TABLE wp_orders ADD INDEX idx_id (id);';
Expand Down
Loading