pohja/lib/Database.php

95 lines
2.7 KiB
PHP

<?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");
$migrationContents = file_get_contents(MIGRATIONS_DIR . "/" . $migration);
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();
}
}