3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Storage
;
24 use Psr\Log\LoggerInterface
;
26 use Wikimedia\Assert\Assert
;
27 use Wikimedia\Rdbms\Database
;
28 use Wikimedia\Rdbms\IDatabase
;
29 use Wikimedia\Rdbms\ILoadBalancer
;
30 use Wikimedia\Rdbms\LoadBalancer
;
36 class NameTableStore
{
38 /** @var LoadBalancer */
39 private $loadBalancer;
41 /** @var WANObjectCache */
44 /** @var LoggerInterface */
48 private $tableCache = null;
50 /** @var bool|string */
51 private $wikiId = false;
62 /** @var null|callable */
63 private $normalizationCallback = null;
64 /** @var null|callable */
65 private $insertCallback = null;
68 * @param ILoadBalancer $dbLoadBalancer A load balancer for acquiring database connections
69 * @param WANObjectCache $cache A cache manager for caching data. This can be the local
70 * wiki's default instance even if $wikiId refers to a different wiki, since
71 * makeGlobalKey() is used to constructed a key that allows cached names from
72 * the same database to be re-used between wikis. For example, enwiki and frwiki will
73 * use the same cache keys for names from the wikidatawiki database, regardless
74 * of the cache's default key space.
75 * @param LoggerInterface $logger
76 * @param string $table
77 * @param string $idField
78 * @param string $nameField
79 * @param callable|null $normalizationCallback Normalization to be applied to names before being
80 * saved or queried. This should be a callback that accepts and returns a single string.
81 * @param bool|string $wikiId The ID of the target wiki database. Use false for the local wiki.
82 * @param callable|null $insertCallback Callback to change insert fields accordingly.
83 * This parameter was introduced in 1.32
85 public function __construct(
86 ILoadBalancer
$dbLoadBalancer,
87 WANObjectCache
$cache,
88 LoggerInterface
$logger,
92 callable
$normalizationCallback = null,
94 callable
$insertCallback = null
96 $this->loadBalancer
= $dbLoadBalancer;
97 $this->cache
= $cache;
98 $this->logger
= $logger;
99 $this->table
= $table;
100 $this->idField
= $idField;
101 $this->nameField
= $nameField;
102 $this->normalizationCallback
= $normalizationCallback;
103 $this->wikiId
= $wikiId;
104 $this->cacheTTL
= IExpiringStore
::TTL_MONTH
;
105 $this->insertCallback
= $insertCallback;
109 * @param int $index A database index, like DB_MASTER or DB_REPLICA
110 * @param int $flags Database connection flags
114 private function getDBConnection( $index, $flags = 0 ) {
115 return $this->loadBalancer
->getConnection( $index, [], $this->wikiId
, $flags );
119 * Gets the cache key for names.
121 * The cache key is constructed based on the wiki ID passed to the constructor, and allows
122 * sharing of name tables cached for a specific database between wikis.
126 private function getCacheKey() {
127 return $this->cache
->makeGlobalKey(
130 $this->loadBalancer
->resolveDomainID( $this->wikiId
)
135 * @param string $name
138 private function normalizeName( $name ) {
139 if ( $this->normalizationCallback
=== null ) {
142 return call_user_func( $this->normalizationCallback
, $name );
146 * Acquire the id of the given name.
147 * This creates a row in the table if it doesn't already exist.
149 * @param string $name
150 * @throws NameTableAccessException
153 public function acquireId( $name ) {
154 Assert
::parameterType( 'string', $name, '$name' );
155 $name = $this->normalizeName( $name );
157 $table = $this->getTableFromCachesOrReplica();
158 $searchResult = array_search( $name, $table, true );
159 if ( $searchResult === false ) {
160 $id = $this->store( $name );
161 if ( $id === null ) {
162 // RACE: $name was already in the db, probably just inserted, so load from master
163 // Use DBO_TRX to avoid missing inserts due to other threads or REPEATABLE-READs
164 $table = $this->loadTable(
165 $this->getDBConnection( DB_MASTER
, LoadBalancer
::CONN_TRX_AUTOCOMMIT
)
167 $searchResult = array_search( $name, $table, true );
168 if ( $searchResult === false ) {
169 // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
170 $m = "No insert possible but master didn't give us a record for " .
171 "'{$name}' in '{$this->table}'";
172 $this->logger
->error( $m );
173 throw new NameTableAccessException( $m );
175 $this->purgeWANCache(
177 $this->cache
->reap( $this->getCacheKey(), INF
);
183 // As store returned an ID we know we inserted so delete from WAN cache
184 $this->purgeWANCache(
186 $this->cache
->delete( $this->getCacheKey() );
190 $this->tableCache
= $table;
193 return $searchResult;
197 * Get the id of the given name.
198 * If the name doesn't exist this will throw.
199 * This should be used in cases where we believe the name already exists or want to check for
202 * @param string $name
203 * @throws NameTableAccessException The name does not exist
206 public function getId( $name ) {
207 Assert
::parameterType( 'string', $name, '$name' );
208 $name = $this->normalizeName( $name );
210 $table = $this->getTableFromCachesOrReplica();
211 $searchResult = array_search( $name, $table, true );
213 if ( $searchResult !== false ) {
214 return $searchResult;
217 throw NameTableAccessException
::newFromDetails( $this->table
, 'name', $name );
221 * Get the name of the given id.
222 * If the id doesn't exist this will throw.
223 * This should be used in cases where we believe the id already exists.
225 * Note: Calls to this method will result in a master select for non existing IDs.
228 * @throws NameTableAccessException The id does not exist
229 * @return string name
231 public function getName( $id ) {
232 Assert
::parameterType( 'integer', $id, '$id' );
234 $table = $this->getTableFromCachesOrReplica();
235 if ( array_key_exists( $id, $table ) ) {
239 $table = $this->cache
->getWithSetCallback(
240 $this->getCacheKey(),
242 function ( $oldValue, &$ttl, &$setOpts ) use ( $id ) {
243 // Check if cached value is up-to-date enough to have $id
244 if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
245 // Completely leave the cache key alone
246 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
250 // Regenerate from replica DB, and master DB if needed
251 foreach ( [ DB_REPLICA
, DB_MASTER
] as $source ) {
252 // Log a fallback to master
253 if ( $source === DB_MASTER
) {
255 __METHOD__
. 'falling back to master select from ' .
256 $this->table
. ' with id ' . $id
259 $db = $this->getDBConnection( $source );
260 $cacheSetOpts = Database
::getCacheSetOptions( $db );
261 $table = $this->loadTable( $db );
262 if ( array_key_exists( $id, $table ) ) {
266 // Use the value from last source checked
267 $setOpts +
= $cacheSetOpts;
271 [ 'minAsOf' => INF
] // force callback run
274 $this->tableCache
= $table;
276 if ( array_key_exists( $id, $table ) ) {
280 throw NameTableAccessException
::newFromDetails( $this->table
, 'id', $id );
284 * Get the whole table, in no particular order as a map of ids to names.
285 * This method could be subject to DB or cache lag.
287 * @return string[] keys are the name ids, values are the names themselves
288 * Example: [ 1 => 'foo', 3 => 'bar' ]
290 public function getMap() {
291 return $this->getTableFromCachesOrReplica();
297 private function getTableFromCachesOrReplica() {
298 if ( $this->tableCache
!== null ) {
299 return $this->tableCache
;
302 $table = $this->cache
->getWithSetCallback(
303 $this->getCacheKey(),
305 function ( $oldValue, &$ttl, &$setOpts ) {
306 $dbr = $this->getDBConnection( DB_REPLICA
);
307 $setOpts +
= Database
::getCacheSetOptions( $dbr );
308 return $this->loadTable( $dbr );
312 $this->tableCache
= $table;
318 * Reap the WANCache entry for this table.
320 * @param callable $purgeCallback callback to 'purge' the WAN cache
322 private function purgeWANCache( $purgeCallback ) {
323 // If the LB has no DB changes don't both with onTransactionPreCommitOrIdle
324 if ( !$this->loadBalancer
->hasOrMadeRecentMasterChanges() ) {
329 $this->getDBConnection( DB_MASTER
)
330 ->onTransactionPreCommitOrIdle( $purgeCallback, __METHOD__
);
334 * Gets the table from the db
336 * @param IDatabase $db
340 private function loadTable( IDatabase
$db ) {
341 $result = $db->select(
344 'id' => $this->idField
,
345 'name' => $this->nameField
349 [ 'ORDER BY' => 'id' ]
353 foreach ( $result as $row ) {
354 $assocArray[$row->id
] = $row->name
;
361 * Stores the given name in the DB, returning the ID when an insert occurs.
363 * @param string $name
364 * @return int|null int if we know the ID, null if we don't
366 private function store( $name ) {
367 Assert
::parameterType( 'string', $name, '$name' );
368 Assert
::parameter( $name !== '', '$name', 'should not be an empty string' );
369 // Note: this is only called internally so normalization of $name has already occurred.
371 $dbw = $this->getDBConnection( DB_MASTER
);
375 $this->getFieldsToStore( $name ),
380 if ( $dbw->affectedRows() === 0 ) {
382 'Tried to insert name into table ' . $this->table
. ', but value already existed.'
387 return $dbw->insertId();
391 * @param string $name
394 private function getFieldsToStore( $name ) {
395 $fields = [ $this->nameField
=> $name ];
396 if ( $this->insertCallback
!== null ) {
397 $fields = call_user_func( $this->insertCallback
, $fields );