From f11e665a2997c901a4355477b01784cf8cf64376 Mon Sep 17 00:00:00 2001 From: Micha Roesler Date: Fri, 27 Nov 2026 16:24:26 +0100 Subject: [PATCH 1/2] fix: Keep the transaction counter from dropping below zero --- src/Connection.php | 27 +++- tests/ConnectionTestCase.php | 9 +- tests/ConnectionTransactionBalanceTest.php | 161 +++++++++++++++++++++ tests/RecordingLogger.php | 33 +++++ 4 files changed, 226 insertions(+), 4 deletions(-) create mode 100644 tests/ConnectionTransactionBalanceTest.php create mode 100644 tests/RecordingLogger.php diff --git a/src/Connection.php b/src/Connection.php index be3472e6..e0d4a81d 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -691,6 +691,12 @@ public function transactionBegin(): void #[Override] public function commit(): void { + if ($this->numberOfOpenTransactions === 0) { + $this->logUnbalancedTransactionCall('Commit without an open transaction was ignored'); + + return; + } + if (!$this->connected) { $this->dbconnect(); } @@ -702,8 +708,8 @@ public function commit(): void if (!$this->currentTransactionIsDirty) { $this->dbDriver->commit(); } else { - $this->dbDriver->rollBack(); $this->currentTransactionIsDirty = false; + $this->dbDriver->rollBack(); throw new CommitException('Could not commit transaction because a rollback occurred inside a nested transaction, because of this we have have executed a rollback on the complete outer transaction which may result in data loss'); } @@ -730,6 +736,12 @@ public function transactionCommit(): void #[Override] public function rollBack(): void { + if ($this->numberOfOpenTransactions === 0) { + $this->logUnbalancedTransactionCall('Rollback without an open transaction was ignored. This is expected right after a failed commit.'); + + return; + } + if (!$this->connected) { $this->dbconnect(); } @@ -750,14 +762,14 @@ public function transactional(Closure $callback): mixed try { $callbackResult = $callback(); - - $this->commit(); } catch (Throwable $exception) { $this->rollBack(); throw $exception; } + $this->commit(); + return $callbackResult; } @@ -777,6 +789,15 @@ public function hasOpenTransactions(): bool return $this->numberOfOpenTransactions > 0; } + /** + * commit() and rollBack() ignore a call without an open transaction, because counting below zero would leave + * the connection without real transactions for the rest of the process. The trace points to the caller. + */ + private function logUnbalancedTransactionCall(string $message): void + { + $this->logger?->warning($message, ['trace' => new RuntimeException()->getTraceAsString()]); + } + /** * @inheritDoc */ diff --git a/tests/ConnectionTestCase.php b/tests/ConnectionTestCase.php index 8625a45b..5fbbb214 100644 --- a/tests/ConnectionTestCase.php +++ b/tests/ConnectionTestCase.php @@ -25,6 +25,8 @@ abstract class ConnectionTestCase extends TestCase { private static ?Connection $connection = null; + private static ?RecordingLogger $logger = null; + protected const string TEST_TABLE_NAME = 'agp_test_table'; #[\Override] @@ -58,11 +60,16 @@ protected function getConnection(): Connection $params = new ConnectionParameters($host, $user, $password, $database, $port, $driver); $factory = new DriverFactory(); - self::$connection = new Connection($params, $factory); + self::$connection = new Connection($params, $factory, self::getLogger()); return self::$connection; } + protected static function getLogger(): RecordingLogger + { + return self::$logger ??= new RecordingLogger(); + } + protected function flushDBCache(): void { $this->getConnection()->flushPreparedStatementsCache(); diff --git a/tests/ConnectionTransactionBalanceTest.php b/tests/ConnectionTransactionBalanceTest.php new file mode 100644 index 00000000..9adadcf5 --- /dev/null +++ b/tests/ConnectionTransactionBalanceTest.php @@ -0,0 +1,161 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Tests; + +use Artemeon\Database\Connection; +use Artemeon\Database\Exception\CommitException; +use Artemeon\Database\Schema\DataType; +use Exception; +use Override; + +/** + * @internal + */ +class ConnectionTransactionBalanceTest extends ConnectionTestCase +{ + private const string TABLE_NAME = 'agp_temp_autotest_balance'; + + private Connection $connection; + + #[Override] + protected function setUp(): void + { + parent::setUp(); + + $this->connection = $this->getConnection(); + $this->connection->createTable(self::TABLE_NAME, ['temp_id' => [DataType::CHAR20, false]], ['temp_id']); + self::getLogger()->records = []; + } + + #[Override] + protected function tearDown(): void + { + $this->connection->dropTable(self::TABLE_NAME); + + parent::tearDown(); + } + + public function testCommitWithoutOpenTransactionKeepsTheNextTransactionIntact(): void + { + $this->connection->commit(); + + $this->connection->beginTransaction(); + $this->insertRow(); + $this->connection->rollBack(); + + $this->assertSame(0, $this->countRows()); + } + + public function testRollBackWithoutOpenTransactionKeepsTheNextCommitIntact(): void + { + $this->connection->rollBack(); + + $this->connection->beginTransaction(); + $this->connection->beginTransaction(); + $this->insertRow(); + $this->connection->commit(); + $this->connection->commit(); + + $this->assertSame(1, $this->countRows()); + } + + public function testCommitWithoutOpenTransactionLogsAWarningWithTheCaller(): void + { + $this->connection->commit(); + + $this->assertWarningPointsTo('/^Commit without an open transaction/', __FUNCTION__); + } + + public function testRollBackWithoutOpenTransactionLogsAWarningWithTheCaller(): void + { + $this->connection->rollBack(); + + $this->assertWarningPointsTo('/^Rollback without an open transaction/', __FUNCTION__); + } + + public function testTransactionalDoesNotRollBackAfterItsOwnCommitFailed(): void + { + try { + $this->connection->transactional(function (): void { + $this->connection->beginTransaction(); + $this->connection->rollBack(); + }); + $this->fail('The nested rollback must make the commit fail.'); + } catch (CommitException) { + } + + $this->assertSame([], $this->getWarnings()); + } + + public function testFailingDriverRollbackOfADirtyCommitKeepsTheNextCommitIntact(): void + { + $this->connection->beginTransaction(); + $this->connection->beginTransaction(); + $this->connection->rollBack(); + // Ends the real transaction behind the connection's back, so that SQLite rejects the driver rollback + // of the dirty commit below. That rejected rollback is the case this test covers. + $this->connection->_pQuery('COMMIT'); + + // The SQLite3 extension also raises a PHP warning for the rejected statement. + set_error_handler(static fn (): bool => true, E_WARNING); + + try { + $this->connection->commit(); + } catch (Exception) { + // Depending on the driver, the rejected rollback or the CommitException ends the commit. + } finally { + restore_error_handler(); + } + + $this->connection->beginTransaction(); + $this->insertRow(); + $this->connection->commit(); + + $this->assertSame(1, $this->countRows()); + } + + private function assertWarningPointsTo(string $messagePattern, string $caller): void + { + $warnings = $this->getWarnings(); + + $this->assertCount(1, $warnings); + $this->assertMatchesRegularExpression($messagePattern, $warnings[0]['message']); + $this->assertIsString($warnings[0]['context']['trace'] ?? null); + $this->assertStringContainsString($caller, $warnings[0]['context']['trace']); + } + + /** + * @return list}> + */ + private function getWarnings(): array + { + return array_values(array_filter( + self::getLogger()->records, + static fn (array $record): bool => $record['level'] === 'warning', + )); + } + + private function insertRow(): void + { + $this->connection->insert(self::TABLE_NAME, ['temp_id' => $this->generateSystemid()]); + } + + private function countRows(): int + { + $count = $this->connection->fetchOne('SELECT COUNT(*) FROM ' . self::TABLE_NAME); + $this->assertIsNumeric($count); + + return (int) $count; + } +} diff --git a/tests/RecordingLogger.php b/tests/RecordingLogger.php new file mode 100644 index 00000000..1264af1c --- /dev/null +++ b/tests/RecordingLogger.php @@ -0,0 +1,33 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +declare(strict_types=1); + +namespace Artemeon\Database\Tests; + +use Override; +use Psr\Log\AbstractLogger; +use Stringable; + +final class RecordingLogger extends AbstractLogger +{ + /** @var list}> */ + public array $records = []; + + /** + * @param array $context + */ + #[Override] + public function log(mixed $level, string | Stringable $message, array $context = []): void + { + $this->records[] = ['level' => $level, 'message' => (string) $message, 'context' => $context]; + } +} From f08418c193f3f53aa1d259d7f5da60b424cc4ffc Mon Sep 17 00:00:00 2001 From: Micha Roesler Date: Mon, 30 Nov 2026 09:48:37 +0100 Subject: [PATCH 2/2] fix: Log a commit without an open transaction as an error --- src/Connection.php | 15 ++++---------- tests/ConnectionTransactionBalanceTest.php | 24 +++++++++++----------- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/src/Connection.php b/src/Connection.php index e0d4a81d..f3d5764a 100755 --- a/src/Connection.php +++ b/src/Connection.php @@ -691,8 +691,10 @@ public function transactionBegin(): void #[Override] public function commit(): void { + // Counting below zero would leave the connection without real transactions for the rest of the process, + // so an unbalanced call is ignored and logged with the trace of its caller. if ($this->numberOfOpenTransactions === 0) { - $this->logUnbalancedTransactionCall('Commit without an open transaction was ignored'); + $this->logger?->error('Commit without an open transaction was ignored', ['trace' => new RuntimeException()->getTraceAsString()]); return; } @@ -737,7 +739,7 @@ public function transactionCommit(): void public function rollBack(): void { if ($this->numberOfOpenTransactions === 0) { - $this->logUnbalancedTransactionCall('Rollback without an open transaction was ignored. This is expected right after a failed commit.'); + $this->logger?->warning('Rollback without an open transaction was ignored. This is expected right after a failed commit.', ['trace' => new RuntimeException()->getTraceAsString()]); return; } @@ -789,15 +791,6 @@ public function hasOpenTransactions(): bool return $this->numberOfOpenTransactions > 0; } - /** - * commit() and rollBack() ignore a call without an open transaction, because counting below zero would leave - * the connection without real transactions for the rest of the process. The trace points to the caller. - */ - private function logUnbalancedTransactionCall(string $message): void - { - $this->logger?->warning($message, ['trace' => new RuntimeException()->getTraceAsString()]); - } - /** * @inheritDoc */ diff --git a/tests/ConnectionTransactionBalanceTest.php b/tests/ConnectionTransactionBalanceTest.php index 9adadcf5..a7675efb 100644 --- a/tests/ConnectionTransactionBalanceTest.php +++ b/tests/ConnectionTransactionBalanceTest.php @@ -70,18 +70,18 @@ public function testRollBackWithoutOpenTransactionKeepsTheNextCommitIntact(): vo $this->assertSame(1, $this->countRows()); } - public function testCommitWithoutOpenTransactionLogsAWarningWithTheCaller(): void + public function testCommitWithoutOpenTransactionLogsAnErrorWithTheCaller(): void { $this->connection->commit(); - $this->assertWarningPointsTo('/^Commit without an open transaction/', __FUNCTION__); + $this->assertLogEntryPointsTo('error', '/^Commit without an open transaction/', __FUNCTION__); } public function testRollBackWithoutOpenTransactionLogsAWarningWithTheCaller(): void { $this->connection->rollBack(); - $this->assertWarningPointsTo('/^Rollback without an open transaction/', __FUNCTION__); + $this->assertLogEntryPointsTo('warning', '/^Rollback without an open transaction/', __FUNCTION__); } public function testTransactionalDoesNotRollBackAfterItsOwnCommitFailed(): void @@ -95,7 +95,7 @@ public function testTransactionalDoesNotRollBackAfterItsOwnCommitFailed(): void } catch (CommitException) { } - $this->assertSame([], $this->getWarnings()); + $this->assertSame([], $this->getLogEntries('warning')); } public function testFailingDriverRollbackOfADirtyCommitKeepsTheNextCommitIntact(): void @@ -125,24 +125,24 @@ public function testFailingDriverRollbackOfADirtyCommitKeepsTheNextCommitIntact( $this->assertSame(1, $this->countRows()); } - private function assertWarningPointsTo(string $messagePattern, string $caller): void + private function assertLogEntryPointsTo(string $level, string $messagePattern, string $caller): void { - $warnings = $this->getWarnings(); + $entries = $this->getLogEntries($level); - $this->assertCount(1, $warnings); - $this->assertMatchesRegularExpression($messagePattern, $warnings[0]['message']); - $this->assertIsString($warnings[0]['context']['trace'] ?? null); - $this->assertStringContainsString($caller, $warnings[0]['context']['trace']); + $this->assertCount(1, $entries); + $this->assertMatchesRegularExpression($messagePattern, $entries[0]['message']); + $this->assertIsString($entries[0]['context']['trace'] ?? null); + $this->assertStringContainsString($caller, $entries[0]['context']['trace']); } /** * @return list}> */ - private function getWarnings(): array + private function getLogEntries(string $level): array { return array_values(array_filter( self::getLogger()->records, - static fn (array $record): bool => $record['level'] === 'warning', + static fn (array $record): bool => $record['level'] === $level, )); }