56 lines
1.9 KiB
PHP
56 lines
1.9 KiB
PHP
<?php
|
|
// Simple migration script
|
|
require_once __DIR__ . '/config.php';
|
|
|
|
try {
|
|
$pdo = db();
|
|
echo "Connected to database successfully.\n";
|
|
|
|
// 1. Create migrations table if it doesn't exist
|
|
$pdo->exec("CREATE TABLE IF NOT EXISTS `migrations` (
|
|
`id` INT AUTO_INCREMENT PRIMARY KEY,
|
|
`migration` VARCHAR(255) NOT NULL,
|
|
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
|
|
echo "Checked/created `migrations` table.\n";
|
|
|
|
// 2. Get all executed migrations
|
|
$executedMigrations = $pdo->query("SELECT migration FROM `migrations`")->fetchAll(PDO::FETCH_COLUMN);
|
|
echo "Found " . count($executedMigrations) . " executed migrations.\n";
|
|
|
|
// 3. Find all migration files
|
|
$migrationFiles = glob(__DIR__ . '/migrations/*.sql');
|
|
echo "Found " . count($migrationFiles) . " migration files.\n";
|
|
|
|
// 4. Run pending migrations
|
|
$migrationsRun = 0;
|
|
foreach ($migrationFiles as $file) {
|
|
$migrationName = basename($file);
|
|
if (!in_array($migrationName, $executedMigrations)) {
|
|
echo "Running migration: {$migrationName}...\n";
|
|
|
|
// Execute the SQL file
|
|
$sql = file_get_contents($file);
|
|
$pdo->exec($sql);
|
|
|
|
// Record the migration
|
|
$stmt = $pdo->prepare("INSERT INTO `migrations` (migration) VALUES (?)");
|
|
$stmt->execute([$migrationName]);
|
|
|
|
echo "Successfully ran and recorded migration: {$migrationName}\n";
|
|
$migrationsRun++;
|
|
}
|
|
}
|
|
|
|
if ($migrationsRun === 0) {
|
|
echo "No new migrations to run.\n";
|
|
} else {
|
|
echo "Finished running {$migrationsRun} new migrations.\n";
|
|
}
|
|
|
|
} catch (PDOException $e) {
|
|
die("Database error: " . $e->getMessage());
|
|
} catch (Exception $e) {
|
|
die("An error occurred: " . $e->getMessage());
|
|
}
|