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
67 changes: 65 additions & 2 deletions system/Database/MySQLi/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,16 @@ class Connection extends BaseConnection
*/
public $foundRows = false;

/**
* InnoDB errno 1213 ended this transaction.
*/
private bool $transServerRolledBack = false;

/**
* The next statement must BEGIN before it runs.
*/
private bool $transNeedsServerRestart = false;

/**
* Connect to the database.
*
Expand Down Expand Up @@ -291,6 +301,18 @@ protected function execute(string $sql)
}

try {
// 1213 ended the server transaction. BEGIN again so this statement
// does not autocommit. A failed BEGIN stays pending. 1205 is unchanged:
// innodb_rollback_on_timeout decides that case.
if ($this->connID instanceof mysqli && $this->serverTransactionRestartPending()) {
// Exception reporting off: a failed BEGIN returns false.
if (! $this->connID->begin_transaction()) {
return false;
}

$this->transNeedsServerRestart = false;
}
Comment thread
michalsn marked this conversation as resolved.

return $this->connID->query($this->prepQuery($sql), $this->resultMode);
} catch (mysqli_sql_exception $e) {
log_message('error', "{message}\nin {exFile} on line {exLine}.\n{trace}", [
Expand All @@ -300,6 +322,10 @@ protected function execute(string $sql)
'trace' => render_backtrace($e->getTrace()),
]);

if ($e->getCode() === 1213 && $this->transDepth > 0) {
$this->markServerRolledBackTransaction();
}

if ($this->DBDebug) {
throw new DatabaseException($e->getMessage(), $e->getCode(), $e);
}
Expand Down Expand Up @@ -574,16 +600,53 @@ public function insertID(): int

protected function _transBegin(): bool
{
return $this->connID->begin_transaction();
if (! $this->connID->begin_transaction()) {
return false;
}

$this->clearDeadlockTransactionState();

return true;
}

protected function _transCommit(): bool
{
// mysqli::commit() returns true after 1213. End the transaction
// and report failure instead.
if ($this->transServerRolledBack) {
$this->transRollback();

return false;
}

return $this->connID->commit();
}

protected function _transRollback(): bool
{
return $this->connID->rollback();
if (! $this->connID->rollback()) {
return false;
}

$this->clearDeadlockTransactionState();

return true;
}

private function markServerRolledBackTransaction(): void
{
$this->transServerRolledBack = true;
$this->transNeedsServerRestart = true;
}

private function serverTransactionRestartPending(): bool
{
return $this->transNeedsServerRestart && $this->transDepth > 0;
}

private function clearDeadlockTransactionState(): void
{
$this->transServerRolledBack = false;
$this->transNeedsServerRestart = false;
}
}
Loading