53 lines
1.6 KiB
PHP
53 lines
1.6 KiB
PHP
<?php
|
|
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
function runMigrations($pdo) {
|
|
$migrationsDir = __DIR__ . '/migrations';
|
|
$appliedMigrationsFile = __DIR__ . '/.applied_migrations';
|
|
|
|
// Ensure the applied migrations file exists
|
|
if (!file_exists($appliedMigrationsFile)) {
|
|
file_put_contents($appliedMigrationsFile, json_encode([]));
|
|
}
|
|
|
|
$appliedMigrations = json_decode(file_get_contents($appliedMigrationsFile), true);
|
|
|
|
$migrationFiles = glob($migrationsDir . '/*.sql');
|
|
sort($migrationFiles);
|
|
|
|
echo "Running database migrations...\n";
|
|
|
|
foreach ($migrationFiles as $file) {
|
|
$fileName = basename($file);
|
|
if (!in_array($fileName, $appliedMigrations)) {
|
|
echo "Applying migration: {$fileName}\n";
|
|
$sql = file_get_contents($file);
|
|
try {
|
|
$pdo->exec($sql);
|
|
$appliedMigrations[] = $fileName;
|
|
} catch (PDOException $e) {
|
|
echo "Error applying migration {$fileName}: " . $e->getMessage() . "\n";
|
|
return false; // Stop on first error
|
|
}
|
|
} else {
|
|
echo "Migration already applied: {$fileName}\n";
|
|
}
|
|
}
|
|
|
|
file_put_contents($appliedMigrationsFile, json_encode($appliedMigrations));
|
|
echo "Migrations finished.\n";
|
|
return true;
|
|
}
|
|
|
|
// Run migrations if this script is executed directly
|
|
if (realpath($argv[0]) === realpath(__FILE__)) {
|
|
try {
|
|
$pdo = db(); // Get PDO connection from config.php
|
|
runMigrations($pdo);
|
|
} catch (PDOException $e) {
|
|
echo "Database connection error: " . $e->getMessage() . "\n";
|
|
}
|
|
}
|
|
|