33892-vm/db/migrate.php
2025-09-04 21:15:45 +00:00

50 lines
1.6 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
function run_migrations() {
$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_file` VARCHAR(255) NOT NULL UNIQUE,
`applied_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
// 2. Get all migration files
$migration_files = glob(__DIR__ . '/migrations/*.sql');
// 3. Get already applied migrations
$stmt = $pdo->query("SELECT `migration_file` FROM `migrations`");
$applied_migrations = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo "Starting migrations...\n";
// 4. Apply pending migrations
foreach ($migration_files as $file) {
$filename = basename($file);
if (!in_array($filename, $applied_migrations)) {
echo "Applying migration: {$filename}...\n";
// Execute the SQL file
$sql = file_get_contents($file);
$pdo->exec($sql);
// Record the migration
$stmt = $pdo->prepare("INSERT INTO `migrations` (`migration_file`) VALUES (?)");
$stmt->execute([$filename]);
echo " ...applied successfully.\n";
} else {
echo "Migration already applied: {$filename}\n";
}
}
echo "Migrations finished.\n";
}
// Run migrations if the script is executed directly
if (php_sapi_name() === 'cli' && basename(__FILE__) == basename($_SERVER['PHP_SELF'])) {
run_migrations();
}