Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 17 additions & 3 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -691,6 +691,14 @@ 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->logger?->error('Commit without an open transaction was ignored', ['trace' => new RuntimeException()->getTraceAsString()]);

return;
}

if (!$this->connected) {
$this->dbconnect();
}
Expand All @@ -702,8 +710,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');
}
Expand All @@ -730,6 +738,12 @@ public function transactionCommit(): void
#[Override]
public function rollBack(): void
{
if ($this->numberOfOpenTransactions === 0) {
$this->logger?->warning('Rollback without an open transaction was ignored. This is expected right after a failed commit.', ['trace' => new RuntimeException()->getTraceAsString()]);

return;
}

if (!$this->connected) {
$this->dbconnect();
}
Expand All @@ -750,14 +764,14 @@ public function transactional(Closure $callback): mixed

try {
$callbackResult = $callback();

$this->commit();
} catch (Throwable $exception) {
$this->rollBack();

throw $exception;
}

$this->commit();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aber haben wir in der transactional nicht allg. das Problem, dass hier sowas wie die RedirectException nicht erkannt wird, bei einer RedirectException müsste ja ein commit passieren, im AGP haben wir das an den meisten stellen. Man kann natürlich auch hinterfragen, ob die RedirectException eine gute Idee ist, aber das würde hier dann auch ein rollback und kein commit erzeugen.

Wir bräuchten im DB Layer sonst ein marker interface was man bei der RedirectException implementieren kann und was dann hier auch verwendet wird.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point, aber ich glaube, das ist eigentlich ein eigenes Thema und evtl. möchte Roman da auch noch was zu sagen.

Das Rollback bei einer RedirectException im Callback gab es in transactional() ja auch schon vorher, der PR ändert daran nichts.
Beim Marker-Interface bin ich mir noch unsicher, weil das DB-Paket dann wissen müsste, dass eine Exception auch "Erfolg" bedeuten kann.
Ich schlage vor dafür einfach ein eigenes Ticket bzw. einen eigenen PR aufzumachen und dort zu klären, wie mit dem Redirect umgegangen wird.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Das eigentliche Problem ist doch, dass das AGP das falsch handhabt.
Es konnte sich ja im Grunde nur deshalb einschleichen weil das hier nicht laut kracht (wie es eigentlihc sein sollte, wie bei anderen ORM), sondern silent versucht wird irgnedwie drumrum zu arbeiten.
Sollten wir nicht darauf hinarbeiten dass das AGP gefixt wird, anstatt hier das stille Schlucken der Fehler noch weiter zu manifestieren?
Das führt ja auch zu nicht wirklcih gut vorhersehbarem Verhalten am Ende.

Vorschlag:

  • unausgleglichene commit/rollback hier als Error loggen und die nächste Zeti die Logeinträge im AGP dazu priorisiert abarbeiten
  • wenn die Fehler nicht mehr auftreten hier LAUT (Exception) krachen lassen, damit solche Fälle sich erst gar nicht mehr einschleichen.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ja, sehe ich eigentlich genauso, das Ignorieren soll ja nur der Übergang sein.
Ich habe den commit() ohne offene Transaktion jetzt als Error geloggt, dann taucht das auch auf und man kann die Stellen in core-ng nach und nach abarbeiten.
Wenn da nichts mehr kommt, lassen wir commit() richtig failen.
Den rollBack() habe ich erstmal als Warning gelassen, weil der nach einem fehlgeschlagenen Commit ja auch an korrekten Stellen auftritt.
Bevor der eine Exception wirft, müssten die Stellen mit try/commit/catch/rollBack halt erstmal auf transactional() umgestellt werden, aber da sind wir noch nciht.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@romankonz @micharoesler bin auch bei euch, dass das im AGP korrekt laufen muss, aber dafür ist ja auch das transactional dass der count immer clean ist. Das Problem mit der RedirectException ist aber ja noch separat, also im AGP wird transactional verwendet, in dem Closure wird AGP Code aufgerufen, der wirft eine RedirectException und dann gibts ein Rollback anstelle von einem Commit. Das ist auf jeden Fall ein Verhalten was wir fixen sollten.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ja, da hast du recht, das sollten wir auf jeden Fall fixen.

Ich würde das aber eigentlich im AGP lösen und nicht in der Library.
Wir haben ja schon eine eigene Database-Klasse, die von Connection erbt, da könnten wir transactional() überschreiben und bei einer RedirectException committen statt zurückrollen.
Dann greift das automatisch überall und die Library muss nichts von Redirects wissen.

Ich würde dafür ein eigenes Ticket bzw. einen eigenen PR aufmachen, aktuell ist auch keine Stelle betroffen, das hat sich Claude angeschaut.
Wäre das für dich ok, dann könnten wir den PR hier abschließen?


return $callbackResult;
}

Expand Down
9 changes: 8 additions & 1 deletion tests/ConnectionTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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();
Expand Down
161 changes: 161 additions & 0 deletions tests/ConnectionTransactionBalanceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
<?php

/*
* This file is part of the Artemeon Core - Web Application Framework.
*
* (c) Artemeon <www.artemeon.de>
*
* 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 testCommitWithoutOpenTransactionLogsAnErrorWithTheCaller(): void
{
$this->connection->commit();

$this->assertLogEntryPointsTo('error', '/^Commit without an open transaction/', __FUNCTION__);
}

public function testRollBackWithoutOpenTransactionLogsAWarningWithTheCaller(): void
{
$this->connection->rollBack();

$this->assertLogEntryPointsTo('warning', '/^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->getLogEntries('warning'));
}

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 assertLogEntryPointsTo(string $level, string $messagePattern, string $caller): void
{
$entries = $this->getLogEntries($level);

$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<array{level: mixed, message: string, context: array<mixed>}>
*/
private function getLogEntries(string $level): array
{
return array_values(array_filter(
self::getLogger()->records,
static fn (array $record): bool => $record['level'] === $level,
));
}

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;
}
}
33 changes: 33 additions & 0 deletions tests/RecordingLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

/*
* This file is part of the Artemeon Core - Web Application Framework.
*
* (c) Artemeon <www.artemeon.de>
*
* 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<array{level: mixed, message: string, context: array<mixed>}> */
public array $records = [];

/**
* @param array<mixed> $context
*/
#[Override]
public function log(mixed $level, string | Stringable $message, array $context = []): void
{
$this->records[] = ['level' => $level, 'message' => (string) $message, 'context' => $context];
}
}
Loading