| 1 |
<?php |
| 2 |
|
| 3 |
namespace MediaWiki\User\TempUser; |
| 4 |
|
| 5 |
use Wikimedia\Rdbms\IDatabase; |
| 6 |
use Wikimedia\Rdbms\RawSQLValue; |
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
abstract class DBSerialProvider implements SerialProvider { |
| 14 |
|
| 15 |
private $numShards; |
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 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 |
|
| 61 |
|
| 62 |
abstract protected function getDB(); |
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
abstract protected function getTableName(); |
| 68 |
} |