Added some of the database utilities from Misuzu to Index.

This commit is contained in:
Pachira 2023-07-21 20:11:02 +00:00
parent fc55b73ba1
commit 64d6bdca1f
3 changed files with 61 additions and 2 deletions

View file

@ -1 +1 @@
0.2307.211801
0.2307.212010

View file

@ -0,0 +1,44 @@
<?php
// DbStatementCache.php
// Created: 2023-07-21
// Updated: 2023-07-21
namespace Index\Data;
/**
* Container to avoid having many prepared instances of the same query.
*/
class DbStatementCache {
private IDbConnection $dbConn;
private array $stmts = [];
public function __construct(IDbConnection $dbConn) {
$this->dbConn = $dbConn;
}
private static function hash(string $query): string {
return hash('xxh3', $query, true);
}
public function get(string $query): IDbStatement {
$hash = self::hash($query);
if(array_key_exists($hash, $this->stmts)) {
$stmt = $this->stmts[$hash];
$stmt->reset();
return $stmt;
}
return $this->stmts[$hash] = $this->dbConn->prepare($query);
}
public function remove(string $query): void {
unset($this->stmts[self::hash($query)]);
}
public function clear(): void {
foreach($this->stmts as $stmt)
$stmt->close();
$this->stmts = [];
}
}

View file

@ -1,10 +1,11 @@
<?php
// DbTools.php
// Created: 2021-05-02
// Updated: 2023-07-11
// Updated: 2023-07-21
namespace Index\Data;
use Countable;
use InvalidArgumentException;
use Index\Type;
@ -114,4 +115,18 @@ final class DbTools {
return DbType::STRING;
return DbType::BLOB;
}
/**
* Constructs a partial query for prepared statements of lists.
*
* @param Countable|array|int $count Amount of times to repeat the string in the $repeat parameter.
* @param string $repeat String to repeat.
* @param string $glue Glue character.
* @return string Glued string ready for being thrown into your prepared statement.
*/
public static function prepareListString(Countable|array|int $count, string $repeat = '?', string $glue = ', '): string {
if(is_countable($count))
$count = count($count);
return implode($glue, array_fill(0, $count, $repeat));
}
}