Skip to content

Commit

Permalink
Merge branch 'feature/use-replace-into-for-pdo' into develop
Browse files Browse the repository at this point in the history
* feature/use-replace-into-for-pdo:
  Remove the now unused keyExists() function
  Use REPLACE INTO to combine two queries into one
  • Loading branch information
pmeulen committed Mar 4, 2024
2 parents f581bb5 + 44a1296 commit 5cf739b
Showing 1 changed file with 8 additions and 29 deletions.
37 changes: 8 additions & 29 deletions library/tiqr/Tiqr/StateStorage/Pdo.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,30 +110,6 @@ public function __construct(PDO $pdoInstance, LoggerInterface $logger, string $t
$this->logger = $logger;
}

/**
* @param string $key to lookup
* @return bool true when $key is found, false when the key does not exist
* @throws ReadWriteException
*/
private function keyExists(string $key): bool
{
if (empty($key)) {
throw new InvalidArgumentException('Empty key not allowed');
}
try {
$sth = $this->handle->prepare('SELECT `key` FROM ' . $this->tablename . ' WHERE `key` = ?');
$sth->execute(array($key));
return $sth->fetchColumn() !== false;
}
catch (Exception $e) {
$this->logger->error(
sprintf('Error checking for key "%s" in PDO StateStorage', $key),
array('exception' => $e)
);
throw ReadWriteException::fromOriginalException($e);
}
}

/**
* Remove expired keys
* This is a maintenance task that should be periodically run
Expand Down Expand Up @@ -167,11 +143,14 @@ public function setValue(string $key, $value, int $expire=0): void
if (((float) rand() /(float) getrandmax()) < $this->cleanupProbability) {
$this->cleanExpired();
}
if ($this->keyExists($key)) {
$sth = $this->handle->prepare("UPDATE ".$this->tablename." SET `value` = ?, `expire` = ? WHERE `key` = ?");
} else {
$sth = $this->handle->prepare("INSERT INTO ".$this->tablename." (`value`,`expire`,`key`) VALUES (?,?,?)");
}
// REPLACE INTO is mysql dialect. Supported by sqlite as well.
// This does:
// INSERT INTO tablename (`value`,`expire`,`key`) VALUES (?,?,?)
// ON CONFLICT UPDATE tablename SET `value`=?, `expire`=? WHERE `key`=?
// in pgsql "ON CONFLICT" is "ON DUPLICATE KEY"

$sth = $this->handle->prepare("REPLACE INTO ".$this->tablename." (`value`,`expire`,`key`) VALUES (?,?,?)");

// $expire == 0 means never expire
if ($expire != 0) {
$expire+=time(); // Store unix timestamp after which the key expires
Expand Down

0 comments on commit 5cf739b

Please sign in to comment.