58 lines
1.9 KiB
PHP
58 lines
1.9 KiB
PHP
<?php
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
try {
|
|
// First, ensure the database exists
|
|
$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);
|
|
|
|
// Now, connect to the actual database
|
|
$pdo = db();
|
|
echo "Successfully connected to database: " . DB_NAME . "\n";
|
|
|
|
// 1. Create migrations tracking table if it doesn't exist
|
|
$pdo->exec("CREATE TABLE IF NOT EXISTS `migrations` (
|
|
`migration` VARCHAR(255) NOT NULL,
|
|
PRIMARY KEY (`migration`)
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
|
|
|
|
// 2. Get all migrations that have been run
|
|
$run_migrations_stmt = $pdo->query("SELECT `migration` FROM `migrations`");
|
|
$run_migrations = $run_migrations_stmt->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
// 3. Get all available migration files
|
|
$migration_files = glob(__DIR__ . '/migrations/*.sql');
|
|
sort($migration_files);
|
|
|
|
$migrations_run_this_time = 0;
|
|
|
|
// 4. Loop through files and run any new migrations
|
|
foreach ($migration_files as $file) {
|
|
$migration_name = basename($file);
|
|
if (!in_array($migration_name, $run_migrations)) {
|
|
echo "Running migration: " . $migration_name . "...\n";
|
|
|
|
$sql = file_get_contents($file);
|
|
$pdo->exec($sql);
|
|
|
|
// Record the migration
|
|
$stmt = $pdo->prepare("INSERT INTO `migrations` (`migration`) VALUES (?)");
|
|
$stmt->execute([$migration_name]);
|
|
|
|
echo " -> Success.\n";
|
|
$migrations_run_this_time++;
|
|
}
|
|
}
|
|
|
|
if ($migrations_run_this_time === 0) {
|
|
echo "All migrations are up to date.\n";
|
|
} else {
|
|
echo "Finished running " . $migrations_run_this_time . " new migration(s).\n";
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
die("Migration failed: " . $e->getMessage() . "\n");
|
|
}
|