DK2/src/database.php
2024-09-27 18:45:33 -05:00

80 lines
2.1 KiB
PHP

<?php
/**
* Return a connection to the auth database.
*/
function db_auth(): SQLite3
{
return $GLOBALS['db_auth'] ??= new SQLite3(__DIR__ . '/../database/auth.db');
}
/**
* Return a connection to the live database.
*/
function db_live(): SQLite3
{
return $GLOBALS['db_live'] ??= new SQLite3(__DIR__ . '/../database/live.db');
}
/**
* Return a connection to the fights database.
*/
function db_fights(): SQLite3
{
return $GLOBALS['db_fights'] ??= new SQLite3(__DIR__ . '/../database/fights.db');
}
/**
* Return a connection to the blueprints database.
*/
function db_blueprints(): SQLite3
{
return $GLOBALS['db_blueprints'] ??= new SQLite3(__DIR__ . '/../database/blueprints.db');
}
/**
* Take a SQLite3 database connection, a query string, and an array of parameters. Prepare the query and
* bind the parameters with proper type casting. Then execute the query and return the result.
*/
function db_query(SQLite3 $db, string $query, array $params = []): SQLite3Result|false
{
$stmt = $db->prepare($query);
if (!empty($params)) foreach ($params as $key => $value) $stmt->bindValue($key, $value, getSQLiteType($value));
$GLOBALS['queries']++;
return $stmt->execute();
}
/**
* Take a SQLite3 database connection and a query string. Execute the query and return the result.
*/
function db_exec(SQLite3 $db, string $query): bool
{
$GLOBALS['queries']++;
return $db->exec($query);
}
/**
* Take a SQLite3 database connection, a column name, and a value. Execute a COUNT query to see if the value
* exists in the column. Return true if the value exists, false otherwise.
*/
function db_exists(SQLite3 $db, string $table, string $column, mixed $value): bool
{
$result = db_query($db, "SELECT 1 FROM $table WHERE $column = :v LIMIT 1", [':v' => $value]);
return $result->fetchArray(SQLITE3_NUM) !== false;
}
/**
* Return the appropriate SQLite type casting for the value.
*/
function getSQLiteType(mixed $value): int
{
return match (true) {
is_int($value) => SQLITE3_INTEGER,
is_float($value) => SQLITE3_FLOAT,
is_null($value) => SQLITE3_NULL,
default => SQLITE3_TEXT
};
}