49 lines
1.8 KiB
PHP
49 lines
1.8 KiB
PHP
<?php
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
try {
|
|
$pdo = db();
|
|
|
|
// 1. Create migrations table if it doesn't exist
|
|
$pdo->exec("CREATE TABLE IF NOT EXISTS `migrations` ( `id` INT AUTO_INCREMENT PRIMARY KEY, `migration` VARCHAR(255) NOT NULL, `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP );");
|
|
|
|
// 2. Get all executed migrations
|
|
$stmt = $pdo->query("SELECT `migration` FROM `migrations`");
|
|
$executed_migrations = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
// 3. Find and execute new migrations
|
|
$migration_files = glob(__DIR__ . '/migrations/*.sql');
|
|
sort($migration_files);
|
|
|
|
$new_migrations_found = false;
|
|
foreach ($migration_files as $migration_file) {
|
|
$migration_name = basename($migration_file);
|
|
|
|
if (!in_array($migration_name, $executed_migrations)) {
|
|
$new_migrations_found = true;
|
|
$sql = file_get_contents($migration_file);
|
|
|
|
try {
|
|
$pdo->exec($sql);
|
|
|
|
// 4. Log the new migration
|
|
$insert_stmt = $pdo->prepare("INSERT INTO `migrations` (`migration`) VALUES (?)");
|
|
$insert_stmt->execute([$migration_name]);
|
|
|
|
echo "Executed migration: " . $migration_name . PHP_EOL;
|
|
} catch (PDOException $e) {
|
|
// If a specific migration fails, output the error and stop.
|
|
die("Migration failed on " . $migration_name . ": " . $e->getMessage() . PHP_EOL);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!$new_migrations_found) {
|
|
echo "No new migrations to execute." . PHP_EOL;
|
|
} else {
|
|
echo "All new migrations executed successfully." . PHP_EOL;
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
die("Database operation failed: " . $e->getMessage() . PHP_EOL);
|
|
} |