24d848e406f95b1244a74155e4faa0170edc8f6f
[lhc/web/wiklou.git] / tests / phpunit / includes / libs / rdbms / database / DatabaseTest.php
1 <?php
2
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;
12
13 class DatabaseTest extends PHPUnit\Framework\TestCase {
14
15 use MediaWikiCoversValidator;
16
17 protected function setUp() {
18 $this->db = new DatabaseTestHelper( __CLASS__ . '::' . $this->getName() );
19 }
20
21 /**
22 * @dataProvider provideAddQuotes
23 * @covers Wikimedia\Rdbms\Database::factory
24 */
25 public function testFactory() {
26 $m = Database::NEW_UNCONNECTED; // no-connect mode
27 $p = [ 'host' => 'localhost', 'user' => 'me', 'password' => 'myself', 'dbname' => 'i' ];
28
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 ) );
34
35 $x = $p + [ 'port' => 10000, 'UseWindowsAuth' => false ];
36 $this->assertInstanceOf( DatabaseMssql::class, Database::factory( 'mssql', $x, $m ) );
37
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 ) );
42 }
43
44 public static function provideAddQuotes() {
45 return [
46 [ null, 'NULL' ],
47 [ 1234, "'1234'" ],
48 [ 1234.5678, "'1234.5678'" ],
49 [ 'string', "'string'" ],
50 [ 'string\'s cause trouble', "'string\'s cause trouble'" ],
51 ];
52 }
53
54 /**
55 * @dataProvider provideAddQuotes
56 * @covers Wikimedia\Rdbms\Database::addQuotes
57 */
58 public function testAddQuotes( $input, $expected ) {
59 $this->assertEquals( $expected, $this->db->addQuotes( $input ) );
60 }
61
62 public static function provideTableName() {
63 // Formatting is mostly ignored since addIdentifierQuotes is abstract.
64 // For testing of addIdentifierQuotes, see actual Database subclas tests.
65 return [
66 'local' => [
67 'tablename',
68 'tablename',
69 'quoted',
70 ],
71 'local-raw' => [
72 'tablename',
73 'tablename',
74 'raw',
75 ],
76 'shared' => [
77 'sharedb.tablename',
78 'tablename',
79 'quoted',
80 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => '' ],
81 ],
82 'shared-raw' => [
83 'sharedb.tablename',
84 'tablename',
85 'raw',
86 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => '' ],
87 ],
88 'shared-prefix' => [
89 'sharedb.sh_tablename',
90 'tablename',
91 'quoted',
92 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => 'sh_' ],
93 ],
94 'shared-prefix-raw' => [
95 'sharedb.sh_tablename',
96 'tablename',
97 'raw',
98 [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => 'sh_' ],
99 ],
100 'foreign' => [
101 'databasename.tablename',
102 'databasename.tablename',
103 'quoted',
104 ],
105 'foreign-raw' => [
106 'databasename.tablename',
107 'databasename.tablename',
108 'raw',
109 ],
110 ];
111 }
112
113 /**
114 * @dataProvider provideTableName
115 * @covers Wikimedia\Rdbms\Database::tableName
116 */
117 public function testTableName( $expected, $table, $format, array $alias = null ) {
118 if ( $alias ) {
119 $this->db->setTableAliases( [ $table => $alias ] );
120 }
121 $this->assertEquals(
122 $expected,
123 $this->db->tableName( $table, $format ?: 'quoted' )
124 );
125 }
126
127 public function provideTableNamesWithIndexClauseOrJOIN() {
128 return [
129 'one-element array' => [
130 [ 'table' ], [], 'table '
131 ],
132 'comma join' => [
133 [ 'table1', 'table2' ], [], 'table1,table2 '
134 ],
135 'real join' => [
136 [ 'table1', 'table2' ],
137 [ 'table2' => [ 'LEFT JOIN', 't1_id = t2_id' ] ],
138 'table1 LEFT JOIN table2 ON ((t1_id = t2_id))'
139 ],
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\'))'
144 ],
145 'join with parenthesized group' => [
146 [ 'table1', 'n' => [ 'table2', 'table3' ] ],
147 [
148 'table3' => [ 'JOIN', 't2_id = t3_id' ],
149 'n' => [ 'LEFT JOIN', 't1_id = t2_id' ],
150 ],
151 'table1 LEFT JOIN (table2 JOIN table3 ON ((t2_id = t3_id))) ON ((t1_id = t2_id))'
152 ],
153 'join with degenerate parenthesized group' => [
154 [ 'table1', 'n' => [ 't2' => 'table2' ] ],
155 [
156 'n' => [ 'LEFT JOIN', 't1_id = t2_id' ],
157 ],
158 'table1 LEFT JOIN table2 t2 ON ((t1_id = t2_id))'
159 ],
160 ];
161 }
162
163 /**
164 * @dataProvider provideTableNamesWithIndexClauseOrJOIN
165 * @covers Wikimedia\Rdbms\Database::tableNamesWithIndexClauseOrJOIN
166 */
167 public function testTableNamesWithIndexClauseOrJOIN( $tables, $join_conds, $expect ) {
168 $clause = TestingAccessWrapper::newFromObject( $this->db )
169 ->tableNamesWithIndexClauseOrJOIN( $tables, [], [], $join_conds );
170 $this->assertSame( $expect, $clause );
171 }
172
173 /**
174 * @covers Wikimedia\Rdbms\Database::onTransactionIdle
175 * @covers Wikimedia\Rdbms\Database::runOnTransactionIdleCallbacks
176 */
177 public function testTransactionIdle() {
178 $db = $this->db;
179
180 $db->setFlag( DBO_TRX );
181 $called = false;
182 $flagSet = null;
183 $db->onTransactionIdle(
184 function () use ( $db, &$flagSet, &$called ) {
185 $called = true;
186 $flagSet = $db->getFlag( DBO_TRX );
187 },
188 __METHOD__
189 );
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' );
193
194 $db->clearFlag( DBO_TRX );
195 $flagSet = null;
196 $db->onTransactionIdle(
197 function () use ( $db, &$flagSet ) {
198 $flagSet = $db->getFlag( DBO_TRX );
199 },
200 __METHOD__
201 );
202 $this->assertFalse( $flagSet, 'DBO_TRX off in callback' );
203 $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
204
205 $db->clearFlag( DBO_TRX );
206 $db->onTransactionIdle(
207 function () use ( $db ) {
208 $db->setFlag( DBO_TRX );
209 },
210 __METHOD__
211 );
212 $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
213 }
214
215 /**
216 * @covers Wikimedia\Rdbms\Database::onTransactionPreCommitOrIdle
217 * @covers Wikimedia\Rdbms\Database::runOnTransactionPreCommitCallbacks
218 */
219 public function testTransactionPreCommitOrIdle() {
220 $db = $this->getMockDB( [ 'isOpen' ] );
221 $db->method( 'isOpen' )->willReturn( true );
222 $db->clearFlag( DBO_TRX );
223
224 $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX is not set' );
225
226 $called = false;
227 $db->onTransactionPreCommitOrIdle(
228 function () use ( &$called ) {
229 $called = true;
230 },
231 __METHOD__
232 );
233 $this->assertTrue( $called, 'Called when idle' );
234
235 $db->begin( __METHOD__ );
236 $called = false;
237 $db->onTransactionPreCommitOrIdle(
238 function () use ( &$called ) {
239 $called = true;
240 },
241 __METHOD__
242 );
243 $this->assertFalse( $called, 'Not called when transaction is active' );
244 $db->commit( __METHOD__ );
245 $this->assertTrue( $called, 'Called when transaction is committed' );
246 }
247
248 /**
249 * @covers Wikimedia\Rdbms\Database::onTransactionPreCommitOrIdle
250 * @covers Wikimedia\Rdbms\Database::runOnTransactionPreCommitCallbacks
251 */
252 public function testTransactionPreCommitOrIdle_TRX() {
253 $db = $this->getMockDB( [ 'isOpen' ] );
254 $db->method( 'isOpen' )->willReturn( true );
255 $db->setFlag( DBO_TRX );
256
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' );
264
265 $called = false;
266 $callback = function () use ( &$called ) {
267 $called = true;
268 };
269 $db->onTransactionPreCommitOrIdle( $callback, __METHOD__ );
270 $this->assertFalse( $called, 'Not called when idle if DBO_TRX is set' );
271
272 $lbFactory->beginMasterChanges( __METHOD__ );
273 $this->assertFalse( $called, 'Not called when lb-transaction is active' );
274
275 $lbFactory->commitMasterChanges( __METHOD__ );
276 $this->assertTrue( $called, 'Called when lb-transaction is committed' );
277
278 $called = false;
279 $lbFactory->beginMasterChanges( __METHOD__ );
280 $db->onTransactionPreCommitOrIdle( $callback, __METHOD__ );
281 $this->assertFalse( $called, 'Not called when lb-transaction is active' );
282
283 $lbFactory->rollbackMasterChanges( __METHOD__ );
284 $this->assertFalse( $called, 'Not called when lb-transaction is rolled back' );
285
286 $lbFactory->commitMasterChanges( __METHOD__ );
287 $this->assertFalse( $called, 'Not called in next round commit' );
288 }
289
290 /**
291 * @covers Wikimedia\Rdbms\Database::onTransactionResolution
292 * @covers Wikimedia\Rdbms\Database::runOnTransactionIdleCallbacks
293 */
294 public function testTransactionResolution() {
295 $db = $this->db;
296
297 $db->clearFlag( DBO_TRX );
298 $db->begin( __METHOD__ );
299 $called = false;
300 $db->onTransactionResolution( function () use ( $db, &$called ) {
301 $called = true;
302 $db->setFlag( DBO_TRX );
303 } );
304 $db->commit( __METHOD__ );
305 $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
306 $this->assertTrue( $called, 'Callback reached' );
307
308 $db->clearFlag( DBO_TRX );
309 $db->begin( __METHOD__ );
310 $called = false;
311 $db->onTransactionResolution( function () use ( $db, &$called ) {
312 $called = true;
313 $db->setFlag( DBO_TRX );
314 } );
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' );
318 }
319
320 /**
321 * @covers Wikimedia\Rdbms\Database::setTransactionListener
322 */
323 public function testTransactionListener() {
324 $db = $this->db;
325
326 $db->setTransactionListener( 'ping', function () use ( $db, &$called ) {
327 $called = true;
328 } );
329
330 $called = false;
331 $db->begin( __METHOD__ );
332 $db->commit( __METHOD__ );
333 $this->assertTrue( $called, 'Callback reached' );
334
335 $called = false;
336 $db->begin( __METHOD__ );
337 $db->commit( __METHOD__ );
338 $this->assertTrue( $called, 'Callback still reached' );
339
340 $called = false;
341 $db->begin( __METHOD__ );
342 $db->rollback( __METHOD__ );
343 $this->assertTrue( $called, 'Callback reached' );
344
345 $db->setTransactionListener( 'ping', null );
346 $called = false;
347 $db->begin( __METHOD__ );
348 $db->commit( __METHOD__ );
349 $this->assertFalse( $called, 'Callback not reached' );
350 }
351
352 /**
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).
358 *
359 * @return Database
360 */
361 private function getMockDB( $methods = [] ) {
362 static $abstractMethods = [
363 'fetchAffectedRowCount',
364 'closeConnection',
365 'dataSeek',
366 'doQuery',
367 'fetchObject', 'fetchRow',
368 'fieldInfo', 'fieldName',
369 'getSoftwareLink', 'getServerVersion',
370 'getType',
371 'indexInfo',
372 'insertId',
373 'lastError', 'lastErrno',
374 'numFields', 'numRows',
375 'open',
376 'strencode',
377 ];
378 $db = $this->getMockBuilder( Database::class )
379 ->disableOriginalConstructor()
380 ->setMethods( array_values( array_unique( array_merge(
381 $abstractMethods,
382 $methods
383 ) ) ) )
384 ->getMock();
385 $wdb = TestingAccessWrapper::newFromObject( $db );
386 $wdb->trxProfiler = new TransactionProfiler();
387 $wdb->connLogger = new \Psr\Log\NullLogger();
388 $wdb->queryLogger = new \Psr\Log\NullLogger();
389 return $db;
390 }
391
392 /**
393 * @covers Wikimedia\Rdbms\Database::flushSnapshot
394 */
395 public function testFlushSnapshot() {
396 $db = $this->getMockDB( [ 'isOpen' ] );
397 $db->method( 'isOpen' )->willReturn( true );
398
399 $db->flushSnapshot( __METHOD__ ); // ok
400 $db->flushSnapshot( __METHOD__ ); // ok
401
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 );
407
408 $this->assertFalse( (bool)$db->trxLevel(), "Transaction cleared." );
409 }
410
411 /**
412 * @covers Wikimedia\Rdbms\Database::getScopedLockAndFlush
413 * @covers Wikimedia\Rdbms\Database::lock
414 * @covers Wikimedia\Rdbms\Database::unlock
415 * @covers Wikimedia\Rdbms\Database::lockIsFree
416 */
417 public function testGetScopedLock() {
418 $db = $this->getMockDB( [ 'isOpen' ] );
419 $db->method( 'isOpen' )->willReturn( true );
420
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() );
428
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 );
436
437 $this->assertEquals( 0, $db->trxLevel() );
438
439 $db->setFlag( DBO_TRX );
440 try {
441 $this->badLockingMethodImplicit( $db );
442 } catch ( RunTimeException $e ) {
443 $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
444 }
445 $db->clearFlag( DBO_TRX );
446 $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
447 $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__ ) );
448
449 try {
450 $this->badLockingMethodExplicit( $db );
451 } catch ( RunTimeException $e ) {
452 $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
453 }
454 $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
455 $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__ ) );
456 }
457
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!" );
462 }
463
464 private function badLockingMethodExplicit( IDatabase $db ) {
465 $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__, 1 );
466 $db->begin( __METHOD__ );
467 throw new RunTimeException( "Uh oh!" );
468 }
469
470 /**
471 * @covers Wikimedia\Rdbms\Database::getFlag
472 * @covers Wikimedia\Rdbms\Database::setFlag
473 * @covers Wikimedia\Rdbms\Database::restoreFlags
474 */
475 public function testFlagSetting() {
476 $db = $this->db;
477 $origTrx = $db->getFlag( DBO_TRX );
478 $origSsl = $db->getFlag( DBO_SSL );
479
480 $origTrx
481 ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
482 : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
483 $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
484
485 $origSsl
486 ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
487 : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
488 $this->assertEquals( !$origSsl, $db->getFlag( DBO_SSL ) );
489
490 $db->restoreFlags( $db::RESTORE_INITIAL );
491 $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
492 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
493
494 $origTrx
495 ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
496 : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
497 $origSsl
498 ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
499 : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
500
501 $db->restoreFlags();
502 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
503 $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
504
505 $db->restoreFlags();
506 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
507 $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
508 }
509
510 /**
511 * @expectedException UnexpectedValueException
512 * @covers Wikimedia\Rdbms\Database::setFlag
513 */
514 public function testDBOIgnoreSet() {
515 $db = $this->getMockBuilder( DatabaseMysqli::class )
516 ->disableOriginalConstructor()
517 ->setMethods( null )
518 ->getMock();
519
520 $db->setFlag( Database::DBO_IGNORE );
521 }
522
523 /**
524 * @expectedException UnexpectedValueException
525 * @covers Wikimedia\Rdbms\Database::clearFlag
526 */
527 public function testDBOIgnoreClear() {
528 $db = $this->getMockBuilder( DatabaseMysqli::class )
529 ->disableOriginalConstructor()
530 ->setMethods( null )
531 ->getMock();
532
533 $db->clearFlag( Database::DBO_IGNORE );
534 }
535
536 /**
537 * @covers Wikimedia\Rdbms\Database::tablePrefix
538 * @covers Wikimedia\Rdbms\Database::dbSchema
539 */
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() );
548
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() );
556 }
557 }