Skip to content

Commit 2dc7af6

Browse files
Kevin Lopezcursoragent
andcommitted
fix: clear transaction state when reconnect() replaces the socket
The server rolls the open transaction back with the dead connection. Keeping transDepth and transStatus made transComplete() return true. Fixes #10648 Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent df8b96b commit 2dc7af6

4 files changed

Lines changed: 150 additions & 1 deletion

File tree

‎system/Database/BaseConnection.php‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -625,13 +625,24 @@ public function close()
625625
* Keep or establish the connection if no queries have been sent for
626626
* a length of time exceeding the server's idle timeout.
627627
*
628+
* A replaced socket is not in the transaction that was open on the old
629+
* one. The server has already rolled that work back. Clear the depth and
630+
* mark the transaction failed so transComplete() cannot report success.
631+
*
628632
* @return void
629633
*/
630634
public function reconnect()
631635
{
632636
if ($this->ping() === false) {
637+
$lostTransaction = $this->transDepth > 0;
638+
633639
$this->close();
634640
$this->initialize();
641+
642+
if ($lostTransaction) {
643+
$this->transDepth = 0;
644+
$this->transStatus = false;
645+
}
635646
}
636647
}
637648

Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database\Live;
15+
16+
use CodeIgniter\Test\CIUnitTestCase;
17+
use CodeIgniter\Test\DatabaseTestTrait;
18+
use Config\Database;
19+
use PHPUnit\Framework\Attributes\Group;
20+
21+
/**
22+
* @internal
23+
*/
24+
#[Group('DatabaseLive')]
25+
final class ReconnectDuringTransactionTest extends CIUnitTestCase
26+
{
27+
use DatabaseTestTrait;
28+
29+
protected $migrate = false;
30+
31+
protected function setUp(): void
32+
{
33+
// Dedicated connection so a forced wait_timeout cannot drop the shared one.
34+
$this->db = Database::connect($this->DBGroup, false);
35+
36+
parent::setUp();
37+
}
38+
39+
public function testReconnectInsideTransactionDoesNotReportSuccess(): void
40+
{
41+
if ($this->db->DBDriver !== 'MySQLi') {
42+
$this->markTestSkipped('Requires the MySQLi driver.');
43+
}
44+
45+
$table = $this->db->escapeIdentifier($this->db->prefixTable('reconnect_probe'));
46+
$this->db->query('DROP TABLE IF EXISTS ' . $table);
47+
$this->db->query(
48+
'CREATE TABLE ' . $table . ' ('
49+
. 'id INT NOT NULL AUTO_INCREMENT, '
50+
. 'note VARCHAR(32) NOT NULL, '
51+
. 'PRIMARY KEY (id)'
52+
. ') ENGINE=InnoDB',
53+
);
54+
55+
$observer = Database::connect($this->DBGroup, false);
56+
$observer->initialize();
57+
58+
try {
59+
$this->db->transStart();
60+
$this->db->table('reconnect_probe')->insert(['note' => 'before-timeout']);
61+
$this->assertSame(1, $this->db->transDepth);
62+
$this->assertTrue($this->db->transStatus());
63+
64+
$this->db->query('SET SESSION wait_timeout = 1');
65+
sleep(3);
66+
67+
$this->assertFalse($this->db->ping(), 'Precondition: the server should have closed the idle socket.');
68+
69+
$this->db->reconnect();
70+
71+
$depthAfterReconnect = $this->db->transDepth;
72+
$statusAfterReconnect = $this->db->transStatus();
73+
$completed = $this->db->transComplete();
74+
$rows = (int) $observer->table('reconnect_probe')->countAllResults();
75+
76+
$this->assertSame(
77+
['depth' => 0, 'status' => false, 'completed' => false, 'rows' => 0],
78+
[
79+
'depth' => $depthAfterReconnect,
80+
'status' => $statusAfterReconnect,
81+
'completed' => $completed,
82+
'rows' => $rows,
83+
],
84+
);
85+
} finally {
86+
if ($this->db->transDepth > 0) {
87+
$this->db->transRollback();
88+
}
89+
90+
$this->db->query('DROP TABLE IF EXISTS ' . $table);
91+
$observer->close();
92+
$this->db->close();
93+
}
94+
}
95+
96+
public function testReconnectKeepsAnOpenTransactionWhenTheSocketIsAlive(): void
97+
{
98+
if ($this->db->DBDriver !== 'MySQLi') {
99+
$this->markTestSkipped('Requires the MySQLi driver.');
100+
}
101+
102+
$table = $this->db->escapeIdentifier($this->db->prefixTable('reconnect_probe'));
103+
$this->db->query('DROP TABLE IF EXISTS ' . $table);
104+
$this->db->query(
105+
'CREATE TABLE ' . $table . ' ('
106+
. 'id INT NOT NULL AUTO_INCREMENT, '
107+
. 'note VARCHAR(32) NOT NULL, '
108+
. 'PRIMARY KEY (id)'
109+
. ') ENGINE=InnoDB',
110+
);
111+
112+
try {
113+
$this->db->transStart();
114+
$this->db->table('reconnect_probe')->insert(['note' => 'still-open']);
115+
$this->assertTrue($this->db->ping());
116+
117+
$this->db->reconnect();
118+
119+
$this->assertSame(1, $this->db->transDepth);
120+
$this->assertTrue($this->db->transStatus());
121+
$this->assertTrue($this->db->transComplete());
122+
$this->assertSame(1, $this->db->table('reconnect_probe')->countAllResults());
123+
} finally {
124+
if ($this->db->transDepth > 0) {
125+
$this->db->transRollback();
126+
}
127+
128+
$this->db->query('DROP TABLE IF EXISTS ' . $table);
129+
$this->db->close();
130+
}
131+
}
132+
}

‎user_guide_src/source/changelogs/v4.7.6.rst‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ Deprecations
3232
Bugs Fixed
3333
**********
3434

35+
- **Database:** Fixed ``reconnect()`` so a replaced socket does not keep the
36+
transaction that died with the old connection. ``transDepth`` is cleared and
37+
the transaction status is failed, so ``transComplete()`` does not report
38+
success. See `#10648 <https://github.com/codeigniter4/CodeIgniter4/issues/10648>`_.
3539
- **Commands:** Fixed a bug where generator commands did not sort the imports of a template with CRLF line endings.
3640
- **Format:** Fixed ``XMLFormatter`` so that an array key that becomes empty after
3741
sanitization no longer triggers a ``ValueError``; the fallback tag name ``item``

‎user_guide_src/source/database/connecting.rst‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,9 @@ which can gracefully keep the connection alive or re-establish it.
9999

100100
The ``reconnect()`` method pings the server to check if the connection is still
101101
alive. If the connection has been lost, it will close and re-establish the
102-
connection.
102+
connection. An open transaction ends with the old connection. ``reconnect()``
103+
clears the transaction depth and marks the transaction failed, so
104+
``transComplete()`` does not report success.
103105

104106
.. literalinclude:: connecting/007.php
105107
:lines: 2-

0 commit comments

Comments
 (0)