1 | <?php |
||
12 | class PagePropsIdGenerator implements IdGenerator { |
||
13 | |||
14 | private const FAKE_PAGE_ID = -42; |
||
15 | |||
16 | private $loadBalancer; |
||
17 | |||
18 | 3 | public function __construct( ILoadBalancer $loadBalancer ) { |
|
21 | |||
22 | 3 | public function getNewId( string $type = '' ): int { |
|
31 | |||
32 | /** |
||
33 | * Generates and returns a new ID. |
||
34 | * |
||
35 | * @param IDatabase $database |
||
36 | * @param string $type |
||
37 | * @param bool $retry Retry once in case of e.g. race conditions. Defaults to true. |
||
38 | * |
||
39 | * @throws RuntimeException |
||
40 | * @return int |
||
41 | */ |
||
42 | 3 | private function generateNewId( IDatabase $database, string $type, $retry = true ): int { |
|
43 | 3 | $database->startAtomic( __METHOD__ ); |
|
44 | |||
45 | 3 | $currentId = $database->selectRow( |
|
46 | 3 | 'page_props', |
|
47 | 3 | 'pp_value', |
|
48 | 3 | $this->getWhere( $type ), |
|
49 | 3 | __METHOD__, |
|
50 | 3 | [ 'FOR UPDATE' ] |
|
51 | ); |
||
52 | |||
53 | 3 | if ( is_object( $currentId ) ) { |
|
54 | 2 | $id = (int)$currentId->pp_value + 1; |
|
55 | 2 | $success = $database->update( |
|
56 | 2 | 'page_props', |
|
57 | 2 | [ 'pp_value' => $id ], |
|
58 | 2 | $this->getWhere( $type ) |
|
59 | ); |
||
60 | } else { |
||
61 | 3 | $id = 1; |
|
62 | |||
63 | 3 | $success = $database->insert( |
|
64 | 3 | 'page_props', |
|
65 | 3 | $this->getInsertValues( $type, $id ) |
|
66 | ); |
||
67 | |||
68 | // Retry once, since a race condition on initial insert can cause one to fail. |
||
69 | // Race condition is possible due to occurrence of phantom reads is possible |
||
70 | // at non serializable transaction isolation level. |
||
71 | 3 | if ( !$success && $retry ) { |
|
72 | $id = $this->generateNewId( $database, $type, false ); |
||
73 | $success = true; |
||
74 | } |
||
75 | } |
||
76 | |||
77 | 3 | $database->endAtomic( __METHOD__ ); |
|
78 | |||
79 | 3 | if ( !$success ) { |
|
80 | throw new RuntimeException( 'Could not generate a reliably unique ID.' ); |
||
81 | } |
||
82 | |||
83 | 3 | return $id; |
|
84 | } |
||
85 | |||
86 | 3 | private function getInsertValues( string $idType, int $id ): array { |
|
91 | |||
92 | 3 | private function getWhere( string $idType ): array { |
|
98 | |||
99 | 3 | private function makePropertyName( string $idType ): string { |
|
102 | |||
103 | } |
||
104 |