Browse Source

Expose PDO::inTransaction() with DriverInterface

Corey Taylor 4 years ago
parent
commit
1b0b84c0ee

+ 12 - 0
src/Database/Driver.php

@@ -262,6 +262,18 @@ abstract class Driver implements DriverInterface
     }
 
     /**
+     * Returns whether a transaction is active for connection.
+     *
+     * @return bool
+     */
+    public function inTransaction(): bool
+    {
+        $this->connect();
+
+        return $this->_connection->inTransaction();
+    }
+
+    /**
      * @inheritDoc
      */
     public function supportsSavePoints(): bool

+ 1 - 0
src/Database/DriverInterface.php

@@ -26,6 +26,7 @@ use Closure;
  * @method int|null getMaxAliasLength() Returns the maximum alias length allowed.
  * @method int getConnectRetries() Returns the number of connection retry attempts made.
  * @method bool supports(string $feature) Checks whether a feature is supported by the driver.
+ * @method bool inTransaction() Returns whether a transaction is active.
  */
 interface DriverInterface
 {

+ 7 - 0
tests/TestCase/Database/ConnectionTest.php

@@ -528,15 +528,19 @@ class ConnectionTest extends TestCase
     public function testSimpleTransactions(): void
     {
         $this->connection->begin();
+        $this->assertTrue($this->connection->getDriver()->inTransaction());
         $this->connection->delete('things', ['id' => 1]);
         $this->connection->rollback();
+        $this->assertFalse($this->connection->getDriver()->inTransaction());
         $result = $this->connection->execute('SELECT * FROM things');
         $this->assertCount(2, $result);
         $result->closeCursor();
 
         $this->connection->begin();
+        $this->assertTrue($this->connection->getDriver()->inTransaction());
         $this->connection->delete('things', ['id' => 1]);
         $this->connection->commit();
+        $this->assertFalse($this->connection->getDriver()->inTransaction());
         $result = $this->connection->execute('SELECT * FROM things');
         $this->assertCount(1, $result);
     }
@@ -573,13 +577,16 @@ class ConnectionTest extends TestCase
         $this->connection->begin();
         $this->connection->begin();
         $this->connection->begin();
+        $this->assertTrue($this->connection->getDriver()->inTransaction());
 
         $this->connection->delete('things', ['id' => 1]);
         $result = $this->connection->execute('SELECT * FROM things');
         $this->assertCount(1, $result);
 
         $this->connection->commit();
+        $this->assertTrue($this->connection->getDriver()->inTransaction());
         $this->connection->rollback();
+        $this->assertFalse($this->connection->getDriver()->inTransaction());
 
         $result = $this->connection->execute('SELECT * FROM things');
         $this->assertCount(2, $result);