MediaWiki  1.33.1
NameTableStore.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Storage;
22 
24 use Psr\Log\LoggerInterface;
26 use Wikimedia\Assert\Assert;
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;
62  private $normalizationCallback = null;
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  $this->purgeWANCache(
187  function () {
188  $this->cache->delete( $this->getCacheKey() );
189  }
190  );
191  }
192  $this->tableCache = $table;
193  }
194 
195  return $searchResult;
196  }
197 
210  public function reloadMap( $connFlags = 0 ) {
211  $this->tableCache = $this->loadTable(
212  $this->getDBConnection( DB_MASTER, $connFlags )
213  );
214  $this->purgeWANCache(
215  function () {
216  $this->cache->reap( $this->getCacheKey(), INF );
217  }
218  );
219 
220  return $this->tableCache;
221  }
222 
233  public function getId( $name ) {
234  Assert::parameterType( 'string', $name, '$name' );
235  $name = $this->normalizeName( $name );
236 
238  $searchResult = array_search( $name, $table, true );
239 
240  if ( $searchResult !== false ) {
241  return $searchResult;
242  }
243 
244  throw NameTableAccessException::newFromDetails( $this->table, 'name', $name );
245  }
246 
258  public function getName( $id ) {
259  Assert::parameterType( 'integer', $id, '$id' );
260 
262  if ( array_key_exists( $id, $table ) ) {
263  return $table[$id];
264  }
265  $fname = __METHOD__;
266 
267  $table = $this->cache->getWithSetCallback(
268  $this->getCacheKey(),
269  $this->cacheTTL,
270  function ( $oldValue, &$ttl, &$setOpts ) use ( $id, $fname ) {
271  // Check if cached value is up-to-date enough to have $id
272  if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
273  // Completely leave the cache key alone
275  // Use the old value
276  return $oldValue;
277  }
278  // Regenerate from replica DB, and master DB if needed
279  foreach ( [ DB_REPLICA, DB_MASTER ] as $source ) {
280  // Log a fallback to master
281  if ( $source === DB_MASTER ) {
282  $this->logger->info(
283  $fname . ' falling back to master select from ' .
284  $this->table . ' with id ' . $id
285  );
286  }
287  $db = $this->getDBConnection( $source );
288  $cacheSetOpts = Database::getCacheSetOptions( $db );
289  $table = $this->loadTable( $db );
290  if ( array_key_exists( $id, $table ) ) {
291  break; // found it
292  }
293  }
294  // Use the value from last source checked
295  $setOpts += $cacheSetOpts;
296 
297  return $table;
298  },
299  [ 'minAsOf' => INF ] // force callback run
300  );
301 
302  $this->tableCache = $table;
303 
304  if ( array_key_exists( $id, $table ) ) {
305  return $table[$id];
306  }
307 
308  throw NameTableAccessException::newFromDetails( $this->table, 'id', $id );
309  }
310 
318  public function getMap() {
319  return $this->getTableFromCachesOrReplica();
320  }
321 
325  private function getTableFromCachesOrReplica() {
326  if ( $this->tableCache !== null ) {
327  return $this->tableCache;
328  }
329 
330  $table = $this->cache->getWithSetCallback(
331  $this->getCacheKey(),
332  $this->cacheTTL,
333  function ( $oldValue, &$ttl, &$setOpts ) {
334  $dbr = $this->getDBConnection( DB_REPLICA );
335  $setOpts += Database::getCacheSetOptions( $dbr );
336  return $this->loadTable( $dbr );
337  }
338  );
339 
340  $this->tableCache = $table;
341 
342  return $table;
343  }
344 
350  private function purgeWANCache( $purgeCallback ) {
351  // If the LB has no DB changes don't bother with onTransactionPreCommitOrIdle
352  if ( !$this->loadBalancer->hasOrMadeRecentMasterChanges() ) {
353  $purgeCallback();
354  return;
355  }
356 
357  $this->getDBConnection( DB_MASTER )
358  ->onTransactionPreCommitOrIdle( $purgeCallback, __METHOD__ );
359  }
360 
368  private function loadTable( IDatabase $db ) {
369  $result = $db->select(
370  $this->table,
371  [
372  'id' => $this->idField,
373  'name' => $this->nameField
374  ],
375  [],
376  __METHOD__,
377  [ 'ORDER BY' => 'id' ]
378  );
379 
380  $assocArray = [];
381  foreach ( $result as $row ) {
382  $assocArray[$row->id] = $row->name;
383  }
384 
385  return $assocArray;
386  }
387 
394  private function store( $name ) {
395  Assert::parameterType( 'string', $name, '$name' );
396  Assert::parameter( $name !== '', '$name', 'should not be an empty string' );
397  // Note: this is only called internally so normalization of $name has already occurred.
398 
399  $dbw = $this->getDBConnection( DB_MASTER );
400 
401  $dbw->insert(
402  $this->table,
403  $this->getFieldsToStore( $name ),
404  __METHOD__,
405  [ 'IGNORE' ]
406  );
407 
408  if ( $dbw->affectedRows() === 0 ) {
409  $this->logger->info(
410  'Tried to insert name into table ' . $this->table . ', but value already existed.'
411  );
412  return null;
413  }
414 
415  return $dbw->insertId();
416  }
417 
422  private function getFieldsToStore( $name ) {
423  $fields = [ $this->nameField => $name ];
424  if ( $this->insertCallback !== null ) {
425  $fields = call_user_func( $this->insertCallback, $fields );
426  }
427  return $fields;
428  }
429 
430 }
MediaWiki\Storage\NameTableStore\$logger
LoggerInterface $logger
Definition: NameTableStore.php:44
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:48
WANObjectCache\TTL_UNCACHEABLE
const TTL_UNCACHEABLE
Idiom for getWithSetCallback() callbacks to avoid calling set()
Definition: WANObjectCache.php:177
MediaWiki\Storage\NameTableStore\$normalizationCallback
null callable $normalizationCallback
Definition: NameTableStore.php:62
$result
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
MediaWiki\Storage\NameTableStore\$insertCallback
null callable $insertCallback
Definition: NameTableStore.php:64
MediaWiki\Storage\NameTableStore\$tableCache
string[] $tableCache
Definition: NameTableStore.php:47
cache
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:52
MediaWiki\Storage\NameTableStore\$idField
string $idField
Definition: NameTableStore.php:58
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:38
$dbr
$dbr
Definition: testCompression.php:50
MediaWiki\Storage\NameTableStore\$cacheTTL
int $cacheTTL
Definition: NameTableStore.php:53
IExpiringStore
Generic interface for lightweight expiring object stores.
Definition: IExpiringStore.php:31
MediaWiki\Storage\NameTableStore\getCacheKey
getCacheKey()
Gets the cache key for names.
Definition: NameTableStore.php:125
Wikimedia\Rdbms\Database\getCacheSetOptions
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:4305
table
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
MediaWiki\Storage\NameTableStore\getTableFromCachesOrReplica
getTableFromCachesOrReplica()
Definition: NameTableStore.php:325
MediaWiki\Storage\NameTableStore\__construct
__construct(ILoadBalancer $dbLoadBalancer, WANObjectCache $cache, LoggerInterface $logger, $table, $idField, $nameField, callable $normalizationCallback=null, $dbDomain=false, callable $insertCallback=null)
Definition: NameTableStore.php:84
MediaWiki\Storage\NameTableStore\normalizeName
normalizeName( $name)
Definition: NameTableStore.php:137
MediaWiki\Storage\NameTableStore\getFieldsToStore
getFieldsToStore( $name)
Definition: NameTableStore.php:422
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
MediaWiki\Storage\NameTableStore\acquireId
acquireId( $name)
Acquire the id of the given name.
Definition: NameTableStore.php:152
MediaWiki\Storage\NameTableStore\$domain
bool string $domain
Definition: NameTableStore.php:50
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
DB_MASTER
const DB_MASTER
Definition: defines.php:26
MediaWiki\Storage\NameTableStore\getName
getName( $id)
Get the name of the given id.
Definition: NameTableStore.php:258
IExpiringStore\TTL_MONTH
const TTL_MONTH
Definition: IExpiringStore.php:38
MediaWiki\Storage\NameTableStore\store
store( $name)
Stores the given name in the DB, returning the ID when an insert occurs.
Definition: NameTableStore.php:394
$fname
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition: Setup.php:123
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
MediaWiki\Storage\NameTableStore\getDBConnection
getDBConnection( $index, $flags=0)
Definition: NameTableStore.php:113
MediaWiki\Storage\NameTableStore\$cache
WANObjectCache $cache
Definition: NameTableStore.php:41
MediaWiki\Storage\NameTableStore\$nameField
string $nameField
Definition: NameTableStore.php:60
MediaWiki\Storage\NameTableStore\reloadMap
reloadMap( $connFlags=0)
Reloads the name table from the master database, and purges the WAN cache entry.
Definition: NameTableStore.php:210
MediaWiki\Storage\NameTableStore\loadTable
loadTable(IDatabase $db)
Gets the table from the db.
Definition: NameTableStore.php:368
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:116
MediaWiki\Storage\NameTableAccessException\newFromDetails
static newFromDetails( $tableName, $accessType, $accessValue)
Definition: NameTableAccessException.php:40
MediaWiki\Storage\NameTableStore
Definition: NameTableStore.php:35
MediaWiki\Storage
Definition: BlobAccessException.php:23
MediaWiki\Storage\NameTableStore\getId
getId( $name)
Get the id of the given name.
Definition: NameTableStore.php:233
MediaWiki\Storage\NameTableStore\$table
string $table
Definition: NameTableStore.php:56
as
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
MediaWiki\Storage\NameTableAccessException
Exception representing a failure to look up a row from a name table.
Definition: NameTableAccessException.php:32
Wikimedia\Rdbms\IDatabase\select
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
$source
$source
Definition: mwdoc-filter.php:46
MediaWiki\Storage\NameTableStore\$loadBalancer
ILoadBalancer $loadBalancer
Definition: NameTableStore.php:38
MediaWiki\Storage\NameTableStore\purgeWANCache
purgeWANCache( $purgeCallback)
Reap the WANCache entry for this table.
Definition: NameTableStore.php:350
MediaWiki\Storage\NameTableStore\getMap
getMap()
Get the whole table, in no particular order as a map of ids to names.
Definition: NameTableStore.php:318
Wikimedia\Rdbms\ILoadBalancer
Database cluster connection, tracking, load balancing, and transaction manager interface.
Definition: ILoadBalancer.php:78