MediaWiki  master
NameTableStore.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Storage;
22 
30 
36 
38  private $loadBalancer;
39 
41  private $cache;
42 
44  private $logger;
45 
47  private $tableCache = null;
48 
50  private $domain = false;
51 
53  private $cacheTTL;
54 
56  private $table;
58  private $idField;
60  private $nameField;
64  private $insertCallback = null;
65 
84  public function __construct(
85  ILoadBalancer $dbLoadBalancer,
87  LoggerInterface $logger,
88  $table,
89  $idField,
90  $nameField,
91  callable $normalizationCallback = null,
92  $dbDomain = false,
93  callable $insertCallback = null
94  ) {
95  $this->loadBalancer = $dbLoadBalancer;
96  $this->cache = $cache;
97  $this->logger = $logger;
98  $this->table = $table;
99  $this->idField = $idField;
100  $this->nameField = $nameField;
101  $this->normalizationCallback = $normalizationCallback;
102  $this->domain = $dbDomain;
103  $this->cacheTTL = IExpiringStore::TTL_MONTH;
104  $this->insertCallback = $insertCallback;
105  }
106 
113  private function getDBConnection( $index, $flags = 0 ) {
114  return $this->loadBalancer->getConnection( $index, [], $this->domain, $flags );
115  }
116 
125  private function getCacheKey() {
126  return $this->cache->makeGlobalKey(
127  'NameTableSqlStore',
128  $this->table,
129  $this->loadBalancer->resolveDomainID( $this->domain )
130  );
131  }
132 
137  private function normalizeName( $name ) {
138  if ( $this->normalizationCallback === null ) {
139  return $name;
140  }
141  return call_user_func( $this->normalizationCallback, $name );
142  }
143 
152  public function acquireId( $name ) {
153  Assert::parameterType( 'string', $name, '$name' );
154  $name = $this->normalizeName( $name );
155 
157  $searchResult = array_search( $name, $table, true );
158  if ( $searchResult === false ) {
159  $id = $this->store( $name );
160  if ( $id === null ) {
161  // RACE: $name was already in the db, probably just inserted, so load from master.
162  // Use DBO_TRX to avoid missing inserts due to other threads or REPEATABLE-READs.
163  // ...but not during unit tests, because we need the fake DB tables of the default
164  // connection.
165  $connFlags = defined( 'MW_PHPUNIT_TEST' ) ? 0 : ILoadBalancer::CONN_TRX_AUTOCOMMIT;
166  $table = $this->reloadMap( $connFlags );
167 
168  $searchResult = array_search( $name, $table, true );
169  if ( $searchResult === false ) {
170  // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
171  $m = "No insert possible but master didn't give us a record for " .
172  "'{$name}' in '{$this->table}'";
173  $this->logger->error( $m );
174  throw new NameTableAccessException( $m );
175  }
176  } elseif ( isset( $table[$id] ) ) {
177  throw new NameTableAccessException(
178  "Expected unused ID from database insert for '$name' "
179  . " into '{$this->table}', but ID $id is already associated with"
180  . " the name '{$table[$id]}'! This may indicate database corruption!" );
181  } else {
182  $table[$id] = $name;
183  $searchResult = $id;
184 
185  // As store returned an ID we know we inserted so delete from WAN cache
186  $dbw = $this->getDBConnection( DB_MASTER );
187  $dbw->onTransactionPreCommitOrIdle( function () {
188  $this->cache->delete( $this->getCacheKey() );
189  } );
190  }
191  $this->tableCache = $table;
192  }
193 
194  return $searchResult;
195  }
196 
209  public function reloadMap( $connFlags = 0 ) {
210  $dbw = $this->getDBConnection( DB_MASTER, $connFlags );
211  $this->tableCache = $this->loadTable( $dbw );
212  $dbw->onTransactionPreCommitOrIdle( function () {
213  $this->cache->reap( $this->getCacheKey(), INF );
214  } );
215 
216  return $this->tableCache;
217  }
218 
229  public function getId( $name ) {
230  Assert::parameterType( 'string', $name, '$name' );
231  $name = $this->normalizeName( $name );
232 
234  $searchResult = array_search( $name, $table, true );
235 
236  if ( $searchResult !== false ) {
237  return $searchResult;
238  }
239 
240  throw NameTableAccessException::newFromDetails( $this->table, 'name', $name );
241  }
242 
254  public function getName( $id ) {
255  Assert::parameterType( 'integer', $id, '$id' );
256 
258  if ( array_key_exists( $id, $table ) ) {
259  return $table[$id];
260  }
261  $fname = __METHOD__;
262 
263  $table = $this->cache->getWithSetCallback(
264  $this->getCacheKey(),
265  $this->cacheTTL,
266  function ( $oldValue, &$ttl, &$setOpts ) use ( $id, $fname ) {
267  // Check if cached value is up-to-date enough to have $id
268  if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
269  // Completely leave the cache key alone
271  // Use the old value
272  return $oldValue;
273  }
274  // Regenerate from replica DB, and master DB if needed
275  foreach ( [ DB_REPLICA, DB_MASTER ] as $source ) {
276  // Log a fallback to master
277  if ( $source === DB_MASTER ) {
278  $this->logger->info(
279  $fname . ' falling back to master select from ' .
280  $this->table . ' with id ' . $id
281  );
282  }
283  $db = $this->getDBConnection( $source );
284  $cacheSetOpts = Database::getCacheSetOptions( $db );
285  $table = $this->loadTable( $db );
286  if ( array_key_exists( $id, $table ) ) {
287  break; // found it
288  }
289  }
290  // Use the value from last source checked
291  $setOpts += $cacheSetOpts;
292 
293  return $table;
294  },
295  [ 'minAsOf' => INF ] // force callback run
296  );
297 
298  $this->tableCache = $table;
299 
300  if ( array_key_exists( $id, $table ) ) {
301  return $table[$id];
302  }
303 
304  throw NameTableAccessException::newFromDetails( $this->table, 'id', $id );
305  }
306 
314  public function getMap() {
315  return $this->getTableFromCachesOrReplica();
316  }
317 
321  private function getTableFromCachesOrReplica() {
322  if ( $this->tableCache !== null ) {
323  return $this->tableCache;
324  }
325 
326  $table = $this->cache->getWithSetCallback(
327  $this->getCacheKey(),
328  $this->cacheTTL,
329  function ( $oldValue, &$ttl, &$setOpts ) {
330  $dbr = $this->getDBConnection( DB_REPLICA );
331  $setOpts += Database::getCacheSetOptions( $dbr );
332  return $this->loadTable( $dbr );
333  }
334  );
335 
336  $this->tableCache = $table;
337 
338  return $table;
339  }
340 
348  private function loadTable( IDatabase $db ) {
349  $result = $db->select(
350  $this->table,
351  [
352  'id' => $this->idField,
353  'name' => $this->nameField
354  ],
355  [],
356  __METHOD__,
357  [ 'ORDER BY' => 'id' ]
358  );
359 
360  $assocArray = [];
361  foreach ( $result as $row ) {
362  $assocArray[$row->id] = $row->name;
363  }
364 
365  return $assocArray;
366  }
367 
374  private function store( $name ) {
375  Assert::parameterType( 'string', $name, '$name' );
376  Assert::parameter( $name !== '', '$name', 'should not be an empty string' );
377  // Note: this is only called internally so normalization of $name has already occurred.
378 
379  $dbw = $this->getDBConnection( DB_MASTER );
380 
381  $dbw->insert(
382  $this->table,
383  $this->getFieldsToStore( $name ),
384  __METHOD__,
385  [ 'IGNORE' ]
386  );
387 
388  if ( $dbw->affectedRows() === 0 ) {
389  $this->logger->info(
390  'Tried to insert name into table ' . $this->table . ', but value already existed.'
391  );
392  return null;
393  }
394 
395  return $dbw->insertId();
396  }
397 
402  private function getFieldsToStore( $name ) {
403  $fields = [ $this->nameField => $name ];
404  if ( $this->insertCallback !== null ) {
405  $fields = call_user_func( $this->insertCallback, $fields );
406  }
407  return $fields;
408  }
409 
410 }
loadTable(IDatabase $db)
Gets the table from the db.
getId( $name)
Get the id of the given name.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Exception representing a failure to look up a row from a name table.
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
store( $name)
Stores the given name in the DB, returning the ID when an insert occurs.
$source
const DB_MASTER
Definition: defines.php:26
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. '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:1980
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
__construct(ILoadBalancer $dbLoadBalancer, WANObjectCache $cache, LoggerInterface $logger, $table, $idField, $nameField, callable $normalizationCallback=null, $dbDomain=false, callable $insertCallback=null)
getMap()
Get the whole table, in no particular order as a map of ids to names.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
static newFromDetails( $tableName, $accessType, $accessValue)
acquireId( $name)
Acquire the id of the given name.
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
Definition: distributors.txt:9
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:123
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
Database cluster connection, tracking, load balancing, and transaction manager interface.
reloadMap( $connFlags=0)
Reloads the name table from the master database, and purges the WAN cache entry.
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
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:11
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
getCacheKey()
Gets the cache key for names.
getName( $id)
Get the name of the given id.
static getCacheSetOptions(IDatabase $db1, IDatabase $db2=null)
Merge the result of getSessionLagStatus() for several DBs using the most pessimistic values to estima...
Definition: Database.php:4287
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
const DB_REPLICA
Definition: defines.php:25