3 namespace Wikimedia\Rdbms
;
5 use InvalidArgumentException
;
8 * Helper class used for automatically marking an IDatabase connection as reusable (once it no
9 * longer matters which DB domain is selected) and for deferring the actual network connection
11 * This uses an RAII-style pattern where calling code is expected to keep the returned reference
12 * handle as a function variable that falls out of scope when no longer needed. This avoids the
13 * need for matching reuseConnection() calls for every "return" statement as well as the tedious
18 * function getRowData() {
19 * $conn = $this->lb->getConnectedRef( DB_REPLICA );
20 * $row = $conn->select( ... );
21 * return $row ? (array)$row : false;
22 * // $conn falls out of scope and $this->lb->reuseConnection() gets called
29 class DBConnRef
implements IDatabase
{
30 /** @var ILoadBalancer */
32 /** @var Database|null Live connection handle */
34 /** @var array|null N-tuple of (server index, group, DatabaseDomain|string) */
36 /** @var int One of DB_MASTER/DB_REPLICA */
45 * @param ILoadBalancer $lb Connection manager for $conn
46 * @param IDatabase|array $conn Database or (server index, query groups, domain, flags)
47 * @param int $role The type of connection asked for; one of DB_MASTER/DB_REPLICA
48 * @internal This method should not be called outside of LoadBalancer
50 public function __construct( ILoadBalancer
$lb, $conn, $role ) {
53 if ( $conn instanceof IDatabase
&& !( $conn instanceof DBConnRef
) ) {
54 $this->conn
= $conn; // live handle
55 } elseif ( is_array( $conn ) && count( $conn ) >= 4 && $conn[self
::FLD_DOMAIN
] !== false ) {
56 $this->params
= $conn;
58 throw new InvalidArgumentException( "Missing lazy connection arguments." );
62 function __call( $name, array $arguments ) {
63 if ( $this->conn
=== null ) {
64 list( $index, $groups, $wiki, $flags ) = $this->params
;
65 $this->conn
= $this->lb
->getConnection( $index, $groups, $wiki, $flags );
68 return $this->conn
->$name( ...$arguments );
72 * @return int DB_MASTER when this *requires* the master DB, otherwise DB_REPLICA
75 public function getReferenceRole() {
79 public function getServerInfo() {
80 return $this->__call( __FUNCTION__
, func_get_args() );
83 public function bufferResults( $buffer = null ) {
84 return $this->__call( __FUNCTION__
, func_get_args() );
87 public function trxLevel() {
88 return $this->__call( __FUNCTION__
, func_get_args() );
91 public function trxTimestamp() {
92 return $this->__call( __FUNCTION__
, func_get_args() );
95 public function explicitTrxActive() {
96 return $this->__call( __FUNCTION__
, func_get_args() );
99 public function assertNoOpenTransactions() {
100 return $this->__call( __FUNCTION__
, func_get_args() );
103 public function tablePrefix( $prefix = null ) {
104 if ( $this->conn
=== null && $prefix === null ) {
105 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
106 // Avoid triggering a database connection
107 return $domain->getTablePrefix();
108 } elseif ( $this->conn
!== null && $prefix === null ) {
109 // This will just return the prefix
110 return $this->__call( __FUNCTION__
, func_get_args() );
112 // Disallow things that might confuse the LoadBalancer tracking
113 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
116 public function dbSchema( $schema = null ) {
117 if ( $this->conn
=== null && $schema === null ) {
118 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
119 // Avoid triggering a database connection
120 return $domain->getSchema();
121 } elseif ( $this->conn
!== null && $schema === null ) {
122 // This will just return the schema
123 return $this->__call( __FUNCTION__
, func_get_args() );
125 // Disallow things that might confuse the LoadBalancer tracking
126 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
129 public function getLBInfo( $name = null ) {
130 return $this->__call( __FUNCTION__
, func_get_args() );
133 public function setLBInfo( $name, $value = null ) {
134 // Disallow things that might confuse the LoadBalancer tracking
135 throw new DBUnexpectedError( $this, "Changing LB info is disallowed to enable reuse." );
138 public function setLazyMasterHandle( IDatabase
$conn ) {
139 // Disallow things that might confuse the LoadBalancer tracking
140 throw new DBUnexpectedError( $this, "Database injection is disallowed to enable reuse." );
143 public function implicitGroupby() {
144 return $this->__call( __FUNCTION__
, func_get_args() );
147 public function implicitOrderby() {
148 return $this->__call( __FUNCTION__
, func_get_args() );
151 public function lastQuery() {
152 return $this->__call( __FUNCTION__
, func_get_args() );
155 public function doneWrites() {
156 return $this->__call( __FUNCTION__
, func_get_args() );
159 public function lastDoneWrites() {
160 return $this->__call( __FUNCTION__
, func_get_args() );
163 public function writesPending() {
164 return $this->__call( __FUNCTION__
, func_get_args() );
167 public function preCommitCallbacksPending() {
168 return $this->__call( __FUNCTION__
, func_get_args() );
171 public function writesOrCallbacksPending() {
172 return $this->__call( __FUNCTION__
, func_get_args() );
175 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
176 return $this->__call( __FUNCTION__
, func_get_args() );
179 public function pendingWriteCallers() {
180 return $this->__call( __FUNCTION__
, func_get_args() );
183 public function pendingWriteRowsAffected() {
184 return $this->__call( __FUNCTION__
, func_get_args() );
187 public function isOpen() {
188 return $this->__call( __FUNCTION__
, func_get_args() );
191 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
192 return $this->__call( __FUNCTION__
, func_get_args() );
195 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
196 return $this->__call( __FUNCTION__
, func_get_args() );
199 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
200 return $this->__call( __FUNCTION__
, func_get_args() );
203 public function getFlag( $flag ) {
204 return $this->__call( __FUNCTION__
, func_get_args() );
207 public function getProperty( $name ) {
208 return $this->__call( __FUNCTION__
, func_get_args() );
211 public function getDomainID() {
212 if ( $this->conn
=== null ) {
213 $domain = $this->params
[self
::FLD_DOMAIN
];
214 // Avoid triggering a database connection
215 return $domain instanceof DatabaseDomain ?
$domain->getId() : $domain;
218 return $this->__call( __FUNCTION__
, func_get_args() );
222 * @codeCoverageIgnore
224 public function getWikiID() {
225 return $this->getDomainID();
228 public function getType() {
229 if ( $this->conn
=== null ) {
230 // Avoid triggering a database connection
231 if ( $this->params
[self
::FLD_INDEX
] === ILoadBalancer
::DB_MASTER
) {
232 $index = $this->lb
->getWriterIndex();
234 $index = $this->params
[self
::FLD_INDEX
];
237 // In theory, if $index is DB_REPLICA, the type could vary
238 return $this->lb
->getServerType( $index );
242 return $this->__call( __FUNCTION__
, func_get_args() );
245 public function fetchObject( $res ) {
246 return $this->__call( __FUNCTION__
, func_get_args() );
249 public function fetchRow( $res ) {
250 return $this->__call( __FUNCTION__
, func_get_args() );
253 public function numRows( $res ) {
254 return $this->__call( __FUNCTION__
, func_get_args() );
257 public function numFields( $res ) {
258 return $this->__call( __FUNCTION__
, func_get_args() );
261 public function fieldName( $res, $n ) {
262 return $this->__call( __FUNCTION__
, func_get_args() );
265 public function insertId() {
266 return $this->__call( __FUNCTION__
, func_get_args() );
269 public function dataSeek( $res, $row ) {
270 return $this->__call( __FUNCTION__
, func_get_args() );
273 public function lastErrno() {
274 return $this->__call( __FUNCTION__
, func_get_args() );
277 public function lastError() {
278 return $this->__call( __FUNCTION__
, func_get_args() );
281 public function affectedRows() {
282 return $this->__call( __FUNCTION__
, func_get_args() );
285 public function getSoftwareLink() {
286 return $this->__call( __FUNCTION__
, func_get_args() );
289 public function getServerVersion() {
290 return $this->__call( __FUNCTION__
, func_get_args() );
293 public function close() {
294 throw new DBUnexpectedError( $this->conn
, 'Cannot close shared connection.' );
297 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
298 if ( $this->role
!== ILoadBalancer
::DB_MASTER
) {
299 $flags |
= IDatabase
::QUERY_REPLICA_ROLE
;
302 return $this->__call( __FUNCTION__
, [ $sql, $fname, $flags ] );
305 public function freeResult( $res ) {
306 return $this->__call( __FUNCTION__
, func_get_args() );
309 public function selectField(
310 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
312 return $this->__call( __FUNCTION__
, func_get_args() );
315 public function selectFieldValues(
316 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
318 return $this->__call( __FUNCTION__
, func_get_args() );
321 public function select(
322 $table, $vars, $conds = '', $fname = __METHOD__
,
323 $options = [], $join_conds = []
325 return $this->__call( __FUNCTION__
, func_get_args() );
328 public function selectSQLText(
329 $table, $vars, $conds = '', $fname = __METHOD__
,
330 $options = [], $join_conds = []
332 return $this->__call( __FUNCTION__
, func_get_args() );
335 public function limitResult( $sql, $limit, $offset = false ) {
336 return $this->__call( __FUNCTION__
, func_get_args() );
339 public function selectRow(
340 $table, $vars, $conds, $fname = __METHOD__
,
341 $options = [], $join_conds = []
343 return $this->__call( __FUNCTION__
, func_get_args() );
346 public function estimateRowCount(
347 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
349 return $this->__call( __FUNCTION__
, func_get_args() );
352 public function selectRowCount(
353 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
355 return $this->__call( __FUNCTION__
, func_get_args() );
358 public function lockForUpdate(
359 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
361 $this->assertRoleAllowsWrites();
363 return $this->__call( __FUNCTION__
, func_get_args() );
366 public function fieldExists( $table, $field, $fname = __METHOD__
) {
367 return $this->__call( __FUNCTION__
, func_get_args() );
370 public function indexExists( $table, $index, $fname = __METHOD__
) {
371 return $this->__call( __FUNCTION__
, func_get_args() );
374 public function tableExists( $table, $fname = __METHOD__
) {
375 return $this->__call( __FUNCTION__
, func_get_args() );
378 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
379 $this->assertRoleAllowsWrites();
381 return $this->__call( __FUNCTION__
, func_get_args() );
384 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
385 $this->assertRoleAllowsWrites();
387 return $this->__call( __FUNCTION__
, func_get_args() );
390 public function makeList( $a, $mode = self
::LIST_COMMA
) {
391 return $this->__call( __FUNCTION__
, func_get_args() );
394 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
395 return $this->__call( __FUNCTION__
, func_get_args() );
398 public function aggregateValue( $valuedata, $valuename = 'value' ) {
399 return $this->__call( __FUNCTION__
, func_get_args() );
402 public function bitNot( $field ) {
403 return $this->__call( __FUNCTION__
, func_get_args() );
406 public function bitAnd( $fieldLeft, $fieldRight ) {
407 return $this->__call( __FUNCTION__
, func_get_args() );
410 public function bitOr( $fieldLeft, $fieldRight ) {
411 return $this->__call( __FUNCTION__
, func_get_args() );
414 public function buildConcat( $stringList ) {
415 return $this->__call( __FUNCTION__
, func_get_args() );
418 public function buildGroupConcatField(
419 $delim, $table, $field, $conds = '', $join_conds = []
421 return $this->__call( __FUNCTION__
, func_get_args() );
424 public function buildSubstring( $input, $startPosition, $length = null ) {
425 return $this->__call( __FUNCTION__
, func_get_args() );
428 public function buildStringCast( $field ) {
429 return $this->__call( __FUNCTION__
, func_get_args() );
432 public function buildIntegerCast( $field ) {
433 return $this->__call( __FUNCTION__
, func_get_args() );
436 public function buildSelectSubquery(
437 $table, $vars, $conds = '', $fname = __METHOD__
,
438 $options = [], $join_conds = []
440 return $this->__call( __FUNCTION__
, func_get_args() );
443 public function databasesAreIndependent() {
444 return $this->__call( __FUNCTION__
, func_get_args() );
447 public function selectDB( $db ) {
448 // Disallow things that might confuse the LoadBalancer tracking
449 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
452 public function selectDomain( $domain ) {
453 // Disallow things that might confuse the LoadBalancer tracking
454 throw new DBUnexpectedError( $this, "Database selection is disallowed to enable reuse." );
457 public function getDBname() {
458 if ( $this->conn
=== null ) {
459 $domain = DatabaseDomain
::newFromId( $this->params
[self
::FLD_DOMAIN
] );
460 // Avoid triggering a database connection
461 return $domain->getDatabase();
464 return $this->__call( __FUNCTION__
, func_get_args() );
467 public function getServer() {
468 return $this->__call( __FUNCTION__
, func_get_args() );
471 public function addQuotes( $s ) {
472 return $this->__call( __FUNCTION__
, func_get_args() );
475 public function addIdentifierQuotes( $s ) {
476 return $this->__call( __FUNCTION__
, func_get_args() );
479 public function buildLike( $param ) {
480 return $this->__call( __FUNCTION__
, func_get_args() );
483 public function anyChar() {
484 return $this->__call( __FUNCTION__
, func_get_args() );
487 public function anyString() {
488 return $this->__call( __FUNCTION__
, func_get_args() );
491 public function nextSequenceValue( $seqName ) {
492 $this->assertRoleAllowsWrites();
494 return $this->__call( __FUNCTION__
, func_get_args() );
497 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
498 $this->assertRoleAllowsWrites();
500 return $this->__call( __FUNCTION__
, func_get_args() );
503 public function upsert(
504 $table, array $rows, $uniqueIndexes, array $set, $fname = __METHOD__
506 $this->assertRoleAllowsWrites();
508 return $this->__call( __FUNCTION__
, func_get_args() );
511 public function deleteJoin(
512 $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
514 $this->assertRoleAllowsWrites();
516 return $this->__call( __FUNCTION__
, func_get_args() );
519 public function delete( $table, $conds, $fname = __METHOD__
) {
520 $this->assertRoleAllowsWrites();
522 return $this->__call( __FUNCTION__
, func_get_args() );
525 public function insertSelect(
526 $destTable, $srcTable, $varMap, $conds,
527 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
529 $this->assertRoleAllowsWrites();
531 return $this->__call( __FUNCTION__
, func_get_args() );
534 public function unionSupportsOrderAndLimit() {
535 return $this->__call( __FUNCTION__
, func_get_args() );
538 public function unionQueries( $sqls, $all ) {
539 return $this->__call( __FUNCTION__
, func_get_args() );
542 public function unionConditionPermutations(
543 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
544 $options = [], $join_conds = []
546 return $this->__call( __FUNCTION__
, func_get_args() );
549 public function conditional( $cond, $trueVal, $falseVal ) {
550 return $this->__call( __FUNCTION__
, func_get_args() );
553 public function strreplace( $orig, $old, $new ) {
554 return $this->__call( __FUNCTION__
, func_get_args() );
557 public function getServerUptime() {
558 return $this->__call( __FUNCTION__
, func_get_args() );
561 public function wasDeadlock() {
562 return $this->__call( __FUNCTION__
, func_get_args() );
565 public function wasLockTimeout() {
566 return $this->__call( __FUNCTION__
, func_get_args() );
569 public function wasConnectionLoss() {
570 return $this->__call( __FUNCTION__
, func_get_args() );
573 public function wasReadOnlyError() {
574 return $this->__call( __FUNCTION__
, func_get_args() );
577 public function wasErrorReissuable() {
578 return $this->__call( __FUNCTION__
, func_get_args() );
581 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
582 return $this->__call( __FUNCTION__
, func_get_args() );
585 public function getReplicaPos() {
586 return $this->__call( __FUNCTION__
, func_get_args() );
589 public function getMasterPos() {
590 return $this->__call( __FUNCTION__
, func_get_args() );
593 public function serverIsReadOnly() {
594 return $this->__call( __FUNCTION__
, func_get_args() );
597 public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
598 // DB_REPLICA role: caller might want to refresh cache after a REPEATABLE-READ snapshot
599 return $this->__call( __FUNCTION__
, func_get_args() );
602 public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
603 // DB_REPLICA role: caller might want to refresh cache after a REPEATABLE-READ snapshot
604 return $this->__call( __FUNCTION__
, func_get_args() );
607 public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
608 return $this->onTransactionCommitOrIdle( $callback, $fname );
611 public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
612 // DB_REPLICA role: caller might want to refresh cache after a cache mutex is released
613 return $this->__call( __FUNCTION__
, func_get_args() );
616 public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
617 return $this->__call( __FUNCTION__
, func_get_args() );
620 public function setTransactionListener( $name, callable
$callback = null ) {
621 return $this->__call( __FUNCTION__
, func_get_args() );
624 public function startAtomic(
625 $fname = __METHOD__
, $cancelable = IDatabase
::ATOMIC_NOT_CANCELABLE
627 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
628 return $this->__call( __FUNCTION__
, func_get_args() );
631 public function endAtomic( $fname = __METHOD__
) {
632 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
633 return $this->__call( __FUNCTION__
, func_get_args() );
636 public function cancelAtomic( $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null ) {
637 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
638 return $this->__call( __FUNCTION__
, func_get_args() );
641 public function doAtomicSection(
642 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
644 // Don't call assertRoleAllowsWrites(); caller might want a REPEATABLE-READ snapshot
645 return $this->__call( __FUNCTION__
, func_get_args() );
648 public function begin( $fname = __METHOD__
, $mode = IDatabase
::TRANSACTION_EXPLICIT
) {
649 return $this->__call( __FUNCTION__
, func_get_args() );
652 public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
653 return $this->__call( __FUNCTION__
, func_get_args() );
656 public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
657 return $this->__call( __FUNCTION__
, func_get_args() );
660 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
661 return $this->__call( __FUNCTION__
, func_get_args() );
664 public function timestamp( $ts = 0 ) {
665 return $this->__call( __FUNCTION__
, func_get_args() );
668 public function timestampOrNull( $ts = null ) {
669 return $this->__call( __FUNCTION__
, func_get_args() );
672 public function ping( &$rtt = null ) {
673 return func_num_args()
674 ?
$this->__call( __FUNCTION__
, [ &$rtt ] )
675 : $this->__call( __FUNCTION__
, [] ); // method cares about null vs missing
678 public function getLag() {
679 return $this->__call( __FUNCTION__
, func_get_args() );
682 public function getSessionLagStatus() {
683 return $this->__call( __FUNCTION__
, func_get_args() );
686 public function maxListLen() {
687 return $this->__call( __FUNCTION__
, func_get_args() );
690 public function encodeBlob( $b ) {
691 return $this->__call( __FUNCTION__
, func_get_args() );
694 public function decodeBlob( $b ) {
695 return $this->__call( __FUNCTION__
, func_get_args() );
698 public function setSessionOptions( array $options ) {
699 return $this->__call( __FUNCTION__
, func_get_args() );
702 public function setSchemaVars( $vars ) {
703 return $this->__call( __FUNCTION__
, func_get_args() );
706 public function lockIsFree( $lockName, $method ) {
707 $this->assertRoleAllowsWrites();
709 return $this->__call( __FUNCTION__
, func_get_args() );
712 public function lock( $lockName, $method, $timeout = 5 ) {
713 $this->assertRoleAllowsWrites();
715 return $this->__call( __FUNCTION__
, func_get_args() );
718 public function unlock( $lockName, $method ) {
719 $this->assertRoleAllowsWrites();
721 return $this->__call( __FUNCTION__
, func_get_args() );
724 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
725 $this->assertRoleAllowsWrites();
727 return $this->__call( __FUNCTION__
, func_get_args() );
730 public function namedLocksEnqueue() {
731 return $this->__call( __FUNCTION__
, func_get_args() );
734 public function getInfinity() {
735 return $this->__call( __FUNCTION__
, func_get_args() );
738 public function encodeExpiry( $expiry ) {
739 return $this->__call( __FUNCTION__
, func_get_args() );
742 public function decodeExpiry( $expiry, $format = TS_MW
) {
743 return $this->__call( __FUNCTION__
, func_get_args() );
746 public function setBigSelects( $value = true ) {
747 return $this->__call( __FUNCTION__
, func_get_args() );
750 public function isReadOnly() {
751 return $this->__call( __FUNCTION__
, func_get_args() );
754 public function setTableAliases( array $aliases ) {
755 return $this->__call( __FUNCTION__
, func_get_args() );
758 public function setIndexAliases( array $aliases ) {
759 return $this->__call( __FUNCTION__
, func_get_args() );
762 public function __toString() {
763 if ( $this->conn
=== null ) {
764 // spl_object_id is PHP >= 7.2
765 $id = function_exists( 'spl_object_id' )
766 ?
spl_object_id( $this )
767 : spl_object_hash( $this );
769 return $this->getType() . ' object #' . $id;
772 return $this->__call( __FUNCTION__
, func_get_args() );
776 * Error out if the role is not DB_MASTER
778 * Note that the underlying connection may or may not itself be read-only.
779 * It could even be to a writable master (both server-side and to the application).
780 * This error is meant for the case when a DB_REPLICA handle was requested but a
781 * a write was attempted on that handle regardless.
783 * In configurations where the master DB has some generic read load or is the only server,
784 * DB_MASTER/DB_REPLICA will sometimes (or always) use the same connection to the master DB.
785 * This does not effect the role of DBConnRef instances.
786 * @throws DBReadOnlyRoleError
788 protected function assertRoleAllowsWrites() {
789 // DB_MASTER is "prima facie" writable
790 if ( $this->role
!== ILoadBalancer
::DB_MASTER
) {
791 throw new DBReadOnlyRoleError( $this->conn
, "Cannot write with role DB_REPLICA" );
796 * Clean up the connection when out of scope
798 function __destruct() {
800 $this->lb
->reuseConnection( $this->conn
);
807 * @deprecated since 1.29
809 class_alias( DBConnRef
::class, 'DBConnRef' );