drink-it-cold/tools/migrate.php

58 lines
1.7 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
/**
* Führt ausstehende SQL-Migrationen aus (CLI).
*
* php tools/migrate.php
*
* Frische Installationen bekommen das komplette Schema über install.php.
* Bestehende Installationen ziehen mit diesem Skript neue Tabellen nach.
*/
if (PHP_SAPI !== 'cli') {
http_response_code(403);
exit("Nur per CLI.\n");
}
require __DIR__ . '/../app/bootstrap.php';
$pdo = db();
$pdo->exec(
'CREATE TABLE IF NOT EXISTS schema_migrations (
version INT UNSIGNED NOT NULL,
applied_at DATETIME NOT NULL,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci'
);
$applied = array_map('intval', $pdo->query('SELECT version FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN));
$files = glob(__DIR__ . '/../sql/migrations/*.sql') ?: [];
sort($files, SORT_STRING);
$count = 0;
foreach ($files as $file) {
$name = basename($file);
if (!preg_match('/^(\d+)_/', $name, $match)) {
fwrite(STDERR, "Überspringe Datei ohne Versionsnummer: $name\n");
continue;
}
$version = (int) $match[1];
if (in_array($version, $applied, true)) {
continue;
}
echo "Migration $version: $name\n";
$sql = preg_replace('/^\s*--.*$/m', '', (string) file_get_contents($file)) ?? '';
foreach (array_filter(array_map('trim', explode(';', $sql))) as $statement) {
if ($statement !== '') {
$pdo->exec($statement);
}
}
$pdo->prepare('INSERT IGNORE INTO schema_migrations (version, applied_at) VALUES (?, ?)')
->execute([$version, utc_now()]);
$count++;
}
echo $count === 0 ? "Keine ausstehenden Migrationen.\n" : "$count Migration(en) angewendet.\n";