feat: runner de migrations
This commit is contained in:
1 parent
c68d49a48a
commit
8118f97b8f
1 file changed
+60
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$root = dirname(__DIR__);
|
||||
|
||||
$pdo = new PDO('sqlite:' . $root . '/database/api_tube.sqlite');
|
||||
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
||||
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
|
||||
|
||||
$pdo->exec(
|
||||
"CREATE TABLE IF NOT EXISTS migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
)"
|
||||
);
|
||||
|
||||
$applied = array_column($pdo->query('SELECT version FROM migrations')->fetchAll(), 'version');
|
||||
|
||||
$files = glob($root . '/database/migrations/*.sql');
|
||||
|
||||
if ($files === false || $files === []) {
|
||||
echo "Aucune migration trouvee.\n";
|
||||
exit(0);
|
||||
}
|
||||
|
||||
sort($files);
|
||||
|
||||
$count = 0;
|
||||
|
||||
foreach ($files as $file) {
|
||||
$version = basename($file);
|
||||
|
||||
if (in_array($version, $applied, true)) {
|
||||
echo "Skipped {$version}\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
$pdo->beginTransaction();
|
||||
|
||||
try {
|
||||
$pdo->exec((string) file_get_contents($file));
|
||||
|
||||
$stmt = $pdo->prepare('INSERT INTO migrations (version) VALUES (:version)');
|
||||
$stmt->execute(['version' => $version]);
|
||||
|
||||
$pdo->commit();
|
||||
} catch (Throwable $e) {
|
||||
$pdo->rollBack();
|
||||
throw $e;
|
||||
}
|
||||
|
||||
echo "Applied {$version}\n";
|
||||
$applied[] = $version;
|
||||
$count++;
|
||||
}
|
||||
|
||||
if ($count === 0) {
|
||||
echo "Nothing to migrate.\n";
|
||||
}
|
||||
Reference in new issue
Block a user