Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
CNDatabase | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
72 | |
0.00% |
0 / 1 |
getDb | |
0.00% |
0 / 15 |
|
0.00% |
0 / 1 |
72 |
1 | <?php |
2 | |
3 | use MediaWiki\MediaWikiServices; |
4 | use Wikimedia\Rdbms\IDatabase; |
5 | |
6 | /** |
7 | * Fetches the CentralNotice infrastructure database. |
8 | */ |
9 | class CNDatabase { |
10 | |
11 | /** @var bool */ |
12 | private static $primaryUsedBefore = false; |
13 | |
14 | /** |
15 | * Get a DB handle. |
16 | * |
17 | * If $target is not set, we use DB_PRIMARY if the current context is an HTTP |
18 | * POST request, or if DB_PRIMARY was used previously. |
19 | * |
20 | * We will either connect to the primary database, or a separate |
21 | * CentralNotice infrastructure DB specified by $wgCentralDBname. This is |
22 | * metawiki for WMF sister projects. Note that the infrastructure DB does |
23 | * not support table prefixes if running in multi-database mode. |
24 | * |
25 | * @param int|null $target Set to DB_PRIMARY or DB_REPLICA to force a connection |
26 | * to that database. If no parameter is given, we attempt to choose a |
27 | * sane default (see above). |
28 | * |
29 | * @return IDatabase |
30 | */ |
31 | public static function getDb( $target = null ) { |
32 | global $wgCentralDBname, $wgDBname, $wgRequest; |
33 | |
34 | // If target is null, and the request was POSTed, force DB_PRIMARY. |
35 | // This is because changes are normally expected to come through |
36 | // Special:CentralNotice form submissions. |
37 | |
38 | // Also, if DB_PRIMARY was used before, use DB_PRIMARY. |
39 | // This might help in the case of read-for-write updates, if DB_PRIMARY |
40 | // was used previously in an execution that didn't come through a POST. |
41 | |
42 | // XXX: global state usage :( |
43 | // XXX: lack of separation of concerns |
44 | // XXX: preventive hack for meandering code |
45 | |
46 | if ( ( $target === null ) && |
47 | ( $wgRequest->wasPosted() || self::$primaryUsedBefore ) |
48 | ) { |
49 | $target = DB_PRIMARY; |
50 | } |
51 | |
52 | // If target is still null, use DB_REPLICA. |
53 | if ( $target === null ) { |
54 | $target = DB_REPLICA; |
55 | } |
56 | |
57 | // If we got DB_PRIMARY for whatever reason, make sure that's remembered |
58 | if ( $target === DB_PRIMARY ) { |
59 | self::$primaryUsedBefore = true; |
60 | } |
61 | |
62 | // Always use the database with CentralNotice data |
63 | if ( $wgCentralDBname === false || $wgCentralDBname === $wgDBname ) { |
64 | return MediaWikiServices::getInstance() |
65 | ->getDBLoadBalancer() |
66 | ->getConnection( $target ); |
67 | } else { |
68 | return MediaWikiServices::getInstance() |
69 | ->getDBLoadBalancerFactory() |
70 | ->getMainLB( $wgCentralDBname ) |
71 | ->getConnection( $target, [], $wgCentralDBname ); |
72 | } |
73 | } |
74 | } |