37018-vm/db/apply_migrations.php
2025-12-18 06:13:19 +00:00

59 lines
1.5 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
echo "Applying migrations...
";
try {
$pdo = db();
// Create migrations table if it doesn't exist
$pdo->exec("
CREATE TABLE IF NOT EXISTS `migrations` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`migration_name` VARCHAR(255) NOT NULL UNIQUE,
`applied_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
");
$migrationsDir = __DIR__ . '/migrations/';
$migrationFiles = glob($migrationsDir . '*.sql');
sort($migrationFiles);
foreach ($migrationFiles as $file) {
$migrationName = basename($file);
// Check if migration has already been applied
$stmt = $pdo->prepare("SELECT COUNT(*) FROM `migrations` WHERE `migration_name` = ?");
$stmt->execute([$migrationName]);
if ($stmt->fetchColumn() > 0) {
echo "Skipping already applied migration: $migrationName
";
continue;
}
echo "Applying migration: $migrationName
";
$sql = file_get_contents($file);
$pdo->exec($sql);
// Record the applied migration
$stmt = $pdo->prepare("INSERT INTO `migrations` (`migration_name`) VALUES (?)");
$stmt->execute([$migrationName]);
echo "Successfully applied migration: $migrationName
";
}
echo "All migrations applied.
";
} catch (PDOException $e) {
echo "Database error: " . $e->getMessage() . "
";
exit(1);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "
";
exit(1);
}