85574b743e20cf17eb956778b9603128399671e9
[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 $db->onTransactionPreCommitOrIdle(
267 function () use ( &$called ) {
268 $called = true;
269 }
270 );
271 $this->assertFalse( $called, 'Not called when idle if DBO_TRX is set' );
272
273 $lbFactory->beginMasterChanges( __METHOD__ );
274 $this->assertFalse( $called, 'Not called when lb-transaction is active' );
275
276 $lbFactory->commitMasterChanges( __METHOD__ );
277 $this->assertTrue( $called, 'Called when lb-transaction is committed' );
278 }
279
280 /**
281 * @covers Wikimedia\Rdbms\Database::onTransactionResolution
282 * @covers Wikimedia\Rdbms\Database::runOnTransactionIdleCallbacks
283 */
284 public function testTransactionResolution() {
285 $db = $this->db;
286
287 $db->clearFlag( DBO_TRX );
288 $db->begin( __METHOD__ );
289 $called = false;
290 $db->onTransactionResolution( function () use ( $db, &$called ) {
291 $called = true;
292 $db->setFlag( DBO_TRX );
293 } );
294 $db->commit( __METHOD__ );
295 $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
296 $this->assertTrue( $called, 'Callback reached' );
297
298 $db->clearFlag( DBO_TRX );
299 $db->begin( __METHOD__ );
300 $called = false;
301 $db->onTransactionResolution( function () use ( $db, &$called ) {
302 $called = true;
303 $db->setFlag( DBO_TRX );
304 } );
305 $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
306 $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
307 $this->assertTrue( $called, 'Callback reached' );
308 }
309
310 /**
311 * @covers Wikimedia\Rdbms\Database::setTransactionListener
312 */
313 public function testTransactionListener() {
314 $db = $this->db;
315
316 $db->setTransactionListener( 'ping', function () use ( $db, &$called ) {
317 $called = true;
318 } );
319
320 $called = false;
321 $db->begin( __METHOD__ );
322 $db->commit( __METHOD__ );
323 $this->assertTrue( $called, 'Callback reached' );
324
325 $called = false;
326 $db->begin( __METHOD__ );
327 $db->commit( __METHOD__ );
328 $this->assertTrue( $called, 'Callback still reached' );
329
330 $called = false;
331 $db->begin( __METHOD__ );
332 $db->rollback( __METHOD__ );
333 $this->assertTrue( $called, 'Callback reached' );
334
335 $db->setTransactionListener( 'ping', null );
336 $called = false;
337 $db->begin( __METHOD__ );
338 $db->commit( __METHOD__ );
339 $this->assertFalse( $called, 'Callback not reached' );
340 }
341
342 /**
343 * Use this mock instead of DatabaseTestHelper for cases where
344 * DatabaseTestHelper is too inflexibile due to mocking too much
345 * or being too restrictive about fname matching (e.g. for tests
346 * that assert behaviour when the name is a mismatch, we need to
347 * catch the error here instead of there).
348 *
349 * @return Database
350 */
351 private function getMockDB( $methods = [] ) {
352 static $abstractMethods = [
353 'fetchAffectedRowCount',
354 'closeConnection',
355 'dataSeek',
356 'doQuery',
357 'fetchObject', 'fetchRow',
358 'fieldInfo', 'fieldName',
359 'getSoftwareLink', 'getServerVersion',
360 'getType',
361 'indexInfo',
362 'insertId',
363 'lastError', 'lastErrno',
364 'numFields', 'numRows',
365 'open',
366 'strencode',
367 ];
368 $db = $this->getMockBuilder( Database::class )
369 ->disableOriginalConstructor()
370 ->setMethods( array_values( array_unique( array_merge(
371 $abstractMethods,
372 $methods
373 ) ) ) )
374 ->getMock();
375 $wdb = TestingAccessWrapper::newFromObject( $db );
376 $wdb->trxProfiler = new TransactionProfiler();
377 $wdb->connLogger = new \Psr\Log\NullLogger();
378 $wdb->queryLogger = new \Psr\Log\NullLogger();
379 return $db;
380 }
381
382 /**
383 * @covers Wikimedia\Rdbms\Database::flushSnapshot
384 */
385 public function testFlushSnapshot() {
386 $db = $this->getMockDB( [ 'isOpen' ] );
387 $db->method( 'isOpen' )->willReturn( true );
388
389 $db->flushSnapshot( __METHOD__ ); // ok
390 $db->flushSnapshot( __METHOD__ ); // ok
391
392 $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
393 $db->query( 'SELECT 1', __METHOD__ );
394 $this->assertTrue( (bool)$db->trxLevel(), "Transaction started." );
395 $db->flushSnapshot( __METHOD__ ); // ok
396 $db->restoreFlags( $db::RESTORE_PRIOR );
397
398 $this->assertFalse( (bool)$db->trxLevel(), "Transaction cleared." );
399 }
400
401 /**
402 * @covers Wikimedia\Rdbms\Database::getScopedLockAndFlush
403 * @covers Wikimedia\Rdbms\Database::lock
404 * @covers Wikimedia\Rdbms\Database::unlock
405 * @covers Wikimedia\Rdbms\Database::lockIsFree
406 */
407 public function testGetScopedLock() {
408 $db = $this->getMockDB( [ 'isOpen' ] );
409 $db->method( 'isOpen' )->willReturn( true );
410
411 $this->assertEquals( 0, $db->trxLevel() );
412 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__ ) );
413 $this->assertEquals( true, $db->lock( 'x', __METHOD__ ) );
414 $this->assertEquals( false, $db->lockIsFree( 'x', __METHOD__ ) );
415 $this->assertEquals( true, $db->unlock( 'x', __METHOD__ ) );
416 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__ ) );
417 $this->assertEquals( 0, $db->trxLevel() );
418
419 $db->setFlag( DBO_TRX );
420 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__ ) );
421 $this->assertEquals( true, $db->lock( 'x', __METHOD__ ) );
422 $this->assertEquals( false, $db->lockIsFree( 'x', __METHOD__ ) );
423 $this->assertEquals( true, $db->unlock( 'x', __METHOD__ ) );
424 $this->assertEquals( true, $db->lockIsFree( 'x', __METHOD__ ) );
425 $db->clearFlag( DBO_TRX );
426
427 $this->assertEquals( 0, $db->trxLevel() );
428
429 $db->setFlag( DBO_TRX );
430 try {
431 $this->badLockingMethodImplicit( $db );
432 } catch ( RunTimeException $e ) {
433 $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
434 }
435 $db->clearFlag( DBO_TRX );
436 $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
437 $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__ ) );
438
439 try {
440 $this->badLockingMethodExplicit( $db );
441 } catch ( RunTimeException $e ) {
442 $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
443 }
444 $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
445 $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__ ) );
446 }
447
448 private function badLockingMethodImplicit( IDatabase $db ) {
449 $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__, 1 );
450 $db->query( "SELECT 1" ); // trigger DBO_TRX
451 throw new RunTimeException( "Uh oh!" );
452 }
453
454 private function badLockingMethodExplicit( IDatabase $db ) {
455 $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__, 1 );
456 $db->begin( __METHOD__ );
457 throw new RunTimeException( "Uh oh!" );
458 }
459
460 /**
461 * @covers Wikimedia\Rdbms\Database::getFlag
462 * @covers Wikimedia\Rdbms\Database::setFlag
463 * @covers Wikimedia\Rdbms\Database::restoreFlags
464 */
465 public function testFlagSetting() {
466 $db = $this->db;
467 $origTrx = $db->getFlag( DBO_TRX );
468 $origSsl = $db->getFlag( DBO_SSL );
469
470 $origTrx
471 ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
472 : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
473 $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
474
475 $origSsl
476 ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
477 : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
478 $this->assertEquals( !$origSsl, $db->getFlag( DBO_SSL ) );
479
480 $db->restoreFlags( $db::RESTORE_INITIAL );
481 $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
482 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
483
484 $origTrx
485 ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
486 : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
487 $origSsl
488 ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
489 : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
490
491 $db->restoreFlags();
492 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
493 $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
494
495 $db->restoreFlags();
496 $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
497 $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
498 }
499
500 /**
501 * @expectedException UnexpectedValueException
502 * @covers Wikimedia\Rdbms\Database::setFlag
503 */
504 public function testDBOIgnoreSet() {
505 $db = $this->getMockBuilder( DatabaseMysqli::class )
506 ->disableOriginalConstructor()
507 ->setMethods( null )
508 ->getMock();
509
510 $db->setFlag( Database::DBO_IGNORE );
511 }
512
513 /**
514 * @expectedException UnexpectedValueException
515 * @covers Wikimedia\Rdbms\Database::clearFlag
516 */
517 public function testDBOIgnoreClear() {
518 $db = $this->getMockBuilder( DatabaseMysqli::class )
519 ->disableOriginalConstructor()
520 ->setMethods( null )
521 ->getMock();
522
523 $db->clearFlag( Database::DBO_IGNORE );
524 }
525
526 /**
527 * @covers Wikimedia\Rdbms\Database::tablePrefix
528 * @covers Wikimedia\Rdbms\Database::dbSchema
529 */
530 public function testMutators() {
531 $old = $this->db->tablePrefix();
532 $this->assertInternalType( 'string', $old, 'Prefix is string' );
533 $this->assertEquals( $old, $this->db->tablePrefix(), "Prefix unchanged" );
534 $this->assertEquals( $old, $this->db->tablePrefix( 'xxx' ) );
535 $this->assertEquals( 'xxx', $this->db->tablePrefix(), "Prefix set" );
536 $this->db->tablePrefix( $old );
537 $this->assertNotEquals( 'xxx', $this->db->tablePrefix() );
538
539 $old = $this->db->dbSchema();
540 $this->assertInternalType( 'string', $old, 'Schema is string' );
541 $this->assertEquals( $old, $this->db->dbSchema(), "Schema unchanged" );
542 $this->assertEquals( $old, $this->db->dbSchema( 'xxx' ) );
543 $this->assertEquals( 'xxx', $this->db->dbSchema(), "Schema set" );
544 $this->db->dbSchema( $old );
545 $this->assertNotEquals( 'xxx', $this->db->dbSchema() );
546 }
547 }