65 lines
2.2 KiB
PHP
65 lines
2.2 KiB
PHP
<?php
|
|
session_start();
|
|
|
|
require_once __DIR__ . '/config.php';
|
|
require_once __DIR__ . '/../includes/uuid.php';
|
|
|
|
$_SESSION['migration_output'] = [];
|
|
|
|
try {
|
|
$pdo = db();
|
|
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
|
|
$pdo->exec('CREATE TABLE IF NOT EXISTS migrations (migration VARCHAR(255) PRIMARY KEY);');
|
|
|
|
$executed_migrations_stmt = $pdo->query('SELECT migration FROM migrations');
|
|
$executed_migrations = $executed_migrations_stmt->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
$migration_files = glob(__DIR__ . '/migrations/*.{sql,php}', GLOB_BRACE);
|
|
sort($migration_files);
|
|
|
|
$ran_a_migration = false;
|
|
|
|
foreach ($migration_files as $migration_file) {
|
|
$migration_name = basename($migration_file);
|
|
|
|
if (!in_array($migration_name, $executed_migrations)) {
|
|
$ran_a_migration = true;
|
|
$_SESSION['migration_output'][] = "Running migration: {$migration_name}...";
|
|
|
|
$extension = pathinfo($migration_file, PATHINFO_EXTENSION);
|
|
|
|
if ($extension === 'sql') {
|
|
$sql = file_get_contents($migration_file);
|
|
$statements = array_filter(array_map('trim', explode(';', $sql)));
|
|
foreach ($statements as $statement) {
|
|
if (!empty($statement)) {
|
|
$pdo->exec($statement);
|
|
}
|
|
}
|
|
} elseif ($extension === 'php') {
|
|
require $migration_file;
|
|
}
|
|
|
|
$stmt = $pdo->prepare('INSERT INTO migrations (migration) VALUES (?)');
|
|
$stmt->execute([$migration_name]);
|
|
|
|
$_SESSION['migration_output'][] = "Successfully ran and recorded migration: {$migration_name}.";
|
|
}
|
|
}
|
|
|
|
if (!$ran_a_migration) {
|
|
$_SESSION['migration_output'][] = "No new migrations to run. Database is up to date.";
|
|
}
|
|
|
|
$_SESSION['migration_status'] = 'success';
|
|
|
|
} catch (Exception $e) {
|
|
$_SESSION['migration_status'] = 'error';
|
|
$_SESSION['migration_output'][] = 'An error occurred: ' . $e->getMessage();
|
|
error_log('Migration Error: ' . $e->getMessage());
|
|
}
|
|
|
|
header('Location: /index.php?migration_status=' . $_SESSION['migration_status']);
|
|
exit;
|