35049-vm/db/migrate.php
Flatlogic Bot 119d467b75 v2.0
2025-10-19 03:32:56 +00:00

57 lines
2.0 KiB
PHP

<?php
require_once __DIR__ . '/config.php';
try {
// Connect without specifying a database to create it if it doesn't exist
$pdo = new PDO('mysql:host='.DB_HOST, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$pdo->exec('CREATE DATABASE IF NOT EXISTS '.DB_NAME);
echo "Database ".DB_NAME." created or already exists.\n";
} catch (PDOException $e) {
// Suppress error if DB exists but user lacks CREATE DB permissions
}
// Now, connect to the specific database
$pdo = db();
// 1. Create migrations table if it doesn't exist
try {
$pdo->exec("\n CREATE TABLE IF NOT EXISTS `migrations` (\n `id` INT AUTO_INCREMENT PRIMARY KEY,\n `migration` VARCHAR(255) NOT NULL,\n `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n )\n ");
} catch (PDOException $e) {
echo "Error creating migrations table: " . $e->getMessage() . "\n";
exit(1);
}
// 2. Get all migrations that have been run
$stmt = $pdo->query("SELECT `migration` FROM `migrations`");
$runMigrations = $stmt->fetchAll(PDO::FETCH_COLUMN);
// 3. Get all available migration files
$migrationsDir = __DIR__ . '/migrations';
$files = glob($migrationsDir . '/*.sql');
sort($files);
// 4. Run migrations that have not been run yet
foreach ($files as $file) {
$migrationName = basename($file);
if (!in_array($migrationName, $runMigrations)) {
echo "Applying migration: " . $migrationName . "\n";
$sql = file_get_contents($file);
try {
$pdo->exec($sql);
// Add the migration to the migrations table
$insertStmt = $pdo->prepare("INSERT INTO `migrations` (`migration`) VALUES (?)");
$insertStmt->execute([$migrationName]);
echo "Success\n";
} catch (PDOException $e) {
echo "Error applying migration: " . $e->getMessage() . "\n";
// Don't exit, allow other migrations to run
}
}
}
echo "Migration check complete.\n";