death-notifier/src/main/php/Database.php

43 lines
1.0 KiB
PHP

<?php
namespace php;
use PDO;
/**
* Helper class for interacting with the database.
*/
class Database
{
/**
* Opens a connection with the database at `filename`.
*
* @param string $filename the path to the database to connect to
* @return PDO a PDO object that connects with the database
*/
public static function connect(string $filename): PDO
{
$conn = new PDO("sqlite:$filename", options: array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$conn->exec("PRAGMA foreign_keys = ON;");
return $conn;
}
/**
* Returns `true` if no tables exist in the database.
*
* @param PDO $conn the database connection to use to check
* @return bool `true` if no tables exist in the database
*/
public static function is_empty(PDO $conn): bool
{
$stmt = $conn->prepare("SELECT count(*) FROM sqlite_master WHERE type = 'table';");
$stmt->execute();
return $stmt->fetch()[0] === 0;
}
// TODO: Add version number, etc., and auto-migration
}