Skip to content

Commit

Permalink
[Core] Fix loading of pselectRow queries
Browse files Browse the repository at this point in the history
Queries which use pselectRow that return data can fail to load with
an error about not being able to execute queries with pending results.

pselectRow does a count on the database connection, which executes
the query. When getFirstRow is called after, the query has already
been executed but the results have not been fetched when getIterator()
attempts to re-execute the query.

This keeps track of the execution state so that it is only executed
the first time.
  • Loading branch information
Dave MacFarlane committed Dec 4, 2024
1 parent e9d002c commit 88798a9
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/Database/Query.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,26 @@
class Query implements \Countable, \IteratorAggregate
{
protected \PDOStatement $stmt;
private bool $executed;

public function __construct(
protected \PDO $DB,
protected string $query,
protected array $params = [],
protected bool $buffered = true
) {
$this->stmt = $DB->prepare($query);
$this->stmt = $DB->prepare($query);
$this->executed = false;
}

public function count(): int
{
// PDOStatement->rowCount only works for buffered connections
if ($this->buffered == true) {
$this->stmt->execute($this->params);
if ($this->executed === false) {
$this->stmt->execute($this->params);
$this->executed = true;
}
return $this->stmt->rowCount();
} else {
$stmt = $this->DB->prepare("SELECT COUNT('x') FROM ({$this->query})");
Expand All @@ -32,14 +37,15 @@ public function getFirstRow() : array
{
$rows = $this->getIterator();
assert($rows instanceof \PDOStatement);
$val = $rows->fetch();
$rows->closeCursor();
return $val;
return $rows->fetch();
}

public function getIterator() : \Traversable
{
$this->stmt->execute($this->params);
if ($this->executed === false) {
$this->stmt->execute($this->params);
$this->executed = true;
}
return $this->stmt;
}
}

0 comments on commit 88798a9

Please sign in to comment.