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"); }