38682-vm/db/migrate.php
2026-02-27 01:20:05 +00:00

46 lines
1.8 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
$pdo = db();
// Ensure migrations table exists
$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
)");
$migrations_folder = array_diff(scandir(__DIR__ . '/migrations'), ['.', '..']);
sort($migrations_folder);
$applied_migrations = $pdo->query("SELECT migration_name FROM migrations")->fetchAll(PDO::FETCH_COLUMN);
foreach ($migrations_folder as $migration) {
if (!in_array($migration, $applied_migrations)) {
echo "Applying migration: $migration\n";
$sql = file_get_contents(__DIR__ . '/migrations/' . $migration);
try {
if (!empty(trim($sql))) {
$pdo->exec($sql);
}
$stmt = $pdo->prepare("INSERT INTO migrations (migration_name) VALUES (?)");
$stmt->execute([$migration]);
echo "Successfully applied $migration\n";
} catch (Exception $e) {
echo "Error applying $migration: " . $e->getMessage() . "\n";
// If it's a "Duplicate column name" error, we can assume it was applied manually and just record it
if (strpos($e->getMessage(), 'Duplicate column name') !== false || strpos($e->getMessage(), 'already exists') !== false) {
echo "Column/Table already exists, recording as applied.\n";
$stmt = $pdo->prepare("INSERT INTO migrations (migration_name) VALUES (?)");
$stmt->execute([$migration]);
} else {
// For other errors, we might want to stop or continue
echo "Stopping migrations due to error.\n";
break;
}
}
}
}
echo "Migration process finished.\n";