1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-23 17:12:41 +00:00
Arsse/vendor/JKingWeb/NewsSync/Db/DriverSQLite3.php

59 lines
2.2 KiB
PHP
Raw Normal View History

2016-10-02 21:07:17 +00:00
<?php
declare(strict_types=1);
2016-10-02 21:07:17 +00:00
namespace JKingWeb\NewsSync\Db;
class DriverSQLite3 implements Driver {
use Common, CommonSQLite3 {
CommonSQLite3::schemaVersion insteadof Common;
}
2016-10-02 21:07:17 +00:00
protected $db;
2016-10-17 20:49:39 +00:00
protected $data;
2016-10-02 21:07:17 +00:00
2016-10-17 20:49:39 +00:00
private function __construct(\JKingWeb\NewsSync\RuntimeData $data, bool $install = false) {
$this->data = $data;
$file = $data->conf->dbSQLite3File;
// if the file exists (or we're initializing the database), try to open it and set initial options
try {
$this->db = new \SQLite3($file, ($install) ? \SQLITE3_OPEN_READWRITE | \SQLITE3_OPEN_CREATE : \SQLITE3_OPEN_READWRITE, $data->conf->dbSQLite3Key);
$this->db->enableExceptions(true);
$this->exec("PRAGMA journal_mode = wal");
$this->exec("PRAGMA foreign_keys = yes");
} catch(\Throwable $e) {
// if opening the database doesn't work, check various pre-conditions to find out what the problem might be
if(!file_exists($file)) {
if($install && !is_writable(dirname($file))) throw new Exception("fileUncreatable", dirname($file));
throw new Exception("fileMissing", $file);
}
if(!is_readable($file) && !is_writable($file)) throw new Exception("fileUnusable", $file);
if(!is_readable($file)) throw new Exception("fileUnreadable", $file);
if(!is_writable($file)) throw new Exception("fileUnwritable", $file);
// otherwise the database is probably corrupt
throw new Exception("fileCorrupt", $mainfile);
}
}
public function __destruct() {
$this->db->close();
unset($this->db);
}
2016-10-17 20:49:39 +00:00
static public function create(\JKingWeb\NewsSync\RuntimeData $data, bool $install = false): Driver {
2016-10-02 21:07:17 +00:00
// check to make sure required extensions are loaded
if(class_exists("SQLite3")) {
2016-10-17 20:49:39 +00:00
return new self($data, $install);
2016-10-02 21:07:17 +00:00
} else if(class_exists("PDO") && in_array("sqlite",\PDO::getAvailableDrivers())) {
2016-10-17 20:49:39 +00:00
return new DriverSQLite3PDO($data, $install);
2016-10-02 21:07:17 +00:00
} else {
throw new Exception("extMissing", self::driverName());
}
}
2016-10-17 20:49:39 +00:00
public function query(string $query): Result {
2016-11-19 14:44:13 +00:00
return new ResultSQLite3($this->db->query($query), $this->db->changes());
}
public function prepareArray(string $query, array $paramTypes): Statement {
2016-11-19 14:44:13 +00:00
return new StatementSQLite3($this->db, $this->db->prepare($query), $paramTypes);
2016-10-02 21:07:17 +00:00
}
}