69 lines
2.0 KiB
PHP
69 lines
2.0 KiB
PHP
<?php
|
|
session_start();
|
|
header('Content-Type: application/json');
|
|
|
|
if (!isset($_SESSION["user_id"]) || ($_SESSION["user_role"] ?? '') !== 'Super User') {
|
|
echo json_encode(['success' => false, 'error' => 'Unauthorized']);
|
|
exit;
|
|
}
|
|
|
|
require_once '../db/config.php';
|
|
|
|
try {
|
|
$db = db();
|
|
|
|
// 1. Ensure migration_history table exists
|
|
$db->exec("CREATE TABLE IF NOT EXISTS migration_history (
|
|
id INT AUTO_INCREMENT PRIMARY KEY,
|
|
filename VARCHAR(255) NOT NULL UNIQUE,
|
|
executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
|
|
|
|
// 2. Scan migrations directory
|
|
$migrations_dir = __DIR__ . '/../db/migrations/';
|
|
$migration_files = glob($migrations_dir . '*.sql');
|
|
sort($migration_files);
|
|
|
|
// 3. Get list of already executed migrations
|
|
$stmt = $db->query("SELECT filename FROM migration_history");
|
|
$executed_migrations = $stmt->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
$executed_count = 0;
|
|
$skipped_count = 0;
|
|
$new_migrations = [];
|
|
|
|
foreach ($migration_files as $file_path) {
|
|
$filename = basename($file_path);
|
|
|
|
if (in_array($filename, $executed_migrations)) {
|
|
$skipped_count++;
|
|
continue;
|
|
}
|
|
|
|
$sql = file_get_contents($file_path);
|
|
if ($sql) {
|
|
// Execute migration
|
|
$db->exec($sql);
|
|
|
|
// Record migration in history
|
|
$stmt = $db->prepare("INSERT INTO migration_history (filename) VALUES (?)");
|
|
$stmt->execute([$filename]);
|
|
|
|
$executed_count++;
|
|
$new_migrations[] = $filename;
|
|
}
|
|
}
|
|
|
|
echo json_encode([
|
|
'success' => true,
|
|
'message' => "Migration process complete.",
|
|
'executed' => $executed_count,
|
|
'skipped' => $skipped_count,
|
|
'new_migrations' => $new_migrations
|
|
]);
|
|
} catch (Exception $e) {
|
|
echo json_encode([
|
|
'success' => false,
|
|
'error' => 'Migration failed: ' . $e->getMessage()
|
|
]);
|
|
} |