MediaWiki REL1_33
NameTableStore.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Storage;
22
23use Exception;
25use Psr\Log\LoggerInterface;
27use Wikimedia\Assert\Assert;
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
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 }
287 $fname = __METHOD__;
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}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1991
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:271
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:37
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