diff --git a/src/Connection.php b/src/Connection.php index b837ae2..a36ddf3 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -13,6 +13,7 @@ use Generator; use PDO; use PDOStatement; +use Throwable; /** * Decorator for PDO instances. @@ -142,7 +143,15 @@ public function perform( array $values = [] ) : PDOStatement { - $sth = $this->prepare($statement); + try { + $sth = $this->prepare($statement); + } catch (Throwable $error) { + $this->addLogEntry( + $this->newLogEntry($statement, $error) + ); + + throw $error; + } foreach ($values as $name => $args) { $this->performBind($sth, $name, $args); @@ -180,9 +189,11 @@ protected function performBind( public function query(string $statement, mixed ...$fetch) : PDOStatement|false { $entry = $this->newLogEntry($statement); - $sth = $this->pdo->query($statement, ...$fetch); - $this->addLogEntry($entry); - return $sth; + try { + return $this->pdo->query($statement, ...$fetch); + } finally { + $this->addLogEntry($entry); + } } /* Fetching */ @@ -389,16 +400,17 @@ public function setQueryLogger(callable $queryLogger) : void $this->queryLogger = $queryLogger; } - protected function newLogEntry(?string $statement = null) : array + protected function newLogEntry(?string $statement = null, ?\Throwable $error = null) : array { return [ 'start' => microtime(true), 'finish' => null, 'duration' => null, - 'performed' => null, + 'performed' => $error ? false : null, 'statement' => $statement, 'values' => [], - 'trace' => null, + 'trace' => $error ? $error->getTrace() : null, + 'error' => $error, ]; } @@ -408,6 +420,10 @@ protected function addLogEntry(array $entry) : void return; } + if ($entry['error']) { + $entry['performed'] = false; + } + if ($entry['performed'] === null) { $entry['performed'] = true; } diff --git a/src/LoggedStatement.php b/src/LoggedStatement.php index 607f7c5..b6b15b5 100644 --- a/src/LoggedStatement.php +++ b/src/LoggedStatement.php @@ -20,13 +20,16 @@ protected function __construct( protected array $logEntry ) { $this->logEntry['statement'] = $this->queryString; + $this->logEntry['start'] = microtime(true); } public function execute(?array $inputParameters = null) : bool { - $result = parent::execute($inputParameters); - $this->log($inputParameters); - return $result; + try { + return parent::execute($inputParameters); + } finally { + $this->log($inputParameters); + } } public function bindValue(