Skip to content

Commit 3896c8c

Browse files
committed
test(Database): fix state leaks and random-order test determinism for MySQLi, PostgreSQL, and OCI8
Fixes database tests to be deterministic under random execution order for MySQLi, PostgreSQL, and OCI8 drivers. Ref #9968. - Fix random-order test execution issues and state leakage under PostgreSQL, MySQL, and OCI8 - Isolate per-component database schemas for parallel random-test runs - Prefer PRIMARY key over UNIQUE index in PostgreSQL upsert constraint selection - Drop team_members and migrations_lock tables during teardowns - Reset and isolate custom connection instances with non-shared connections - Exclude Oracle from parallel random-test matrix due to shared schema collisions - Optimize SQLSRV test database settings with RECOVERY SIMPLE and DELAYED_DURABILITY
1 parent df8b96b commit 3896c8c

14 files changed

Lines changed: 244 additions & 52 deletions

File tree

‎.github/scripts/random-tests-config.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ Config
1818
Cookie
1919
# DataCaster
2020
# DataConverter
21-
# Database
21+
Database
2222
# Debug
2323
Email
2424
# Encryption

‎.github/workflows/test-random-execution.yml‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,10 @@ jobs:
7575
- Postgre
7676
- SQLSRV
7777
- SQLite3
78-
- Oracle
78+
# Oracle is excluded: OCI8 uses a single shared schema via DSN
79+
# and cannot be isolated with per-component databases, causing
80+
# ORA-00955 collisions when components run in parallel.
81+
# - Oracle
7982

8083
services:
8184
mysql:
@@ -165,7 +168,7 @@ jobs:
165168
sqlcmd -S 127.0.0.1 \
166169
-U sa -P 1Secure*Password1 \
167170
-N -C \
168-
-Q "CREATE DATABASE test COLLATE Latin1_General_100_CS_AS_SC_UTF8"
171+
-Q "CREATE DATABASE test COLLATE Latin1_General_100_CS_AS_SC_UTF8; ALTER DATABASE test SET RECOVERY SIMPLE, DELAYED_DURABILITY = FORCED;"
169172
170173
- name: Checkout
171174
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -177,7 +180,7 @@ jobs:
177180
uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # 2.40.0
178181
with:
179182
php-version: ${{ matrix.php-version }}
180-
extensions: gd, curl, iconv, json, mbstring, openssl, sodium
183+
extensions: gd, curl, iconv, json, mbstring, openssl, sodium, mysqli, oci8, pgsql, sqlsrv, pdo_sqlsrv, sqlite3
181184
ini-values: opcache.enable_cli=0
182185
coverage: none
183186

‎system/Database/Postgre/Builder.php‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -509,13 +509,25 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri
509509
$constraints = $this->QBOptions['constraints'] ?? [];
510510

511511
if ($constraints === []) {
512-
$allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool {
512+
$tableIndexes = $this->db->getIndexData($table);
513+
514+
$uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool {
513515
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
514516

515-
return ($index->type === 'UNIQUE' || $index->type === 'PRIMARY') && $hasAllFields;
517+
return $index->type === 'PRIMARY' && $hasAllFields;
516518
});
517519

518-
foreach ($allIndexes as $index) {
520+
// if no primary found then look for unique - since indexes have no order
521+
if ($uniqueIndexes === []) {
522+
$uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool {
523+
$hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields);
524+
525+
return $index->type === 'UNIQUE' && $hasAllFields;
526+
});
527+
}
528+
529+
// only take first index
530+
foreach ($uniqueIndexes as $index) {
519531
$constraints = $index->fields;
520532
break;
521533
}

‎tests/_support/Config/Registrar.php‎

Lines changed: 68 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@
1313

1414
namespace Tests\Support\Config;
1515

16+
use mysqli;
17+
use PDO;
18+
use Throwable;
19+
1620
/**
1721
* Class Registrar
1822
*
@@ -137,7 +141,70 @@ public static function Database(): array
137141
// so that we can test against multiple databases.
138142
$group = env('DB', 'SQLite3');
139143

140-
$config['tests'] = self::$dbConfig[$group] ?? [];
144+
if ($group === 'Oracle') {
145+
$group = 'OCI8';
146+
}
147+
148+
$dbParams = self::$dbConfig[$group] ?? [];
149+
150+
if (! empty($dbParams) && ! in_array($group, ['SQLite3', 'OCI8'], true)) {
151+
$componentName = '';
152+
153+
foreach ($_SERVER['argv'] ?? [] as $arg) {
154+
if (str_contains($arg, 'tests/system/')) {
155+
$parts = explode('tests/system/', $arg);
156+
if (isset($parts[1])) {
157+
$componentName = explode('/', $parts[1])[0];
158+
break;
159+
}
160+
}
161+
}
162+
163+
if ($componentName !== '') {
164+
$dbParams['database'] = 'test_' . strtolower($componentName);
165+
166+
try {
167+
if ($group === 'MySQLi') {
168+
$conn = new mysqli(
169+
$dbParams['hostname'],
170+
$dbParams['username'],
171+
$dbParams['password'],
172+
'',
173+
(int) $dbParams['port'],
174+
);
175+
if (! $conn->connect_error) {
176+
$dbName = '`' . str_replace('`', '``', $dbParams['database']) . '`';
177+
$conn->query('CREATE DATABASE IF NOT EXISTS ' . $dbName);
178+
$conn->close();
179+
}
180+
} elseif ($group === 'Postgre') {
181+
$dsn = 'pgsql:host=' . $dbParams['hostname'] . ';port=' . $dbParams['port'] . ';user=' . $dbParams['username'] . ';password=' . $dbParams['password'];
182+
$pdo = new PDO($dsn);
183+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
184+
$stmt = $pdo->prepare('SELECT 1 FROM pg_database WHERE datname = ?');
185+
$stmt->execute([$dbParams['database']]);
186+
if (! $stmt->fetchColumn()) {
187+
$dbName = str_replace('"', '""', $dbParams['database']);
188+
$pdo->exec('CREATE DATABASE "' . $dbName . '"');
189+
}
190+
} elseif ($group === 'SQLSRV') {
191+
$dsn = 'sqlsrv:Server=' . $dbParams['hostname'] . ',' . $dbParams['port'] . ';Encrypt=False;TrustServerCertificate=True';
192+
$pdo = new PDO($dsn, $dbParams['username'], $dbParams['password']);
193+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
194+
$stmt = $pdo->prepare('SELECT 1 FROM sys.databases WHERE name = ?');
195+
$stmt->execute([$dbParams['database']]);
196+
if (! $stmt->fetchColumn()) {
197+
$escapedDb = str_replace(']', ']]', $dbParams['database']);
198+
$pdo->exec('CREATE DATABASE [' . $escapedDb . '] COLLATE Latin1_General_100_CS_AS_SC_UTF8; ALTER DATABASE [' . $escapedDb . '] SET RECOVERY SIMPLE, DELAYED_DURABILITY = FORCED');
199+
}
200+
}
201+
} catch (Throwable) {
202+
// Ignore any error and let the connection fail naturally
203+
}
204+
}
205+
}
206+
207+
$config['tests'] = $dbParams;
141208

142209
return $config;
143210
}

‎tests/_support/Database/Migrations/20160428212500_Create_test_tables.php‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace Tests\Support\Database\Migrations;
1515

1616
use CodeIgniter\Database\Migration;
17+
use Throwable;
1718

1819
class Migration_Create_test_tables extends Migration
1920
{
@@ -183,6 +184,7 @@ public function down(): void
183184
$this->forge->dropTable('user', true);
184185
$this->forge->dropTable('job', true);
185186
$this->forge->dropTable('misc', true);
187+
$this->forge->dropTable('team_members', true);
186188
$this->forge->dropTable('type_test', true);
187189
$this->forge->dropTable('empty', true);
188190
$this->forge->dropTable('secondary', true);
@@ -196,9 +198,25 @@ public function down(): void
196198
}
197199

198200
if ($this->db->DBDriver === 'OCI8') {
199-
$this->db->query('DROP PROCEDURE one');
200-
$this->db->query('DROP PROCEDURE plus');
201-
$this->db->query('DROP PACKAGE BODY calculator');
201+
try {
202+
$this->db->query('DROP PROCEDURE one');
203+
} catch (Throwable) {
204+
}
205+
206+
try {
207+
$this->db->query('DROP PROCEDURE plus');
208+
} catch (Throwable) {
209+
}
210+
211+
try {
212+
$this->db->query('DROP PACKAGE BODY calculator');
213+
} catch (Throwable) {
214+
}
215+
216+
try {
217+
$this->db->query('DROP PACKAGE calculator');
218+
} catch (Throwable) {
219+
}
202220
}
203221
}
204222
}

‎tests/system/Database/Live/ConnectTest.php‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -57,19 +57,28 @@ protected function setUp(): void
5757
$this->group2['DBDriver'] = 'Postgre';
5858
}
5959

60+
protected function tearDown(): void
61+
{
62+
parent::tearDown();
63+
$this->setPrivateProperty(Database::class, 'instances', []);
64+
}
65+
6066
public function testConnectWithMultipleCustomGroups(): void
6167
{
68+
$this->group1['DBPrefix'] = uniqid('g1_', true);
69+
$this->group2['DBPrefix'] = uniqid('g2_', true);
70+
6271
// We should have our test database connection already.
63-
$instances = $this->getPrivateProperty(Database::class, 'instances');
64-
$this->assertCount(1, $instances);
72+
$instances = $this->getPrivateProperty(Database::class, 'instances');
73+
$initialCount = count($instances);
6574

6675
$db1 = Database::connect($this->group1);
6776
$db2 = Database::connect($this->group2);
6877

6978
$this->assertNotSame($db1, $db2);
7079

7180
$instances = $this->getPrivateProperty(Database::class, 'instances');
72-
$this->assertCount(3, $instances);
81+
$this->assertCount($initialCount + 2, $instances);
7382
}
7483

7584
public function testConnectReturnsProvidedConnection(): void

‎tests/system/Database/Live/ExecuteLogMessageFormatTest.php‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public function testLogMessageWhenExecuteFailsShowFullStructuredBacktrace(): voi
4747
$db->query($sql, [3, 'live', 'Rick']);
4848

4949
$pattern = match ($db->DBDriver) {
50-
'MySQLi' => '/Table \'test\.some_table\' doesn\'t exist/',
50+
'MySQLi' => '/Table \'' . preg_quote($db->database, '/') . '\.some_table\' doesn\'t exist/',
5151
'Postgre' => '/pg_query\(\): Query failed: ERROR: relation "some_table" does not exist/',
5252
'SQLite3' => '/Unable to prepare statement:\s(\d+,\s)?no such table: some_table/',
5353
'OCI8' => '/oci_execute\(\): ORA-00942: table or view "ORACLE"\."SOME_TABLE" does not exist/',
@@ -60,11 +60,18 @@ public function testLogMessageWhenExecuteFailsShowFullStructuredBacktrace(): voi
6060

6161
if ($db->DBDriver === 'Postgre') {
6262
$messageFromLogs = array_slice($messageFromLogs, 2);
63-
} elseif ($db->DBDriver === 'OCI8') {
64-
$messageFromLogs = array_slice($messageFromLogs, 1);
6563
}
6664

67-
$this->assertMatchesRegularExpression('/^in \S+ on line \d+\.$/', array_shift($messageFromLogs));
65+
$inLine = null;
66+
67+
while (($line = array_shift($messageFromLogs)) !== null) {
68+
if (preg_match('/^in \S+ on line \d+\.$/', $line)) {
69+
$inLine = $line;
70+
break;
71+
}
72+
}
73+
74+
$this->assertNotNull($inLine, 'Could not find "in ... on line ..." in log message');
6875

6976
foreach ($messageFromLogs as $line) {
7077
$this->assertMatchesRegularExpression('/^\s*\d* .+(?:\(\d+\))?: \S+(?:(?:\->|::)\S+)?\(.*\)$/', $line);

‎tests/system/Database/Live/ForgeTest.php‎

Lines changed: 57 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,25 +36,64 @@ final class ForgeTest extends CIUnitTestCase
3636
protected $seed = CITestSeeder::class;
3737
private Forge $forge;
3838

39+
private function dropAllMockTables(): void
40+
{
41+
$tablesToDrop = [
42+
'forge_test_invoices',
43+
'forge_test_inv',
44+
'forge_test_users',
45+
'actions',
46+
'forge_test_table',
47+
'test_exists',
48+
'forge_test_attributes',
49+
'forge_array_constraint',
50+
'forge_nullable_table',
51+
'forge_test_1',
52+
'forge_test_two',
53+
'forge_test_three',
54+
'forge_test_four',
55+
'forge_test_modify',
56+
'droptest',
57+
'key_test_users',
58+
'test_stores',
59+
'user2',
60+
'forge_test_table_dummy',
61+
];
62+
63+
foreach ($tablesToDrop as $table) {
64+
$this->forge->dropTable($table, true);
65+
}
66+
}
67+
3968
protected function setUp(): void
4069
{
4170
$this->forge = Database::forge($this->DBGroup);
4271

43-
// when running locally if one of these tables isn't dropped it may cause error
44-
$this->forge->dropTable('forge_test_invoices', true);
45-
$this->forge->dropTable('forge_test_inv', true);
46-
$this->forge->dropTable('forge_test_users', true);
47-
$this->forge->dropTable('actions', true);
72+
$this->dropAllMockTables();
73+
74+
db_connect($this->DBGroup)->resetDataCache();
4875

4976
parent::setUp();
5077
}
5178

79+
protected function tearDown(): void
80+
{
81+
parent::tearDown();
82+
$this->dropAllMockTables();
83+
}
84+
5285
public function testCreateDatabase(): void
5386
{
5487
if ($this->db->DBDriver === 'OCI8') {
5588
$this->markTestSkipped('OCI8 does not support create database.');
5689
}
5790

91+
try {
92+
$this->forge->dropDatabase('test_forge_database');
93+
} catch (DatabaseException) {
94+
// Ignore if doesn't exist
95+
}
96+
5897
$databaseCreated = $this->forge->createDatabase('test_forge_database');
5998

6099
$this->assertTrue($databaseCreated);
@@ -68,14 +107,20 @@ public function testCreateDatabaseWithDots(): void
68107

69108
$dbName = 'test_com.sitedb.web';
70109

110+
try {
111+
$this->forge->dropDatabase($dbName);
112+
} catch (DatabaseException) {
113+
// Ignore if doesn't exist
114+
}
115+
71116
$databaseCreated = $this->forge->createDatabase($dbName);
72117

73118
$this->assertTrue($databaseCreated);
74119

75120
// Checks if tableExists() works.
76121
$config = config(Database::class)->{$this->DBGroup};
77122
$config['database'] = $dbName;
78-
$db = db_connect($config);
123+
$db = db_connect($config, false);
79124
$result = $db->tableExists('not_exist');
80125

81126
$this->assertFalse($result);
@@ -151,6 +196,12 @@ public function testDropDatabase(): void
151196
$this->markTestSkipped('SQLite3 requires file path to drop database');
152197
}
153198

199+
try {
200+
$this->forge->createDatabase('test_forge_database');
201+
} catch (DatabaseException) {
202+
// Ignore if exists
203+
}
204+
154205
$databaseDropped = $this->forge->dropDatabase('test_forge_database');
155206

156207
$this->assertTrue($databaseDropped);

‎tests/system/Database/Live/MetadataTest.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ protected function setUp(): void
3838
{
3939
parent::setUp();
4040

41+
Database::forge($this->DBGroup)->dropTable('migrations_lock', true);
42+
4143
$prefix = $this->db->getPrefix();
4244

4345
$tables = [
@@ -124,12 +126,10 @@ public function testListTablesConstrainedByPrefixReturnsOnlyTablesWithMatchingPr
124126

125127
public function testListTablesConstrainedByExtraneousPrefixReturnsOnlyTheExtraneousTable(): void
126128
{
127-
$oldPrefix = '';
129+
$oldPrefix = $this->db->getPrefix();
128130

129131
try {
130132
$this->createExtraneousTable();
131-
132-
$oldPrefix = $this->db->getPrefix();
133133
$this->db->setPrefix('tmp_');
134134

135135
$tables = $this->db->listTables(true);

0 commit comments

Comments
 (0)