52 lines
1.2 KiB
PHP
52 lines
1.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
function run_migrations(): void
|
|
{
|
|
static $hasRun = false;
|
|
|
|
if ($hasRun) {
|
|
return;
|
|
}
|
|
|
|
$hasRun = true;
|
|
$pdo = db();
|
|
|
|
$pdo->exec(
|
|
"CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
"
|
|
. " filename VARCHAR(190) NOT NULL PRIMARY KEY,
|
|
"
|
|
. " applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
"
|
|
. ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
|
|
);
|
|
|
|
$files = glob(__DIR__ . '/migrations/*.sql') ?: [];
|
|
sort($files, SORT_STRING);
|
|
|
|
$checkStmt = $pdo->prepare('SELECT 1 FROM schema_migrations WHERE filename = :filename LIMIT 1');
|
|
$insertStmt = $pdo->prepare('INSERT INTO schema_migrations (filename) VALUES (:filename)');
|
|
|
|
foreach ($files as $file) {
|
|
$filename = basename($file);
|
|
$checkStmt->bindValue(':filename', $filename, PDO::PARAM_STR);
|
|
$checkStmt->execute();
|
|
|
|
if ($checkStmt->fetchColumn()) {
|
|
continue;
|
|
}
|
|
|
|
$sql = trim((string) file_get_contents($file));
|
|
|
|
if ($sql !== '') {
|
|
$pdo->exec($sql);
|
|
}
|
|
|
|
$insertStmt->bindValue(':filename', $filename, PDO::PARAM_STR);
|
|
$insertStmt->execute();
|
|
}
|
|
}
|