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\LoadBalancer
;
35 class NameTableStore
{
37 /** @var LoadBalancer */
38 private $loadBalancer;
40 /** @var WANObjectCache */
43 /** @var LoggerInterface */
47 private $tableCache = null;
49 /** @var bool|string */
50 private $wikiId = false;
61 /** @var null|callable */
62 private $normalizationCallback = null;
63 /** @var null|callable */
64 private $insertCallback = null;
67 * @param LoadBalancer $dbLoadBalancer A load balancer for acquiring database connections
68 * @param WANObjectCache $cache A cache manager for caching data
69 * @param LoggerInterface $logger
70 * @param string $table
71 * @param string $idField
72 * @param string $nameField
73 * @param callable|null $normalizationCallback Normalization to be applied to names before being
74 * saved or queried. This should be a callback that accepts and returns a single string.
75 * @param bool|string $wikiId The ID of the target wiki database. Use false for the local wiki.
76 * @param callable|null $insertCallback Callback to change insert fields accordingly.
77 * This parameter was introduced in 1.32
79 public function __construct(
80 LoadBalancer
$dbLoadBalancer,
81 WANObjectCache
$cache,
82 LoggerInterface
$logger,
86 callable
$normalizationCallback = null,
88 callable
$insertCallback = null
90 $this->loadBalancer
= $dbLoadBalancer;
91 $this->cache
= $cache;
92 $this->logger
= $logger;
93 $this->table
= $table;
94 $this->idField
= $idField;
95 $this->nameField
= $nameField;
96 $this->normalizationCallback
= $normalizationCallback;
97 $this->wikiId
= $wikiId;
98 $this->cacheTTL
= IExpiringStore
::TTL_MONTH
;
99 $this->insertCallback
= $insertCallback;
103 * @param int $index A database index, like DB_MASTER or DB_REPLICA
104 * @param int $flags Database connection flags
108 private function getDBConnection( $index, $flags = 0 ) {
109 return $this->loadBalancer
->getConnection( $index, [], $this->wikiId
, $flags );
113 * Gets the cache key for names.
115 * The cache key is constructed based on the wiki ID passed to the constructor, and allows
116 * sharing of name tables cached for a specific database between wikis.
120 private function getCacheKey() {
121 return $this->cache
->makeGlobalKey(
124 $this->loadBalancer
->resolveDomainID( $this->wikiId
)
129 * @param string $name
132 private function normalizeName( $name ) {
133 if ( $this->normalizationCallback
=== null ) {
136 return call_user_func( $this->normalizationCallback
, $name );
140 * Acquire the id of the given name.
141 * This creates a row in the table if it doesn't already exist.
143 * @param string $name
144 * @throws NameTableAccessException
147 public function acquireId( $name ) {
148 Assert
::parameterType( 'string', $name, '$name' );
149 $name = $this->normalizeName( $name );
151 $table = $this->getTableFromCachesOrReplica();
152 $searchResult = array_search( $name, $table, true );
153 if ( $searchResult === false ) {
154 $id = $this->store( $name );
155 if ( $id === null ) {
156 // RACE: $name was already in the db, probably just inserted, so load from master
157 // Use DBO_TRX to avoid missing inserts due to other threads or REPEATABLE-READs
158 $table = $this->loadTable(
159 $this->getDBConnection( DB_MASTER
, LoadBalancer
::CONN_TRX_AUTOCOMMIT
)
161 $searchResult = array_search( $name, $table, true );
162 if ( $searchResult === false ) {
163 // Insert failed due to IGNORE flag, but DB_MASTER didn't give us the data
164 $m = "No insert possible but master didn't give us a record for " .
165 "'{$name}' in '{$this->table}'";
166 $this->logger
->error( $m );
167 throw new NameTableAccessException( $m );
169 $this->purgeWANCache(
171 $this->cache
->reap( $this->getCacheKey(), INF
);
177 // As store returned an ID we know we inserted so delete from WAN cache
178 $this->purgeWANCache(
180 $this->cache
->delete( $this->getCacheKey() );
184 $this->tableCache
= $table;
187 return $searchResult;
191 * Get the id of the given name.
192 * If the name doesn't exist this will throw.
193 * This should be used in cases where we believe the name already exists or want to check for
196 * @param string $name
197 * @throws NameTableAccessException The name does not exist
200 public function getId( $name ) {
201 Assert
::parameterType( 'string', $name, '$name' );
202 $name = $this->normalizeName( $name );
204 $table = $this->getTableFromCachesOrReplica();
205 $searchResult = array_search( $name, $table, true );
207 if ( $searchResult !== false ) {
208 return $searchResult;
211 throw NameTableAccessException
::newFromDetails( $this->table
, 'name', $name );
215 * Get the name of the given id.
216 * If the id doesn't exist this will throw.
217 * This should be used in cases where we believe the id already exists.
219 * Note: Calls to this method will result in a master select for non existing IDs.
222 * @throws NameTableAccessException The id does not exist
223 * @return string name
225 public function getName( $id ) {
226 Assert
::parameterType( 'integer', $id, '$id' );
228 $table = $this->getTableFromCachesOrReplica();
229 if ( array_key_exists( $id, $table ) ) {
233 $table = $this->cache
->getWithSetCallback(
234 $this->getCacheKey(),
236 function ( $oldValue, &$ttl, &$setOpts ) use ( $id ) {
237 // Check if cached value is up-to-date enough to have $id
238 if ( is_array( $oldValue ) && array_key_exists( $id, $oldValue ) ) {
239 // Completely leave the cache key alone
240 $ttl = WANObjectCache
::TTL_UNCACHEABLE
;
244 // Regenerate from replica DB, and master DB if needed
245 foreach ( [ DB_REPLICA
, DB_MASTER
] as $source ) {
246 // Log a fallback to master
247 if ( $source === DB_MASTER
) {
249 __METHOD__
. 'falling back to master select from ' .
250 $this->table
. ' with id ' . $id
253 $db = $this->getDBConnection( $source );
254 $cacheSetOpts = Database
::getCacheSetOptions( $db );
255 $table = $this->loadTable( $db );
256 if ( array_key_exists( $id, $table ) ) {
260 // Use the value from last source checked
261 $setOpts +
= $cacheSetOpts;
265 [ 'minAsOf' => INF
] // force callback run
268 $this->tableCache
= $table;
270 if ( array_key_exists( $id, $table ) ) {
274 throw NameTableAccessException
::newFromDetails( $this->table
, 'id', $id );
278 * Get the whole table, in no particular order as a map of ids to names.
279 * This method could be subject to DB or cache lag.
281 * @return string[] keys are the name ids, values are the names themselves
282 * Example: [ 1 => 'foo', 3 => 'bar' ]
284 public function getMap() {
285 return $this->getTableFromCachesOrReplica();
291 private function getTableFromCachesOrReplica() {
292 if ( $this->tableCache
!== null ) {
293 return $this->tableCache
;
296 $table = $this->cache
->getWithSetCallback(
297 $this->getCacheKey(),
299 function ( $oldValue, &$ttl, &$setOpts ) {
300 $dbr = $this->getDBConnection( DB_REPLICA
);
301 $setOpts +
= Database
::getCacheSetOptions( $dbr );
302 return $this->loadTable( $dbr );
306 $this->tableCache
= $table;
312 * Reap the WANCache entry for this table.
314 * @param callable $purgeCallback callback to 'purge' the WAN cache
316 private function purgeWANCache( $purgeCallback ) {
317 // If the LB has no DB changes don't both with onTransactionPreCommitOrIdle
318 if ( !$this->loadBalancer
->hasOrMadeRecentMasterChanges() ) {
323 $this->getDBConnection( DB_MASTER
)
324 ->onTransactionPreCommitOrIdle( $purgeCallback, __METHOD__
);
328 * Gets the table from the db
330 * @param IDatabase $db
334 private function loadTable( IDatabase
$db ) {
335 $result = $db->select(
338 'id' => $this->idField
,
339 'name' => $this->nameField
343 [ 'ORDER BY' => 'id' ]
347 foreach ( $result as $row ) {
348 $assocArray[$row->id
] = $row->name
;
355 * Stores the given name in the DB, returning the ID when an insert occurs.
357 * @param string $name
358 * @return int|null int if we know the ID, null if we don't
360 private function store( $name ) {
361 Assert
::parameterType( 'string', $name, '$name' );
362 Assert
::parameter( $name !== '', '$name', 'should not be an empty string' );
363 // Note: this is only called internally so normalization of $name has already occurred.
365 $dbw = $this->getDBConnection( DB_MASTER
);
369 $this->getFieldsToStore( $name ),
374 if ( $dbw->affectedRows() === 0 ) {
376 'Tried to insert name into table ' . $this->table
. ', but value already existed.'
381 return $dbw->insertId();
385 * @param string $name
388 private function getFieldsToStore( $name ) {
389 $fields = [ $this->nameField
=> $name ];
390 if ( $this->insertCallback
!== null ) {
391 $fields = call_user_func( $this->insertCallback
, $fields );