rpg-westreiche/westreiche_website/app/migrations.php

57 lines
2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
declare(strict_types=1);
/**
* Westreiche – Schema-Migrationen.
*
* Wird bei jedem Verbindungsaufbau (db()) einmal pro Request angewendet: Die
* Tabelle schema_migrations merkt sich, was bereits gelaufen ist. Damit
* erreichen Spalten-Erweiterungen auch Installationen, die vor der Änderung
* angelegt wurden (der Installer läuft nur einmal).
*
* Regeln:
* - Jede Migration bekommt eine neue, fortlaufende Version.
* - Statements müssen in sich abgeschlossen und wiederholbar formuliert sein
* (IF NOT EXISTS), damit ein abgebrochener Lauf nachholbar bleibt.
* - Bestehende Einträge nie ändern – nur hinten anhängen.
*/
const WS_MIGRATIONS = [
// 1: Vollständiger Regeltext der Zauber für den Detail-Schirm im Bogen.
1 => [
'ALTER TABLE spells ADD COLUMN IF NOT EXISTS body LONGTEXT NULL AFTER summary',
],
];
function ws_migrations_apply(PDO $pdo): void
{
static $applied = false;
if ($applied) {
return;
}
$applied = true;
try {
$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'
);
$done = array_map('intval', $pdo->query('SELECT version FROM schema_migrations')->fetchAll(PDO::FETCH_COLUMN));
foreach (WS_MIGRATIONS as $version => $statements) {
if (in_array((int) $version, $done, true)) {
continue;
}
foreach ((array) $statements as $sql) {
$pdo->exec($sql);
}
$pdo->prepare('INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)')
->execute([(int) $version, gmdate('Y-m-d H:i:s')]);
}
} catch (Throwable $error) {
// Migration darf die Seite nicht lahmlegen; Fehler landet im Log.
error_log('Westreiche-Migration: ' . $error->getMessage());
}
}