75 lines
2.1 KiB
PHP
75 lines
2.1 KiB
PHP
<?php
|
|
// SQLiteBackend.php
|
|
// Created: 2021-05-02
|
|
// Updated: 2022-02-28
|
|
|
|
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);
|
|
}
|
|
|
|
/**
|
|
* @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.');
|
|
}
|
|
|
|
$path = $dsn['path'] ?? '';
|
|
|
|
if($path === 'memory:')
|
|
$path = ':memory:';
|
|
|
|
if(!isset($dsn['query'])) {
|
|
$encKey = '';
|
|
$readOnly = false;
|
|
$create = true;
|
|
} else {
|
|
parse_str(str_replace('+', '%2B', $dsn['query']), $query);
|
|
|
|
$encKey = $query['key'] ?? '';
|
|
$readOnly = !empty($query['readOnly']);
|
|
$create = empty($query['openOnly']);
|
|
}
|
|
|
|
return new SQLiteConnectionInfo($path, $encKey, $readOnly, $create);
|
|
}
|
|
}
|