2016-10-05 22:08:43 -04:00
|
|
|
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace JKingWeb\NewsSync\Db;
|
|
|
|
|
|
|
|
Trait CommonSQLite3 {
|
|
|
|
|
|
|
|
static public function driverName(): string {
|
|
|
|
return "SQLite 3";
|
|
|
|
}
|
|
|
|
|
2016-10-18 11:42:21 -04:00
|
|
|
public function schemaVersion(): int {
|
|
|
|
return $this->query("PRAGMA user_version")->getSingle();
|
2016-10-05 22:08:43 -04:00
|
|
|
}
|
|
|
|
|
2016-10-17 16:49:39 -04:00
|
|
|
public function update(int $to): bool {
|
|
|
|
$ver = $this->schemaVersion();
|
|
|
|
if(!$this->data->conf->dbSQLite3AutoUpd) throw new Update\Exception("manual", ['version' => $ver, 'driver_name' => $this->driverName()]);
|
|
|
|
if($ver >= $to) throw new Update\Exception("tooNew", ['difference' => ($ver - $to), 'current' => $ver, 'target' => $to, 'driver_name' => $this->driverName()]);
|
2016-10-15 09:45:23 -04:00
|
|
|
$sep = \DIRECTORY_SEPARATOR;
|
|
|
|
$path = \JKingWeb\NewsSync\BASE."sql".$sep."SQLite3".$sep;
|
2016-10-17 16:49:39 -04:00
|
|
|
$this->lock();
|
2016-10-15 09:45:23 -04:00
|
|
|
$this->begin();
|
2016-10-17 16:49:39 -04:00
|
|
|
for($a = $ver; $a < $to; $a++) {
|
|
|
|
$this->begin();
|
2016-10-18 11:42:21 -04:00
|
|
|
try {
|
|
|
|
$file = $path.$a.".sql";
|
2016-10-28 08:27:35 -04:00
|
|
|
if(!file_exists($file)) throw new Update\Exception("fileMissing", ['file' => $file, 'driver_name' => $this->driverName()]);
|
|
|
|
if(!is_readable($file)) throw new Update\Exception("fileUnreadable", ['file' => $file, 'driver_name' => $this->driverName()]);
|
2016-10-18 11:42:21 -04:00
|
|
|
$sql = @file_get_contents($file);
|
2016-10-28 08:27:35 -04:00
|
|
|
if($sql===false) throw new Update\Exception("fileUnusable", ['file' => $file, 'driver_name' => $this->driverName()]);
|
2016-10-18 11:42:21 -04:00
|
|
|
$this->exec($sql);
|
|
|
|
} catch(\Throwable $e) {
|
|
|
|
// undo any partial changes from the failed update
|
|
|
|
$this->rollback();
|
|
|
|
// commit any successful updates if updating by more than one version
|
|
|
|
$this->commit(true);
|
|
|
|
// throw the error received
|
|
|
|
throw $e;
|
2016-10-17 16:49:39 -04:00
|
|
|
}
|
|
|
|
$this->commit();
|
2016-10-15 09:45:23 -04:00
|
|
|
}
|
2016-10-17 16:49:39 -04:00
|
|
|
$this->unlock();
|
2016-10-15 09:45:23 -04:00
|
|
|
$this->commit();
|
2016-10-17 16:49:39 -04:00
|
|
|
return true;
|
2016-10-15 09:45:23 -04:00
|
|
|
}
|
|
|
|
|
2016-10-05 22:08:43 -04:00
|
|
|
public function exec(string $query): bool {
|
|
|
|
return (bool) $this->db->exec($query);
|
|
|
|
}
|
|
|
|
}
|