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