refactor: simplifier Database avec schema.sql (suppression des migrations)
This commit is contained in:
1 parent
7de8e4782b
commit
e2aaa5dcd4
3 files changed
+1
-66
No files matched your search
@@ -1,16 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
declare(strict_types=1);
|
|
||||||
|
|
||||||
require dirname(__DIR__) . '/src/Database.php';
|
|
||||||
|
|
||||||
$applied = Database::runMigrations();
|
|
||||||
|
|
||||||
if ($applied === []) {
|
|
||||||
echo "Nothing to migrate.\n";
|
|
||||||
exit(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
foreach ($applied as $version) {
|
|
||||||
echo "Applied {$version}\n";
|
|
||||||
}
|
|
||||||
File renamed without changes.
+1
-50
@@ -10,61 +10,12 @@ final class Database
|
|||||||
{
|
{
|
||||||
if (self::$pdo === null) {
|
if (self::$pdo === null) {
|
||||||
self::init();
|
self::init();
|
||||||
self::runMigrations();
|
self::$pdo->exec((string) file_get_contents(dirname(__DIR__) . '/database/schema.sql'));
|
||||||
}
|
}
|
||||||
|
|
||||||
return self::$pdo;
|
return self::$pdo;
|
||||||
}
|
}
|
||||||
|
|
||||||
public static function runMigrations(): array
|
|
||||||
{
|
|
||||||
if (self::$pdo === null) {
|
|
||||||
self::init();
|
|
||||||
}
|
|
||||||
|
|
||||||
$root = dirname(__DIR__);
|
|
||||||
|
|
||||||
self::$pdo->exec(
|
|
||||||
"CREATE TABLE IF NOT EXISTS migrations (
|
|
||||||
version TEXT PRIMARY KEY,
|
|
||||||
applied_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
||||||
)"
|
|
||||||
);
|
|
||||||
|
|
||||||
$applied = array_column(self::$pdo->query('SELECT version FROM migrations')->fetchAll(), 'version');
|
|
||||||
|
|
||||||
$files = glob($root . '/database/migrations/*.sql') ?: [];
|
|
||||||
sort($files);
|
|
||||||
|
|
||||||
$newlyApplied = [];
|
|
||||||
|
|
||||||
foreach ($files as $file) {
|
|
||||||
$version = basename($file);
|
|
||||||
|
|
||||||
if (in_array($version, $applied, true)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
self::$pdo->beginTransaction();
|
|
||||||
|
|
||||||
try {
|
|
||||||
self::$pdo->exec((string) file_get_contents($file));
|
|
||||||
|
|
||||||
$stmt = self::$pdo->prepare('INSERT INTO migrations (version) VALUES (:version)');
|
|
||||||
$stmt->execute(['version' => $version]);
|
|
||||||
|
|
||||||
self::$pdo->commit();
|
|
||||||
} catch (Throwable $e) {
|
|
||||||
self::$pdo->rollBack();
|
|
||||||
throw $e;
|
|
||||||
}
|
|
||||||
|
|
||||||
$newlyApplied[] = $version;
|
|
||||||
}
|
|
||||||
|
|
||||||
return $newlyApplied;
|
|
||||||
}
|
|
||||||
|
|
||||||
private static function init(): void
|
private static function init(): void
|
||||||
{
|
{
|
||||||
$root = dirname(__DIR__);
|
$root = dirname(__DIR__);
|
||||||
|
|||||||
Reference in new issue
Block a user