84 lines
2.7 KiB
PHP
84 lines
2.7 KiB
PHP
<?php
|
|
/**
|
|
* Datenbankverbindung (PDO).
|
|
* Unterstützt sowohl MySQL (Produktivbetrieb) als auch SQLite (lokale Tests),
|
|
* gesteuert über config/config.php -> db.driver
|
|
*/
|
|
require_once __DIR__ . '/../database/sqlite_schema.php';
|
|
|
|
function config(): array
|
|
{
|
|
static $config = null;
|
|
if ($config === null) {
|
|
$config = require __DIR__ . '/../config/config.php';
|
|
// Nur für Tests: einzelne Werte überschreiben (wirkt ausschließlich mit DESKHUB_TESTING=1)
|
|
if (getenv('DESKHUB_TESTING') === '1' && ($extra = json_decode((string) getenv('DESKHUB_CONFIG_JSON'), true)) && is_array($extra)) {
|
|
$config = array_replace_recursive($config, $extra);
|
|
}
|
|
}
|
|
return $config;
|
|
}
|
|
|
|
function get_db(): PDO
|
|
{
|
|
static $pdo = null;
|
|
if ($pdo !== null) {
|
|
return $pdo;
|
|
}
|
|
|
|
$cfg = config()['db'];
|
|
|
|
if ($cfg['driver'] === 'sqlite') {
|
|
$dbPath = $cfg['sqlite_path'];
|
|
$needInit = !file_exists($dbPath) || filesize($dbPath) === 0;
|
|
|
|
$pdo = new PDO('sqlite:' . $dbPath);
|
|
$pdo->exec('PRAGMA journal_mode = WAL;');
|
|
$pdo->exec('PRAGMA foreign_keys = ON;');
|
|
|
|
if ($needInit) {
|
|
$schemaFile = __DIR__ . '/../database/schema.sql';
|
|
if (!file_exists($schemaFile)) {
|
|
throw new \RuntimeException("Schema-Datei nicht gefunden: $schemaFile");
|
|
}
|
|
$sql = file_get_contents($schemaFile);
|
|
|
|
$pdo->exec(convert_schema_to_sqlite($sql));
|
|
}
|
|
} else {
|
|
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8mb4', $cfg['host'], $cfg['name']);
|
|
$pdo = new PDO($dsn, $cfg['user'], $cfg['pass'], [
|
|
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
|
|
]);
|
|
}
|
|
|
|
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
|
|
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
|
|
|
|
// Ausstehende Schema-Migrationen automatisch einspielen.
|
|
// Bereits angewendete werden übersprungen → Einstellungen bleiben erhalten.
|
|
$migrateFile = __DIR__ . '/../database/migrate.php';
|
|
if (file_exists($migrateFile)) {
|
|
require_once $migrateFile;
|
|
$migrationResult = run_migrations($pdo);
|
|
if ($migrationResult['errors']) {
|
|
throw new RuntimeException('Datenbankmigration fehlgeschlagen: ' . implode('; ', $migrationResult['errors']));
|
|
}
|
|
}
|
|
|
|
return $pdo;
|
|
}
|
|
|
|
/** Liefert NOW() als DATETIME-String, kompatibel zu beiden Treibern */
|
|
function db_now(): string
|
|
{
|
|
return date('Y-m-d H:i:s');
|
|
}
|
|
|
|
/** SQL-Datum-Differenz (Stunden addieren), kompatibel zu beiden Treibern -> wird in PHP berechnet */
|
|
function add_hours(string $datetime, int $hours): string
|
|
{
|
|
$ts = strtotime($datetime) + ($hours * 3600);
|
|
return date('Y-m-d H:i:s', $ts);
|
|
}
|