Skip to content

Commit a5594ee

Browse files
committed
Modernized MySQL class to allow changing the "current" database connection
- Created a new MySQL::setConnection method - Basic test for it - Tests now run MySQL::setConnection('tests-mysql'); during the PHPUnit bootstrap instead of overriding `MySQL::$defaultProductionLabel`.
1 parent aad9c20 commit a5594ee

3 files changed

Lines changed: 64 additions & 20 deletions

File tree

src/IO/Database/MySQL.php

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
*/
1010
namespace Divergence\IO\Database;
1111

12-
use \PDO as PDO;
13-
use \Divergence\App as App;
12+
use PDO as PDO;
13+
use Exception;
14+
use Divergence\App as App;
1415

1516
/**
1617
* MySQL.
@@ -56,6 +57,13 @@ class MySQL
5657
*/
5758
public static $defaultDevLabel = 'dev-mysql';
5859

60+
/**
61+
* Current connection label
62+
*
63+
* @var string|null $currentConnection
64+
*/
65+
public static $currentConnection = null;
66+
5967
/**
6068
* Internal reference list of connections
6169
*
@@ -84,6 +92,28 @@ class MySQL
8492
*/
8593
protected static $Config;
8694

95+
96+
/**
97+
* Sets the connection that should be returned by getConnection when $label is null
98+
*
99+
* @param string $label
100+
* @return void
101+
*/
102+
public static function setConnection(string $label=null)
103+
{
104+
if ($label === null && static::$currentConnection === null) {
105+
static::$currentConnection = static::getDefaultLabel();
106+
return;
107+
}
108+
109+
$config = static::config();
110+
if (isset($config[$label])) {
111+
static::$currentConnection = $label;
112+
} else {
113+
throw new Exception('The provided label does not exist in the config.');
114+
}
115+
}
116+
87117
/**
88118
* Attempts to make, store, and return a PDO connection.
89119
* - By default will use the label provided by static::getDefaultLabel()
@@ -95,7 +125,7 @@ class MySQL
95125
* @param string|null $label A specific connection.
96126
* @return PDO A PDO connection
97127
*
98-
* @throws \Exception
128+
* @throws Exception
99129
*
100130
* @uses static::$Connections
101131
* @uses static::getDefaultLabel()
@@ -104,8 +134,11 @@ class MySQL
104134
*/
105135
public static function getConnection($label=null)
106136
{
107-
if (!$label) {
108-
$label = static::getDefaultLabel();
137+
if ($label === null) {
138+
if (static::$currentConnection === null) {
139+
static::setConnection();
140+
}
141+
$label = static::$currentConnection;
109142
}
110143

111144
if (!isset(static::$Connections[$label])) {
@@ -128,7 +161,7 @@ public static function getConnection($label=null)
128161
// try to initiate connection
129162
static::$Connections[$label] = new PDO($DSN, $config['username'], $config['password']);
130163
} catch (\PDOException $e) {
131-
throw new \Exception('PDO failed to connect on config "'.$label.'" '.$DSN);
164+
throw new Exception('PDO failed to connect on config "'.$label.'" '.$DSN);
132165
}
133166

134167
// set timezone

tests/Divergence/IO/Database/MySQLTest.php

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,17 @@ public function testGetConnection()
7878
$this->assertInstanceOf(\PDO::class, DB::getConnection('mysql'));
7979
}
8080

81+
/**
82+
* @covers Divergence\IO\Database\MySQL::setConnection
83+
*/
84+
public function testSetConnection()
85+
{
86+
TestUtils::requireDB($this);
87+
DB::setConnection('tests-mysql-socket');
88+
$this->assertEquals('tests-mysql-socket',DB::$currentConnection);
89+
DB::setConnection('tests-mysql');
90+
}
91+
8192
/**
8293
* @covers Divergence\IO\Database\MySQL::escape
8394
*
@@ -96,7 +107,7 @@ public function testEscape()
96107

97108
$littleBobbyTables = 'Robert\'); DROP TABLE Students;--';
98109
$safeLittleBobbyTables = $z($littleBobbyTables);
99-
110+
100111
$arrayOfBobbies = [
101112
'lorum ipsum',
102113
$littleBobbyTables,
@@ -107,7 +118,7 @@ public function testEscape()
107118
foreach ($arrayOfBobbies as $oneBob) {
108119
$safeArrayOfBobbies[] = $z($oneBob);
109120
}
110-
121+
111122
$this->assertEquals($safeLittleBobbyTables, DB::escape($littleBobbyTables));
112123
$this->assertEquals($safeArrayOfBobbies, DB::escape($arrayOfBobbies));
113124
$this->assertEquals(new \stdClass(), DB::escape(new \stdClass()));
@@ -126,7 +137,7 @@ public function testAffectedRows()
126137

127138
$this->assertEquals(2, DB::affectedRows());
128139
}
129-
140+
130141
/**
131142
* @covers Divergence\IO\Database\MySQL::foundRows
132143
* @covers Divergence\IO\Database\MySQL::oneValue
@@ -139,7 +150,7 @@ public function testFoundRows()
139150
$tags = DB::allRecords('select SQL_CALC_FOUND_ROWS * from `tags` LIMIT 1;');
140151
$foundRows = DB::oneValue('SELECT FOUND_ROWS()');
141152
$tagsCount = DB::oneValue('SELECT COUNT(*) as `Count` FROM `tags`');
142-
153+
143154
$this->assertEquals($tagsCount, $foundRows);
144155
$this->assertCount(1, $tags);
145156

@@ -149,7 +160,7 @@ public function testFoundRows()
149160
// valid query. no records found
150161
$this->assertFalse(DB::oneValue('SELECT * FROM `tags` WHERE 1=0'));
151162
}
152-
163+
153164
/**
154165
* @covers Divergence\IO\Database\MySQL::insertID
155166
* @covers Divergence\IO\Database\MySQL::oneRecord
@@ -335,7 +346,7 @@ public function testNonQueryExceptionDevException()
335346
public function testNonQueryHandledException()
336347
{
337348
TestUtils::requireDB($this);
338-
349+
339350
$Context = $this;
340351
// another bad query but this time we handle the problem
341352
DB::nonQuery('UPDATE `%s` SET fake`=%d WHERE `ID`=%d', [
@@ -366,7 +377,7 @@ public function testAllRecords()
366377
TestUtils::requireDB($this);
367378

368379
$tables = DB::allRecords('SHOW TABLES');
369-
380+
370381
$this->assertCount(9, $tables);
371382
foreach ($tables as $table) {
372383
$this->assertNotEmpty($table['Tables_in_test']);
@@ -409,7 +420,7 @@ public function testClearCachedRecord()
409420
'Tag',
410421
'Linux',
411422
];
412-
423+
413424
$key = sprintf('%s/%s:%s', Tag::$tableName, 'Tag', 'Linux');
414425
$record = testableDB::oneRecordCached($key, $query, $params);
415426
$cache = testableDB::getProtected('_record_cache');
@@ -418,7 +429,7 @@ public function testClearCachedRecord()
418429
$cache = testableDB::getProtected('_record_cache');
419430
$this->assertNull($cache[$key]);
420431
}
421-
432+
422433
/**
423434
* @covers Divergence\IO\Database\MySQL::oneRecordCached
424435
*
@@ -433,7 +444,7 @@ public function testOneRecordCached()
433444
'Tag',
434445
'Linux',
435446
];
436-
447+
437448
$key = sprintf('%s/%s:%s', Tag::$tableName, 'Tag', 'Linux');
438449
$record = testableDB::oneRecordCached($key, $query, $params);
439450
$cache = testableDB::getProtected('_record_cache');
@@ -504,7 +515,7 @@ public function testFinishQueryLog()
504515
$result->num_rows = 5;
505516

506517
testableDB::_finishQueryLog($x, $result);
507-
518+
508519
$expected_time_duration_ms = ($x['time_finish'] - $x['time_start']) * 1000;
509520

510521
$this->assertEquals('SELECT corgies', $x['query']);
@@ -539,7 +550,7 @@ public function testConfig()
539550
public function testGetDefaultLabel()
540551
{
541552
TestUtils::requireDB($this);
542-
553+
543554
$this->assertEquals(testableDB::$defaultProductionLabel, testableDB::_getDefaultLabel());
544555
App::$Config['environment'] = 'dev';
545556
$this->assertEquals(testableDB::$defaultDevLabel, testableDB::_getDefaultLabel());

tests/Divergence/TestListener.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public function addWarning(Test $test, \PHPUnit\Framework\Warning $e, float $tim
2424
{
2525
//printf("Warning while running test '%s'.\n", $test->getName());
2626
}
27-
27+
2828

2929
public function addFailure(Test $test, \PHPUnit\Framework\AssertionFailedError $e, float $time): void
3030
{
@@ -60,8 +60,8 @@ public function startTestSuite(TestSuite $suite): void
6060
{
6161
//printf("TestSuite '%s' started.\n", $suite->getName());
6262
if ($suite->getName() == 'all') {
63-
MySQL::$defaultProductionLabel = 'tests-mysql';
6463
App::init(__DIR__.'/../../');
64+
MySQL::setConnection('tests-mysql');
6565
App::setUp();
6666
fwrite(STDERR, 'Starting Divergence Mock Environment for PHPUnit'."\n");
6767
}

0 commit comments

Comments
 (0)