Skip to content
Closed
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
2 changes: 1 addition & 1 deletion .github/scripts/random-tests-config.txt
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ Config
Cookie
# DataCaster
# DataConverter
# Database
Database
# Debug
# Email
# Encryption
Expand Down
13 changes: 12 additions & 1 deletion system/Database/OCI8/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,17 @@ public function connect(bool $persistent = false)
: $func($this->username, $this->password, $this->DSN, $this->charset);
}

public function initialize()
{
parent::initialize();

if ($this->connID) {
$this->simpleQuery("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
$this->simpleQuery("ALTER SESSION SET NLS_TIMESTAMP_FORMAT='YYYY-MM-DD HH24:MI:SS'");
$this->simpleQuery("ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT='YYYY-MM-DD HH24:MI:SS'");
}
}

/**
* Close the database connection.
*
Expand Down Expand Up @@ -422,7 +433,7 @@ protected function _indexData(string $table): array
$retVal[$row->INDEX_NAME] = new stdClass();
$retVal[$row->INDEX_NAME]->name = $row->INDEX_NAME;
$retVal[$row->INDEX_NAME]->fields = [$row->COLUMN_NAME];
$retVal[$row->INDEX_NAME]->type = $constraintTypes[$row->CONSTRAINT_TYPE] ?? 'INDEX';
$retVal[$row->INDEX_NAME]->type = $constraintTypes[$row->CONSTRAINT_TYPE ?? ''] ?? 'INDEX';
}

return $retVal;
Expand Down
62 changes: 61 additions & 1 deletion tests/_support/Config/Registrar.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@

namespace Tests\Support\Config;

use mysqli;
use PDO;
use Throwable;

/**
* Class Registrar
*
Expand Down Expand Up @@ -137,7 +141,63 @@ public static function Database(): array
// so that we can test against multiple databases.
$group = env('DB', 'SQLite3');

$config['tests'] = self::$dbConfig[$group] ?? [];
$dbParams = self::$dbConfig[$group] ?? [];

if (! empty($dbParams) && $group !== 'SQLite3') {
$componentName = '';

foreach ($_SERVER['argv'] ?? [] as $arg) {
if (str_contains($arg, 'tests/system/')) {
$parts = explode('tests/system/', $arg);
if (isset($parts[1])) {
$componentName = explode('/', $parts[1])[0];
break;
}
}
}

if ($componentName !== '') {
$dbParams['database'] = 'test_' . strtolower($componentName);

try {
if ($group === 'MySQLi') {
$conn = @new mysqli(
$dbParams['hostname'],
$dbParams['username'],
$dbParams['password'],
'',
(int) $dbParams['port'],
);
if (! $conn->connect_error) {
$conn->query('CREATE DATABASE IF NOT EXISTS ' . $conn->real_escape_string($dbParams['database']));
$conn->close();
}
} elseif ($group === 'Postgre') {
$dsn = 'pgsql:host=' . $dbParams['hostname'] . ';port=' . $dbParams['port'] . ';user=' . $dbParams['username'] . ';password=' . $dbParams['password'];
$pdo = new PDO($dsn);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT 1 FROM pg_database WHERE datname = ?');
$stmt->execute([$dbParams['database']]);
if (! $stmt->fetchColumn()) {
$pdo->exec('CREATE DATABASE ' . $pdo->quote($dbParams['database']));
}
} elseif ($group === 'SQLSRV') {
$dsn = 'sqlsrv:Server=' . $dbParams['hostname'] . ',' . $dbParams['port'] . ';Encrypt=False;TrustServerCertificate=True';
$pdo = new PDO($dsn, $dbParams['username'], $dbParams['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('SELECT 1 FROM sys.databases WHERE name = ?');
$stmt->execute([$dbParams['database']]);
if (! $stmt->fetchColumn()) {
$pdo->exec('CREATE DATABASE [' . str_replace(']', ']]', $dbParams['database']) . ']');
}
}
} catch (Throwable $e) {
// Ignore any error and let the connection fail naturally
}
}
}

$config['tests'] = $dbParams;

return $config;
}
Expand Down
15 changes: 12 additions & 3 deletions tests/system/Database/Live/ConnectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,28 @@ protected function setUp(): void
$this->group2['DBDriver'] = 'Postgre';
}

protected function tearDown(): void
{
parent::tearDown();
$this->setPrivateProperty(Database::class, 'instances', []);
}

public function testConnectWithMultipleCustomGroups(): void
{
$this->group1['DBPrefix'] = uniqid('g1_', true);
$this->group2['DBPrefix'] = uniqid('g2_', true);

// We should have our test database connection already.
$instances = $this->getPrivateProperty(Database::class, 'instances');
$this->assertCount(1, $instances);
$instances = $this->getPrivateProperty(Database::class, 'instances');
$initialCount = count($instances);

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

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

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

public function testConnectReturnsProvidedConnection(): void
Expand Down
15 changes: 11 additions & 4 deletions tests/system/Database/Live/ExecuteLogMessageFormatTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public function testLogMessageWhenExecuteFailsShowFullStructuredBacktrace(): voi
$db->query($sql, [3, 'live', 'Rick']);

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

if ($db->DBDriver === 'Postgre') {
$messageFromLogs = array_slice($messageFromLogs, 2);
} elseif ($db->DBDriver === 'OCI8') {
$messageFromLogs = array_slice($messageFromLogs, 1);
}

$this->assertMatchesRegularExpression('/^in \S+ on line \d+\.$/', array_shift($messageFromLogs));
$inLine = null;

while (($line = array_shift($messageFromLogs)) !== null) {
if (preg_match('/^in \S+ on line \d+\.$/', $line)) {
$inLine = $line;
break;
}
}

$this->assertNotNull($inLine, 'Could not find "in ... on line ..." in log message');

foreach ($messageFromLogs as $line) {
$this->assertMatchesRegularExpression('/^\s*\d* .+(?:\(\d+\))?: \S+(?:(?:\->|::)\S+)?\(.*\)$/', $line);
Expand Down
63 changes: 57 additions & 6 deletions tests/system/Database/Live/ForgeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,25 +36,64 @@ final class ForgeTest extends CIUnitTestCase
protected $seed = CITestSeeder::class;
private Forge $forge;

private function dropAllMockTables(): void
{
$tablesToDrop = [
'forge_test_invoices',
'forge_test_inv',
'forge_test_users',
'actions',
'forge_test_table',
'test_exists',
'forge_test_attributes',
'forge_array_constraint',
'forge_nullable_table',
'forge_test_1',
'forge_test_two',
'forge_test_three',
'forge_test_four',
'forge_test_modify',
'droptest',
'key_test_users',
'test_stores',
'user2',
'forge_test_table_dummy',
];

foreach ($tablesToDrop as $table) {
$this->forge->dropTable($table, true);
}
}

protected function setUp(): void
{
$this->forge = Database::forge($this->DBGroup);

// when running locally if one of these tables isn't dropped it may cause error
$this->forge->dropTable('forge_test_invoices', true);
$this->forge->dropTable('forge_test_inv', true);
$this->forge->dropTable('forge_test_users', true);
$this->forge->dropTable('actions', true);
$this->dropAllMockTables();

db_connect($this->DBGroup)->resetDataCache();

parent::setUp();
}

protected function tearDown(): void
{
parent::tearDown();
$this->dropAllMockTables();
}

public function testCreateDatabase(): void
{
if ($this->db->DBDriver === 'OCI8') {
$this->markTestSkipped('OCI8 does not support create database.');
}

try {
$this->forge->dropDatabase('test_forge_database');
} catch (DatabaseException) {
// Ignore if doesn't exist
}

$databaseCreated = $this->forge->createDatabase('test_forge_database');

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

$dbName = 'test_com.sitedb.web';

try {
$this->forge->dropDatabase($dbName);
} catch (DatabaseException) {
// Ignore if doesn't exist
}

$databaseCreated = $this->forge->createDatabase($dbName);

$this->assertTrue($databaseCreated);

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

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

try {
$this->forge->createDatabase('test_forge_database');
} catch (DatabaseException) {
// Ignore if exists
}

$databaseDropped = $this->forge->dropDatabase('test_forge_database');

$this->assertTrue($databaseDropped);
Expand Down
3 changes: 1 addition & 2 deletions tests/system/Database/Live/GetVersionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public function testGetVersion(): void
$this->db->connID = false;

$version = $this->db->getVersion();

$this->assertMatchesRegularExpression('/\A\d+(\.\d+)*\z/', $version);
$this->assertMatchesRegularExpression('/\A\d+(\.\d+)*/', $version);
}
}
4 changes: 1 addition & 3 deletions tests/system/Database/Live/MetadataTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,10 @@ public function testListTablesConstrainedByPrefixReturnsOnlyTablesWithMatchingPr

public function testListTablesConstrainedByExtraneousPrefixReturnsOnlyTheExtraneousTable(): void
{
$oldPrefix = '';
$oldPrefix = $this->db->getPrefix();

try {
$this->createExtraneousTable();

$oldPrefix = $this->db->getPrefix();
$this->db->setPrefix('tmp_');

$tables = $this->db->listTables(true);
Expand Down
16 changes: 8 additions & 8 deletions tests/system/Database/Live/MySQLi/FoundRowsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function testEnableFoundRows(): void
{
$this->tests['foundRows'] = true;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$this->assertTrue($db1->foundRows);
}
Expand All @@ -63,7 +63,7 @@ public function testDisableFoundRows(): void
{
$this->tests['foundRows'] = false;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$this->assertFalse($db1->foundRows);
}
Expand All @@ -72,7 +72,7 @@ public function testAffectedRowsAfterEnableFoundRowsWithNoChange(): void
{
$this->tests['foundRows'] = true;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$db1->table('db_user')
->set('country', 'US')
Expand All @@ -88,7 +88,7 @@ public function testAffectedRowsAfterDisableFoundRowsWithNoChange(): void
{
$this->tests['foundRows'] = false;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$db1->table('db_user')
->set('country', 'US')
Expand All @@ -104,7 +104,7 @@ public function testAffectedRowsAfterEnableFoundRowsWithChange(): void
{
$this->tests['foundRows'] = true;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$db1->table('db_user')
->set('country', 'NZ')
Expand All @@ -120,7 +120,7 @@ public function testAffectedRowsAfterDisableFoundRowsWithChange(): void
{
$this->tests['foundRows'] = false;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$db1->table('db_user')
->set('country', 'NZ')
Expand All @@ -136,7 +136,7 @@ public function testAffectedRowsAfterEnableFoundRowsWithPartialChange(): void
{
$this->tests['foundRows'] = true;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$db1->table('db_user')
->set('name', 'Derek Jones')
Expand All @@ -152,7 +152,7 @@ public function testAffectedRowsAfterDisableFoundRowsWithPartialChange(): void
{
$this->tests['foundRows'] = false;

$db1 = Database::connect($this->tests);
$db1 = Database::connect($this->tests, false);

$db1->table('db_user')
->set('name', 'Derek Jones')
Expand Down
Loading
Loading