MediaWiki REL1_32
NameTableStore.php
Go to the documentation of this file.
1<?php
21namespace MediaWiki\Storage;
22
24use Psr\Log\LoggerInterface;
26use Wikimedia\Assert\Assert;
30
36
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;
64 private $insertCallback = null;
65
84 public function __construct(
85 ILoadBalancer $dbLoadBalancer,
87 LoggerInterface $logger,
88 $table,
91 callable $normalizationCallback = null,
92 $wikiId = 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->wikiId = $wikiId;
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->wikiId, $flags );
115 }
116
125 private function getCacheKey() {
126 return $this->cache->makeGlobalKey(
127 'NameTableSqlStore',
128 $this->table,
129 $this->loadBalancer->resolveDomainID( $this->wikiId )
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
274 $ttl = WANObjectCache::TTL_UNCACHEABLE;
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 both 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}
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
Definition Setup.php:121
Exception representing a failure to look up a row from a name table.
static newFromDetails( $tableName, $accessType, $accessValue)
purgeWANCache( $purgeCallback)
Reap the WANCache entry for this table.
__construct(ILoadBalancer $dbLoadBalancer, WANObjectCache $cache, LoggerInterface $logger, $table, $idField, $nameField, callable $normalizationCallback=null, $wikiId=false, callable $insertCallback=null)
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.
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.
Multi-datacenter aware caching interface.
Relational database abstraction object.
Definition Database.php:48
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:302
Generic base class for storage interfaces.
Basic database interface for live and lazy-loaded relation database handles.
Definition IDatabase.php:38
select( $table, $vars, $conds='', $fname=__METHOD__, $options=[], $join_conds=[])
Execute a SELECT query constructed using the various parameters provided.
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
MediaWiki s SiteStore can be cached and stored in a flat in a json format If the SiteStore is frequently the file cache may provide a performance benefit over a database store
Definition sitescache.txt:4