pohja/lib/Database.php

110 lines
3.1 KiB
PHP
Raw Normal View History

2024-02-03 14:08:03 +01:00
<?php
class Database
{
public static $handle = null;
public function __construct($createDatabase = false)
{
if (self::$handle === null) {
self::$handle = new SQLite3(SQLITE_DB);
self::$handle->enableExceptions(true);
if ($createDatabase === true) {
$this->createDatabase();
}
}
}
public function createDatabase()
{
$schemaFiles = [
LIB_MIGRATIONS_DIR . "/_schema.sql",
MIGRATIONS_DIR . "/_schema.sql"
];
foreach ($schemaFiles as $schemaFile) {
if (file_exists($schemaFile)) {
$schema = file_get_contents($schemaFile);
self::$handle->exec($schema);
}
}
}
public function runMigrations()
{
$currentTableVersions = [];
$result = self::$handle->query("SELECT `table`,`version` FROM `migrations`");
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
$currentTableVersions[$row["table"]] = $row["version"];
}
$migrations = [];
$migrationPaths = [LIB_MIGRATIONS_DIR, MIGRATIONS_DIR];
foreach ($migrationPaths as $migrationPath) {
if (is_dir($migrationPath)) {
$migrations = array_merge($migrations, scandir($migrationPath));
}
}
$migrationCount = 0;
foreach ($migrations as $migration) {
if ($migration == "." || $migration == ".." || $migration == "_schema.sql") {
continue;
}
$migrationParts = explode("-", str_replace(".sql", "", $migration));
$migrationTable = $migrationParts[0];
$migrationVersion = $migrationParts[1];
$run = false;
if (!isset($currentTableVersions[$migrationTable])) {
$run = true;
} else {
if ($migrationVersion > $currentTableVersions[$migrationTable]) {
$run = true;
}
}
if ($run === true) {
Logger::log("Found migration for table " . $migrationTable . " version " . $migrationVersion, LOGGER::INFO, "Database");
2024-03-22 17:04:46 +01:00
$possiblePaths = [LIB_MIGRATIONS_DIR, MIGRATIONS_DIR];
$migrationFile = null;
foreach ($possiblePaths as $possiblePath) {
if (file_exists($possiblePath . "/" . $migration)) {
$migrationFile = $possiblePath . "/" . $migration;
break;
}
}
if ($migrationFile === null) {
Logger::log("Could not find migration file for table " . $migrationTable . " version " . $migrationVersion, LOGGER::ERROR, "Database");
continue;
}
$migrationContents = file_get_contents($migrationFile);
2024-02-03 14:08:03 +01:00
if (@self::$handle->exec($migrationContents)) {
self::$handle->exec("INSERT INTO `migrations` (`table`,`version`, `schemafile`, `created`) VALUES ('" . $migrationTable . "'," . $migrationVersion . ",'" . $migration . "', strftime('%Y-%m-%d %H:%M:%S','now'))");
$migrationCount++;
} else {
Logger::log("Failed to run migration for table " . $migrationTable . " version " . $migrationVersion . " with error: " . self::$handle->lastErrorMsg(), LOGGER::ERROR, "Database");
}
}
}
if ($migrationCount > 0) {
Logger::log("Ran " . $migrationCount . " migrations", LOGGER::DEBUG, "Database");
} else {
Logger::log("No migrations to run", LOGGER::DEBUG, "Database");
}
}
public function close()
{
self::$handle->close();
}
}