1
1
Fork 0
mirror of https://code.mensbeam.com/MensBeam/Arsse.git synced 2024-12-23 09:02:41 +00:00
Arsse/lib/Db/AbstractDriver.php

73 lines
2.4 KiB
PHP
Raw Normal View History

<?php
declare(strict_types=1);
namespace JKingWeb\NewsSync\Db;
2016-10-17 20:49:39 +00:00
use JKingWeb\DrUUID\UUID as UUID;
abstract class AbstractDriver implements Driver {
2017-02-16 20:29:42 +00:00
protected $transDepth = 0;
2017-02-16 20:29:42 +00:00
public function schemaVersion(): int {
try {
2017-03-09 22:14:26 +00:00
return (int) $this->query("SELECT value from newssync_settings where key is schema_version")->getValue();
} catch(Exception $e) {
2017-02-16 20:29:42 +00:00
return 0;
}
}
2017-02-16 20:29:42 +00:00
public function begin(): bool {
$this->exec("SAVEPOINT newssync_".(++$this->transDepth));
2017-02-16 20:29:42 +00:00
return true;
}
2017-02-16 20:29:42 +00:00
public function commit(bool $all = false): bool {
if($this->transDepth==0) return false;
if(!$all) {
$this->exec("RELEASE SAVEPOINT newssync_".($this->transDepth--));
2017-02-16 20:29:42 +00:00
} else {
$this->exec("COMMIT TRANSACTION");
$this->transDepth = 0;
2017-02-16 20:29:42 +00:00
}
return true;
}
2017-02-16 20:29:42 +00:00
public function rollback(bool $all = false): bool {
if($this->transDepth==0) return false;
if(!$all) {
$this->exec("ROLLBACK TRANSACTION TO SAVEPOINT newssync_".($this->transDepth));
2017-02-16 20:29:42 +00:00
// rollback to savepoint does not collpase the savepoint
$this->exec("RELEASE SAVEPOINT newssync_".($this->transDepth--));
2017-02-16 20:29:42 +00:00
} else {
$this->exec("ROLLBACK TRANSACTION");
$this->transDepth = 0;
}
return true;
}
2017-02-16 20:29:42 +00:00
public function lock(): bool {
if($this->schemaVersion() < 1) return true;
if($this->isLocked()) return false;
$uuid = UUID::mintStr();
2017-03-09 22:14:26 +00:00
try {
$this->prepare("INSERT INTO newssync_settings(key,value) values(?,?)", "str", "str")->run("lock", $uuid);
} catch(ExceptionInput $e) {
return false;
}
2017-02-16 20:29:42 +00:00
sleep(1);
2017-03-09 22:14:26 +00:00
return ($this->query("SELECT value from newssync_settings where key is 'lock'")->getValue() == $uuid);
2017-02-16 20:29:42 +00:00
}
2016-10-17 20:49:39 +00:00
2017-02-16 20:29:42 +00:00
public function unlock(): bool {
2017-03-10 02:39:42 +00:00
if($this->schemaVersion() < 1) return true;
2017-03-09 22:14:26 +00:00
$this->exec("DELETE from newssync_settings where key is 'lock'");
return true;
2017-02-16 20:29:42 +00:00
}
2016-10-17 20:49:39 +00:00
2017-02-16 20:29:42 +00:00
public function isLocked(): bool {
if($this->schemaVersion() < 1) return false;
2017-03-09 22:14:26 +00:00
return ($this->query("SELECT count(*) from newssync_settings where key is 'lock'")->getValue() > 0);
2017-02-16 20:29:42 +00:00
}
2016-10-17 20:49:39 +00:00
2017-02-16 20:29:42 +00:00
public function prepare(string $query, string ...$paramType): Statement {
return $this->prepareArray($query, $paramType);
}
}