index/src/Data/SQLite/SQLiteBackend.php

83 lines
2.5 KiB
PHP

<?php
// SQLiteBackend.php
// Created: 2021-05-02
// Updated: 2024-04-10
namespace Index\Data\SQLite;
use SQLite3;
use InvalidArgumentException;
use Index\Version;
use Index\Data\IDbBackend;
use Index\Data\IDbConnection;
use Index\Data\IDbConnectionInfo;
/**
* Information about the SQLite 3 database layer.
*/
class SQLiteBackend implements IDbBackend {
public function isAvailable(): bool {
return extension_loaded('sqlite3');
}
/**
* Gets the version of the underlying library.
*
* @return Version Version of the library.
*/
public function getVersion(): Version {
return Version::parse(SQLite3::version()['versionString']);
}
/**
* Creates a new SQLite client.
*
* @param SQLiteConnectionInfo $connectionInfo Object that describes the desired connection.
* @return SQLiteConnection A client for an SQLite database.
*/
public function createConnection(IDbConnectionInfo $connectionInfo): IDbConnection {
if(!($connectionInfo instanceof SQLiteConnectionInfo))
throw new InvalidArgumentException('$connectionInfo must by of type SQLiteConnectionInfo');
return new SQLiteConnection($connectionInfo);
}
/**
* Constructs a connection info instance from a dsn.
*
* SQLite DSNs have no username, password, host or port parts.
*
* The path can be set to any location on the filesystem to specify what file to use, or the special `:memory:` value to use an in-memory database.
*
* Supported query parameters are:
* - `key=<string>` to specify an encryption key.
* - `readOnly` to open a database in read-only mode.
* - `openOnly` to prevent a new file from being created if the specified path does not exist.
*
* @param string|array $dsn DSN with connection information.
* @return SQLiteConnectionInfo SQLite connection info.
*/
public function parseDsn(string|array $dsn): IDbConnectionInfo {
if(is_string($dsn)) {
$dsn = parse_url($dsn);
if($dsn === false)
throw new InvalidArgumentException('$dsn is not a valid uri.');
}
$encKey = '';
$path = $dsn['path'] ?? '';
if($path === 'memory:')
$path = ':memory:';
parse_str(str_replace('+', '%2B', $dsn['query'] ?? ''), $query);
$encKey = $query['key'] ?? '';
$readOnly = isset($query['readOnly']);
$create = !isset($query['openOnly']);
return new SQLiteConnectionInfo($path, $encKey, $readOnly, $create);
}
}