MediaWiki REL1_31
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;
63
75 public function __construct(
76 LoadBalancer $dbLoadBalancer,
78 LoggerInterface $logger,
79 $table,
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
222 $ttl = WANObjectCache::TTL_UNCACHEABLE;
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}
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(LoadBalancer $dbLoadBalancer, WANObjectCache $cache, LoggerInterface $logger, $table, $idField, $nameField, callable $normalizationCallback=null, $wikiId=false)
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.
Multi-datacenter aware caching interface.
Relational database abstraction object.
Definition Database.php:48
Database connection, tracking, load balancing, and transaction manager for a cluster.
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.
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:29
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