index/src/Data/SQLite/SQLiteResult.php

90 lines
2.4 KiB
PHP

<?php
// SQLiteResult.php
// Created: 2021-05-02
// Updated: 2022-02-16
namespace Index\Data\SQLite;
use SQLite3Result;
use InvalidArgumentException;
use Index\AString;
use Index\WString;
use Index\Data\IDbResult;
use Index\IO\Stream;
use Index\IO\TempFileStream;
/**
* Represents an SQLite result set.
*/
class SQLiteResult implements IDbResult {
private SQLite3Result $result;
private array $currentRow = [];
/**
* Creates a new instance of SQLiteResult.
*
* @param SQLite3Result $result Raw underlying result class.
* @return SQLiteResult A new SQLiteResult instance.
*/
public function __construct(SQLite3Result $result) {
$this->result = $result;
}
/**
* Gets the number of columns per row in the result.
*
* @return int|string Number of columns in a row.
*/
public function getFieldCount(): int|string {
return $this->result->numColumns();
}
public function next(): bool {
$result = $this->result->fetchArray(SQLITE3_BOTH);
if($result === false)
return false;
$this->currentRow = $result;
return true;
}
public function isNull(int|string $index): bool {
return array_key_exists($index, $this->currentRow) && $this->currentRow[$index] === null;
}
public function getValue(int|string $index): mixed {
return $this->currentRow[$index] ?? null;
}
public function getString(int|string $index): string {
return strval($this->getValue($index));
}
public function getAString(int|string $index): AString {
return new AString($this->getString($index));
}
public function getWString(int|string $index, string $encoding): WString {
return new WString($this->getString($index), $encoding);
}
public function getInteger(int|string $index): int {
return intval($this->getValue($index));
}
public function getFloat(int|string $index): float {
return floatval($this->getValue($index));
}
/**
* Gets the value from the target index as a Stream.
* If you're aware that you're using SQLite it may make more sense to use SQLiteConnection::getBlobStream instead.
*/
public function getStream(int|string $index): ?Stream {
if($this->isNull($index))
return null;
return new TempFileStream($this->getValue($index));
}
public function close(): void {}
}