WIP on connection management

This commit is contained in:
2024-06-04 19:55:22 -04:00
parent afc5d80095
commit c2dc111dce
2 changed files with 18 additions and 17 deletions

View File

@@ -18,6 +18,7 @@ class Custom
* @param array $parameters The parameters for the query
* @param PDO $pdo The database connection on which the query should be run
* @return PDOStatement The result of executing the query
* @throws DocumentException If the query execution is unsuccessful
*/
public static function runQuery(string $query, array $parameters, PDO $pdo): PDOStatement
{
@@ -28,8 +29,9 @@ class Custom
$stmt->bindValue($key, $value);
}
if ($debug) echo '<pre>SQL: ' . $stmt->queryString . '</pre>';
$stmt->execute();
return $stmt;
if ($stmt->execute()) return $stmt;
$keyword = explode(' ', $query, 2)[0];
throw new DocumentException("Error executing $keyword statement: " . $stmt->errorCode());
}
/**
@@ -87,8 +89,12 @@ class Custom
*/
public static function nonQuery(string $query, array $parameters, ?PDO $pdo = null): void
{
$stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn());
if ($stmt->errorCode()) throw new DocumentException('Error executing command: ' . $stmt->errorCode());
try {
$stmt = self::runQuery($query, $parameters, is_null($pdo) ? $actualPDO = Configuration::dbConn() : $pdo);
$stmt = null;
} finally {
if (isset($actualPDO)) $actualPDO = null;
}
}
/**
@@ -105,9 +111,6 @@ class Custom
public static function scalar(string $query, array $parameters, Mapper $mapper, ?PDO $pdo = null): mixed
{
$stmt = self::runQuery($query, $parameters, $pdo ?? Configuration::dbConn());
if ($stmt->errorCode()) {
throw new DocumentException('Error retrieving scalar value: ' . $stmt->errorCode());
}
if ($stmt->rowCount() > 0) {
$first = $stmt->fetch(PDO::FETCH_NUM);
return $first ? $mapper->map($first) : false;