35512-vm/run-migrations.php
2025-11-08 20:43:02 +00:00

79 lines
2.6 KiB
PHP

<?php
require_once 'db/config.php';
try {
$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 1. Create migrations table if it doesn't exist
$pdo->exec("CREATE TABLE IF NOT EXISTS migrations (
id INT AUTO_INCREMENT PRIMARY KEY,
migration_file VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY (migration_file)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
// 2. Pre-populate with migrations that are known to have run already
$known_migrations = [
'001_create_assets_table.sql',
'002_create_users_table.sql',
'003_create_permissions_table.sql',
'004_create_categories_table.sql',
'005_add_category_id_to_assets.sql'
];
$stmt = $pdo->prepare("INSERT IGNORE INTO migrations (migration_file) VALUES (?)");
foreach ($known_migrations as $migration) {
$stmt->execute([$migration]);
}
// 3. Get all migrations that have already been run
$ran_migrations_stmt = $pdo->query("SELECT migration_file FROM migrations");
$ran_migrations = $ran_migrations_stmt->fetchAll(PDO::FETCH_COLUMN);
// 4. Get all available migration files
$migration_files = glob('db/migrations/*.sql');
sort($migration_files);
// 5. Determine which migrations to run
$migrations_to_run = [];
foreach ($migration_files as $file) {
if (!in_array(basename($file), $ran_migrations)) {
$migrations_to_run[] = $file;
}
}
if (empty($migrations_to_run)) {
echo "Database is already up to date.\n";
} else {
// 6. Run the new migrations
foreach ($migrations_to_run as $file) {
try {
$sql = file_get_contents($file);
if (empty(trim($sql))) {
echo "Skipping empty migration file: $file\n";
$stmt = $pdo->prepare("INSERT INTO migrations (migration_file) VALUES (?)");
$stmt->execute([basename($file)]);
continue;
}
$pdo->exec($sql);
$stmt = $pdo->prepare("INSERT INTO migrations (migration_file) VALUES (?)");
$stmt->execute([basename($file)]);
echo "Successfully ran migration: " . basename($file) . "\n";
} catch (PDOException $e) {
echo "Error running migration " . basename($file) . ": " . $e->getMessage() . "\n";
exit(1);
}
}
echo "All new migrations ran successfully.\n";
}
} catch (PDOException $e) {
die("Database error: " . $e->getMessage());
}
?>