Debian Codegraph @

includes/user/TempUser/DBSerialProvider.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\User\TempUser;
4
5 use Wikimedia\Rdbms\IDatabase;
6 use Wikimedia\Rdbms\RawSQLValue;
7
8 /**
9 * Base class for serial acquisition code shared between core and CentralAuth.
10 *
11 * @since 1.39
12 */
13 abstract class DBSerialProvider implements SerialProvider {
14 /** @var int */
15 private $numShards;
16
17 /**
18 * @param array $config
19 * - numShards (int, default 1): A small integer. This can be set to a
20 * value greater than 1 to avoid acquiring a global lock when
21 * allocating IDs, at the expense of making the IDs be non-monotonic.
22 */
23 public function __construct( $config ) {
24 $this->numShards = $config['numShards'] ?? 1;
25 }
26
27 public function acquireIndex( int $year = 0 ): int {
28 if ( $this->numShards ) {
29 $shard = mt_rand( 0, $this->numShards - 1 );
30 } else {
31 $shard = 0;
32 }
33
34 $dbw = $this->getDB();
35 $table = $this->getTableName();
36 $dbw->startAtomic( __METHOD__ );
37 $dbw->newInsertQueryBuilder()
38 ->insertInto( $table )
39 ->row( [
40 'uas_shard' => $shard,
41 'uas_year' => $year,
42 'uas_value' => 1
43 ] )
44 ->onDuplicateKeyUpdate()
45 ->uniqueIndexFields( [ 'uas_shard', 'uas_year' ] )
46 ->set( [ 'uas_value' => new RawSQLValue( 'uas_value+1' ) ] )
47 ->caller( __METHOD__ )->execute();
48 $value = $dbw->newSelectQueryBuilder()
49 ->select( 'uas_value' )
50 ->from( $table )
51 ->where( [ 'uas_shard' => $shard ] )
52 ->andWhere( [ 'uas_year' => $year ] )
53 ->caller( __METHOD__ )
54 ->fetchField();
55 $dbw->endAtomic( __METHOD__ );
56 return $value * $this->numShards + $shard;
57 }
58
59 /**
60 * @return IDatabase
61 */
62 abstract protected function getDB();
63
64 /**
65 * @return string
66 */
67 abstract protected function getTableName();
68 }