-
Notifications
You must be signed in to change notification settings - Fork 55
1.x #706
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughIntroduces resilient error handling in the PDO wrapper to detect lost connections, log, conditionally reconnect, and retry non-transactional calls. Updates unit tests to validate the retry-on-lost-connection behavior using mocks and reflection to simulate failure on first call and success after reconnection. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor Caller
participant Wrapper as PDO Wrapper
participant PDO as Inner \PDO
participant Conn as Connection
participant Log as Console
Caller->>Wrapper: invoke dynamic PDO method (e.g., query)
Wrapper->>PDO: call method
PDO-->>Wrapper: Throwable (lost connection)
Wrapper->>Conn: hasError(e)?
Conn-->>Wrapper: true
Wrapper->>Wrapper: inTransaction?
alt In transaction
Wrapper-->>Caller: rethrow error
else Not in transaction
Wrapper->>Log: warn(lost connection, will reconnect)
Wrapper->>Wrapper: reconnect()
Wrapper->>PDO: retry method
PDO-->>Wrapper: result
Wrapper-->>Caller: result
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✨ Finishing touches
🧪 Generate unit tests
Tip 👮 Agentic pre-merge checks are now available in preview!Pro plan users can now enable pre-merge checks in their settings to enforce checklists before merging PRs.
Please see the documentation for more information. Example: reviews:
pre_merge_checks:
custom_checks:
- name: "Undocumented Breaking Changes"
mode: "warning"
instructions: |
Pass/fail criteria: All breaking changes to public APIs, CLI flags, environment variables, configuration keys, database schemas, or HTTP/GraphQL endpoints must be documented in the "Breaking Change" section of the PR description and in CHANGELOG.md. Exclude purely internal or private changes (e.g., code not exported from package entry points or explicitly marked as internal).Please share your feedback with us on this Discord post. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (3)
src/Database/PDO.php (1)
6-6: Prefer PSR‑3 logger injection over static Console usage.Static Console writes to stdout and couples the library to CLI. Consider accepting an optional Psr\Log\LoggerInterface (default NullLogger) and log via it.
tests/unit/PDOTest.php (2)
44-81: Make the “lost connection” trigger deterministic against Connection::hasError().Using new \Exception("Lost connection") depends on detector heuristics. Throw a driver-typical PDOException (e.g., “server has gone away”) to avoid false negatives.
Apply this diff:
- ->will($this->onConsecutiveCalls( - $this->throwException(new \Exception("Lost connection")), - $pdoStatementMock - )); + ->will($this->onConsecutiveCalls( + $this->throwException(new \PDOException('SQLSTATE[HY000]: General error: 2006 MySQL server has gone away')), + $pdoStatementMock + ));
44-81: Add coverage: no retry when in a transaction and for commit/rollBack.Stub inTransaction() to true and assert:
- reconnect() is called once,
- query() is not retried,
- the original exception is rethrown.
Also add a test that commit() is not retried on lost connection.I can draft these tests if you want.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
src/Database/PDO.php(2 hunks)tests/unit/PDOTest.php(1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
src/Database/PDO.php (4)
src/Database/Connection.php (2)
Connection(7-38)hasError(22-37)src/Database/Adapter.php (1)
inTransaction(366-369)src/Database/Adapter/SQL.php (1)
reconnect(153-156)src/Database/Database.php (1)
reconnect(1225-1228)
tests/unit/PDOTest.php (1)
src/Database/PDO.php (1)
PDO(13-143)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Setup & Build Docker Image
| try { | ||
| return $this->pdo->{$method}(...$args); | ||
| } catch (\Throwable $e) { | ||
| if (Connection::hasError($e)) { | ||
| Console::warning('[Database] ' . $e->getMessage()); | ||
| Console::warning('[Database] Lost connection detected. Reconnecting...'); | ||
|
|
||
| $inTransaction = $this->pdo->inTransaction(); | ||
|
|
||
| // Attempt to reconnect | ||
| $this->reconnect(); | ||
|
|
||
| // If we weren't in a transaction, also retry the query | ||
| // In a transaction we can't retry as the state is attached to the previous connection | ||
| if (!$inTransaction) { | ||
| return $this->pdo->{$method}(...$args); | ||
| } | ||
| } | ||
|
|
||
| throw $e; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid unsafe retries; guard inTransaction() and never retry commit/rollBack.
- Don’t retry stateful methods like commit/rollBack; risk of double-commit or inconsistent state.
- inTransaction() can itself throw on a dead handle; default conservatively (no retry) if it does.
Apply this diff inside the catch block:
} catch (\Throwable $e) {
if (Connection::hasError($e)) {
Console::warning('[Database] ' . $e->getMessage());
Console::warning('[Database] Lost connection detected. Reconnecting...');
-
- $inTransaction = $this->pdo->inTransaction();
+ // Methods we will never retry to avoid duplicating side effects.
+ $methodLower = \strtolower($method);
+ $isRetryableMethod = !\in_array($methodLower, ['commit', 'rollback'], true);
+
+ // Safely detect transaction state; if uncertain, treat as in-transaction (no retry).
+ $inTransaction = true;
+ try {
+ $inTransaction = $this->pdo->inTransaction();
+ } catch (\Throwable $_) {
+ // keep $inTransaction = true
+ }
// Attempt to reconnect
$this->reconnect();
// If we weren't in a transaction, also retry the query
// In a transaction we can't retry as the state is attached to the previous connection
- if (!$inTransaction) {
+ if ($isRetryableMethod && !$inTransaction) {
return $this->pdo->{$method}(...$args);
}
}
throw $e;
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| try { | |
| return $this->pdo->{$method}(...$args); | |
| } catch (\Throwable $e) { | |
| if (Connection::hasError($e)) { | |
| Console::warning('[Database] ' . $e->getMessage()); | |
| Console::warning('[Database] Lost connection detected. Reconnecting...'); | |
| $inTransaction = $this->pdo->inTransaction(); | |
| // Attempt to reconnect | |
| $this->reconnect(); | |
| // If we weren't in a transaction, also retry the query | |
| // In a transaction we can't retry as the state is attached to the previous connection | |
| if (!$inTransaction) { | |
| return $this->pdo->{$method}(...$args); | |
| } | |
| } | |
| throw $e; | |
| } | |
| try { | |
| return $this->pdo->{$method}(...$args); | |
| } catch (\Throwable $e) { | |
| if (Connection::hasError($e)) { | |
| Console::warning('[Database] ' . $e->getMessage()); | |
| Console::warning('[Database] Lost connection detected. Reconnecting...'); | |
| // Methods we will never retry to avoid duplicating side effects. | |
| $methodLower = \strtolower($method); | |
| $isRetryableMethod = !\in_array($methodLower, ['commit', 'rollback'], true); | |
| // Safely detect transaction state; if uncertain, treat as in-transaction (no retry). | |
| $inTransaction = true; | |
| try { | |
| $inTransaction = $this->pdo->inTransaction(); | |
| } catch (\Throwable $_) { | |
| // keep $inTransaction = true | |
| } | |
| // Attempt to reconnect | |
| $this->reconnect(); | |
| // If we weren't in a transaction, also retry the query | |
| // In a transaction we can't retry as the state is attached to the previous connection | |
| if ($isRetryableMethod && !$inTransaction) { | |
| return $this->pdo->{$method}(...$args); | |
| } | |
| } | |
| throw $e; | |
| } |
Summary by CodeRabbit
Bug Fixes
Tests