index/src/Data/SQLite/SQLiteStatement.php

101 lines
3.3 KiB
PHP

<?php
// SQLiteStatement.php
// Created: 2021-05-02
// Updated: 2022-02-16
namespace Index\Data\SQLite;
use SQLite3Result;
use SQLite3Stmt;
use InvalidArgumentException;
use RuntimeException;
use Index\Data\DbTools;
use Index\Data\DbType;
use Index\Data\QueryExecuteException;
use Index\Data\IDbStatement;
use Index\Data\IDbResult;
use Index\IO\Stream;
/**
* Represents a prepared SQLite SQL statement.
*/
class SQLiteStatement implements IDbStatement {
private SQLiteConnection $connection;
private SQLite3Stmt $statement;
private ?SQLite3Result $result = null;
/**
* Creates a new SQLiteStatement instance.
*
* @param SQLiteConnection $connection A reference to the connection which creates this statement.
* @param SQLite3Stmt $statement The raw statement instance.
* @return SQLiteStatement A new statement instance.
*/
public function __construct(SQLiteConnection $connection, SQLite3Stmt $statement) {
$this->connection = $connection;
$this->statement = $statement;
}
public function getParameterCount(): int {
return $this->statement->paramCount();
}
public function addParameter(int $ordinal, mixed $value, int $type = DbType::AUTO): void {
if($ordinal < 1 || $ordinal > $this->getParameterCount())
throw new InvalidArgumentException('$ordinal is not a valid parameter number.');
if($type === DbType::AUTO)
$type = DbTools::detectType($value);
switch($type) {
case DbType::NULL:
$value = null;
$type = SQLITE3_NULL;
break;
case DbType::INTEGER:
$type = SQLITE3_INTEGER;
break;
case DbType::FLOAT:
$type = SQLITE3_FLOAT;
break;
case DbType::STRING:
$type = SQLITE3_TEXT;
break;
case DbType::BLOB:
$type = SQLITE3_BLOB;
break;
default:
throw new InvalidArgumentException('$type is not a supported type.');
}
if(!$this->statement->bindValue($ordinal, $value, $type))
throw new QueryExecuteException((string)$this->connection->getLastErrorString(), $this->connection->getLastErrorCode());
}
public function getResult(): IDbResult {
if($this->result === null)
throw new RuntimeException('No result is available.');
return new SQLiteResult($this->result);
}
public function getLastInsertId(): int|string {
return $this->connection->getLastInsertId();
}
public function execute(): void {
$result = $this->statement->execute();
if($result === false)
throw new QueryExecuteException((string)$this->connection->getLastErrorString(), $this->connection->getLastErrorCode());
$this->result = $result;
}
public function reset(): void {
$this->result = null;
if(!$this->statement->clear())
throw new QueryExecuteException((string)$this->connection->getLastErrorString(), $this->connection->getLastErrorCode());
if(!$this->statement->reset())
throw new QueryExecuteException((string)$this->connection->getLastErrorString(), $this->connection->getLastErrorCode());
}
public function close(): void {}
}