102 lines
2.8 KiB
PHP
102 lines
2.8 KiB
PHP
<?php
|
|
|
|
namespace Ulmus\Common;
|
|
|
|
use PDO,
|
|
PDOStatement;
|
|
|
|
class PdoObject extends PDO {
|
|
|
|
public static ? string $dump = null;
|
|
|
|
public bool $executionStatus;
|
|
|
|
public function select(string $sql, array $parameters = []): PDOStatement
|
|
{
|
|
static::$dump && call_user_func_array(static::$dump, [ $sql, $parameters ]);
|
|
|
|
try {
|
|
if (false !== ( $statement = $this->prepare($sql) )) {
|
|
$statement = $this->execute($statement, $parameters, false);
|
|
$statement->setFetchMode(\PDO::FETCH_ASSOC);
|
|
|
|
return $statement;
|
|
}
|
|
}
|
|
catch (\PDOException $e) {
|
|
throw new \PdoException($e->getMessage() . " `$sql` with data:" . json_encode($parameters));
|
|
}
|
|
}
|
|
|
|
public function runQuery(string $sql, array $parameters = []): ? PDOStatement
|
|
{
|
|
static::$dump && call_user_func_array(static::$dump, [ $sql, $parameters ]);
|
|
|
|
try {
|
|
if (false !== ( $statement = $this->prepare($sql) )) {
|
|
return $this->execute($statement, $parameters, true);
|
|
}
|
|
}
|
|
catch (\PDOException $e) {
|
|
throw new \PdoException($e->getMessage() . " `$sql` with data:" . json_encode($parameters));
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public function runInsertQuery(array $filter, array $dataset)
|
|
{
|
|
return $this->runQuery($filter, $dataset);
|
|
}
|
|
|
|
public function runUpdateQuery(array $filter, array $dataset)
|
|
{
|
|
return $this->runQuery($filter, $dataset);
|
|
}
|
|
|
|
public function runDeleteQuery(string $sql, array $parameters = []): ? PDOStatement
|
|
{
|
|
return $this->runQuery($sql, $parameters);
|
|
}
|
|
|
|
public function execute(PDOStatement $statement, array $parameters = [], bool $commit = true): ? PDOStatement
|
|
{
|
|
$this->executionStatus = false;
|
|
|
|
try {
|
|
if ( ! $this->inTransaction() ) {
|
|
$this->beginTransaction();
|
|
}
|
|
|
|
$this->executionStatus = empty($parameters) ? $statement->execute() : $statement->execute($parameters);
|
|
|
|
if ( $this->executionStatus ) {
|
|
$statement->lastInsertId = $this->lastInsertId();
|
|
|
|
if ( $commit ) {
|
|
$this->commit();
|
|
}
|
|
|
|
return $statement;
|
|
}
|
|
else {
|
|
throw new \PDOException($statement->errorCode() . " - " . json_encode($statement->errorInfo()));
|
|
}
|
|
}
|
|
catch (\PDOException $e) {
|
|
$this->rollback();
|
|
|
|
throw $e;
|
|
}
|
|
catch (\Throwable $e) {
|
|
if ( function_exists("debogueur") ) {
|
|
debogueur($statement, $parameters, $commit);
|
|
}
|
|
|
|
throw $e;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
}
|