HifiPlanet-Website/hifi/api/src/Controllers/SchemaController.php

171 lines
5.9 KiB
PHP

<?php
namespace App\Controllers;
use App\Config\Database;
use App\Support\Http;
use App\Support\Schema;
class SchemaController
{
public static function check(): void
{
Http::send(self::buildReport());
}
public static function migrate(): void
{
$actions = self::runMigration();
Http::send(['ok' => true, 'actions' => $actions, 'report' => self::buildReport()]);
}
/**
* Ruestet fehlende Tabellen/Spalten automatisch nach, sobald sich der Soll-Zustand in
* Schema.php geaendert hat (z. B. nach einem "git pull"). Der Fingerabdruck des Soll-
* Zustands liegt in einer kleinen Datei - im Normalfall kostet das pro Request nur ein
* file_get_contents. Fehler werden geschluckt: die Seite soll deswegen nie ausfallen,
* der Button unter System -> Datenbank bleibt als manueller Weg.
*/
public static function ensureCurrent(): void
{
try {
$version = md5(json_encode([array_keys(Schema::CREATE_STATEMENTS), Schema::COLUMNS]));
$dir = is_writable(__DIR__ . '/../../config') ? __DIR__ . '/../../config' : sys_get_temp_dir();
$file = $dir . '/.schema-version';
if (is_file($file) && trim((string) file_get_contents($file)) === $version) {
return;
}
$lock = @fopen($file . '.lock', 'c');
if (!$lock || !flock($lock, LOCK_EX | LOCK_NB)) {
return;
}
$actions = self::runMigration();
$failed = array_filter($actions, fn($a) => str_starts_with($a, 'FEHLER'));
if (!$failed) {
file_put_contents($file, $version);
}
flock($lock, LOCK_UN);
fclose($lock);
} catch (\Throwable $e) {
// bewusst still, siehe oben
}
}
/**
* Der eigentliche additive Migrations-Lauf, losgeloest von Http::send()/exit - damit
* z.B. GitUpdateService das nach einem Auto-Update genauso aufrufen kann wie der
* "Datenbankstruktur aktualisieren"-Button, ohne die laufende Response zu beenden.
* Verhalten unveraendert gegenueber vorher, nur aus migrate() herausgezogen.
*
* @return string[]
*/
public static function runMigration(): array
{
$db = Database::connection();
$existingTables = self::existingTables($db);
$actions = [];
foreach (Schema::CREATE_STATEMENTS as $table => $createSql) {
if (!in_array($table, $existingTables, true)) {
try {
$db->exec($createSql);
$actions[] = "Tabelle `$table` angelegt";
self::seedTable($db, $table, $actions);
} catch (\Throwable $e) {
$actions[] = "FEHLER beim Anlegen von `$table`: " . $e->getMessage();
}
continue;
}
$existingColumns = self::existingColumns($db, $table);
foreach (Schema::COLUMNS[$table] ?? [] as $column => $definition) {
if ($column === 'id' || in_array($column, $existingColumns, true)) {
continue;
}
try {
$db->exec("ALTER TABLE `$table` ADD COLUMN `$column` $definition");
$actions[] = "Spalte `$table`.`$column` ergänzt";
} catch (\Throwable $e) {
$actions[] = "FEHLER bei `$table`.`$column`: " . $e->getMessage();
}
}
}
return $actions;
}
/**
* @param string[] $actions
*/
private static function seedTable(\PDO $db, string $table, array &$actions): void
{
$rows = Schema::SEED_DATA[$table] ?? [];
if ($rows === []) {
return;
}
$columns = array_keys($rows[0]);
$placeholders = implode(', ', array_fill(0, count($columns), '?'));
$columnList = implode(', ', array_map(fn($c) => "`$c`", $columns));
$stmt = $db->prepare("INSERT INTO `$table` ($columnList) VALUES ($placeholders)");
foreach ($rows as $row) {
$stmt->execute(array_values($row));
}
$actions[] = "Tabelle `$table` mit " . count($rows) . " Standardeinträgen befüllt";
}
public static function buildReport(): array
{
$db = Database::connection();
$existingTables = self::existingTables($db);
$tables = [];
$allOk = true;
foreach (Schema::CREATE_STATEMENTS as $table => $createSql) {
$exists = in_array($table, $existingTables, true);
$missingColumns = [];
if ($exists) {
$existingColumns = self::existingColumns($db, $table);
foreach (array_keys(Schema::COLUMNS[$table] ?? []) as $column) {
if ($column !== 'id' && !in_array($column, $existingColumns, true)) {
$missingColumns[] = $column;
}
}
}
$tableOk = $exists && count($missingColumns) === 0;
if (!$tableOk) {
$allOk = false;
}
$tables[] = [
'table' => $table,
'exists' => $exists,
'missing_columns' => $missingColumns,
'ok' => $tableOk,
];
}
return ['ok' => $allOk, 'tables' => $tables];
}
/** @return string[] */
private static function existingTables(\PDO $db): array
{
$stmt = $db->query('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE()');
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
/** @return string[] */
private static function existingColumns(\PDO $db, string $table): array
{
$stmt = $db->prepare('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?');
$stmt->execute([$table]);
return $stmt->fetchAll(\PDO::FETCH_COLUMN);
}
}