Skip to content

Commit 45aea06

Browse files
committed
test(Database): isolate database name per test component to prevent race conditions during parallel run
1 parent 6b5e65c commit 45aea06

1 file changed

Lines changed: 61 additions & 1 deletion

File tree

tests/_support/Config/Registrar.php

Lines changed: 61 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,63 @@ 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+
$dbParams = self::$dbConfig[$group] ?? [];
145+
146+
if (! empty($dbParams) && $group !== 'SQLite3') {
147+
$componentName = '';
148+
149+
foreach ($_SERVER['argv'] ?? [] as $arg) {
150+
if (str_contains($arg, 'tests/system/')) {
151+
$parts = explode('tests/system/', $arg);
152+
if (isset($parts[1])) {
153+
$componentName = explode('/', $parts[1])[0];
154+
break;
155+
}
156+
}
157+
}
158+
159+
if ($componentName !== '') {
160+
$dbParams['database'] = 'test_' . strtolower($componentName);
161+
162+
try {
163+
if ($group === 'MySQLi') {
164+
$conn = @new mysqli(
165+
$dbParams['hostname'],
166+
$dbParams['username'],
167+
$dbParams['password'],
168+
'',
169+
(int) $dbParams['port'],
170+
);
171+
if (! $conn->connect_error) {
172+
$conn->query('CREATE DATABASE IF NOT EXISTS ' . $conn->real_escape_string($dbParams['database']));
173+
$conn->close();
174+
}
175+
} elseif ($group === 'Postgre') {
176+
$dsn = 'pgsql:host=' . $dbParams['hostname'] . ';port=' . $dbParams['port'] . ';user=' . $dbParams['username'] . ';password=' . $dbParams['password'];
177+
$pdo = new PDO($dsn);
178+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
179+
$stmt = $pdo->prepare('SELECT 1 FROM pg_database WHERE datname = ?');
180+
$stmt->execute([$dbParams['database']]);
181+
if (! $stmt->fetchColumn()) {
182+
$pdo->exec('CREATE DATABASE ' . $pdo->quote($dbParams['database']));
183+
}
184+
} elseif ($group === 'SQLSRV') {
185+
$dsn = 'sqlsrv:Server=' . $dbParams['hostname'] . ',' . $dbParams['port'] . ';Encrypt=False;TrustServerCertificate=True';
186+
$pdo = new PDO($dsn, $dbParams['username'], $dbParams['password']);
187+
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
188+
$stmt = $pdo->prepare('SELECT 1 FROM sys.databases WHERE name = ?');
189+
$stmt->execute([$dbParams['database']]);
190+
if (! $stmt->fetchColumn()) {
191+
$pdo->exec('CREATE DATABASE [' . str_replace(']', ']]', $dbParams['database']) . ']');
192+
}
193+
}
194+
} catch (Throwable $e) {
195+
// Ignore any error and let the connection fail naturally
196+
}
197+
}
198+
}
199+
200+
$config['tests'] = $dbParams;
141201

142202
return $config;
143203
}

0 commit comments

Comments
 (0)