58 lines
2.2 KiB
PHP
58 lines
2.2 KiB
PHP
<?php
|
|
// Database configuration
|
|
define('DB_HOST', getenv('DB_HOST') ?: '127.0.0.1');
|
|
define('DB_PORT', getenv('DB_PORT') ?: '3306');
|
|
define('DB_NAME', getenv('DB_NAME') ?: 'flatlogic');
|
|
define('DB_USER', getenv('DB_USER') ?: 'flatlogic');
|
|
define('DB_PASS', getenv('DB_PASS') ?: 'flatlogic');
|
|
|
|
function db() {
|
|
static $pdo;
|
|
if ($pdo) {
|
|
return $pdo;
|
|
}
|
|
try {
|
|
// Connect without specifying a database to create it if it doesn't exist
|
|
$dsn_init = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';charset=utf8mb4';
|
|
$pdo_init = new PDO($dsn_init, DB_USER, DB_PASS, [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
]);
|
|
$pdo_init->exec('CREATE DATABASE IF NOT EXISTS `' . DB_NAME . '`');
|
|
|
|
// Now connect to the specific database
|
|
$dsn = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4';
|
|
$pdo = new PDO($dsn, DB_USER, DB_PASS, [
|
|
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
|
|
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
|
|
PDO::ATTR_EMULATE_PREPARES => false,
|
|
]);
|
|
|
|
run_migrations($pdo);
|
|
|
|
return $pdo;
|
|
} catch (PDOException $e) {
|
|
// In a real app, you'd log this error and show a generic message
|
|
throw new PDOException($e->getMessage(), (int)$e->getCode());
|
|
}
|
|
}
|
|
|
|
function run_migrations($pdo) {
|
|
$pdo->exec('CREATE TABLE IF NOT EXISTS `migrations` (`migration` VARCHAR(255) NOT NULL, PRIMARY KEY (`migration`))');
|
|
$applied_migrations = $pdo->query('SELECT `migration` FROM `migrations`')->fetchAll(PDO::FETCH_COLUMN);
|
|
|
|
$migration_files = glob(__DIR__ . '/migrations/*.sql');
|
|
sort($migration_files);
|
|
|
|
foreach ($migration_files as $file) {
|
|
$migration_name = basename($file);
|
|
if (!in_array($migration_name, $applied_migrations)) {
|
|
$sql = file_get_contents($file);
|
|
$pdo->exec($sql);
|
|
$stmt = $pdo->prepare('INSERT INTO `migrations` (`migration`) VALUES (?)');
|
|
$stmt->execute([$migration_name]);
|
|
}
|
|
}
|
|
}
|