MediaWiki REL1_33
NameTableStore.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Storage;
22
23use Exception;
31
37
40
42 private $cache;
43
45 private $logger;
46
48 private $tableCache = null;
49
51 private $domain = false;
52
54 private $cacheTTL;
55
57 private $table;
59 private $idField;
61 private $nameField;
63 private $normalizationCallback = null;
65 private $insertCallback = null;
66
85 public function __construct(
86 ILoadBalancer $dbLoadBalancer,
88 LoggerInterface $logger,
89 $table,
92 callable $normalizationCallback = null,
93 $dbDomain = false,
94 callable $insertCallback = null
95 ) {
96 $this->loadBalancer = $dbLoadBalancer;
97 $this->cache = $cache;
98 $this->logger = $logger;
99 $this->table = $table;
100 $this->idField = $idField;
101 $this->nameField = $nameField;
102 $this->normalizationCallback = $normalizationCallback;
103 $this->domain = $dbDomain;
104 $this->cacheTTL = IExpiringStore::TTL_MONTH;
105 $this->insertCallback = $insertCallback;
106 }
107
114 private function getDBConnection( $index, $flags = 0 ) {
115 return $this->loadBalancer->getConnectionRef( $index, [], $this->domain, $flags );
116 }
117
126 private function getCacheKey() {
127 return $this->cache->makeGlobalKey(
128 'NameTableSqlStore',
129 $this->table,
130 $this->loadBalancer->resolveDomainID( $this->domain )
131 );
132 }
133
138 private function normalizeName( $name ) {
139 if ( $this->normalizationCallback === null ) {
140 return $name;
141 }
142 return call_user_func( $this->normalizationCallback, $name );
143 }
144
162 public function acquireId( $name ) {
163 Assert::parameterType( 'string', $name, '$name' );
164 $name = $this->normalizeName( $name );
165
167 $searchResult = array_search( $name, $table, true );
168 if ( $searchResult === false ) {
169 $id = $this->store( $name );
170 if ( $id === null ) {
171 // RACE: $name was already in the db, probably just inserted, so load from master.
172 // Use DBO_TRX to avoid missing inserts due to other threads or REPEATABLE-READs.
173 // ...but not during unit tests, because we need the fake DB tables of the default
174 // connection.
175 $connFlags = defined( 'MW_PHPUNIT_TEST' ) ? 0 : ILoadBalancer::CONN_TRX_AUTOCOMMIT;
176 $table = $this->reloadMap( $connFlags );
177
178 $searchResult = array_search( $name, $table, true );
179 if ( $searchResult === false ) {
180 // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
181 $m = "No insert possible but master didn't give us a record for " .
182 "'{$name}' in '{$this->table}'";
183 $this->logger->error( $m );
184 throw new NameTableAccessException( $m );
185 }
186 } else {
187 if ( isset( $table[$id] ) ) {
188 // This can happen when a transaction is rolled back and acquireId is called in
189 // an onTransactionResolution() callback, which gets executed before retryStore()
190 // has a chance to run. The right thing to do in this case is to discard the old
191 // value. According to the contract of acquireId, the caller should not have
192 // used it outside the transaction, so it should not be persisted anywhere after
193 // the rollback.
194 $m = "Got ID $id for '$name' from insert"
195 . " into '{$this->table}', but ID $id was previously associated with"
196 . " the name '{$table[$id]}'. Overriding the old value, which presumably"
197 . " has been removed from the database due to a transaction rollback.";
198
199 $this->logger->warning( $m );
200 }
201
202 $table[$id] = $name;
203 $searchResult = $id;
204
205 // As store returned an ID we know we inserted so delete from WAN cache
206 $dbw = $this->getDBConnection( DB_MASTER );
207 $dbw->onTransactionPreCommitOrIdle( function () {
208 $this->cache->delete( $this->getCacheKey() );
209 } );
210 }
211 $this->tableCache = $table;
212 }
213
214 return $searchResult;
215 }
216
229 public function reloadMap( $connFlags = 0 ) {
230 if ( $connFlags !== 0 && defined( 'MW_PHPUNIT_TEST' ) ) {
231 // HACK: We can't use $connFlags while doing PHPUnit tests, because the
232 // fake database tables are bound to a single connection.
233 $connFlags = 0;
234 }
235
236 $dbw = $this->getDBConnection( DB_MASTER, $connFlags );
237 $this->tableCache = $this->loadTable( $dbw );
238 $dbw->onTransactionPreCommitOrIdle( function () {
239 $this->cache->reap( $this->getCacheKey(), INF );
240 } );
241
242 return $this->tableCache;
243 }
244
255 public function getId( $name ) {
256 Assert::parameterType( 'string', $name, '$name' );
257 $name = $this->normalizeName( $name );
258
260 $searchResult = array_search( $name, $table, true );
261
262 if ( $searchResult !== false ) {
263 return $searchResult;
264 }
265
266 throw NameTableAccessException::newFromDetails( $this->table, 'name', $name );
267 }
268
280 public function getName( $id ) {
281 Assert::parameterType( 'integer', $id, '$id' );
282
284 if ( array_key_exists( $id, $table ) ) {
285 return $table[$id];
286 }
288
289 $table = $this->cache->getWithSetCallback(
290 $this->getCacheKey(),
291 $this->cacheTTL,
292 function ( $oldValue, &$ttl, &$setOpts ) use ( $id, $fname ) {
293 // Check if cached value is up-to-date enough to have $id
294 if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
295 // Completely leave the cache key alone
296 $ttl = WANObjectCache::TTL_UNCACHEABLE;
297 // Use the old value
298 return $oldValue;
299 }
300 // Regenerate from replica DB, and master DB if needed
301 foreach ( [ DB_REPLICA, DB_MASTER ] as $source ) {
302 // Log a fallback to master
303 if ( $source === DB_MASTER ) {
304 $this->logger->info(
305 $fname . ' falling back to master select from ' .
306 $this->table . ' with id ' . $id
307 );
308 }
309 $db = $this->getDBConnection( $source );
310 $cacheSetOpts = Database::getCacheSetOptions( $db );
311 $table = $this->loadTable( $db );
312 if ( array_key_exists( $id, $table ) ) {
313 break; // found it
314 }
315 }
316 // Use the value from last source checked
317 $setOpts += $cacheSetOpts;
318
319 return $table;
320 },
321 [ 'minAsOf' => INF ] // force callback run
322 );
323
324 $this->tableCache = $table;
325
326 if ( array_key_exists( $id, $table ) ) {
327 return $table[$id];
328 }
329
330 throw NameTableAccessException::newFromDetails( $this->table, 'id', $id );
331 }
332
340 public function getMap() {
341 return $this->getTableFromCachesOrReplica();
342 }
343
347 private function getTableFromCachesOrReplica() {
348 if ( $this->tableCache !== null ) {
349 return $this->tableCache;
350 }
351
352 $table = $this->cache->getWithSetCallback(
353 $this->getCacheKey(),
354 $this->cacheTTL,
355 function ( $oldValue, &$ttl, &$setOpts ) {
356 $dbr = $this->getDBConnection( DB_REPLICA );
357 $setOpts += Database::getCacheSetOptions( $dbr );
358 return $this->loadTable( $dbr );
359 }
360 );
361
362 $this->tableCache = $table;
363
364 return $table;
365 }
366
374 private function loadTable( IDatabase $db ) {
375 $result = $db->select(
376 $this->table,
377 [
378 'id' => $this->idField,
379 'name' => $this->nameField
380 ],
381 [],
382 __METHOD__,
383 [ 'ORDER BY' => 'id' ]
384 );
385
386 $assocArray = [];
387 foreach ( $result as $row ) {
388 $assocArray[$row->id] = $row->name;
389 }
390
391 return $assocArray;
392 }
393
400 private function store( $name ) {
401 Assert::parameterType( 'string', $name, '$name' );
402 Assert::parameter( $name !== '', '$name', 'should not be an empty string' );
403 // Note: this is only called internally so normalization of $name has already occurred.
404
405 $dbw = $this->getDBConnection( DB_MASTER );
406
407 $id = null;
408 $dbw->doAtomicSection(
409 __METHOD__,
410 function ( IDatabase $unused, $fname )
411 use ( $name, &$id, $dbw ) {
412 // NOTE: use IDatabase from the parent scope here, not the function parameter.
413 // If $dbw is a wrapper around the actual DB, we need to call the wrapper here,
414 // not the inner instance.
415 $dbw->insert(
416 $this->table,
417 $this->getFieldsToStore( $name ),
418 $fname,
419 [ 'IGNORE' ]
420 );
421
422 if ( $dbw->affectedRows() === 0 ) {
423 $this->logger->info(
424 'Tried to insert name into table ' . $this->table . ', but value already existed.'
425 );
426
427 return;
428 }
429
430 $id = $dbw->insertId();
431
432 // Any open transaction may still be rolled back. If that happens, we have to re-try the
433 // insertion and restore a consistent state of the cached table.
434 $dbw->onAtomicSectionCancel(
435 function ( $trigger, IDatabase $unused ) use ( $name, $id, $dbw ) {
436 $this->retryStore( $dbw, $name, $id );
437 },
438 $fname );
439 },
440 IDatabase::ATOMIC_CANCELABLE
441 );
442
443 return $id;
444 }
445
454 private function retryStore( IDatabase $dbw, $name, $id ) {
455 // NOTE: in the closure below, use the IDatabase from the original method call,
456 // not the one passed to the closure as a parameter.
457 // If $dbw is a wrapper around the actual DB, we need to call the wrapper,
458 // not the inner instance.
459
460 try {
461 $dbw->doAtomicSection(
462 __METHOD__,
463 function ( IDatabase $unused, $fname ) use ( $name, $id, &$ok, $dbw ) {
464 // Try to insert a row with the ID we originally got.
465 // If that fails (because of a key conflict), we will just try to get another ID again later.
466 $dbw->insert(
467 $this->table,
468 $this->getFieldsToStore( $name, $id ),
469 $fname
470 );
471
472 // Make sure we re-load the map in case this gets rolled back again.
473 // We could re-try once more, but that bears the risk of an infinite loop.
474 // So let's just give up on the ID.
476 function ( $trigger, IDatabase $unused ) use ( $name, $id, $dbw ) {
477 $this->logger->warning(
478 'Re-insertion of name into table ' . $this->table
479 . ' was rolled back. Giving up and reloading the cache.'
480 );
481 $this->reloadMap( ILoadBalancer::CONN_TRX_AUTOCOMMIT );
482 },
483 $fname
484 );
485
486 $this->logger->info(
487 'Re-insert name into table ' . $this->table . ' after failed transaction.'
488 );
489 },
490 IDatabase::ATOMIC_CANCELABLE
491 );
492 } catch ( Exception $ex ) {
493 $this->logger->error(
494 'Re-insertion of name into table ' . $this->table . ' failed: ' . $ex->getMessage()
495 );
496 } finally {
497 // NOTE: we reload regardless of whether the above insert succeeded. There is
498 // only three possibilities: the insert succeeded, so the new map will have
499 // the desired $id/$name mapping. Or the insert failed because another
500 // process already inserted that same $id/$name mapping, in which case the
501 // new map will also have it. Or another process grabbed the desired ID for
502 // another name, or the database refuses to insert the given ID into the
503 // auto increment field - in that case, the new map will not have a mapping
504 // for $name (or has a different mapping for $name). In that last case, we can
505 // only hope that the ID produced within the failed transaction has not been
506 // used outside that transaction.
507
508 $this->reloadMap( ILoadBalancer::CONN_TRX_AUTOCOMMIT );
509 }
510 }
511
517 private function getFieldsToStore( $name, $id = null ) {
518 $fields = [];
519
520 $fields[$this->nameField] = $name;
521
522 if ( $id !== null ) {
523 $fields[$this->idField] = $id;
524 }
525
526 if ( $this->insertCallback !== null ) {
527 $fields = call_user_func( $this->insertCallback, $fields );
528 }
529 return $fields;
530 }
531
532}
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:123
Exception representing a failure to look up a row from a name table.
static newFromDetails( $tableName, $accessType, $accessValue)
store( $name)
Stores the given name in the DB, returning the ID when an insert occurs.
getId( $name)
Get the id of the given name.
getName( $id)
Get the name of the given id.
getMap()
Get the whole table, in no particular order as a map of ids to names.
acquireId( $name)
Acquire the id of the given name.
retryStore(IDatabase $dbw, $name, $id)
After the initial insertion got rolled back, this can be used to try the insertion again,...
loadTable(IDatabase $db)
Gets the table from the db.
getCacheKey()
Gets the cache key for names.
reloadMap( $connFlags=0)
Reloads the name table from the master database, and purges the WAN cache entry.
__construct(ILoadBalancer $dbLoadBalancer, WANObjectCache $cache, LoggerInterface $logger, $table, $idField, $nameField, callable $normalizationCallback=null, $dbDomain=false, callable $insertCallback=null)
Multi-datacenter aware caching interface.
Relational database abstraction object.
Definition Database.php:49
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs table
Definition deferred.txt:16
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
Generic interface for lightweight expiring object stores.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
doAtomicSection( $fname, callable $callback, $cancelable=self::ATOMIC_NOT_CANCELABLE)
Perform an atomic section of reversable SQL statements from a callback.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
onAtomicSectionCancel(callable $callback, $fname=__METHOD__)
Run a callback when the atomic section is cancelled.
insert( $table, $a, $fname=__METHOD__, $options=[])
INSERT wrapper, inserts an array into a table.
Database cluster connection, tracking, load balancing, and transaction manager interface.
you have access to all of the normal MediaWiki so you can get a DB use the cache
$source
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:26