MediaWiki  REL1_31
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 $wikiId = false;
51 
53  private $cacheTTL;
54 
56  private $table;
58  private $idField;
60  private $nameField;
62  private $normalizationCallback = null;
63 
75  public function __construct(
76  LoadBalancer $dbLoadBalancer,
78  LoggerInterface $logger,
79  $table,
80  $idField,
81  $nameField,
82  callable $normalizationCallback = null,
83  $wikiId = false
84  ) {
85  $this->loadBalancer = $dbLoadBalancer;
86  $this->cache = $cache;
87  $this->logger = $logger;
88  $this->table = $table;
89  $this->idField = $idField;
90  $this->nameField = $nameField;
91  $this->normalizationCallback = $normalizationCallback;
92  $this->wikiId = $wikiId;
93  $this->cacheTTL = IExpiringStore::TTL_MONTH;
94  }
95 
102  private function getDBConnection( $index, $flags = 0 ) {
103  return $this->loadBalancer->getConnection( $index, [], $this->wikiId, $flags );
104  }
105 
106  private function getCacheKey() {
107  return $this->cache->makeKey( 'NameTableSqlStore', $this->table, $this->wikiId );
108  }
109 
114  private function normalizeName( $name ) {
115  if ( $this->normalizationCallback === null ) {
116  return $name;
117  }
118  return call_user_func( $this->normalizationCallback, $name );
119  }
120 
129  public function acquireId( $name ) {
130  Assert::parameterType( 'string', $name, '$name' );
131  $name = $this->normalizeName( $name );
132 
134  $searchResult = array_search( $name, $table, true );
135  if ( $searchResult === false ) {
136  $id = $this->store( $name );
137  if ( $id === null ) {
138  // RACE: $name was already in the db, probably just inserted, so load from master
139  // Use DBO_TRX to avoid missing inserts due to other threads or REPEATABLE-READs
140  $table = $this->loadTable(
141  $this->getDBConnection( DB_MASTER, LoadBalancer::CONN_TRX_AUTOCOMMIT )
142  );
143  $searchResult = array_search( $name, $table, true );
144  if ( $searchResult === false ) {
145  // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
146  $m = "No insert possible but master didn't give us a record for " .
147  "'{$name}' in '{$this->table}'";
148  $this->logger->error( $m );
149  throw new NameTableAccessException( $m );
150  }
151  $this->purgeWANCache(
152  function () {
153  $this->cache->reap( $this->getCacheKey(), INF );
154  }
155  );
156  } else {
157  $table[$id] = $name;
158  $searchResult = $id;
159  // As store returned an ID we know we inserted so delete from WAN cache
160  $this->purgeWANCache(
161  function () {
162  $this->cache->delete( $this->getCacheKey() );
163  }
164  );
165  }
166  $this->tableCache = $table;
167  }
168 
169  return $searchResult;
170  }
171 
182  public function getId( $name ) {
183  Assert::parameterType( 'string', $name, '$name' );
184  $name = $this->normalizeName( $name );
185 
187  $searchResult = array_search( $name, $table, true );
188 
189  if ( $searchResult !== false ) {
190  return $searchResult;
191  }
192 
193  throw NameTableAccessException::newFromDetails( $this->table, 'name', $name );
194  }
195 
207  public function getName( $id ) {
208  Assert::parameterType( 'integer', $id, '$id' );
209 
211  if ( array_key_exists( $id, $table ) ) {
212  return $table[$id];
213  }
214 
215  $table = $this->cache->getWithSetCallback(
216  $this->getCacheKey(),
217  $this->cacheTTL,
218  function ( $oldValue, &$ttl, &$setOpts ) use ( $id ) {
219  // Check if cached value is up-to-date enough to have $id
220  if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
221  // Completely leave the cache key alone
223  // Use the old value
224  return $oldValue;
225  }
226  // Regenerate from replica DB, and master DB if needed
227  foreach ( [ DB_REPLICA, DB_MASTER ] as $source ) {
228  // Log a fallback to master
229  if ( $source === DB_MASTER ) {
230  $this->logger->info(
231  __METHOD__ . 'falling back to master select from ' .
232  $this->table . ' with id ' . $id
233  );
234  }
235  $db = $this->getDBConnection( $source );
236  $cacheSetOpts = Database::getCacheSetOptions( $db );
237  $table = $this->loadTable( $db );
238  if ( array_key_exists( $id, $table ) ) {
239  break; // found it
240  }
241  }
242  // Use the value from last source checked
243  $setOpts += $cacheSetOpts;
244 
245  return $table;
246  },
247  [ 'minAsOf' => INF ] // force callback run
248  );
249 
250  $this->tableCache = $table;
251 
252  if ( array_key_exists( $id, $table ) ) {
253  return $table[$id];
254  }
255 
256  throw NameTableAccessException::newFromDetails( $this->table, 'id', $id );
257  }
258 
266  public function getMap() {
267  return $this->getTableFromCachesOrReplica();
268  }
269 
273  private function getTableFromCachesOrReplica() {
274  if ( $this->tableCache !== null ) {
275  return $this->tableCache;
276  }
277 
278  $table = $this->cache->getWithSetCallback(
279  $this->getCacheKey(),
280  $this->cacheTTL,
281  function ( $oldValue, &$ttl, &$setOpts ) {
282  $dbr = $this->getDBConnection( DB_REPLICA );
283  $setOpts += Database::getCacheSetOptions( $dbr );
284  return $this->loadTable( $dbr );
285  }
286  );
287 
288  $this->tableCache = $table;
289 
290  return $table;
291  }
292 
298  private function purgeWANCache( $purgeCallback ) {
299  // If the LB has no DB changes don't both with onTransactionPreCommitOrIdle
300  if ( !$this->loadBalancer->hasOrMadeRecentMasterChanges() ) {
301  $purgeCallback();
302  return;
303  }
304 
305  $this->getDBConnection( DB_MASTER )
306  ->onTransactionPreCommitOrIdle( $purgeCallback, __METHOD__ );
307  }
308 
316  private function loadTable( IDatabase $db ) {
317  $result = $db->select(
318  $this->table,
319  [
320  'id' => $this->idField,
321  'name' => $this->nameField
322  ],
323  [],
324  __METHOD__,
325  [ 'ORDER BY' => 'id' ]
326  );
327 
328  $assocArray = [];
329  foreach ( $result as $row ) {
330  $assocArray[$row->id] = $row->name;
331  }
332 
333  return $assocArray;
334  }
335 
342  private function store( $name ) {
343  Assert::parameterType( 'string', $name, '$name' );
344  Assert::parameter( $name !== '', '$name', 'should not be an empty string' );
345  // Note: this is only called internally so normalization of $name has already occurred.
346 
347  $dbw = $this->getDBConnection( DB_MASTER );
348 
349  $dbw->insert(
350  $this->table,
351  [ $this->nameField => $name ],
352  __METHOD__,
353  [ 'IGNORE' ]
354  );
355 
356  if ( $dbw->affectedRows() === 0 ) {
357  $this->logger->info(
358  'Tried to insert name into table ' . $this->table . ', but value already existed.'
359  );
360  return null;
361  }
362 
363  return $dbw->insertId();
364  }
365 
366 }
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:151
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
MediaWiki\Storage\NameTableStore\$normalizationCallback
null callable $normalizationCallback
Definition: NameTableStore.php:62
MediaWiki\Storage\NameTableStore\$tableCache
string[] $tableCache
Definition: NameTableStore.php:47
$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. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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! 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:1993
cache
you have access to all of the normal MediaWiki so you can get a DB use the cache
Definition: maintenance.txt:55
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:37
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 base class for storage interfaces.
Definition: IExpiringStore.php:31
MediaWiki\Storage\NameTableStore\getCacheKey
getCacheKey()
Definition: NameTableStore.php:106
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:4069
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:16
MediaWiki\Storage\NameTableStore\getTableFromCachesOrReplica
getTableFromCachesOrReplica()
Definition: NameTableStore.php:273
MediaWiki\Storage\NameTableStore\normalizeName
normalizeName( $name)
Definition: NameTableStore.php:114
MediaWiki\Storage\NameTableStore\acquireId
acquireId( $name)
Acquire the id of the given name.
Definition: NameTableStore.php:129
MediaWiki\Storage\NameTableStore\$loadBalancer
LoadBalancer $loadBalancer
Definition: NameTableStore.php:38
MediaWiki\Storage\NameTableStore\__construct
__construct(LoadBalancer $dbLoadBalancer, WANObjectCache $cache, LoggerInterface $logger, $table, $idField, $nameField, callable $normalizationCallback=null, $wikiId=false)
Definition: NameTableStore.php:75
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:207
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:342
Wikimedia\Rdbms\LoadBalancer
Database connection, tracking, load balancing, and transaction manager for a cluster.
Definition: LoadBalancer.php:41
MediaWiki\Storage\NameTableStore\getDBConnection
getDBConnection( $index, $flags=0)
Definition: NameTableStore.php:102
MediaWiki\Storage\NameTableStore\$cache
WANObjectCache $cache
Definition: NameTableStore.php:41
MediaWiki\Storage\NameTableStore\$nameField
string $nameField
Definition: NameTableStore.php:60
MediaWiki\Storage\NameTableStore\loadTable
loadTable(IDatabase $db)
Gets the table from the db.
Definition: NameTableStore.php:316
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:87
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:182
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
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:22
MediaWiki\Storage\NameTableStore\$wikiId
bool string $wikiId
Definition: NameTableStore.php:50
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\purgeWANCache
purgeWANCache( $purgeCallback)
Reap the WANCache entry for this table.
Definition: NameTableStore.php:298
MediaWiki\Storage\NameTableStore\getMap
getMap()
Get the whole table, in no particular order as a map of ids to names.
Definition: NameTableStore.php:266