use inTransaction() instead of trying to maintain our own state

This commit is contained in:
Shish 2020-10-27 21:51:15 +00:00
parent e8561f6a04
commit 6c223d16bd

View file

@ -33,14 +33,6 @@ class Database
*/ */
private $engine = null; private $engine = null;
/**
* A boolean flag to track if we already have an active transaction.
* (ie: True if beginTransaction() already called)
*
* @var bool
*/
public $transaction = false;
/** /**
* How many queries this DB object has run * How many queries this DB object has run
*/ */
@ -53,13 +45,9 @@ class Database
private function connect_db(): void private function connect_db(): void
{ {
$this->db = new PDO($this->dsn, [ $this->db = new PDO($this->dsn);
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
$this->connect_engine(); $this->connect_engine();
$this->engine->init($this->db); $this->engine->init($this->db);
$this->begin_transaction(); $this->begin_transaction();
} }
@ -87,21 +75,19 @@ class Database
public function begin_transaction(): void public function begin_transaction(): void
{ {
if ($this->transaction === false) { if ($this->is_transaction_open() === false) {
$this->db->beginTransaction(); $this->db->beginTransaction();
$this->transaction = true;
} }
} }
public function is_transaction_open(): bool public function is_transaction_open(): bool
{ {
return !is_null($this->db) && $this->transaction === true; return !is_null($this->db) && $this->db->inTransaction();
} }
public function commit(): bool public function commit(): bool
{ {
if ($this->is_transaction_open()) { if ($this->is_transaction_open()) {
$this->transaction = false;
return $this->db->commit(); return $this->db->commit();
} else { } else {
throw new SCoreException("Unable to call commit() as there is no transaction currently open."); throw new SCoreException("Unable to call commit() as there is no transaction currently open.");
@ -111,7 +97,6 @@ class Database
public function rollback(): bool public function rollback(): bool
{ {
if ($this->is_transaction_open()) { if ($this->is_transaction_open()) {
$this->transaction = false;
return $this->db->rollback(); return $this->db->rollback();
} else { } else {
throw new SCoreException("Unable to call rollback() as there is no transaction currently open."); throw new SCoreException("Unable to call rollback() as there is no transaction currently open.");