1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-22 21:22:40 +00:00
Arsse/lib/Db/PDOStatement.php
J. King 4a1c23ba45 Munge PostgreSQL queries instead of adding explicit casts
PDO does not adequately inform PostgreSQL of a parameter's type, so type
casts are required. Rather than adding these to each query manually, the
queries are instead processed to add type hints automatically.

Unfortunately the queries are processed rather naively; question-mark
characters in string constants, identifiers, regex patterns, or geometry
operators will break things spectacularly.
2018-11-29 13:45:37 -05:00

55 lines
1.7 KiB
PHP

<?php
/** @license MIT
* Copyright 2017 J. King, Dustin Wilson et al.
* See LICENSE and AUTHORS files for details */
declare(strict_types=1);
namespace JKingWeb\Arsse\Db;
class PDOStatement extends AbstractStatement {
use PDOError;
const BINDINGS = [
"integer" => \PDO::PARAM_INT,
"float" => \PDO::PARAM_STR,
"datetime" => \PDO::PARAM_STR,
"binary" => \PDO::PARAM_LOB,
"string" => \PDO::PARAM_STR,
"boolean" => \PDO::PARAM_INT, // FIXME: using \PDO::PARAM_BOOL leads to incompatibilities with versions of SQLite bundled prior to PHP 7.3
];
protected $st;
protected $db;
public function __construct(\PDO $db, \PDOStatement $st, array $bindings = []) {
$this->db = $db;
$this->st = $st;
$this->retypeArray($bindings);
}
public function __destruct() {
unset($this->st, $this->db);
}
public function runArray(array $values = []): Result {
$this->st->closeCursor();
$this->bindValues($values);
try {
$this->st->execute();
} catch (\PDOException $e) {
list($excClass, $excMsg, $excData) = $this->exceptionBuild();
throw new $excClass($excMsg, $excData);
}
$changes = $this->st->rowCount();
try {
$lastId = ($changes) ? $this->db->lastInsertId() : 0;
} catch (\PDOException $e) { // @codeCoverageIgnore
$lastId = 0;
}
return new PDOResult($this->st, [$changes, $lastId]);
}
protected function bindValue($value, string $type, int $position): bool {
return $this->st->bindValue($position, $value, is_null($value) ? \PDO::PARAM_NULL : self::BINDINGS[$type]);
}
}