1
0

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:
2026-04-29 08:59:57 +02:00
parent 0c78dc4355
commit 2e73cb98b4
17 changed files with 651 additions and 37 deletions

View File

@@ -0,0 +1,130 @@
<?php
namespace MintyPHP\Service\Database;
use MintyPHP\Repository\Database\CoreMigrationRepositoryInterface;
use MintyPHP\Support\SqlStatementParser;
use RuntimeException;
/**
* Discovers and applies pending SQL migrations from db/updates/*.sql.
*
* Mirror of ModuleMigrationService for core schema changes. Each file MUST be
* idempotent (CLAUDE.md / GR-CORE-010); applied filenames are tracked in
* core_migrations so subsequent runs only apply genuinely new files.
*
* Orchestration only — SQL lives in CoreMigrationRepository,
* statement parsing in SqlStatementParser.
*/
final class CoreMigrationService
{
public function __construct(
private readonly CoreMigrationRepositoryInterface $repository,
private readonly string $updatesPath,
) {
}
/**
* Apply all pending core migrations.
*
* @return array{ok: bool, applied: int, skipped_empty: int, total_files: int, applied_filenames: list<string>}
*/
public function applyPendingMigrations(): array
{
$this->repository->ensureTrackingTable();
$files = $this->discoverFiles();
$applied = $this->repository->getAppliedFilenames();
$totalApplied = 0;
$skippedEmpty = 0;
$appliedFilenames = [];
foreach ($files as $file) {
$filename = basename($file);
if (isset($applied[$filename])) {
continue;
}
$sql = file_get_contents($file);
if ($sql === false || trim($sql) === '') {
$skippedEmpty++;
continue;
}
$this->repository->beginTransaction();
try {
$statements = SqlStatementParser::splitStatements($sql);
foreach ($statements as $statement) {
$this->repository->executeStatement($statement);
}
$this->repository->recordApplied($filename);
$this->repository->commit();
} catch (\Throwable $migrationError) {
$this->repository->rollback();
throw new RuntimeException(
sprintf("Core migration %s failed: %s", $filename, $migrationError->getMessage()),
0,
$migrationError
);
}
$totalApplied++;
$appliedFilenames[] = $filename;
}
return [
'ok' => true,
'applied' => $totalApplied,
'skipped_empty' => $skippedEmpty,
'total_files' => count($files),
'applied_filenames' => $appliedFilenames,
];
}
/**
* Inspect applied vs. pending migrations without running anything.
*
* @return array{applied: list<string>, pending: list<string>}
*/
public function status(): array
{
$this->repository->ensureTrackingTable();
$files = $this->discoverFiles();
$appliedMap = $this->repository->getAppliedFilenames();
$applied = [];
$pending = [];
foreach ($files as $file) {
$filename = basename($file);
if (isset($appliedMap[$filename])) {
$applied[] = $filename;
} else {
$pending[] = $filename;
}
}
sort($applied);
sort($pending);
return ['applied' => $applied, 'pending' => $pending];
}
/**
* @return list<string> Absolute paths of `*.sql` files in updates dir, sorted alphabetically.
*/
private function discoverFiles(): array
{
if (!is_dir($this->updatesPath)) {
return [];
}
$files = glob($this->updatesPath . '/*.sql');
if ($files === false || count($files) === 0) {
return [];
}
sort($files);
return $files;
}
}