3 namespace MediaWiki\Tests\Storage
;
8 use MediaWiki\Storage\NameTableAccessException
;
9 use MediaWiki\Storage\NameTableStore
;
10 use MediaWikiTestCase
;
11 use Psr\Log\NullLogger
;
13 use Wikimedia\Rdbms\IDatabase
;
14 use Wikimedia\Rdbms\LoadBalancer
;
15 use Wikimedia\TestingAccessWrapper
;
20 * @covers \MediaWiki\Storage\NameTableStore
22 class NameTableStoreTest
extends MediaWikiTestCase
{
24 public function setUp() {
25 $this->tablesUsed
[] = 'slot_roles';
29 protected function addCoreDBData() {
30 // The default implementation causes the slot_roles to already have content. Skip that.
33 private function populateTable( $values ) {
35 foreach ( $values as $name ) {
36 $insertValues[] = [ 'role_name' => $name ];
38 $this->db
->insert( 'slot_roles', $insertValues );
41 private function getHashWANObjectCache( $cacheBag ) {
42 return new WANObjectCache( [ 'cache' => $cacheBag ] );
47 * @return \PHPUnit_Framework_MockObject_MockObject|LoadBalancer
49 private function getMockLoadBalancer( $db ) {
50 $mock = $this->getMockBuilder( LoadBalancer
::class )
51 ->disableOriginalConstructor()
53 $mock->expects( $this->any() )
54 ->method( 'getConnection' )
59 private function getCallCheckingDb( $insertCalls, $selectCalls ) {
61 'select' => $selectCalls,
62 'insert' => $insertCalls,
63 'affectedRows' => null,
65 'getSessionLagStatus' => null,
66 'writesPending' => null,
67 'onTransactionPreCommitOrIdle' => null
69 $mock = $this->getMockBuilder( IDatabase
::class )
70 ->disableOriginalConstructor()
72 foreach ( $proxiedMethods as $method => $count ) {
73 $mock->expects( is_int( $count ) ?
$this->exactly( $count ) : $this->any() )
75 ->willReturnCallback( function ( ...$args ) use ( $method ) {
76 return call_user_func_array( [ $this->db
, $method ], $args );
82 private function getNameTableSqlStore(
86 $normalizationCallback = null,
87 $insertCallback = null
89 return new NameTableStore(
90 $this->getMockLoadBalancer( $this->getCallCheckingDb( $insertCalls, $selectCalls ) ),
91 $this->getHashWANObjectCache( $cacheBag ),
93 'slot_roles', 'role_id', 'role_name',
94 $normalizationCallback,
100 public function provideGetAndAcquireId() {
102 'no wancache, empty table' =>
103 [ new EmptyBagOStuff(), true, 1, [], 'foo', 1 ],
104 'no wancache, one matching value' =>
105 [ new EmptyBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
106 'no wancache, one not matching value' =>
107 [ new EmptyBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
108 'no wancache, multiple, one matching value' =>
109 [ new EmptyBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
110 'no wancache, multiple, no matching value' =>
111 [ new EmptyBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
112 'wancache, empty table' =>
113 [ new HashBagOStuff(), true, 1, [], 'foo', 1 ],
114 'wancache, one matching value' =>
115 [ new HashBagOStuff(), false, 1, [ 'foo' ], 'foo', 1 ],
116 'wancache, one not matching value' =>
117 [ new HashBagOStuff(), true, 1, [ 'bar' ], 'foo', 2 ],
118 'wancache, multiple, one matching value' =>
119 [ new HashBagOStuff(), false, 1, [ 'foo', 'bar' ], 'bar', 2 ],
120 'wancache, multiple, no matching value' =>
121 [ new HashBagOStuff(), true, 1, [ 'foo', 'bar' ], 'baz', 3 ],
126 * @dataProvider provideGetAndAcquireId
127 * @param BagOStuff $cacheBag to use in the WANObjectCache service
128 * @param bool $needsInsert Does the value we are testing need to be inserted?
129 * @param int $selectCalls Number of times the select DB method will be called
130 * @param string[] $existingValues to be added to the db table
131 * @param string $name name to acquire
132 * @param int $expectedId the id we expect the name to have
134 public function testGetAndAcquireId(
142 // Make sure the table is empty!
143 $this->truncateTable( 'slot_roles' );
145 $this->populateTable( $existingValues );
146 $store = $this->getNameTableSqlStore( $cacheBag, (int)$needsInsert, $selectCalls );
148 // Some names will not initially exist
150 $result = $store->getId( $name );
151 $this->assertSame( $expectedId, $result );
152 } catch ( NameTableAccessException
$e ) {
153 if ( $needsInsert ) {
154 $this->assertTrue( true ); // Expected exception
156 $this->fail( 'Did not expect an exception, but got one: ' . $e->getMessage() );
160 // All names should return their id here
161 $this->assertSame( $expectedId, $store->acquireId( $name ) );
163 // acquireId inserted these names, so now everything should exist with getId
164 $this->assertSame( $expectedId, $store->getId( $name ) );
166 // calling getId again will also still work, and not result in more selects
167 $this->assertSame( $expectedId, $store->getId( $name ) );
170 public function provideTestGetAndAcquireIdNameNormalization() {
171 yield
[ 'A', 'a', 'strtolower' ];
172 yield
[ 'b', 'B', 'strtoupper' ];
180 yield
[ 'ZZ', 'ZZ-a', __CLASS__
. '::appendDashAToString' ];
183 public static function appendDashAToString( $string ) {
184 return $string . '-a';
188 * @dataProvider provideTestGetAndAcquireIdNameNormalization
190 public function testGetAndAcquireIdNameNormalization(
193 $normalizationCallback
195 $store = $this->getNameTableSqlStore(
196 new EmptyBagOStuff(),
199 $normalizationCallback
201 $acquiredId = $store->acquireId( $nameIn );
202 $this->assertSame( $nameOut, $store->getName( $acquiredId ) );
205 public function provideGetName() {
207 [ new HashBagOStuff(), 3, 2 ],
208 [ new EmptyBagOStuff(), 3, 3 ],
213 * @dataProvider provideGetName
215 public function testGetName( BagOStuff
$cacheBag, $insertCalls, $selectCalls ) {
216 $now = microtime( true );
217 $cacheBag->setMockTime( $now );
218 // Check for operations to in-memory cache (IMC) and persistent cache (PC)
219 $store = $this->getNameTableSqlStore( $cacheBag, $insertCalls, $selectCalls );
221 // Get 1 ID and make sure getName returns correctly
222 $fooId = $store->acquireId( 'foo' ); // regen PC, set IMC, update IMC, tombstone PC
224 $this->assertSame( 'foo', $store->getName( $fooId ) ); // use IMC
227 // Get another ID and make sure getName returns correctly
228 $barId = $store->acquireId( 'bar' ); // update IMC, tombstone PC
230 $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
233 // Blitz the cache and make sure it still returns
234 TestingAccessWrapper
::newFromObject( $store )->tableCache
= null; // clear IMC
235 $this->assertSame( 'foo', $store->getName( $fooId ) ); // regen interim PC, set IMC
236 $this->assertSame( 'bar', $store->getName( $barId ) ); // use IMC
238 // Blitz the cache again and get another ID and make sure getName returns correctly
239 TestingAccessWrapper
::newFromObject( $store )->tableCache
= null; // clear IMC
240 $bazId = $store->acquireId( 'baz' ); // set IMC using interim PC, update IMC, tombstone PC
242 $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
243 $this->assertSame( 'baz', $store->getName( $bazId ) ); // uses IMC
246 public function testGetName_masterFallback() {
247 $store = $this->getNameTableSqlStore( new EmptyBagOStuff(), 1, 2 );
250 $fooId = $store->acquireId( 'foo' );
252 // Empty the process cache, getCachedTable() will now return this empty array
253 TestingAccessWrapper
::newFromObject( $store )->tableCache
= [];
255 // getName should fallback to master, which is why we assert 2 selectCalls above
256 $this->assertSame( 'foo', $store->getName( $fooId ) );
259 public function testGetMap_empty() {
260 $this->populateTable( [] );
261 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
262 $table = $store->getMap();
263 $this->assertSame( [], $table );
266 public function testGetMap_twoValues() {
267 $this->populateTable( [ 'foo', 'bar' ] );
268 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 1 );
270 // We are using a cache, so 2 calls should only result in 1 select on the db
272 $table = $store->getMap();
274 $expected = [ 1 => 'foo', 2 => 'bar' ];
275 $this->assertSame( $expected, $table );
276 // Make sure the table returned is the same as the cached table
277 $this->assertSame( $expected, TestingAccessWrapper
::newFromObject( $store )->tableCache
);
280 public function testReloadMap() {
281 $this->populateTable( [ 'foo' ] );
282 $store = $this->getNameTableSqlStore( new HashBagOStuff(), 0, 2 );
285 $this->assertCount( 1, $store->getMap() );
287 // add more stuff to the table, so the cache gets out of sync
288 $this->populateTable( [ 'bar' ] );
290 $expected = [ 1 => 'foo', 2 => 'bar' ];
291 $this->assertSame( $expected, $store->reloadMap() );
292 $this->assertSame( $expected, $store->getMap() );
295 public function testCacheRaceCondition() {
296 $wanHashBag = new HashBagOStuff();
297 $store1 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
298 $store2 = $this->getNameTableSqlStore( $wanHashBag, 1, 0 );
299 $store3 = $this->getNameTableSqlStore( $wanHashBag, 1, 1 );
301 // Cache the current table in the instances we will use
302 // This simulates multiple requests running simultaneously
307 // Store 2 separate names using different instances
308 $fooId = $store1->acquireId( 'foo' );
309 $barId = $store2->acquireId( 'bar' );
311 // Each of these instances should be aware of what they have inserted
312 $this->assertSame( $fooId, $store1->acquireId( 'foo' ) );
313 $this->assertSame( $barId, $store2->acquireId( 'bar' ) );
315 // A new store should be able to get both of these new Ids
316 // Note: before there was a race condition here where acquireId( 'bar' ) would update the
317 // cache with data missing the 'foo' key that it was not aware of
318 $store4 = $this->getNameTableSqlStore( $wanHashBag, 0, 1 );
319 $this->assertSame( $fooId, $store4->getId( 'foo' ) );
320 $this->assertSame( $barId, $store4->getId( 'bar' ) );
322 // If a store with old cached data tries to acquire these we will get the same ids.
323 $this->assertSame( $fooId, $store3->acquireId( 'foo' ) );
324 $this->assertSame( $barId, $store3->acquireId( 'bar' ) );
327 public function testGetAndAcquireIdInsertCallback() {
328 // FIXME: fails under postgres
329 $this->markTestSkippedIfDbType( 'postgres' );
331 $store = $this->getNameTableSqlStore(
332 new EmptyBagOStuff(),
336 function ( $insertFields ) {
337 $insertFields['role_id'] = 7251;
338 return $insertFields;
341 $this->assertSame( 7251, $store->acquireId( 'A' ) );