feat(console): add db:migrate CLI for idempotent core schema updates
Existing systems used to have no automatic mechanism for the db/updates/*.sql idempotent updates after `git pull` — devs had to remember which files were already applied and run new ones manually with `mariadb < ...`. Mirror module:migrate to fix this: - New `bin/console db:migrate` walks db/updates/*.sql in alphabetical order, skipping anything already recorded in the new core_migrations tracking table. Each file runs in its own transaction; failure rolls back so the file is retried on the next run. - New `db:migrate --status` lists applied vs. pending files without running anything. Useful for ops debugging "schema seems stale" symptoms. - module:sync now runs db:migrate as its first step, so the standard post-pull command stays a single invocation. README's 3-step setup is unchanged — module:sync now also covers core schema updates. CoreMigrationRepository owns its own mysqli connection (using the same DB credentials as MintyPHP\DB) and runs raw `$mysqli->query()` instead of going through DB::query's prepared statement path — MariaDB rejects some DDL (e.g. ALTER TABLE … ADD CONSTRAINT CHECK) in the prepared protocol, which the existing 18 db/updates files trip on. ModuleMigrationRepository is left untouched (no module migration uses such DDL today and changing the vendor pattern is out of scope). End-to-end verified: against an existing DB the first run applies all 19 idempotent files as no-ops and records them, second run reports "all updates already applied". Against a freshly init'd DB the same thing happens — no double work, no surprises. All encrypted seed secrets keep decrypting because APP_CRYPTO_KEY is unchanged. Tests: tests/Console/CoreCommandsTest covers success/failure/status output shapes against a FakeModuleRunner (mirror of the existing ModuleCommandsTest pattern). 5 stale baseline entries in phpstan-baseline removed (covered by the new @api annotation on the test fixture class). Docs: CLAUDE.md and docs/reference-cli-commands.md document the new command + --status flag; docs/howto-fehlerbehebung.md gains a "schema seems stale after git pull" section pointing at db:migrate --status. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
90
core/Console/Commands/Database/MigrateCommand.php
Normal file
90
core/Console/Commands/Database/MigrateCommand.php
Normal file
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
namespace MintyPHP\Console\Commands\Database;
|
||||
|
||||
use MintyPHP\Console\Commands\Module\AbstractModuleCommand;
|
||||
use MintyPHP\Console\Runner\Module\ModuleRunnerInterface;
|
||||
|
||||
/**
|
||||
* Apply pending core SQL migrations from db/updates/.
|
||||
*
|
||||
* Mirror of `module:migrate` for core schema changes. Each `db/updates/*.sql`
|
||||
* file MUST be idempotent; applied filenames are tracked in `core_migrations`.
|
||||
*
|
||||
* `--status` prints applied/pending lists without running anything.
|
||||
*/
|
||||
final class MigrateCommand extends AbstractModuleCommand
|
||||
{
|
||||
public function __construct(?ModuleRunnerInterface $moduleRunner = null)
|
||||
{
|
||||
parent::__construct($moduleRunner);
|
||||
}
|
||||
|
||||
public function name(): string
|
||||
{
|
||||
return 'db:migrate';
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return 'Apply pending core SQL migrations from db/updates/';
|
||||
}
|
||||
|
||||
public function usage(): string
|
||||
{
|
||||
return <<<'USAGE'
|
||||
Usage: php bin/console db:migrate [--status]
|
||||
|
||||
Options:
|
||||
--status Print applied / pending migration filenames without running anything
|
||||
|
||||
Each file under db/updates/*.sql is applied at most once and tracked in
|
||||
the core_migrations table. Files MUST be idempotent (e.g. CREATE TABLE
|
||||
IF NOT EXISTS, INSERT … ON DUPLICATE KEY UPDATE) so first-run on an
|
||||
existing schema is a no-op.
|
||||
|
||||
`bin/console module:sync` runs db:migrate as its first step.
|
||||
USAGE;
|
||||
}
|
||||
|
||||
public function execute(array $args, array $options): int
|
||||
{
|
||||
if (!empty($options['status'])) {
|
||||
$status = $this->moduleRunner()->dbMigrateStatus();
|
||||
|
||||
$appliedCount = count($status['applied']);
|
||||
$pendingCount = count($status['pending']);
|
||||
|
||||
echo sprintf("db-migrate-status: %d applied, %d pending\n\n", $appliedCount, $pendingCount);
|
||||
|
||||
echo "applied:\n";
|
||||
if ($appliedCount === 0) {
|
||||
echo " (none)\n";
|
||||
} else {
|
||||
foreach ($status['applied'] as $filename) {
|
||||
echo ' ' . $filename . PHP_EOL;
|
||||
}
|
||||
}
|
||||
|
||||
echo "\npending:\n";
|
||||
if ($pendingCount === 0) {
|
||||
echo " (none)\n";
|
||||
} else {
|
||||
foreach ($status['pending'] as $filename) {
|
||||
echo ' ' . $filename . PHP_EOL;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
$result = $this->moduleRunner()->dbMigrate();
|
||||
if ($result['exit_code'] === 0) {
|
||||
echo $result['message'] . PHP_EOL;
|
||||
} else {
|
||||
fwrite(STDERR, $result['message'] . PHP_EOL);
|
||||
}
|
||||
|
||||
return (int) $result['exit_code'];
|
||||
}
|
||||
}
|
||||
@@ -11,11 +11,73 @@ use MintyPHP\App\Module\ModulePermissionSynchronizer;
|
||||
use MintyPHP\App\Module\ModuleRegistry;
|
||||
use MintyPHP\App\Module\ModuleRuntimeAssetPublisher;
|
||||
use MintyPHP\App\Module\ModuleRuntimePageBuilder;
|
||||
use MintyPHP\Console\Support\CliAppBootstrap;
|
||||
use MintyPHP\Console\Support\ModuleCliRuntime;
|
||||
use MintyPHP\Service\Database\CoreMigrationService;
|
||||
use MintyPHP\Service\Module\ModuleMigrationService;
|
||||
|
||||
final class ModuleRunner implements ModuleRunnerInterface
|
||||
{
|
||||
public function dbMigrate(): array
|
||||
{
|
||||
$summary = ['applied' => 0, 'skipped_empty' => 0, 'total_files' => 0, 'applied_filenames' => []];
|
||||
$message = 'db-migrate: all updates already applied.';
|
||||
$step = ModuleCliRuntime::runStep('db-migrate', function () use (&$summary, &$message): int {
|
||||
$lockResult = ModuleCliRuntime::withFileLock(
|
||||
ModuleCliRuntime::projectRoot() . '/storage/runtime/.db-migrate.lock',
|
||||
'db-migrate: another migration run is in progress, skipping.',
|
||||
function () use (&$summary, &$message): int {
|
||||
/** @var CoreMigrationService $service */
|
||||
$service = app(CoreMigrationService::class);
|
||||
$result = $service->applyPendingMigrations();
|
||||
$summary = $result;
|
||||
|
||||
if ($result['total_files'] === 0) {
|
||||
$message = 'db-migrate: no update files in db/updates/, nothing to do.';
|
||||
} elseif ($result['applied'] === 0) {
|
||||
$message = 'db-migrate: all updates already applied.';
|
||||
} else {
|
||||
$message = sprintf('db-migrate: applied %d migration(s).', $result['applied']);
|
||||
}
|
||||
|
||||
if ($result['skipped_empty'] > 0) {
|
||||
$message .= sprintf(' (%d empty file(s) skipped)', $result['skipped_empty']);
|
||||
}
|
||||
|
||||
return $result['ok'] ? 0 : 1;
|
||||
}
|
||||
);
|
||||
|
||||
if ($lockResult['busy']) {
|
||||
$message = (string) $lockResult['message'];
|
||||
}
|
||||
|
||||
return $lockResult['exit_code'];
|
||||
});
|
||||
|
||||
return [
|
||||
'command' => 'db:migrate',
|
||||
'status' => $step['status'],
|
||||
'exit_code' => $step['exit_code'],
|
||||
'vendor_warnings_ignored' => $step['vendor_warnings_ignored'],
|
||||
'message' => $step['error'] ?? $message,
|
||||
];
|
||||
}
|
||||
|
||||
public function dbMigrateStatus(): array
|
||||
{
|
||||
CliAppBootstrap::bootstrap('cli', 'bin/console db:migrate --status');
|
||||
/** @var CoreMigrationService $service */
|
||||
$service = app(CoreMigrationService::class);
|
||||
$status = $service->status();
|
||||
|
||||
return [
|
||||
'command' => 'db:migrate --status',
|
||||
'applied' => $status['applied'],
|
||||
'pending' => $status['pending'],
|
||||
];
|
||||
}
|
||||
|
||||
public function migrate(): array
|
||||
{
|
||||
$summary = ['applied' => 0, 'modules_enabled' => 0, 'skipped_empty' => 0];
|
||||
@@ -287,6 +349,7 @@ final class ModuleRunner implements ModuleRunnerInterface
|
||||
{
|
||||
$startedAt = microtime(true);
|
||||
$steps = [
|
||||
'db-migrate' => ['status' => 'pending', 'exit_code' => 0, 'vendor_warnings_ignored' => 0],
|
||||
'migrate' => ['status' => 'pending', 'exit_code' => 0, 'vendor_warnings_ignored' => 0],
|
||||
'permissions-sync' => ['status' => 'pending', 'exit_code' => 0, 'vendor_warnings_ignored' => 0],
|
||||
'build' => ['status' => 'pending', 'exit_code' => 0, 'vendor_warnings_ignored' => 0],
|
||||
@@ -300,6 +363,7 @@ final class ModuleRunner implements ModuleRunnerInterface
|
||||
'module-runtime-sync: another runtime sync is in progress, skipping.',
|
||||
function () use (&$steps): int {
|
||||
$orderedSteps = [
|
||||
'db-migrate' => fn (): array => $this->dbMigrate(),
|
||||
'migrate' => fn (): array => $this->migrate(),
|
||||
'permissions-sync' => fn (): array => $this->permissionsSync(),
|
||||
'build' => fn (): array => $this->build(),
|
||||
@@ -332,7 +396,8 @@ final class ModuleRunner implements ModuleRunnerInterface
|
||||
|
||||
if ($message === '') {
|
||||
$message = sprintf(
|
||||
'module-runtime-sync: summary migrate=%s permissions-sync=%s build=%s assets-sync=%s vendor_warnings_ignored=%d',
|
||||
'module-runtime-sync: summary db-migrate=%s migrate=%s permissions-sync=%s build=%s assets-sync=%s vendor_warnings_ignored=%d',
|
||||
$steps['db-migrate']['status'],
|
||||
$steps['migrate']['status'],
|
||||
$steps['permissions-sync']['status'],
|
||||
$steps['build']['status'],
|
||||
|
||||
@@ -6,6 +6,16 @@ namespace MintyPHP\Console\Runner\Module;
|
||||
|
||||
interface ModuleRunnerInterface
|
||||
{
|
||||
/**
|
||||
* @return array{command: string, status: string, exit_code: int, vendor_warnings_ignored: int, message: string}
|
||||
*/
|
||||
public function dbMigrate(): array;
|
||||
|
||||
/**
|
||||
* @return array{command: string, applied: list<string>, pending: list<string>}
|
||||
*/
|
||||
public function dbMigrateStatus(): array;
|
||||
|
||||
/**
|
||||
* @return array{command: string, status: string, exit_code: int, vendor_warnings_ignored: int, message: string}
|
||||
*/
|
||||
@@ -77,6 +87,9 @@ interface ModuleRunnerInterface
|
||||
* steps: array<string, array{status: string, exit_code: int, vendor_warnings_ignored: int}>,
|
||||
* message: string
|
||||
* }
|
||||
*
|
||||
* The `steps` map is keyed in execution order:
|
||||
* `db-migrate`, `migrate`, `permissions-sync`, `build`, `assets-sync`.
|
||||
*/
|
||||
public function runtimeSync(): array;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user