MediaWiki  1.30.0
DatabaseTest.php
Go to the documentation of this file.
1 <?php
2 
6 use Wikimedia\TestingAccessWrapper;
7 
8 class DatabaseTest extends PHPUnit_Framework_TestCase {
9 
10  protected function setUp() {
11  $this->db = new DatabaseTestHelper( __CLASS__ . '::' . $this->getName() );
12  }
13 
14  public static function provideAddQuotes() {
15  return [
16  [ null, 'NULL' ],
17  [ 1234, "'1234'" ],
18  [ 1234.5678, "'1234.5678'" ],
19  [ 'string', "'string'" ],
20  [ 'string\'s cause trouble', "'string\'s cause trouble'" ],
21  ];
22  }
23 
28  public function testAddQuotes( $input, $expected ) {
29  $this->assertEquals( $expected, $this->db->addQuotes( $input ) );
30  }
31 
32  public static function provideTableName() {
33  // Formatting is mostly ignored since addIdentifierQuotes is abstract.
34  // For testing of addIdentifierQuotes, see actual Database subclas tests.
35  return [
36  'local' => [
37  'tablename',
38  'tablename',
39  'quoted',
40  ],
41  'local-raw' => [
42  'tablename',
43  'tablename',
44  'raw',
45  ],
46  'shared' => [
47  'sharedb.tablename',
48  'tablename',
49  'quoted',
50  [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => '' ],
51  ],
52  'shared-raw' => [
53  'sharedb.tablename',
54  'tablename',
55  'raw',
56  [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => '' ],
57  ],
58  'shared-prefix' => [
59  'sharedb.sh_tablename',
60  'tablename',
61  'quoted',
62  [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => 'sh_' ],
63  ],
64  'shared-prefix-raw' => [
65  'sharedb.sh_tablename',
66  'tablename',
67  'raw',
68  [ 'dbname' => 'sharedb', 'schema' => null, 'prefix' => 'sh_' ],
69  ],
70  'foreign' => [
71  'databasename.tablename',
72  'databasename.tablename',
73  'quoted',
74  ],
75  'foreign-raw' => [
76  'databasename.tablename',
77  'databasename.tablename',
78  'raw',
79  ],
80  ];
81  }
82 
87  public function testTableName( $expected, $table, $format, array $alias = null ) {
88  if ( $alias ) {
89  $this->db->setTableAliases( [ $table => $alias ] );
90  }
91  $this->assertEquals(
92  $expected,
93  $this->db->tableName( $table, $format ?: 'quoted' )
94  );
95  }
96 
101  public function testTransactionIdle() {
102  $db = $this->db;
103 
104  $db->setFlag( DBO_TRX );
105  $called = false;
106  $flagSet = null;
107  $db->onTransactionIdle(
108  function () use ( $db, &$flagSet, &$called ) {
109  $called = true;
110  $flagSet = $db->getFlag( DBO_TRX );
111  },
112  __METHOD__
113  );
114  $this->assertFalse( $flagSet, 'DBO_TRX off in callback' );
115  $this->assertTrue( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
116  $this->assertTrue( $called, 'Callback reached' );
117 
118  $db->clearFlag( DBO_TRX );
119  $flagSet = null;
120  $db->onTransactionIdle(
121  function () use ( $db, &$flagSet ) {
122  $flagSet = $db->getFlag( DBO_TRX );
123  },
124  __METHOD__
125  );
126  $this->assertFalse( $flagSet, 'DBO_TRX off in callback' );
127  $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
128 
129  $db->clearFlag( DBO_TRX );
130  $db->onTransactionIdle(
131  function () use ( $db ) {
132  $db->setFlag( DBO_TRX );
133  },
134  __METHOD__
135  );
136  $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
137  }
138 
143  public function testTransactionPreCommitOrIdle() {
144  $db = $this->getMockDB( [ 'isOpen' ] );
145  $db->method( 'isOpen' )->willReturn( true );
146  $db->clearFlag( DBO_TRX );
147 
148  $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX is not set' );
149 
150  $called = false;
151  $db->onTransactionPreCommitOrIdle(
152  function () use ( &$called ) {
153  $called = true;
154  },
155  __METHOD__
156  );
157  $this->assertTrue( $called, 'Called when idle' );
158 
159  $db->begin( __METHOD__ );
160  $called = false;
161  $db->onTransactionPreCommitOrIdle(
162  function () use ( &$called ) {
163  $called = true;
164  },
165  __METHOD__
166  );
167  $this->assertFalse( $called, 'Not called when transaction is active' );
168  $db->commit( __METHOD__ );
169  $this->assertTrue( $called, 'Called when transaction is committed' );
170  }
171 
177  $db = $this->getMockDB( [ 'isOpen' ] );
178  $db->method( 'isOpen' )->willReturn( true );
179  $db->setFlag( DBO_TRX );
180 
181  $lbFactory = LBFactorySingle::newFromConnection( $db );
182  // Ask for the connectin so that LB sets internal state
183  // about this connection being the master connection
184  $lb = $lbFactory->getMainLB();
185  $conn = $lb->openConnection( $lb->getWriterIndex() );
186  $this->assertSame( $db, $conn, 'Same DB instance' );
187  $this->assertTrue( $db->getFlag( DBO_TRX ), 'DBO_TRX is set' );
188 
189  $called = false;
190  $db->onTransactionPreCommitOrIdle(
191  function () use ( &$called ) {
192  $called = true;
193  }
194  );
195  $this->assertFalse( $called, 'Not called when idle if DBO_TRX is set' );
196 
197  $lbFactory->beginMasterChanges( __METHOD__ );
198  $this->assertFalse( $called, 'Not called when lb-transaction is active' );
199 
200  $lbFactory->commitMasterChanges( __METHOD__ );
201  $this->assertTrue( $called, 'Called when lb-transaction is committed' );
202  }
203 
208  public function testTransactionResolution() {
209  $db = $this->db;
210 
211  $db->clearFlag( DBO_TRX );
212  $db->begin( __METHOD__ );
213  $called = false;
214  $db->onTransactionResolution( function () use ( $db, &$called ) {
215  $called = true;
216  $db->setFlag( DBO_TRX );
217  } );
218  $db->commit( __METHOD__ );
219  $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
220  $this->assertTrue( $called, 'Callback reached' );
221 
222  $db->clearFlag( DBO_TRX );
223  $db->begin( __METHOD__ );
224  $called = false;
225  $db->onTransactionResolution( function () use ( $db, &$called ) {
226  $called = true;
227  $db->setFlag( DBO_TRX );
228  } );
229  $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
230  $this->assertFalse( $db->getFlag( DBO_TRX ), 'DBO_TRX restored to default' );
231  $this->assertTrue( $called, 'Callback reached' );
232  }
233 
237  public function testTransactionListener() {
238  $db = $this->db;
239 
240  $db->setTransactionListener( 'ping', function () use ( $db, &$called ) {
241  $called = true;
242  } );
243 
244  $called = false;
245  $db->begin( __METHOD__ );
246  $db->commit( __METHOD__ );
247  $this->assertTrue( $called, 'Callback reached' );
248 
249  $called = false;
250  $db->begin( __METHOD__ );
251  $db->commit( __METHOD__ );
252  $this->assertTrue( $called, 'Callback still reached' );
253 
254  $called = false;
255  $db->begin( __METHOD__ );
256  $db->rollback( __METHOD__ );
257  $this->assertTrue( $called, 'Callback reached' );
258 
259  $db->setTransactionListener( 'ping', null );
260  $called = false;
261  $db->begin( __METHOD__ );
262  $db->commit( __METHOD__ );
263  $this->assertFalse( $called, 'Callback not reached' );
264  }
265 
275  private function getMockDB( $methods = [] ) {
276  static $abstractMethods = [
277  'affectedRows',
278  'closeConnection',
279  'dataSeek',
280  'doQuery',
281  'fetchObject', 'fetchRow',
282  'fieldInfo', 'fieldName',
283  'getSoftwareLink', 'getServerVersion',
284  'getType',
285  'indexInfo',
286  'insertId',
287  'lastError', 'lastErrno',
288  'numFields', 'numRows',
289  'open',
290  'strencode',
291  ];
292  $db = $this->getMockBuilder( Database::class )
293  ->disableOriginalConstructor()
294  ->setMethods( array_values( array_unique( array_merge(
295  $abstractMethods,
296  $methods
297  ) ) ) )
298  ->getMock();
299  $wdb = TestingAccessWrapper::newFromObject( $db );
300  $wdb->trxProfiler = new TransactionProfiler();
301  $wdb->connLogger = new \Psr\Log\NullLogger();
302  $wdb->queryLogger = new \Psr\Log\NullLogger();
303  return $db;
304  }
305 
309  public function testFlushSnapshot() {
310  $db = $this->getMockDB( [ 'isOpen' ] );
311  $db->method( 'isOpen' )->willReturn( true );
312 
313  $db->flushSnapshot( __METHOD__ ); // ok
314  $db->flushSnapshot( __METHOD__ ); // ok
315 
316  $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
317  $db->query( 'SELECT 1', __METHOD__ );
318  $this->assertTrue( (bool)$db->trxLevel(), "Transaction started." );
319  $db->flushSnapshot( __METHOD__ ); // ok
320  $db->restoreFlags( $db::RESTORE_PRIOR );
321 
322  $this->assertFalse( (bool)$db->trxLevel(), "Transaction cleared." );
323  }
324 
325  public function testGetScopedLock() {
326  $db = $this->getMockDB( [ 'isOpen' ] );
327  $db->method( 'isOpen' )->willReturn( true );
328 
329  $db->setFlag( DBO_TRX );
330  try {
331  $this->badLockingMethodImplicit( $db );
332  } catch ( RunTimeException $e ) {
333  $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
334  }
335  $db->clearFlag( DBO_TRX );
336  $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
337  $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__ ) );
338 
339  try {
340  $this->badLockingMethodExplicit( $db );
341  } catch ( RunTimeException $e ) {
342  $this->assertTrue( $db->trxLevel() > 0, "Transaction not committed." );
343  }
344  $db->rollback( __METHOD__, IDatabase::FLUSHING_ALL_PEERS );
345  $this->assertTrue( $db->lockIsFree( 'meow', __METHOD__ ) );
346  }
347 
348  private function badLockingMethodImplicit( IDatabase $db ) {
349  $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__, 1 );
350  $db->query( "SELECT 1" ); // trigger DBO_TRX
351  throw new RunTimeException( "Uh oh!" );
352  }
353 
354  private function badLockingMethodExplicit( IDatabase $db ) {
355  $lock = $db->getScopedLockAndFlush( 'meow', __METHOD__, 1 );
356  $db->begin( __METHOD__ );
357  throw new RunTimeException( "Uh oh!" );
358  }
359 
365  public function testFlagSetting() {
366  $db = $this->db;
367  $origTrx = $db->getFlag( DBO_TRX );
368  $origSsl = $db->getFlag( DBO_SSL );
369 
370  $origTrx
371  ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
372  : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
373  $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
374 
375  $origSsl
376  ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
377  : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
378  $this->assertEquals( !$origSsl, $db->getFlag( DBO_SSL ) );
379 
380  $db->restoreFlags( $db::RESTORE_INITIAL );
381  $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
382  $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
383 
384  $origTrx
385  ? $db->clearFlag( DBO_TRX, $db::REMEMBER_PRIOR )
386  : $db->setFlag( DBO_TRX, $db::REMEMBER_PRIOR );
387  $origSsl
388  ? $db->clearFlag( DBO_SSL, $db::REMEMBER_PRIOR )
389  : $db->setFlag( DBO_SSL, $db::REMEMBER_PRIOR );
390 
391  $db->restoreFlags();
392  $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
393  $this->assertEquals( !$origTrx, $db->getFlag( DBO_TRX ) );
394 
395  $db->restoreFlags();
396  $this->assertEquals( $origSsl, $db->getFlag( DBO_SSL ) );
397  $this->assertEquals( $origTrx, $db->getFlag( DBO_TRX ) );
398  }
399 
404  public function testMutators() {
405  $old = $this->db->tablePrefix();
406  $this->assertInternalType( 'string', $old, 'Prefix is string' );
407  $this->assertEquals( $old, $this->db->tablePrefix(), "Prefix unchanged" );
408  $this->assertEquals( $old, $this->db->tablePrefix( 'xxx' ) );
409  $this->assertEquals( 'xxx', $this->db->tablePrefix(), "Prefix set" );
410  $this->db->tablePrefix( $old );
411  $this->assertNotEquals( 'xxx', $this->db->tablePrefix() );
412 
413  $old = $this->db->dbSchema();
414  $this->assertInternalType( 'string', $old, 'Schema is string' );
415  $this->assertEquals( $old, $this->db->dbSchema(), "Schema unchanged" );
416  $this->assertEquals( $old, $this->db->dbSchema( 'xxx' ) );
417  $this->assertEquals( 'xxx', $this->db->dbSchema(), "Schema set" );
418  $this->db->dbSchema( $old );
419  $this->assertNotEquals( 'xxx', $this->db->dbSchema() );
420  }
421 }
Wikimedia\Rdbms\IDatabase\query
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
DatabaseTest\setUp
setUp()
Definition: DatabaseTest.php:10
DatabaseTest\badLockingMethodImplicit
badLockingMethodImplicit(IDatabase $db)
Definition: DatabaseTest.php:348
DatabaseTest\getMockDB
getMockDB( $methods=[])
Use this mock instead of DatabaseTestHelper for cases where DatabaseTestHelper is too inflexibile due...
Definition: DatabaseTest.php:275
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DatabaseTest\badLockingMethodExplicit
badLockingMethodExplicit(IDatabase $db)
Definition: DatabaseTest.php:354
DBO_SSL
const DBO_SSL
Definition: defines.php:17
DatabaseTest\testAddQuotes
testAddQuotes( $input, $expected)
provideAddQuotes Wikimedia\Rdbms\Database::addQuotes
Definition: DatabaseTest.php:28
DBO_TRX
const DBO_TRX
Definition: defines.php:12
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:40
DatabaseTest\testTransactionPreCommitOrIdle
testTransactionPreCommitOrIdle()
Wikimedia\Rdbms\Database::onTransactionPreCommitOrIdle Wikimedia\Rdbms\Database::runOnTransactionPreC...
Definition: DatabaseTest.php:143
DatabaseTest\testFlagSetting
testFlagSetting()
Wikimedia\Rdbms\Database::getFlag Wikimedia\Rdbms\Database::setFlag Wikimedia\Rdbms\Database::restore...
Definition: DatabaseTest.php:365
Wikimedia\Rdbms\LBFactorySingle
An LBFactory class that always returns a single database object.
Definition: LBFactorySingle.php:32
DatabaseTest\testGetScopedLock
testGetScopedLock()
Definition: DatabaseTest.php:325
$input
if(is_array( $mode)) switch( $mode) $input
Definition: postprocess-phan.php:141
DatabaseTest\testTransactionResolution
testTransactionResolution()
Wikimedia\Rdbms\Database::onTransactionResolution Wikimedia\Rdbms\Database::runOnTransactionIdleCallb...
Definition: DatabaseTest.php:208
$e
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
Definition: hooks.txt:2141
DatabaseTest\testTransactionPreCommitOrIdle_TRX
testTransactionPreCommitOrIdle_TRX()
Wikimedia\Rdbms\Database::onTransactionPreCommitOrIdle Wikimedia\Rdbms\Database::runOnTransactionPreC...
Definition: DatabaseTest.php:176
Wikimedia\Rdbms\IDatabase\getScopedLockAndFlush
getScopedLockAndFlush( $lockKey, $fname, $timeout)
Acquire a named lock, flush any transaction, and return an RAII style unlocker object.
DatabaseTest\testTransactionListener
testTransactionListener()
Wikimedia\Rdbms\Database::setTransactionListener.
Definition: DatabaseTest.php:237
DatabaseTest\testFlushSnapshot
testFlushSnapshot()
Wikimedia\Rdbms\Database::flushSnapshot.
Definition: DatabaseTest.php:309
DatabaseTest\testTransactionIdle
testTransactionIdle()
Wikimedia\Rdbms\Database::onTransactionIdle Wikimedia\Rdbms\Database::runOnTransactionIdleCallbacks.
Definition: DatabaseTest.php:101
DatabaseTestHelper
Helper for testing the methods from the Database class.
Definition: DatabaseTestHelper.php:10
DatabaseTest\testMutators
testMutators()
Wikimedia\Rdbms\Database::tablePrefix Wikimedia\Rdbms\Database::dbSchema.
Definition: DatabaseTest.php:404
DatabaseTest\testTableName
testTableName( $expected, $table, $format, array $alias=null)
provideTableName Wikimedia\Rdbms\Database::tableName
Definition: DatabaseTest.php:87
DatabaseTest
Definition: DatabaseTest.php:8
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
DatabaseTest\provideAddQuotes
static provideAddQuotes()
Definition: DatabaseTest.php:14
Wikimedia\Rdbms\TransactionProfiler
Helper class that detects high-contention DB queries via profiling calls.
Definition: TransactionProfiler.php:38
DatabaseTest\provideTableName
static provideTableName()
Definition: DatabaseTest.php:32
Wikimedia\Rdbms\IDatabase\begin
begin( $fname=__METHOD__, $mode=self::TRANSACTION_EXPLICIT)
Begin a transaction.
array
the array() calling protocol came about after MediaWiki 1.4rc1.