46 lines
1.7 KiB
PHP
46 lines
1.7 KiB
PHP
<?php
|
|
require_once 'db/config.php';
|
|
|
|
echo "Starting database setup...\n";
|
|
|
|
try {
|
|
// Connect without specifying a database to create it if it doesn't exist
|
|
$pdo_setup = new PDO('mysql:host='.DB_HOST.';charset=utf8mb4', DB_USER, DB_PASS, [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
]);
|
|
$pdo_setup->exec('CREATE DATABASE IF NOT EXISTS `'.DB_NAME.'`');
|
|
echo "Database `".DB_NAME."` ensured to exist.\n";
|
|
|
|
// Now connect to the database
|
|
$pdo = db();
|
|
|
|
// 1. Ensure migrations table exists
|
|
$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;");
|
|
|
|
// 2. Get all executed migrations
|
|
$executedMigrations = $pdo->query("SELECT migration FROM migrations")->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
// 3. Get all migration files
|
|
$migrationsDir = __DIR__ . '/db/migrations';
|
|
$migrationFiles = glob($migrationsDir . '/*.sql');
|
|
sort($migrationFiles);
|
|
|
|
// 4. Run pending migrations
|
|
foreach ($migrationFiles as $file) {
|
|
$migrationName = basename($file);
|
|
if (!in_array($migrationName, $executedMigrations)) {
|
|
echo "Running migration: " . $migrationName . "\n";
|
|
$sql = file_get_contents($file);
|
|
$pdo->exec($sql);
|
|
|
|
// 5. Log the migration
|
|
$stmt = $pdo->prepare("INSERT INTO migrations (migration) VALUES (?)");
|
|
$stmt->execute([$migrationName]);
|
|
}
|
|
}
|
|
|
|
echo "Migrations completed successfully.\n";
|
|
|
|
} catch (PDOException $e) {
|
|
die("Database setup or migration failed: " . $e->getMessage() . "\n");
|
|
} |