3 use Wikimedia\Rdbms\Database
;
4 use Wikimedia\Rdbms\IDatabase
;
5 use Wikimedia\Rdbms\DatabaseMysqli
;
6 use Wikimedia\Rdbms\LBFactorySingle
;
7 use Wikimedia\Rdbms\TransactionProfiler
;
8 use Wikimedia\TestingAccessWrapper
;
9 use Wikimedia\Rdbms\DatabaseSqlite
;
10 use Wikimedia\Rdbms\DatabasePostgres
;
11 use Wikimedia\Rdbms\DatabaseMssql
;
13 class DatabaseTest
extends PHPUnit\Framework\TestCase
{
15 use MediaWikiCoversValidator
;
17 protected function setUp() {
18 $this->db
= new DatabaseTestHelper( __CLASS__
. '::' . $this->getName() );
22 * @dataProvider provideAddQuotes
23 * @covers Wikimedia\Rdbms\Database::factory
25 public function testFactory() {
26 $m = Database
::NEW_UNCONNECTED
; // no-connect mode
27 $p = [ 'host' => 'localhost', 'user' => 'me', 'password' => 'myself', 'dbname' => 'i' ];
29 $this->assertInstanceOf( DatabaseMysqli
::class, Database
::factory( 'mysqli', $p, $m ) );
30 $this->assertInstanceOf( DatabaseMysqli
::class, Database
::factory( 'MySqli', $p, $m ) );
31 $this->assertInstanceOf( DatabaseMysqli
::class, Database
::factory( 'MySQLi', $p, $m ) );
32 $this->assertInstanceOf( DatabasePostgres
::class, Database
::factory( 'postgres', $p, $m ) );
33 $this->assertInstanceOf( DatabasePostgres
::class, Database
::factory( 'Postgres', $p, $m ) );
35 $x = $p +
[ 'port' => 10000, 'UseWindowsAuth' => false ];
36 $this->assertInstanceOf( DatabaseMssql
::class, Database
::factory( 'mssql', $x, $m ) );
38 $x = $p +
[ 'dbFilePath' => 'some/file.sqlite' ];
39 $this->assertInstanceOf( DatabaseSqlite
::class, Database
::factory( 'sqlite', $x, $m ) );
40 $x = $p +
[ 'dbDirectory' => 'some/file' ];
41 $this->assertInstanceOf( DatabaseSqlite
::class, Database
::factory( 'sqlite', $x, $m ) );
44 public static function provideAddQuotes() {
48 [ 1234.5678, "'1234.5678'" ],
49 [ 'string', "'string'" ],
50 [ 'string\'s cause trouble', "'string\'s cause trouble'" ],
55 * @dataProvider provideAddQuotes
56 * @covers Wikimedia\Rdbms\Database::addQuotes
58 public function testAddQuotes( $input, $expected ) {
59 $this->assertEquals( $expected, $this->db
->addQuotes( $input ) );
62 public static function provideTableName() {
63 // Formatting is mostly ignored since addIdentifierQuotes is abstract.
64 // For testing of addIdentifierQuotes, see actual Database subclas tests.
80 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => '' ],
86 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => '' ],
89 'sharedb.sh_tablename',
92 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => 'sh_' ],
94 'shared-prefix-raw' => [
95 'sharedb.sh_tablename',
98 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => 'sh_' ],
101 'databasename.tablename',
102 'databasename.tablename',
106 'databasename.tablename',
107 'databasename.tablename',
114 * @dataProvider provideTableName
115 * @covers Wikimedia\Rdbms\Database::tableName
117 public function testTableName( $expected, $table, $format, array $alias = null ) {
119 $this->db
->setTableAliases( [ $table => $alias ] );
123 $this->db
->tableName( $table, $format ?
: 'quoted' )
127 public function provideTableNamesWithIndexClauseOrJOIN() {
129 'one-element array' => [
130 [ 'table' ], [], 'table '
133 [ 'table1', 'table2' ], [], 'table1,table2 '
136 [ 'table1', 'table2' ],
137 [ 'table2' => [ 'LEFT JOIN', 't1_id = t2_id' ] ],
138 'table1 LEFT JOIN table2 ON ((t1_id = t2_id))'
140 'real join with multiple conditionals' => [
141 [ 'table1', 'table2' ],
142 [ 'table2' => [ 'LEFT JOIN', [ 't1_id = t2_id', 't2_x = \'X\'' ] ] ],
143 'table1 LEFT JOIN table2 ON ((t1_id = t2_id) AND (t2_x = \'X\'))'
145 'join with parenthesized group' => [
146 [ 'table1', 'n' => [ 'table2', 'table3' ] ],
148 'table3' => [ 'JOIN', 't2_id = t3_id' ],
149 'n' => [ 'LEFT JOIN', 't1_id = t2_id' ],
151 'table1 LEFT JOIN (table2 JOIN table3 ON ((t2_id = t3_id))) ON ((t1_id = t2_id))'
153 'join with degenerate parenthesized group' => [
154 [ 'table1', 'n' => [ 't2' => 'table2' ] ],
156 'n' => [ 'LEFT JOIN', 't1_id = t2_id' ],
158 'table1 LEFT JOIN table2 t2 ON ((t1_id = t2_id))'
164 * @dataProvider provideTableNamesWithIndexClauseOrJOIN
165 * @covers Wikimedia\Rdbms\Database::tableNamesWithIndexClauseOrJOIN
167 public function testTableNamesWithIndexClauseOrJOIN( $tables, $join_conds, $expect ) {
168 $clause = TestingAccessWrapper
::newFromObject( $this->db
)
169 ->tableNamesWithIndexClauseOrJOIN( $tables, [], [], $join_conds );
170 $this->assertSame( $expect, $clause );
174 * @covers Wikimedia\Rdbms\Database::onTransactionIdle
175 * @covers Wikimedia\Rdbms\Database::runOnTransactionIdleCallbacks
177 public function testTransactionIdle() {
180 $db->setFlag( DBO_TRX
);
183 $db->onTransactionIdle(
184 function () use ( $db, &$flagSet, &$called ) {
186 $flagSet = $db->getFlag( DBO_TRX
);
190 $this->assertFalse( $flagSet, 'DBO_TRX off in callback' );
191 $this->assertTrue( $db->getFlag( DBO_TRX
), 'DBO_TRX restored to default' );
192 $this->assertTrue( $called, 'Callback reached' );
194 $db->clearFlag( DBO_TRX
);
196 $db->onTransactionIdle(
197 function () use ( $db, &$flagSet ) {
198 $flagSet = $db->getFlag( DBO_TRX
);
202 $this->assertFalse( $flagSet, 'DBO_TRX off in callback' );
203 $this->assertFalse( $db->getFlag( DBO_TRX
), 'DBO_TRX restored to default' );
205 $db->clearFlag( DBO_TRX
);
206 $db->onTransactionIdle(
207 function () use ( $db ) {
208 $db->setFlag( DBO_TRX
);
212 $this->assertFalse( $db->getFlag( DBO_TRX
), 'DBO_TRX restored to default' );
216 * @covers Wikimedia\Rdbms\Database::onTransactionPreCommitOrIdle
217 * @covers Wikimedia\Rdbms\Database::runOnTransactionPreCommitCallbacks
219 public function testTransactionPreCommitOrIdle() {
220 $db = $this->getMockDB( [ 'isOpen' ] );
221 $db->method( 'isOpen' )->willReturn( true );
222 $db->clearFlag( DBO_TRX
);
224 $this->assertFalse( $db->getFlag( DBO_TRX
), 'DBO_TRX is not set' );
227 $db->onTransactionPreCommitOrIdle(
228 function () use ( &$called ) {
233 $this->assertTrue( $called, 'Called when idle' );
235 $db->begin( __METHOD__
);
237 $db->onTransactionPreCommitOrIdle(
238 function () use ( &$called ) {
243 $this->assertFalse( $called, 'Not called when transaction is active' );
244 $db->commit( __METHOD__
);
245 $this->assertTrue( $called, 'Called when transaction is committed' );
249 * @covers Wikimedia\Rdbms\Database::onTransactionPreCommitOrIdle
250 * @covers Wikimedia\Rdbms\Database::runOnTransactionPreCommitCallbacks
252 public function testTransactionPreCommitOrIdle_TRX() {
253 $db = $this->getMockDB( [ 'isOpen' ] );
254 $db->method( 'isOpen' )->willReturn( true );
255 $db->setFlag( DBO_TRX
);
257 $lbFactory = LBFactorySingle
::newFromConnection( $db );
258 // Ask for the connectin so that LB sets internal state
259 // about this connection being the master connection
260 $lb = $lbFactory->getMainLB();
261 $conn = $lb->openConnection( $lb->getWriterIndex() );
262 $this->assertSame( $db, $conn, 'Same DB instance' );
263 $this->assertTrue( $db->getFlag( DBO_TRX
), 'DBO_TRX is set' );
266 $callback = function () use ( &$called ) {
269 $db->onTransactionPreCommitOrIdle( $callback, __METHOD__
);
270 $this->assertFalse( $called, 'Not called when idle if DBO_TRX is set' );
272 $lbFactory->beginMasterChanges( __METHOD__
);
273 $this->assertFalse( $called, 'Not called when lb-transaction is active' );
275 $lbFactory->commitMasterChanges( __METHOD__
);
276 $this->assertTrue( $called, 'Called when lb-transaction is committed' );
279 $lbFactory->beginMasterChanges( __METHOD__
);
280 $db->onTransactionPreCommitOrIdle( $callback, __METHOD__
);
281 $this->assertFalse( $called, 'Not called when lb-transaction is active' );
283 $lbFactory->rollbackMasterChanges( __METHOD__
);
284 $this->assertFalse( $called, 'Not called when lb-transaction is rolled back' );
286 $lbFactory->commitMasterChanges( __METHOD__
);
287 $this->assertFalse( $called, 'Not called in next round commit' );
291 * @covers Wikimedia\Rdbms\Database::onTransactionResolution
292 * @covers Wikimedia\Rdbms\Database::runOnTransactionIdleCallbacks
294 public function testTransactionResolution() {
297 $db->clearFlag( DBO_TRX
);
298 $db->begin( __METHOD__
);
300 $db->onTransactionResolution( function () use ( $db, &$called ) {
302 $db->setFlag( DBO_TRX
);
304 $db->commit( __METHOD__
);
305 $this->assertFalse( $db->getFlag( DBO_TRX
), 'DBO_TRX restored to default' );
306 $this->assertTrue( $called, 'Callback reached' );
308 $db->clearFlag( DBO_TRX
);
309 $db->begin( __METHOD__
);
311 $db->onTransactionResolution( function () use ( $db, &$called ) {
313 $db->setFlag( DBO_TRX
);
315 $db->rollback( __METHOD__
, IDatabase
::FLUSHING_ALL_PEERS
);
316 $this->assertFalse( $db->getFlag( DBO_TRX
), 'DBO_TRX restored to default' );
317 $this->assertTrue( $called, 'Callback reached' );
321 * @covers Wikimedia\Rdbms\Database::setTransactionListener
323 public function testTransactionListener() {
326 $db->setTransactionListener( 'ping', function () use ( $db, &$called ) {
331 $db->begin( __METHOD__
);
332 $db->commit( __METHOD__
);
333 $this->assertTrue( $called, 'Callback reached' );
336 $db->begin( __METHOD__
);
337 $db->commit( __METHOD__
);
338 $this->assertTrue( $called, 'Callback still reached' );
341 $db->begin( __METHOD__
);
342 $db->rollback( __METHOD__
);
343 $this->assertTrue( $called, 'Callback reached' );
345 $db->setTransactionListener( 'ping', null );
347 $db->begin( __METHOD__
);
348 $db->commit( __METHOD__
);
349 $this->assertFalse( $called, 'Callback not reached' );
353 * Use this mock instead of DatabaseTestHelper for cases where
354 * DatabaseTestHelper is too inflexibile due to mocking too much
355 * or being too restrictive about fname matching (e.g. for tests
356 * that assert behaviour when the name is a mismatch, we need to
357 * catch the error here instead of there).
361 private function getMockDB( $methods = [] ) {
362 static $abstractMethods = [
363 'fetchAffectedRowCount',
367 'fetchObject', 'fetchRow',
368 'fieldInfo', 'fieldName',
369 'getSoftwareLink', 'getServerVersion',
373 'lastError', 'lastErrno',
374 'numFields', 'numRows',
378 $db = $this->getMockBuilder( Database
::class )
379 ->disableOriginalConstructor()
380 ->setMethods( array_values( array_unique( array_merge(
385 $wdb = TestingAccessWrapper
::newFromObject( $db );
386 $wdb->trxProfiler
= new TransactionProfiler();
387 $wdb->connLogger
= new \Psr\Log\
NullLogger();
388 $wdb->queryLogger
= new \Psr\Log\
NullLogger();
393 * @covers Wikimedia\Rdbms\Database::flushSnapshot
395 public function testFlushSnapshot() {
396 $db = $this->getMockDB( [ 'isOpen' ] );
397 $db->method( 'isOpen' )->willReturn( true );
399 $db->flushSnapshot( __METHOD__
); // ok
400 $db->flushSnapshot( __METHOD__
); // ok
402 $db->setFlag( DBO_TRX
, $db::REMEMBER_PRIOR
);
403 $db->query( 'SELECT 1', __METHOD__
);
404 $this->assertTrue( (bool)$db->trxLevel(), "Transaction started." );
405 $db->flushSnapshot( __METHOD__
); // ok
406 $db->restoreFlags( $db::RESTORE_PRIOR
);
408 $this->assertFalse( (bool)$db->trxLevel(), "Transaction cleared." );
412 * @covers Wikimedia\Rdbms\Database::getScopedLockAndFlush
413 * @covers Wikimedia\Rdbms\Database::lock
414 * @covers Wikimedia\Rdbms\Database::unlock
415 * @covers Wikimedia\Rdbms\Database::lockIsFree
417 public function testGetScopedLock() {
418 $db = $this->getMockDB( [ 'isOpen' ] );
419 $db->method( 'isOpen' )->willReturn( true );
421 $this->assertEquals( 0, $db->trxLevel() );
422 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__
) );
423 $this->assertEquals( true, $db->lock( 'x', __METHOD__
) );
424 $this->assertEquals( false, $db->lockIsFree( 'x', __METHOD__
) );
425 $this->assertEquals( true, $db->unlock( 'x', __METHOD__
) );
426 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__
) );
427 $this->assertEquals( 0, $db->trxLevel() );
429 $db->setFlag( DBO_TRX
);
430 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__
) );
431 $this->assertEquals( true, $db->lock( 'x', __METHOD__
) );
432 $this->assertEquals( false, $db->lockIsFree( 'x', __METHOD__
) );
433 $this->assertEquals( true, $db->unlock( 'x', __METHOD__
) );
434 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__
) );
435 $db->clearFlag( DBO_TRX
);
437 $this->assertEquals( 0, $db->trxLevel() );
439 $db->setFlag( DBO_TRX
);
441 $this->badLockingMethodImplicit( $db );
442 } catch ( RunTimeException
$e ) {
443 $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
445 $db->clearFlag( DBO_TRX
);
446 $db->rollback( __METHOD__
, IDatabase
::FLUSHING_ALL_PEERS
);
447 $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__
) );
450 $this->badLockingMethodExplicit( $db );
451 } catch ( RunTimeException
$e ) {
452 $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
454 $db->rollback( __METHOD__
, IDatabase
::FLUSHING_ALL_PEERS
);
455 $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__
) );
458 private function badLockingMethodImplicit( IDatabase
$db ) {
459 $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__
, 1 );
460 $db->query( "SELECT 1" ); // trigger DBO_TRX
461 throw new RunTimeException( "Uh oh!" );
464 private function badLockingMethodExplicit( IDatabase
$db ) {
465 $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__
, 1 );
466 $db->begin( __METHOD__
);
467 throw new RunTimeException( "Uh oh!" );
471 * @covers Wikimedia\Rdbms\Database::getFlag
472 * @covers Wikimedia\Rdbms\Database::setFlag
473 * @covers Wikimedia\Rdbms\Database::restoreFlags
475 public function testFlagSetting() {
477 $origTrx = $db->getFlag( DBO_TRX
);
478 $origSsl = $db->getFlag( DBO_SSL
);
481 ?
$db->clearFlag( DBO_TRX
, $db::REMEMBER_PRIOR
)
482 : $db->setFlag( DBO_TRX
, $db::REMEMBER_PRIOR
);
483 $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX
) );
486 ?
$db->clearFlag( DBO_SSL
, $db::REMEMBER_PRIOR
)
487 : $db->setFlag( DBO_SSL
, $db::REMEMBER_PRIOR
);
488 $this->assertEquals( !$origSsl, $db->getFlag( DBO_SSL
) );
490 $db->restoreFlags( $db::RESTORE_INITIAL
);
491 $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX
) );
492 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL
) );
495 ?
$db->clearFlag( DBO_TRX
, $db::REMEMBER_PRIOR
)
496 : $db->setFlag( DBO_TRX
, $db::REMEMBER_PRIOR
);
498 ?
$db->clearFlag( DBO_SSL
, $db::REMEMBER_PRIOR
)
499 : $db->setFlag( DBO_SSL
, $db::REMEMBER_PRIOR
);
502 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL
) );
503 $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX
) );
506 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL
) );
507 $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX
) );
511 * @expectedException UnexpectedValueException
512 * @covers Wikimedia\Rdbms\Database::setFlag
514 public function testDBOIgnoreSet() {
515 $db = $this->getMockBuilder( DatabaseMysqli
::class )
516 ->disableOriginalConstructor()
520 $db->setFlag( Database
::DBO_IGNORE
);
524 * @expectedException UnexpectedValueException
525 * @covers Wikimedia\Rdbms\Database::clearFlag
527 public function testDBOIgnoreClear() {
528 $db = $this->getMockBuilder( DatabaseMysqli
::class )
529 ->disableOriginalConstructor()
533 $db->clearFlag( Database
::DBO_IGNORE
);
537 * @covers Wikimedia\Rdbms\Database::tablePrefix
538 * @covers Wikimedia\Rdbms\Database::dbSchema
540 public function testMutators() {
541 $old = $this->db
->tablePrefix();
542 $this->assertInternalType( 'string', $old, 'Prefix is string' );
543 $this->assertEquals( $old, $this->db
->tablePrefix(), "Prefix unchanged" );
544 $this->assertEquals( $old, $this->db
->tablePrefix( 'xxx' ) );
545 $this->assertEquals( 'xxx', $this->db
->tablePrefix(), "Prefix set" );
546 $this->db
->tablePrefix( $old );
547 $this->assertNotEquals( 'xxx', $this->db
->tablePrefix() );
549 $old = $this->db
->dbSchema();
550 $this->assertInternalType( 'string', $old, 'Schema is string' );
551 $this->assertEquals( $old, $this->db
->dbSchema(), "Schema unchanged" );
552 $this->assertEquals( $old, $this->db
->dbSchema( 'xxx' ) );
553 $this->assertEquals( 'xxx', $this->db
->dbSchema(), "Schema set" );
554 $this->db
->dbSchema( $old );
555 $this->assertNotEquals( 'xxx', $this->db
->dbSchema() );