Debian Codegraph @

includes/libs/rdbms/database/Database.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20 namespace Wikimedia\Rdbms;
21
22 use InvalidArgumentException;
23 use LogicException;
24 use Psr\Log\LoggerAwareInterface;
25 use Psr\Log\LoggerInterface;
26 use Psr\Log\NullLogger;
27 use RuntimeException;
28 use Stringable;
29 use Throwable;
30 use Wikimedia\AtEase\AtEase;
31 use Wikimedia\Rdbms\Database\DatabaseFlags;
32 use Wikimedia\Rdbms\Platform\SQLPlatform;
33 use Wikimedia\Rdbms\Replication\ReplicationReporter;
34 use Wikimedia\RequestTimeout\CriticalSectionProvider;
35 use Wikimedia\RequestTimeout\CriticalSectionScope;
36 use Wikimedia\ScopedCallback;
37
38 /**
39 * A single concrete connection to a relational database.
40 *
41 * This is the base class for all connection-specific relational database handles.
42 * No two instances of this class should share the same underlying network connection.
43 *
44 * @see IDatabase
45 * @ingroup Database
46 * @since 1.28
47 */
48 abstract class Database implements Stringable, IDatabaseForOwner, IMaintainableDatabase, LoggerAwareInterface {
49 /** @var CriticalSectionProvider|null */
50 protected $csProvider;
51 /** @var LoggerInterface */
52 protected $logger;
53 /** @var callable Error logging callback */
54 protected $errorLogger;
55 /** @var callable Deprecation logging callback */
56 protected $deprecationLogger;
57 /** @var callable|null */
58 protected $profiler;
59 /** @var TransactionManager */
60 private $transactionManager;
61
62 /** @var DatabaseDomain */
63 protected $currentDomain;
64 /** @var DatabaseFlags */
65 protected $flagsHolder;
66
67 // phpcs:ignore MediaWiki.Commenting.PropertyDocumentation.ObjectTypeHintVar
68 /** @var object|resource|null Database connection */
69 protected $conn;
70
71 /** @var string|null Readable name or host/IP of the database server */
72 protected $serverName;
73 /** @var bool Whether this PHP instance is for a CLI script */
74 protected $cliMode;
75 /** @var int|null Maximum seconds to wait on connection attempts */
76 protected $connectTimeout;
77 /** @var int|null Maximum seconds to wait on receiving query results */
78 protected $receiveTimeout;
79 /** @var string Agent name for query profiling */
80 protected $agent;
81 /** @var array<string,mixed> Connection parameters used by initConnection() and open() */
82 protected $connectionParams;
83 /** @var string[]|int[]|float[] SQL variables values to use for all new connections */
84 protected $connectionVariables;
85 /** @var int Row batch size to use for emulated INSERT SELECT queries */
86 protected $nonNativeInsertSelectBatchSize;
87
88 /** @var bool Whether to use SSL connections */
89 protected $ssl;
90 /** @var bool Whether to check for warnings */
91 protected $strictWarnings;
92 /** @var array Current LoadBalancer tracking information */
93 protected $lbInfo = [];
94 /** @var string|false Current SQL query delimiter */
95 protected $delimiter = ';';
96
97 /** @var string|bool|null Stashed value of html_errors INI setting */
98 private $htmlErrors;
99
100 /** @var array<string,array> Map of (lock name => (UNIX time,trx ID)) */
101 protected $sessionNamedLocks = [];
102 /** @var array<string,array<string, TempTableInfo>> Map of (DB name => table name => info) */
103 protected $sessionTempTables = [];
104
105 /** @var int Affected row count for the last statement to query() */
106 protected $lastQueryAffectedRows = 0;
107 /** @var int|null Insert (row) ID for the last statement to query() (null if not supported) */
108 protected $lastQueryInsertId;
109
110 /** @var int|null Affected row count for the last query method call; null if unspecified */
111 protected $lastEmulatedAffectedRows;
112 /** @var int|null Insert (row) ID for the last query method call; null if unspecified */
113 protected $lastEmulatedInsertId;
114
115 /** @var string Last error during connection; empty string if none */
116 protected $lastConnectError = '';
117
118 /** @var float UNIX timestamp of the last server response */
119 private $lastPing = 0.0;
120 /** @var float|false UNIX timestamp of last write query */
121 private $lastWriteTime = false;
122 /** @var string|false The last PHP error from a query or connection attempt */
123 private $lastPhpError = false;
124
125 /** @var int|null Current critical section numeric ID */
126 private $csmId;
127 /** @var string|null Last critical section caller name */
128 private $csmFname;
129 /** @var DBUnexpectedError|null Last unresolved critical section error */
130 private $csmError;
131
132 /** Whether the database is a file on disk */
133 public const ATTR_DB_IS_FILE = 'db-is-file';
134 /** Lock granularity is on the level of the entire database */
135 public const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
136 /** The SCHEMA keyword refers to a grouping of tables in a database */
137 public const ATTR_SCHEMAS_AS_TABLE_GROUPS = 'supports-schemas';
138
139 /** New Database instance will not be connected yet when returned */
140 public const NEW_UNCONNECTED = 0;
141 /** New Database instance will already be connected when returned */
142 public const NEW_CONNECTED = 1;
143
144 /** No errors occurred during the query */
145 protected const ERR_NONE = 0;
146 /** Retry query due to a connection loss detected while sending the query (session intact) */
147 protected const ERR_RETRY_QUERY = 1;
148 /** Abort query (no retries) due to a statement rollback (session/transaction intact) */
149 protected const ERR_ABORT_QUERY = 2;
150 /** Abort any current transaction, by rolling it back, due to an error during the query */
151 protected const ERR_ABORT_TRX = 4;
152 /** Abort and reset session due to server-side session-level state loss (locks, temp tables) */
153 protected const ERR_ABORT_SESSION = 8;
154
155 /** Assume that queries taking this long to yield connection loss errors are at fault */
156 protected const DROPPED_CONN_BLAME_THRESHOLD_SEC = 3.0;
157
158 /** @var string Idiom used when a cancelable atomic section started the transaction */
159 private const NOT_APPLICABLE = 'n/a';
160
161 /** How long before it is worth doing a dummy query to test the connection */
162 private const PING_TTL = 1.0;
163 /** Dummy SQL query */
164 private const PING_QUERY = 'SELECT 1 AS ping';
165
166 /** Hostname or IP address to use on all connections */
167 protected const CONN_HOST = 'host';
168 /** Database server username to use on all connections */
169 protected const CONN_USER = 'user';
170 /** Database server password to use on all connections */
171 protected const CONN_PASSWORD = 'password';
172 /** Database name to use on initial connection */
173 protected const CONN_INITIAL_DB = 'dbname';
174 /** Schema name to use on initial connection */
175 protected const CONN_INITIAL_SCHEMA = 'schema';
176 /** Table prefix to use on initial connection */
177 protected const CONN_INITIAL_TABLE_PREFIX = 'tablePrefix';
178
179 /** @var SQLPlatform */
180 protected $platform;
181
182 /** @var ReplicationReporter */
183 protected $replicationReporter;
184
185 /**
186 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
187 * @param array $params Parameters passed from Database::factory()
188 */
189 public function __construct( array $params ) {
190 $this->logger = $params['logger'] ?? new NullLogger();
191 $this->transactionManager = new TransactionManager(
192 $this->logger,
193 $params['trxProfiler']
194 );
195 $this->connectionParams = [
196 self::CONN_HOST => ( isset( $params['host'] ) && $params['host'] !== '' )
197 ? $params['host']
198 : null,
199 self::CONN_USER => ( isset( $params['user'] ) && $params['user'] !== '' )
200 ? $params['user']
201 : null,
202 self::CONN_INITIAL_DB => ( isset( $params['dbname'] ) && $params['dbname'] !== '' )
203 ? $params['dbname']
204 : null,
205 self::CONN_INITIAL_SCHEMA => ( isset( $params['schema'] ) && $params['schema'] !== '' )
206 ? $params['schema']
207 : null,
208 self::CONN_PASSWORD => is_string( $params['password'] ) ? $params['password'] : null,
209 self::CONN_INITIAL_TABLE_PREFIX => (string)$params['tablePrefix']
210 ];
211
212 $this->lbInfo = $params['lbInfo'] ?? [];
213 $this->connectionVariables = $params['variables'] ?? [];
214 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
215 if ( is_string( $params['sqlMode'] ?? null ) ) {
216 $this->connectionVariables['sql_mode'] = $params['sqlMode'];
217 }
218 $flags = (int)$params['flags'];
219 $this->flagsHolder = new DatabaseFlags( $flags );
220 $this->ssl = $params['ssl'] ?? (bool)( $flags & self::DBO_SSL );
221 $this->connectTimeout = $params['connectTimeout'] ?? null;
222 $this->receiveTimeout = $params['receiveTimeout'] ?? null;
223 $this->cliMode = (bool)$params['cliMode'];
224 $this->agent = (string)$params['agent'];
225 $this->serverName = $params['serverName'];
226 $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'] ?? 10000;
227 $this->strictWarnings = !empty( $params['strictWarnings'] );
228
229 $this->profiler = is_callable( $params['profiler'] ) ? $params['profiler'] : null;
230 $this->errorLogger = $params['errorLogger'];
231 $this->deprecationLogger = $params['deprecationLogger'];
232
233 $this->csProvider = $params['criticalSectionProvider'] ?? null;
234
235 // Set initial dummy domain until open() sets the final DB/prefix
236 $this->currentDomain = new DatabaseDomain(
237 $params['dbname'] != '' ? $params['dbname'] : null,
238 $params['schema'] != '' ? $params['schema'] : null,
239 $params['tablePrefix']
240 );
241 $this->platform = new SQLPlatform(
242 $this,
243 $this->logger,
244 $this->currentDomain,
245 $this->errorLogger
246 );
247 // Children classes must set $this->replicationReporter.
248 }
249
250 /**
251 * Initialize the connection to the database over the wire (or to local files)
252 *
253 * @throws LogicException
254 * @throws InvalidArgumentException
255 * @throws DBConnectionError
256 * @since 1.31
257 */
258 final public function initConnection() {
259 if ( $this->isOpen() ) {
260 throw new LogicException( __METHOD__ . ': already connected' );
261 }
262 // Establish the connection
263 $this->open(
264 $this->connectionParams[self::CONN_HOST],
265 $this->connectionParams[self::CONN_USER],
266 $this->connectionParams[self::CONN_PASSWORD],
267 $this->connectionParams[self::CONN_INITIAL_DB],
268 $this->connectionParams[self::CONN_INITIAL_SCHEMA],
269 $this->connectionParams[self::CONN_INITIAL_TABLE_PREFIX]
270 );
271 $this->lastPing = microtime( true );
272 }
273
274 /**
275 * Open a new connection to the database (closing any existing one)
276 *
277 * @param string|null $server Server host/address and optional port {@see connectionParams}
278 * @param string|null $user User name {@see connectionParams}
279 * @param string|null $password User password {@see connectionParams}
280 * @param string|null $db Database name
281 * @param string|null $schema Database schema name
282 * @param string $tablePrefix
283 * @throws DBConnectionError
284 */
285 abstract protected function open( $server, $user, $password, $db, $schema, $tablePrefix );
286
287 /**
288 * @return array Map of (Database::ATTR_* constant => value)
289 * @since 1.31
290 */
291 public static function getAttributes() {
292 return [];
293 }
294
295 /**
296 * Set the PSR-3 logger interface to use.
297 *
298 * @param LoggerInterface $logger
299 */
300 public function setLogger( LoggerInterface $logger ) {
301 $this->logger = $logger;
302 }
303
304 public function getServerInfo() {
305 return $this->getServerVersion();
306 }
307
308 public function tablePrefix( $prefix = null ) {
309 $old = $this->currentDomain->getTablePrefix();
310
311 if ( $prefix !== null ) {
312 $this->currentDomain = new DatabaseDomain(
313 $this->currentDomain->getDatabase(),
314 $this->currentDomain->getSchema(),
315 $prefix
316 );
317 $this->platform->setCurrentDomain( $this->currentDomain );
318 }
319
320 return $old;
321 }
322
323 public function dbSchema( $schema = null ) {
324 $old = $this->currentDomain->getSchema();
325
326 if ( $schema !== null ) {
327 if ( $schema !== '' && $this->getDBname() === null ) {
328 throw new DBUnexpectedError(
329 $this,
330 "Cannot set schema to '$schema'; no database set"
331 );
332 }
333
334 $this->currentDomain = new DatabaseDomain(
335 $this->currentDomain->getDatabase(),
336 // DatabaseDomain uses null for unspecified schemas
337 ( $schema !== '' ) ? $schema : null,
338 $this->currentDomain->getTablePrefix()
339 );
340 $this->platform->setCurrentDomain( $this->currentDomain );
341 }
342
343 return (string)$old;
344 }
345
346 public function getLBInfo( $name = null ) {
347 if ( $name === null ) {
348 return $this->lbInfo;
349 }
350
351 if ( array_key_exists( $name, $this->lbInfo ) ) {
352 return $this->lbInfo[$name];
353 }
354
355 return null;
356 }
357
358 public function setLBInfo( $nameOrArray, $value = null ) {
359 if ( is_array( $nameOrArray ) ) {
360 $this->lbInfo = $nameOrArray;
361 } elseif ( is_string( $nameOrArray ) ) {
362 if ( $value !== null ) {
363 $this->lbInfo[$nameOrArray] = $value;
364 } else {
365 unset( $this->lbInfo[$nameOrArray] );
366 }
367 } else {
368 throw new InvalidArgumentException( "Got non-string key" );
369 }
370 }
371
372 public function lastDoneWrites() {
373 return $this->lastWriteTime ?: false;
374 }
375
376 /**
377 * @return bool
378 * @since 1.39
379 * @internal For use by Database/LoadBalancer only
380 */
381 public function sessionLocksPending() {
382 return (bool)$this->sessionNamedLocks;
383 }
384
385 /**
386 * @return string|null ID of the active explicit transaction round being participating in
387 */
388 final protected function getTransactionRoundId() {
389 if ( $this->flagsHolder->hasImplicitTrxFlag() ) {
390 // LoadBalancer transaction round participation is enabled for this DB handle;
391 // get the ID of the active explicit transaction round (if any)
392 $id = $this->getLBInfo( self::LB_TRX_ROUND_ID );
393
394 return is_string( $id ) ? $id : null;
395 }
396
397 return null;
398 }
399
400 public function isOpen() {
401 return (bool)$this->conn;
402 }
403
404 public function getDomainID() {
405 return $this->currentDomain->getId();
406 }
407
408 /**
409 * Wrapper for addslashes()
410 *
411 * @param string $s String to be slashed.
412 * @return string Slashed string.
413 */
414 abstract public function strencode( $s );
415
416 /**
417 * Set a custom error handler for logging errors during database connection
418 */
419 protected function installErrorHandler() {
420 $this->lastPhpError = false;
421 $this->htmlErrors = ini_set( 'html_errors', '0' );
422 set_error_handler( [ $this, 'connectionErrorLogger' ] );
423 }
424
425 /**
426 * Restore the previous error handler and return the last PHP error for this DB
427 *
428 * @return string|false
429 */
430 protected function restoreErrorHandler() {
431 restore_error_handler();
432 if ( $this->htmlErrors !== false ) {
433 ini_set( 'html_errors', $this->htmlErrors );
434 }
435
436 return $this->getLastPHPError();
437 }
438
439 /**
440 * @return string|false Last PHP error for this DB (typically connection errors)
441 */
442 protected function getLastPHPError() {
443 if ( $this->lastPhpError ) {
444 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError );
445 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
446
447 return $error;
448 }
449
450 return false;
451 }
452
453 /**
454 * Error handler for logging errors during database connection
455 *
456 * @internal This method should not be used outside of Database classes
457 *
458 * @param int|string $errno
459 * @param string $errstr
460 */
461 public function connectionErrorLogger( $errno, $errstr ) {
462 $this->lastPhpError = $errstr;
463 }
464
465 /**
466 * Create a log context to pass to PSR-3 logger functions.
467 *
468 * @param array $extras Additional data to add to context
469 * @return array
470 */
471 protected function getLogContext( array $extras = [] ) {
472 return array_merge(
473 [
474 'db_server' => $this->getServerName(),
475 'db_name' => $this->getDBname(),
476 'db_user' => $this->connectionParams[self::CONN_USER] ?? null,
477 ],
478 $extras
479 );
480 }
481
482 final public function close( $fname = __METHOD__ ) {
483 $error = null; // error to throw after disconnecting
484
485 $wasOpen = (bool)$this->conn;
486 // This should mostly do nothing if the connection is already closed
487 if ( $this->conn ) {
488 // Roll back any dangling transaction first
489 if ( $this->trxLevel() ) {
490 $error = $this->transactionManager->trxCheckBeforeClose( $this, $fname );
491 // Rollback the changes and run any callbacks as needed
492 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
493 $this->runTransactionPostRollbackCallbacks();
494 }
495
496 // Close the actual connection in the binding handle
497 $closed = $this->closeConnection();
498 } else {
499 $closed = true; // already closed; nothing to do
500 }
501
502 $this->conn = null;
503
504 // Log any unexpected errors after having disconnected
505 if ( $error !== null ) {
506 // T217819, T231443: this is probably just LoadBalancer trying to recover from
507 // errors and shutdown. Log any problems and move on since the request has to
508 // end one way or another. Throwing errors is not very useful at some point.
509 $this->logger->error( $error, [ 'db_log_category' => 'query' ] );
510 }
511
512 // Note that various subclasses call close() at the start of open(), which itself is
513 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
514 // callbacks are pending does not mean that an exception should be thrown. Rather, they
515 // will be executed after the reconnection step.
516 if ( $wasOpen ) {
517 // Double check that no callbacks are dangling
518 $fnames = $this->pendingWriteAndCallbackCallers();
519 if ( $fnames ) {
520 throw new RuntimeException(
521 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
522 );
523 }
524 }
525
526 return $closed;
527 }
528
529 /**
530 * Make sure there is an open connection handle (alive or not)
531 *
532 * This guards against fatal errors to the binding handle not being defined in cases
533 * where open() was never called or close() was already called.
534 *
535 * @throws DBUnexpectedError
536 */
537 final protected function assertHasConnectionHandle() {
538 if ( !$this->isOpen() ) {
539 throw new DBUnexpectedError( $this, "DB connection was already closed" );
540 }
541 }
542
543 /**
544 * Closes underlying database connection
545 * @return bool Whether connection was closed successfully
546 * @since 1.20
547 */
548 abstract protected function closeConnection();
549
550 /**
551 * Run a query and return a QueryStatus instance with the query result information
552 *
553 * This is meant to handle the basic command of actually sending a query to the
554 * server via the driver. No implicit transaction, reconnection, nor retry logic
555 * should happen here. The higher level query() method is designed to handle those
556 * sorts of concerns. This method should not trigger such higher level methods.
557 *
558 * The lastError() and lastErrno() methods should meaningfully reflect what error,
559 * if any, occurred during the last call to this method. Methods like executeQuery(),
560 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
561 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
562 * meaningfully reflects any error that occurred during that public query method call.
563 *
564 * For SELECT queries, the result field contains either:
565 * - a) A driver-specific IResultWrapper describing the query results
566 * - b) False, on any query failure
567 *
568 * For non-SELECT queries, the result field contains either:
569 * - a) A driver-specific IResultWrapper, only on success
570 * - b) True, only on success (e.g. no meaningful result other than "OK")
571 * - c) False, on any query failure
572 *
573 * @param string $sql Single-statement SQL query
574 * @return QueryStatus
575 * @since 1.39
576 */
577 abstract protected function doSingleStatementQuery( string $sql ): QueryStatus;
578
579 /**
580 * Determine whether a write query affects a permanent table.
581 * This includes pseudo-permanent tables.
582 *
583 * @param Query $query
584 * @return bool
585 */
586 private function hasPermanentTable( Query $query ) {
587 if ( $query->getVerb() === 'CREATE TEMPORARY' ) {
588 // Temporary table creation is allowed
589 return false;
590 }
591 $table = $query->getWriteTable();
592 if ( $table === null ) {
593 // Parse error? Assume permanent.
594 return true;
595 }
596 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
597 $tempInfo = $this->sessionTempTables[$db][$pt] ?? null;
598 return !$tempInfo || $tempInfo->pseudoPermanent;
599 }
600
601 /**
602 * Register creation and dropping of temporary tables
603 *
604 * @param Query $query
605 */
606 protected function registerTempTables( Query $query ) {
607 $table = $query->getWriteTable();
608 if ( $table === null ) {
609 return;
610 }
611 switch ( $query->getVerb() ) {
612 case 'CREATE TEMPORARY':
613 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
614 $this->sessionTempTables[$db][$pt] = new TempTableInfo(
615 $this->transactionManager->getTrxId(),
616 (bool)( $query->getFlags() & self::QUERY_PSEUDO_PERMANENT )
617 );
618 break;
619
620 case 'DROP':
621 [ $db, $pt ] = $this->platform->getDatabaseAndTableIdentifier( $table );
622 unset( $this->sessionTempTables[$db][$pt] );
623 }
624 }
625
626 public function query( $sql, $fname = __METHOD__, $flags = 0 ) {
627 if ( !( $sql instanceof Query ) ) {
628 $flags = (int)$flags; // b/c; this field used to be a bool
629 $sql = QueryBuilderFromRawSql::buildQuery( $sql, $flags, $this->currentDomain->getTablePrefix() );
630 } else {
631 $flags = $sql->getFlags();
632 }
633
634 // Make sure that this caller is allowed to issue this query statement
635 $this->assertQueryIsCurrentlyAllowed( $sql->getVerb(), $fname );
636
637 // Send the query to the server and fetch any corresponding errors
638 $status = $this->executeQuery( $sql, $fname, $flags );
639 if ( $status->res === false ) {
640 // An error occurred; log, and, if needed, report an exception.
641 // Errors that corrupt the transaction/session state cannot be silenced.
642 $ignore = (
643 $this->flagsHolder::contains( $flags, self::QUERY_SILENCE_ERRORS ) &&
644 !$this->flagsHolder::contains( $status->flags, self::ERR_ABORT_SESSION ) &&
645 !$this->flagsHolder::contains( $status->flags, self::ERR_ABORT_TRX )
646 );
647 $this->reportQueryError( $status->message, $status->code, $sql->getSQL(), $fname, $ignore );
648 }
649
650 return $status->res;
651 }
652
653 /**
654 * Execute a query without enforcing public (non-Database) caller restrictions.
655 *
656 * Retry it if there is a recoverable connection loss (e.g. no important state lost).
657 *
658 * This does not precheck for transaction/session state errors or critical section errors.
659 *
660 * @see Database::query()
661 *
662 * @param Query $sql SQL statement
663 * @param string $fname Name of the calling function
664 * @param int $flags Bit field of ISQLPlatform::QUERY_* constants
665 * @return QueryStatus
666 * @throws DBUnexpectedError
667 * @since 1.34
668 */
669 final protected function executeQuery( $sql, $fname, $flags ) {
670 $this->assertHasConnectionHandle();
671
672 $isPermWrite = false;
673 $isWrite = $sql->isWriteQuery();
674 if ( $isWrite ) {
675 ChangedTablesTracker::recordQuery( $this->currentDomain, $sql );
676 // Permit temporary table writes on replica connections, but require a writable
677 // master connection for writes to persistent tables.
678 if ( $this->hasPermanentTable( $sql ) ) {
679 $isPermWrite = true;
680 $info = $this->getReadOnlyReason();
681 if ( $info ) {
682 [ $reason, $source ] = $info;
683 if ( $source === 'role' ) {
684 throw new DBReadOnlyRoleError( $this, "Database is read-only: $reason" );
685 } else {
686 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
687 }
688 }
689 // DBConnRef uses QUERY_REPLICA_ROLE to enforce replica roles during query()
690 if ( $this->flagsHolder::contains( $sql->getFlags(), self::QUERY_REPLICA_ROLE ) ) {
691 throw new DBReadOnlyRoleError(
692 $this,
693 "Cannot write; target role is DB_REPLICA"
694 );
695 }
696 }
697 }
698
699 // Whether a silent retry attempt is left for recoverable connection loss errors
700 $retryLeft = !$this->flagsHolder::contains( $flags, self::QUERY_NO_RETRY );
701
702 $cs = $this->commenceCriticalSection( __METHOD__ );
703
704 do {
705 // Start a DBO_TRX wrapper transaction as needed (throw an error on failure)
706 if ( $this->beginIfImplied( $sql, $fname, $flags ) ) {
707 // Since begin() was called, any connection loss was already handled
708 $retryLeft = false;
709 }
710 // Send the query statement to the server and fetch any results.
711 $status = $this->attemptQuery( $sql, $fname, $isPermWrite );
712 } while (
713 // An error occurred that can be recovered from via query retry
714 $this->flagsHolder::contains( $status->flags, self::ERR_RETRY_QUERY ) &&
715 // The retry has not been exhausted (consume it now)
716 // phpcs:ignore Generic.CodeAnalysis.AssignmentInCondition.FoundInWhileCondition
717 $retryLeft && !( $retryLeft = false )
718 );
719
720 // Register creation and dropping of temporary tables
721 if ( $status->res ) {
722 $this->registerTempTables( $sql );
723 }
724 $this->completeCriticalSection( __METHOD__, $cs );
725
726 return $status;
727 }
728
729 /**
730 * Query method wrapper handling profiling, logging, affected row count tracking, and
731 * automatic reconnections (without retry) on query failure due to connection loss
732 *
733 * Note that this does not handle DBO_TRX logic.
734 *
735 * This method handles profiling, debug logging, reconnection and the tracking of:
736 * - write callers
737 * - last write time
738 * - affected row count of the last write
739 * - whether writes occurred in a transaction
740 * - last successful query time (confirming that the connection was not dropped)
741 *
742 * @see doSingleStatementQuery()
743 *
744 * @param Query $sql SQL statement
745 * @param string $fname Name of the calling function
746 * @param bool $isPermWrite Whether it's a query writing to permanent tables
747 * @return QueryStatus statement result
748 * @throws DBUnexpectedError
749 */
750 private function attemptQuery(
751 $sql,
752 string $fname,
753 bool $isPermWrite
754 ) {
755 // Transaction attributes before issuing this query
756 $priorSessInfo = new CriticalSessionInfo(
757 $this->transactionManager->getTrxId(),
758 $this->transactionManager->explicitTrxActive(),
759 $this->transactionManager->pendingWriteCallers(),
760 $this->transactionManager->pendingPreCommitCallbackCallers(),
761 $this->sessionNamedLocks,
762 $this->sessionTempTables
763 );
764 // Get the transaction-aware SQL string used for profiling
765 $prefix = (
766 $this->replicationReporter->getTopologyRole() === self::ROLE_STREAMING_MASTER
767 ) ? 'role-primary: ' : '';
768
769 // Start profile section
770 if ( $sql->getCleanedSql() ) {
771 $generalizedSql = $sql;
772 $ps = $this->profiler ? ( $this->profiler )( $sql->getCleanedSql() ) : null;
773 } else {
774 $generalizedSql = new GeneralizedSql( $sql->getSQL(), $prefix );
775 $ps = $this->profiler ? ( $this->profiler )( $generalizedSql->stringify() ) : null;
776 }
777 // Add agent and calling method comments to the SQL
778 $cStatement = $this->makeCommentedSql( $sql->getSQL(), $fname );
779 $startTime = microtime( true );
780
781 // Clear any overrides from a prior "query method". Note that this does not affect
782 // any such methods that are currently invoking query() itself since those query
783 // methods set these fields before returning.
784 $this->lastEmulatedAffectedRows = null;
785 $this->lastEmulatedInsertId = null;
786
787 $status = $this->doSingleStatementQuery( $cStatement );
788
789 // End profile section
790 $endTime = microtime( true );
791 $queryRuntime = max( $endTime - $startTime, 0.0 );
792 unset( $ps );
793
794 if ( $status->res !== false ) {
795 $this->lastPing = $endTime;
796 }
797
798 $affectedRowCount = $status->rowsAffected;
799 $returnedRowCount = $status->rowsReturned;
800 $this->lastQueryAffectedRows = $affectedRowCount;
801
802 if ( $status->res !== false ) {
803 if ( $isPermWrite ) {
804 $this->lastWriteTime = $startTime;
805 if ( $this->trxLevel() ) {
806 $this->transactionManager->transactionWritingIn(
807 $this->getServerName(),
808 $this->getDomainID(),
809 $startTime
810 );
811 $this->transactionManager->updateTrxWriteQueryReport(
812 $sql->getSQL(),
813 $queryRuntime,
814 $affectedRowCount,
815 $fname
816 );
817 }
818 }
819 }
820
821 $this->transactionManager->recordQueryCompletion(
822 $generalizedSql,
823 $startTime,
824 $isPermWrite,
825 $isPermWrite ? $affectedRowCount : $returnedRowCount,
826 $this->getServerName()
827 );
828
829 // Check if the query failed...
830 $status->flags = $this->handleErroredQuery( $status, $sql, $fname, $queryRuntime, $priorSessInfo );
831 // Avoid the overhead of logging calls unless debug mode is enabled
832 if ( $this->flagsHolder->getFlag( self::DBO_DEBUG ) ) {
833 $this->logger->debug(
834 "{method} [{runtime_ms}ms] {db_server}: {sql}",
835 $this->getLogContext( [
836 'method' => $fname,
837 'sql' => $sql->getSQL(),
838 'domain' => $this->getDomainID(),
839 'runtime_ms' => round( $queryRuntime * 1000, 3 ),
840 'db_log_category' => 'query'
841 ] )
842 );
843 }
844
845 return $status;
846 }
847
848 private function handleErroredQuery( QueryStatus $status, $sql, $fname, $queryRuntime, $priorSessInfo ) {
849 $errflags = self::ERR_NONE;
850 $error = $status->message;
851 $errno = $status->code;
852 if ( $status->res !== false ) {
853 // Statement succeeded
854 return $errflags;
855 }
856 if ( $this->isConnectionError( $errno ) ) {
857 // Connection lost before or during the query...
858 // Determine how to proceed given the lost session state
859 $connLossFlag = $this->assessConnectionLoss(
860 $sql->getVerb(),
861 $queryRuntime,
862 $priorSessInfo
863 );
864 // Update session state tracking and try to reestablish a connection
865 $reconnected = $this->replaceLostConnection( $errno, __METHOD__ );
866 // Check if important server-side session-level state was lost
867 if ( $connLossFlag >= self::ERR_ABORT_SESSION ) {
868 $ex = $this->getQueryException( $error, $errno, $sql->getSQL(), $fname );
869 $this->transactionManager->setSessionError( $ex );
870 }
871 // Check if important server-side transaction-level state was lost
872 if ( $connLossFlag >= self::ERR_ABORT_TRX ) {
873 $ex = $this->getQueryException( $error, $errno, $sql->getSQL(), $fname );
874 $this->transactionManager->setTransactionError( $ex );
875 }
876 // Check if the query should be retried (having made the reconnection attempt)
877 if ( $connLossFlag === self::ERR_RETRY_QUERY ) {
878 $errflags |= ( $reconnected ? self::ERR_RETRY_QUERY : self::ERR_ABORT_QUERY );
879 } else {
880 $errflags |= $connLossFlag;
881 }
882 } elseif ( $this->isKnownStatementRollbackError( $errno ) ) {
883 // Query error triggered a server-side statement-only rollback...
884 $errflags |= self::ERR_ABORT_QUERY;
885 if ( $this->trxLevel() ) {
886 // Allow legacy callers to ignore such errors via QUERY_IGNORE_DBO_TRX and
887 // try/catch. However, a deprecation notice will be logged on the next query.
888 $cause = [ $error, $errno, $fname ];
889 $this->transactionManager->setTrxStatusIgnoredCause( $cause );
890 }
891 } elseif ( $this->trxLevel() ) {
892 // Some other error occurred during the query, within a transaction...
893 // Server-side handling of errors during transactions varies widely depending on
894 // the RDBMS type and configuration. There are several possible results: (a) the
895 // whole transaction is rolled back, (b) only the queries after BEGIN are rolled
896 // back, (c) the transaction is marked as "aborted" and a ROLLBACK is required
897 // before other queries are permitted. For compatibility reasons, pessimistically
898 // require a ROLLBACK query (not using SAVEPOINT) before allowing other queries.
899 $ex = $this->getQueryException( $error, $errno, $sql->getSQL(), $fname );
900 $this->transactionManager->setTransactionError( $ex );
901 $errflags |= self::ERR_ABORT_TRX;
902 } else {
903 // Some other error occurred during the query, without a transaction...
904 $errflags |= self::ERR_ABORT_QUERY;
905 }
906
907 return $errflags;
908 }
909
910 /**
911 * @param string $sql
912 * @param string $fname
913 * @return string
914 */
915 private function makeCommentedSql( $sql, $fname ): string {
916 // Add trace comment to the begin of the sql string, right after the operator.
917 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598).
918 // NOTE: Don't add varying ids such as request id or session id to the comment.
919 // It would break aggregation of similar queries in analysis tools (see T193050#7512149)
920 $encName = preg_replace( '/[\x00-\x1F\/]/', '-', "$fname {$this->agent}" );
921 return preg_replace( '/\s|$/', " /* $encName */ ", $sql, 1 );
922 }
923
924 /**
925 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
926 *
927 * @param Query $sql SQL statement
928 * @param string $fname
929 * @param int $flags Bit field of ISQLPlatform::QUERY_* constants
930 * @return bool Whether an implicit transaction was started
931 * @throws DBError
932 */
933 private function beginIfImplied( $sql, $fname, $flags ) {
934 if ( !$this->trxLevel() && $this->flagsHolder->hasApplicableImplicitTrxFlag( $flags ) ) {
935 if ( $this->platform->isTransactableQuery( $sql ) ) {
936 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
937 $this->transactionManager->turnOnAutomatic();
938
939 return true;
940 }
941 }
942
943 return false;
944 }
945
946 /**
947 * Check if callers outside of Database can run the given query given the session state
948 *
949 * In order to keep the DB handle's session state tracking in sync, certain queries
950 * like "USE", "BEGIN", "COMMIT", and "ROLLBACK" must not be issued directly from
951 * outside callers. Such commands should only be issued through dedicated methods
952 * like selectDomain(), begin(), commit(), and rollback(), respectively.
953 *
954 * This also checks if the session state tracking was corrupted by a prior exception.
955 *
956 * @param string $verb
957 * @param string $fname
958 * @throws DBUnexpectedError
959 * @throws DBTransactionStateError
960 */
961 private function assertQueryIsCurrentlyAllowed( string $verb, string $fname ) {
962 if ( $verb === 'USE' ) {
963 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
964 }
965
966 if ( $verb === 'ROLLBACK' ) {
967 // Whole transaction rollback is used for recovery
968 // @TODO: T269161; prevent "BEGIN"/"COMMIT"/"ROLLBACK" from outside callers
969 return;
970 }
971
972 if ( $this->csmError ) {
973 throw new DBTransactionStateError(
974 $this,
975 "Cannot execute query from $fname while session state is out of sync",
976 [],
977 $this->csmError
978 );
979 }
980
981 $this->transactionManager->assertSessionStatus( $this, $fname );
982
983 if ( $verb !== 'ROLLBACK TO SAVEPOINT' ) {
984 $this->transactionManager->assertTransactionStatus(
985 $this,
986 $this->deprecationLogger,
987 $fname
988 );
989 }
990 }
991
992 /**
993 * Determine how to handle a connection lost discovered during a query attempt
994 *
995 * This checks if explicit transactions, pending transaction writes, and important
996 * session-level state (locks, temp tables) was lost. Point-in-time read snapshot loss
997 * is considered acceptable for DBO_TRX logic.
998 *
999 * If state was lost, but that loss was discovered during a ROLLBACK that would have
1000 * destroyed that state anyway, treat the error as recoverable.
1001 *
1002 * @param string $verb SQL query verb
1003 * @param float $walltime How many seconds passes while attempting the query
1004 * @param CriticalSessionInfo $priorSessInfo Session state just before the query
1005 * @return int Recovery approach. One of the following ERR_* class constants:
1006 * - Database::ERR_RETRY_QUERY: reconnect silently, retry query
1007 * - Database::ERR_ABORT_QUERY: reconnect silently, do not retry query
1008 * - Database::ERR_ABORT_TRX: reconnect, throw error, enforce transaction rollback
1009 * - Database::ERR_ABORT_SESSION: reconnect, throw error, enforce session rollback
1010 */
1011 private function assessConnectionLoss(
1012 string $verb,
1013 float $walltime,
1014 CriticalSessionInfo $priorSessInfo
1015 ) {
1016 if ( $walltime < self::DROPPED_CONN_BLAME_THRESHOLD_SEC ) {
1017 // Query failed quickly; the connection was probably lost before the query was sent
1018 $res = self::ERR_RETRY_QUERY;
1019 } else {
1020 // Query took a long time; the connection was probably lost during query execution
1021 $res = self::ERR_ABORT_QUERY;
1022 }
1023
1024 // List of problems causing session/transaction state corruption
1025 $blockers = [];
1026 // Loss of named locks breaks future callers relying on those locks for critical sections
1027 foreach ( $priorSessInfo->namedLocks as $lockName => $lockInfo ) {
1028 if ( $lockInfo['trxId'] && $lockInfo['trxId'] === $priorSessInfo->trxId ) {
1029 // Treat lost locks acquired during the lost transaction as a transaction state
1030 // problem. Connection loss on ROLLBACK (non-SAVEPOINT) is tolerable since
1031 // rollback automatically triggered server-side.
1032 if ( $verb !== 'ROLLBACK' ) {
1033 $res = max( $res, self::ERR_ABORT_TRX );
1034 $blockers[] = "named lock '$lockName'";
1035 }
1036 } else {
1037 // Treat lost locks acquired either during prior transactions or during no
1038 // transaction as a session state problem.
1039 $res = max( $res, self::ERR_ABORT_SESSION );
1040 $blockers[] = "named lock '$lockName'";
1041 }
1042 }
1043 // Loss of temp tables breaks future callers relying on those tables for queries
1044 foreach ( $priorSessInfo->tempTables as $domainTempTables ) {
1045 foreach ( $domainTempTables as $tableName => $tableInfo ) {
1046 if ( $tableInfo->trxId && $tableInfo->trxId === $priorSessInfo->trxId ) {
1047 // Treat lost temp tables created during the lost transaction as a
1048 // transaction state problem. Connection loss on ROLLBACK (non-SAVEPOINT)
1049 // is tolerable since rollback automatically triggered server-side.
1050 if ( $verb !== 'ROLLBACK' ) {
1051 $res = max( $res, self::ERR_ABORT_TRX );
1052 $blockers[] = "temp table '$tableName'";
1053 }
1054 } else {
1055 // Treat lost temp tables created either during prior transactions or during
1056 // no transaction as a session state problem.
1057 $res = max( $res, self::ERR_ABORT_SESSION );
1058 $blockers[] = "temp table '$tableName'";
1059 }
1060 }
1061 }
1062 // Loss of transaction writes breaks future callers and DBO_TRX logic relying on those
1063 // writes to be atomic and still pending. Connection loss on ROLLBACK (non-SAVEPOINT) is
1064 // tolerable since rollback automatically triggered server-side.
1065 if ( $priorSessInfo->trxWriteCallers && $verb !== 'ROLLBACK' ) {
1066 $res = max( $res, self::ERR_ABORT_TRX );
1067 $blockers[] = 'uncommitted writes';
1068 }
1069 if ( $priorSessInfo->trxPreCommitCbCallers && $verb !== 'ROLLBACK' ) {
1070 $res = max( $res, self::ERR_ABORT_TRX );
1071 $blockers[] = 'pre-commit callbacks';
1072 }
1073 if ( $priorSessInfo->trxExplicit && $verb !== 'ROLLBACK' && $verb !== 'COMMIT' ) {
1074 // Transaction automatically rolled back, breaking the expectations of callers
1075 // relying on the continued existence of that transaction for things like atomic
1076 // writes, serializability, or reads from the same point-in-time snapshot. If the
1077 // connection loss occured on ROLLBACK (non-SAVEPOINT) or COMMIT, then we do not
1078 // need to mark the transaction state as corrupt, since no transaction would still
1079 // be open even if the query did succeed (T127428).
1080 $res = max( $res, self::ERR_ABORT_TRX );
1081 $blockers[] = 'explicit transaction';
1082 }
1083
1084 if ( $blockers ) {
1085 $this->logger->warning(
1086 "cannot reconnect to {db_server} silently: {error}",
1087 $this->getLogContext( [
1088 'error' => 'session state loss (' . implode( ', ', $blockers ) . ')',
1089 'exception' => new RuntimeException(),
1090 'db_log_category' => 'connection'
1091 ] )
1092 );
1093 }
1094
1095 return $res;
1096 }
1097
1098 /**
1099 * Clean things up after session (and thus transaction) loss before reconnect
1100 */
1101 private function handleSessionLossPreconnect() {
1102 // Clean up tracking of session-level things...
1103 // https://mariadb.com/kb/en/create-table/#create-temporary-table
1104 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1105 $this->sessionTempTables = [];
1106 // https://mariadb.com/kb/en/get_lock/
1107 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1108 $this->sessionNamedLocks = [];
1109 // Session loss implies transaction loss (T67263)
1110 $this->transactionManager->onSessionLoss( $this );
1111 // Clear additional subclass fields
1112 $this->doHandleSessionLossPreconnect();
1113 }
1114
1115 /**
1116 * Reset any additional subclass trx* and session* fields
1117 */
1118 protected function doHandleSessionLossPreconnect() {
1119 // no-op
1120 }
1121
1122 /**
1123 * Checks whether the cause of the error is detected to be a timeout.
1124 *
1125 * It returns false by default, and not all engines support detecting this yet.
1126 * If this returns false, it will be treated as a generic query error.
1127 *
1128 * @param int|string $errno Error number
1129 * @return bool
1130 * @since 1.39
1131 */
1132 protected function isQueryTimeoutError( $errno ) {
1133 return false;
1134 }
1135
1136 /**
1137 * Report a query error
1138 *
1139 * If $ignore is set, emit a DEBUG level log entry and continue,
1140 * otherwise, emit an ERROR level log entry and throw an exception.
1141 *
1142 * @param string $error
1143 * @param int|string $errno
1144 * @param string $sql
1145 * @param string $fname
1146 * @param bool $ignore Whether to just log an error rather than throw an exception
1147 * @throws DBQueryError
1148 */
1149 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1150 if ( $ignore ) {
1151 $this->logger->debug(
1152 "SQL ERROR (ignored): $error",
1153 [ 'db_log_category' => 'query' ]
1154 );
1155 } else {
1156 throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1157 }
1158 }
1159
1160 /**
1161 * @param string $error
1162 * @param string|int $errno
1163 * @param string $sql
1164 * @param string $fname
1165 * @return DBError
1166 */
1167 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1168 // Information that instances of the same problem have in common should
1169 // not be normalized (T255202).
1170 $this->logger->error(
1171 "Error $errno from $fname, {error} {sql1line} {db_server}",
1172 $this->getLogContext( [
1173 'method' => __METHOD__,
1174 'errno' => $errno,
1175 'error' => $error,
1176 'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1177 'fname' => $fname,
1178 'db_log_category' => 'query',
1179 'exception' => new RuntimeException()
1180 ] )
1181 );
1182 return $this->getQueryException( $error, $errno, $sql, $fname );
1183 }
1184
1185 /**
1186 * @param string $error
1187 * @param string|int $errno
1188 * @param string $sql
1189 * @param string $fname
1190 * @return DBError
1191 */
1192 private function getQueryException( $error, $errno, $sql, $fname ) {
1193 if ( $this->isQueryTimeoutError( $errno ) ) {
1194 return new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1195 } elseif ( $this->isConnectionError( $errno ) ) {
1196 return new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1197 } else {
1198 return new DBQueryError( $this, $error, $errno, $sql, $fname );
1199 }
1200 }
1201
1202 /**
1203 * @param string $error
1204 * @return DBConnectionError
1205 */
1206 final protected function newExceptionAfterConnectError( $error ) {
1207 // Connection was not fully initialized and is not safe for use.
1208 // Stash any error associated with the handle before destroying it.
1209 $this->lastConnectError = $error;
1210 $this->conn = null;
1211
1212 $this->logger->error(
1213 "Error connecting to {db_server} as user {db_user}: {error}",
1214 $this->getLogContext( [
1215 'error' => $error,
1216 'exception' => new RuntimeException(),
1217 'db_log_category' => 'connection',
1218 ] )
1219 );
1220
1221 return new DBConnectionError( $this, $error );
1222 }
1223
1224 /**
1225 * Get a SelectQueryBuilder bound to this connection. This is overridden by
1226 * DBConnRef.
1227 *
1228 * @return SelectQueryBuilder
1229 */
1230 public function newSelectQueryBuilder(): SelectQueryBuilder {
1231 return new SelectQueryBuilder( $this );
1232 }
1233
1234 /**
1235 * Get a UnionQueryBuilder bound to this connection. This is overridden by
1236 * DBConnRef.
1237 *
1238 * @return UnionQueryBuilder
1239 */
1240 public function newUnionQueryBuilder(): UnionQueryBuilder {
1241 return new UnionQueryBuilder( $this );
1242 }
1243
1244 /**
1245 * Get an UpdateQueryBuilder bound to this connection. This is overridden by
1246 * DBConnRef.
1247 *
1248 * @return UpdateQueryBuilder
1249 */
1250 public function newUpdateQueryBuilder(): UpdateQueryBuilder {
1251 return new UpdateQueryBuilder( $this );
1252 }
1253
1254 /**
1255 * Get a DeleteQueryBuilder bound to this connection. This is overridden by
1256 * DBConnRef.
1257 *
1258 * @return DeleteQueryBuilder
1259 */
1260 public function newDeleteQueryBuilder(): DeleteQueryBuilder {
1261 return new DeleteQueryBuilder( $this );
1262 }
1263
1264 /**
1265 * Get a InsertQueryBuilder bound to this connection. This is overridden by
1266 * DBConnRef.
1267 *
1268 * @return InsertQueryBuilder
1269 */
1270 public function newInsertQueryBuilder(): InsertQueryBuilder {
1271 return new InsertQueryBuilder( $this );
1272 }
1273
1274 /**
1275 * Get a ReplaceQueryBuilder bound to this connection. This is overridden by
1276 * DBConnRef.
1277 *
1278 * @return ReplaceQueryBuilder
1279 */
1280 public function newReplaceQueryBuilder(): ReplaceQueryBuilder {
1281 return new ReplaceQueryBuilder( $this );
1282 }
1283
1284 public function selectField(
1285 $tables, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1286 ) {
1287 if ( $var === '*' ) {
1288 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1289 } elseif ( is_array( $var ) && count( $var ) !== 1 ) {
1290 throw new DBUnexpectedError( $this, 'Cannot use more than one field' );
1291 }
1292
1293 $options = $this->platform->normalizeOptions( $options );
1294 $options['LIMIT'] = 1;
1295
1296 $res = $this->select( $tables, $var, $cond, $fname, $options, $join_conds );
1297 if ( $res === false ) {
1298 throw new DBUnexpectedError( $this, "Got false from select()" );
1299 }
1300
1301 $row = $res->fetchRow();
1302 if ( $row === false ) {
1303 return false;
1304 }
1305
1306 return reset( $row );
1307 }
1308
1309 public function selectFieldValues(
1310 $tables, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1311 ): array {
1312 if ( $var === '*' ) {
1313 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1314 } elseif ( !is_string( $var ) ) {
1315 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1316 }
1317
1318 $options = $this->platform->normalizeOptions( $options );
1319 $res = $this->select( $tables, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1320 if ( $res === false ) {
1321 throw new DBUnexpectedError( $this, "Got false from select()" );
1322 }
1323
1324 $values = [];
1325 foreach ( $res as $row ) {
1326 $values[] = $row->value;
1327 }
1328
1329 return $values;
1330 }
1331
1332 public function select(
1333 $tables, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1334 ) {
1335 $options = (array)$options;
1336 // Don't turn this into using platform directly, DatabaseMySQL overrides this.
1337 $sql = $this->selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
1338 // Treat SELECT queries with FOR UPDATE as writes. This matches
1339 // how MySQL enforces read_only (FOR SHARE and LOCK IN SHADE MODE are allowed).
1340 $flags = in_array( 'FOR UPDATE', $options, true )
1341 ? self::QUERY_CHANGE_ROWS
1342 : self::QUERY_CHANGE_NONE;
1343
1344 $query = new Query( $sql, $flags, 'SELECT' );
1345 return $this->query( $query, $fname );
1346 }
1347
1348 public function selectRow( $tables, $vars, $conds, $fname = __METHOD__,
1349 $options = [], $join_conds = []
1350 ) {
1351 $options = (array)$options;
1352 $options['LIMIT'] = 1;
1353
1354 $res = $this->select( $tables, $vars, $conds, $fname, $options, $join_conds );
1355 if ( $res === false ) {
1356 throw new DBUnexpectedError( $this, "Got false from select()" );
1357 }
1358
1359 if ( !$res->numRows() ) {
1360 return false;
1361 }
1362
1363 return $res->fetchObject();
1364 }
1365
1366 /**
1367 * @inheritDoc
1368 */
1369 public function estimateRowCount(
1370 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1371 ): int {
1372 $conds = $this->platform->normalizeConditions( $conds, $fname );
1373 $column = $this->platform->extractSingleFieldFromList( $var );
1374 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1375 $conds[] = "$column IS NOT NULL";
1376 }
1377
1378 $res = $this->select(
1379 $tables, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1380 );
1381 $row = $res ? $res->fetchRow() : [];
1382
1383 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1384 }
1385
1386 public function selectRowCount(
1387 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1388 ): int {
1389 $conds = $this->platform->normalizeConditions( $conds, $fname );
1390 $column = $this->platform->extractSingleFieldFromList( $var );
1391 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1392 $conds[] = "$column IS NOT NULL";
1393 }
1394 if ( in_array( 'DISTINCT', (array)$options ) ) {
1395 if ( $column === null ) {
1396 throw new DBUnexpectedError( $this,
1397 '$var cannot be empty when the DISTINCT option is given' );
1398 }
1399 $innerVar = $column;
1400 } else {
1401 $innerVar = '1';
1402 }
1403
1404 $res = $this->select(
1405 [
1406 'tmp_count' => $this->platform->buildSelectSubquery(
1407 $tables,
1408 $innerVar,
1409 $conds,
1410 $fname,
1411 $options,
1412 $join_conds
1413 )
1414 ],
1415 [ 'rowcount' => 'COUNT(*)' ],
1416 [],
1417 $fname
1418 );
1419 $row = $res ? $res->fetchRow() : [];
1420
1421 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1422 }
1423
1424 public function lockForUpdate(
1425 $table, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1426 ) {
1427 if ( !$this->trxLevel() && !$this->flagsHolder->hasImplicitTrxFlag() ) {
1428 throw new DBUnexpectedError(
1429 $this,
1430 __METHOD__ . ': no transaction is active nor is DBO_TRX set'
1431 );
1432 }
1433
1434 $options = (array)$options;
1435 $options[] = 'FOR UPDATE';
1436
1437 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
1438 }
1439
1440 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1441 $info = $this->fieldInfo( $table, $field );
1442
1443 return (bool)$info;
1444 }
1445
1446 abstract public function tableExists( $table, $fname = __METHOD__ );
1447
1448 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1449 $info = $this->indexInfo( $table, $index, $fname );
1450
1451 return (bool)$info;
1452 }
1453
1454 public function indexUnique( $table, $index, $fname = __METHOD__ ) {
1455 $info = $this->indexInfo( $table, $index, $fname );
1456
1457 return $info ? $info['unique'] : null;
1458 }
1459
1460 /**
1461 * Get information about an index into an object
1462 *
1463 * @param string $table The unqualified name of a table
1464 * @param string $index Index name
1465 * @param string $fname Calling function name
1466 * @return array<string,mixed>|false Index info map; false if it does not exist
1467 * @phan-return array{unique:bool}|false
1468 */
1469 abstract public function indexInfo( $table, $index, $fname = __METHOD__ );
1470
1471 public function insert( $table, $rows, $fname = __METHOD__, $options = [] ) {
1472 $query = $this->platform->dispatchingInsertSqlText( $table, $rows, $options );
1473 if ( !$query ) {
1474 return true;
1475 }
1476 $this->query( $query, $fname );
1477 if ( $this->strictWarnings ) {
1478 $this->checkInsertWarnings( $query, $fname );
1479 }
1480 return true;
1481 }
1482
1483 /**
1484 * Check for warnings after performing an INSERT query, and throw exceptions
1485 * if necessary.
1486 *
1487 * @param Query $query
1488 * @param string $fname
1489 * @return void
1490 */
1491 protected function checkInsertWarnings( Query $query, $fname ) {
1492 }
1493
1494 public function update( $table, $set, $conds, $fname = __METHOD__, $options = [] ) {
1495 $query = $this->platform->updateSqlText( $table, $set, $conds, $options );
1496 $this->query( $query, $fname );
1497
1498 return true;
1499 }
1500
1501 public function databasesAreIndependent() {
1502 return false;
1503 }
1504
1505 final public function selectDomain( $domain ) {
1506 $cs = $this->commenceCriticalSection( __METHOD__ );
1507
1508 try {
1509 $this->doSelectDomain( DatabaseDomain::newFromId( $domain ) );
1510 } catch ( DBError $e ) {
1511 $this->completeCriticalSection( __METHOD__, $cs );
1512 throw $e;
1513 }
1514
1515 $this->completeCriticalSection( __METHOD__, $cs );
1516 }
1517
1518 /**
1519 * @param DatabaseDomain $domain
1520 * @throws DBConnectionError
1521 * @throws DBError
1522 * @since 1.32
1523 */
1524 protected function doSelectDomain( DatabaseDomain $domain ) {
1525 $this->currentDomain = $domain;
1526 $this->platform->setCurrentDomain( $this->currentDomain );
1527 }
1528
1529 public function getDBname() {
1530 return $this->currentDomain->getDatabase();
1531 }
1532
1533 public function getServer() {
1534 return $this->connectionParams[self::CONN_HOST] ?? null;
1535 }
1536
1537 public function getServerName() {
1538 return $this->serverName ?? $this->getServer() ?? 'unknown';
1539 }
1540
1541 public function addQuotes( $s ) {
1542 if ( $s instanceof RawSQLValue ) {
1543 return $s->toSql();
1544 }
1545 if ( $s instanceof Blob ) {
1546 $s = $s->fetch();
1547 }
1548 if ( $s === null ) {
1549 return 'NULL';
1550 } elseif ( is_bool( $s ) ) {
1551 return (string)(int)$s;
1552 } elseif ( is_int( $s ) ) {
1553 return (string)$s;
1554 } else {
1555 return "'" . $this->strencode( $s ) . "'";
1556 }
1557 }
1558
1559 public function expr( string $field, string $op, $value ): Expression {
1560 return new Expression( $field, $op, $value );
1561 }
1562
1563 public function andExpr( array $conds ): AndExpressionGroup {
1564 return AndExpressionGroup::newFromArray( $conds );
1565 }
1566
1567 public function orExpr( array $conds ): OrExpressionGroup {
1568 return OrExpressionGroup::newFromArray( $conds );
1569 }
1570
1571 public function replace( $table, $uniqueKeys, $rows, $fname = __METHOD__ ) {
1572 $uniqueKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
1573 if ( !$rows ) {
1574 return;
1575 }
1576 $affectedRowCount = 0;
1577 $insertId = null;
1578 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
1579 try {
1580 foreach ( $rows as $row ) {
1581 // Delete any conflicting rows (including ones inserted from $rows)
1582 $query = $this->platform->deleteSqlText(
1583 $table,
1584 [ $this->platform->makeKeyCollisionCondition( [ $row ], $uniqueKey ) ]
1585 );
1586 $this->query( $query, $fname );
1587 // Insert the new row
1588 $query = $this->platform->dispatchingInsertSqlText( $table, $row, [] );
1589 $this->query( $query, $fname );
1590 $affectedRowCount += $this->lastQueryAffectedRows;
1591 $insertId = $insertId ?: $this->lastQueryInsertId;
1592 }
1593 $this->endAtomic( $fname );
1594 } catch ( DBError $e ) {
1595 $this->cancelAtomic( $fname );
1596 throw $e;
1597 }
1598 $this->lastEmulatedAffectedRows = $affectedRowCount;
1599 $this->lastEmulatedInsertId = $insertId;
1600 }
1601
1602 public function upsert( $table, array $rows, $uniqueKeys, array $set, $fname = __METHOD__ ) {
1603 $uniqueKey = $this->platform->normalizeUpsertParams( $uniqueKeys, $rows );
1604 if ( !$rows ) {
1605 return true;
1606 }
1607 $this->platform->assertValidUpsertSetArray( $set, $uniqueKey, $rows );
1608
1609 $encTable = $this->tableName( $table );
1610 $sqlColumnAssignments = $this->makeList( $set, self::LIST_SET );
1611 // Get any AUTO_INCREMENT/SERIAL column for this table so we can set insertId()
1612 $autoIncrementColumn = $this->getInsertIdColumnForUpsert( $table );
1613 // Check if there is a SQL assignment expression in $set (as generated by SQLPlatform::buildExcludedValue)
1614 $useWith = (bool)array_filter(
1615 $set,
1616 static function ( $v, $k ) {
1617 return $v instanceof RawSQLValue || is_int( $k );
1618 },
1619 ARRAY_FILTER_USE_BOTH
1620 );
1621 // Subclasses might need explicit type casting within "WITH...AS (VALUES ...)"
1622 // so that these CTE rows can be referenced within the SET clause assigments.
1623 $typeByColumn = $useWith ? $this->getValueTypesForWithClause( $table ) : [];
1624
1625 $first = true;
1626 $affectedRowCount = 0;
1627 $insertId = null;
1628 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
1629 try {
1630 foreach ( $rows as $row ) {
1631 // Update any existing conflicting row (including ones inserted from $rows)
1632 [ $sqlColumns, $sqlTuples, $sqlVals ] = $this->platform->makeInsertLists(
1633 [ $row ],
1634 '__',
1635 $typeByColumn
1636 );
1637 $sqlConditions = $this->platform->makeKeyCollisionCondition(
1638 [ $row ],
1639 $uniqueKey
1640 );
1641 $query = new Query(
1642 ( $useWith ? "WITH __VALS ($sqlVals) AS (VALUES $sqlTuples) " : "" ) .
1643 "UPDATE $encTable SET $sqlColumnAssignments " .
1644 "WHERE ($sqlConditions)",
1645 self::QUERY_CHANGE_ROWS,
1646 'UPDATE',
1647 $table
1648 );
1649 $this->query( $query, $fname );
1650 $rowsUpdated = $this->lastQueryAffectedRows;
1651 $affectedRowCount += $rowsUpdated;
1652 if ( $rowsUpdated > 0 ) {
1653 // Conflicting row found and updated
1654 if ( $first && $autoIncrementColumn !== null ) {
1655 // @TODO: use "RETURNING" instead (when supported by SQLite)
1656 $query = new Query(
1657 "SELECT $autoIncrementColumn AS id FROM $encTable " .
1658 "WHERE ($sqlConditions)",
1659 self::QUERY_CHANGE_NONE,
1660 'SELECT'
1661 );
1662 $sRes = $this->query( $query, $fname, self::QUERY_CHANGE_ROWS );
1663 $insertId = (int)$sRes->fetchRow()['id'];
1664 }
1665 } else {
1666 // No conflicting row found
1667 $query = new Query(
1668 "INSERT INTO $encTable ($sqlColumns) VALUES $sqlTuples",
1669 self::QUERY_CHANGE_ROWS,
1670 'INSERT',
1671 $table
1672 );
1673 $this->query( $query, $fname );
1674 $affectedRowCount += $this->lastQueryAffectedRows;
1675 }
1676 $first = false;
1677 }
1678 $this->endAtomic( $fname );
1679 } catch ( DBError $e ) {
1680 $this->cancelAtomic( $fname );
1681 throw $e;
1682 }
1683 $this->lastEmulatedAffectedRows = $affectedRowCount;
1684 $this->lastEmulatedInsertId = $insertId;
1685 return true;
1686 }
1687
1688 /**
1689 * @param string $table The unqualified name of a table
1690 * @return string|null The AUTO_INCREMENT/SERIAL column; null if not needed
1691 */
1692 protected function getInsertIdColumnForUpsert( $table ) {
1693 return null;
1694 }
1695
1696 /**
1697 * @param string $table The unqualified name of a table
1698 * @return array<string,string> Map of (column => type); [] if not needed
1699 */
1700 protected function getValueTypesForWithClause( $table ) {
1701 return [];
1702 }
1703
1704 public function deleteJoin(
1705 $delTable,
1706 $joinTable,
1707 $delVar,
1708 $joinVar,
1709 $conds,
1710 $fname = __METHOD__
1711 ) {
1712 $sql = $this->platform->deleteJoinSqlText( $delTable, $joinTable, $delVar, $joinVar, $conds );
1713 $query = new Query( $sql, self::QUERY_CHANGE_ROWS, 'DELETE', $delTable );
1714 $this->query( $query, $fname );
1715 }
1716
1717 public function delete( $table, $conds, $fname = __METHOD__ ) {
1718 $this->query( $this->platform->deleteSqlText( $table, $conds ), $fname );
1719
1720 return true;
1721 }
1722
1723 final public function insertSelect(
1724 $destTable,
1725 $srcTable,
1726 $varMap,
1727 $conds,
1728 $fname = __METHOD__,
1729 $insertOptions = [],
1730 $selectOptions = [],
1731 $selectJoinConds = []
1732 ) {
1733 static $hints = [ 'NO_AUTO_COLUMNS' ];
1734
1735 $insertOptions = $this->platform->normalizeOptions( $insertOptions );
1736 $selectOptions = $this->platform->normalizeOptions( $selectOptions );
1737
1738 if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions, $fname ) ) {
1739 // For massive migrations with downtime, we don't want to select everything
1740 // into memory and OOM, so do all this native on the server side if possible.
1741 $this->doInsertSelectNative(
1742 $destTable,
1743 $srcTable,
1744 $varMap,
1745 $conds,
1746 $fname,
1747 array_diff( $insertOptions, $hints ),
1748 $selectOptions,
1749 $selectJoinConds
1750 );
1751 } else {
1752 $this->doInsertSelectGeneric(
1753 $destTable,
1754 $srcTable,
1755 $varMap,
1756 $conds,
1757 $fname,
1758 array_diff( $insertOptions, $hints ),
1759 $selectOptions,
1760 $selectJoinConds
1761 );
1762 }
1763
1764 return true;
1765 }
1766
1767 /**
1768 * @param array $insertOptions
1769 * @param array $selectOptions
1770 * @param string $fname
1771 * @return bool Whether an INSERT SELECT with these options will be replication safe
1772 * @since 1.31
1773 */
1774 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions, $fname ) {
1775 return true;
1776 }
1777
1778 /**
1779 * Implementation of insertSelect() based on select() and insert()
1780 *
1781 * @see IDatabase::insertSelect()
1782 * @param string $destTable Unqualified name of destination table
1783 * @param string|array $srcTable Unqualified name of source table
1784 * @param array $varMap
1785 * @param array $conds
1786 * @param string $fname
1787 * @param array $insertOptions
1788 * @param array $selectOptions
1789 * @param array $selectJoinConds
1790 * @since 1.35
1791 */
1792 private function doInsertSelectGeneric(
1793 $destTable,
1794 $srcTable,
1795 array $varMap,
1796 $conds,
1797 $fname,
1798 array $insertOptions,
1799 array $selectOptions,
1800 $selectJoinConds
1801 ) {
1802 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
1803 // on only the primary DB (without needing row-based-replication). It also makes it easy to
1804 // know how big the INSERT is going to be.
1805 $fields = [];
1806 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
1807 $fields[] = $this->platform->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
1808 }
1809 $res = $this->select(
1810 $srcTable,
1811 implode( ',', $fields ),
1812 $conds,
1813 $fname,
1814 array_merge( $selectOptions, [ 'FOR UPDATE' ] ),
1815 $selectJoinConds
1816 );
1817
1818 $affectedRowCount = 0;
1819 $insertId = null;
1820 if ( $res ) {
1821 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
1822 try {
1823 $rows = [];
1824 foreach ( $res as $row ) {
1825 $rows[] = (array)$row;
1826 }
1827 // Avoid inserts that are too huge
1828 $rowBatches = array_chunk( $rows, $this->nonNativeInsertSelectBatchSize );
1829 foreach ( $rowBatches as $rows ) {
1830 $query = $this->platform->dispatchingInsertSqlText( $destTable, $rows, $insertOptions );
1831 $this->query( $query, $fname );
1832 $affectedRowCount += $this->lastQueryAffectedRows;
1833 $insertId = $insertId ?: $this->lastQueryInsertId;
1834 }
1835 $this->endAtomic( $fname );
1836 } catch ( DBError $e ) {
1837 $this->cancelAtomic( $fname );
1838 throw $e;
1839 }
1840 }
1841 $this->lastEmulatedAffectedRows = $affectedRowCount;
1842 $this->lastEmulatedInsertId = $insertId;
1843 }
1844
1845 /**
1846 * Native server-side implementation of insertSelect() for situations where
1847 * we don't want to select everything into memory
1848 *
1849 * @see IDatabase::insertSelect()
1850 * @param string $destTable The unqualified name of destination table
1851 * @param string|array $srcTable The unqualified name of source table
1852 * @param array $varMap
1853 * @param array $conds
1854 * @param string $fname
1855 * @param array $insertOptions
1856 * @param array $selectOptions
1857 * @param array $selectJoinConds
1858 * @since 1.35
1859 */
1860 protected function doInsertSelectNative(
1861 $destTable,
1862 $srcTable,
1863 array $varMap,
1864 $conds,
1865 $fname,
1866 array $insertOptions,
1867 array $selectOptions,
1868 $selectJoinConds
1869 ) {
1870 $sql = $this->platform->insertSelectNativeSqlText(
1871 $destTable,
1872 $srcTable,
1873 $varMap,
1874 $conds,
1875 $fname,
1876 $insertOptions,
1877 $selectOptions,
1878 $selectJoinConds
1879 );
1880 $query = new Query(
1881 $sql,
1882 self::QUERY_CHANGE_ROWS,
1883 'INSERT',
1884 $destTable
1885 );
1886 $this->query( $query, $fname );
1887 }
1888
1889 /**
1890 * Do not use this method outside of Database/DBError classes
1891 *
1892 * @param int|string $errno
1893 * @return bool Whether the given query error was a connection drop
1894 * @since 1.38
1895 */
1896 protected function isConnectionError( $errno ) {
1897 return false;
1898 }
1899
1900 /**
1901 * @param int|string $errno
1902 * @return bool Whether it is known that the last query error only caused statement rollback
1903 * @note This is for backwards compatibility for callers catching DBError exceptions in
1904 * order to ignore problems like duplicate key errors or foreign key violations
1905 * @since 1.39
1906 */
1907 protected function isKnownStatementRollbackError( $errno ) {
1908 return false; // don't know; it could have caused a transaction rollback
1909 }
1910
1911 /**
1912 * @inheritDoc
1913 */
1914 public function serverIsReadOnly() {
1915 return false;
1916 }
1917
1918 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
1919 $this->transactionManager->onTransactionResolution( $this, $callback, $fname );
1920 }
1921
1922 final public function onTransactionCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
1923 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
1924 // This DB handle is set to participate in LoadBalancer transaction rounds and
1925 // an explicit transaction round is active. Start an implicit transaction on this
1926 // DB handle (setting trxAutomatic) similar to how query() does in such situations.
1927 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1928 }
1929
1930 $this->transactionManager->addPostCommitOrIdleCallback( $callback, $fname );
1931 if ( !$this->trxLevel() ) {
1932 $dbErrors = [];
1933 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE, $dbErrors );
1934 if ( $dbErrors ) {
1935 throw $dbErrors[0];
1936 }
1937 }
1938 }
1939
1940 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
1941 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
1942 // This DB handle is set to participate in LoadBalancer transaction rounds and
1943 // an explicit transaction round is active. Start an implicit transaction on this
1944 // DB handle (setting trxAutomatic) similar to how query() does in such situations.
1945 $this->begin( __METHOD__, self::TRANSACTION_INTERNAL );
1946 }
1947
1948 if ( $this->trxLevel() ) {
1949 $this->transactionManager->addPreCommitOrIdleCallback(
1950 $callback,
1951 $fname
1952 );
1953 } else {
1954 // No transaction is active nor will start implicitly, so make one for this callback
1955 $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
1956 try {
1957 $callback( $this );
1958 } catch ( Throwable $e ) {
1959 // Avoid confusing error reporting during critical section errors
1960 if ( !$this->csmError ) {
1961 $this->cancelAtomic( __METHOD__ );
1962 }
1963 throw $e;
1964 }
1965 $this->endAtomic( __METHOD__ );
1966 }
1967 }
1968
1969 final public function onAtomicSectionCancel( callable $callback, $fname = __METHOD__ ) {
1970 $this->transactionManager->onAtomicSectionCancel( $this, $callback, $fname );
1971 }
1972
1973 final public function setTransactionListener( $name, ?callable $callback = null ) {
1974 $this->transactionManager->setTransactionListener( $name, $callback );
1975 }
1976
1977 /**
1978 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
1979 *
1980 * @internal This method should not be used outside of Database/LoadBalancer
1981 *
1982 * @since 1.28
1983 * @param bool $suppress
1984 */
1985 final public function setTrxEndCallbackSuppression( $suppress ) {
1986 $this->transactionManager->setTrxEndCallbackSuppression( $suppress );
1987 }
1988
1989 /**
1990 * Consume and run any "on transaction idle/resolution" callbacks
1991 *
1992 * @internal This method should not be used outside of Database/LoadBalancer
1993 *
1994 * @since 1.20
1995 * @param int $trigger IDatabase::TRIGGER_* constant
1996 * @param DBError[] &$errors DB exceptions caught [returned]
1997 * @return int Number of callbacks attempted
1998 * @throws DBUnexpectedError
1999 * @throws Throwable Any non-DBError exception thrown by a callback
2000 */
2001 public function runOnTransactionIdleCallbacks( $trigger, array &$errors = [] ) {
2002 if ( $this->trxLevel() ) {
2003 throw new DBUnexpectedError( $this, __METHOD__ . ': a transaction is still open' );
2004 }
2005
2006 if ( $this->transactionManager->isEndCallbacksSuppressed() ) {
2007 // Execution deferred by LoadBalancer for explicit execution later
2008 return 0;
2009 }
2010
2011 $cs = $this->commenceCriticalSection( __METHOD__ );
2012
2013 $count = 0;
2014 $autoTrx = $this->flagsHolder->hasImplicitTrxFlag(); // automatic begin() enabled?
2015 // Drain the queues of transaction "idle" and "end" callbacks until they are empty
2016 do {
2017 $callbackEntries = $this->transactionManager->consumeEndCallbacks( $trigger );
2018 $count += count( $callbackEntries );
2019 foreach ( $callbackEntries as $entry ) {
2020 $this->flagsHolder->clearFlag( self::DBO_TRX ); // make each query its own transaction
2021 try {
2022 $entry[0]( $trigger, $this );
2023 } catch ( DBError $ex ) {
2024 call_user_func( $this->errorLogger, $ex );
2025 $errors[] = $ex;
2026 // Some callbacks may use startAtomic/endAtomic, so make sure
2027 // their transactions are ended so other callbacks don't fail
2028 if ( $this->trxLevel() ) {
2029 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2030 }
2031 } finally {
2032 if ( $autoTrx ) {
2033 $this->flagsHolder->setFlag( self::DBO_TRX ); // restore automatic begin()
2034 } else {
2035 $this->flagsHolder->clearFlag( self::DBO_TRX ); // restore auto-commit
2036 }
2037 }
2038 }
2039 } while ( $this->transactionManager->countPostCommitOrIdleCallbacks() );
2040
2041 $this->completeCriticalSection( __METHOD__, $cs );
2042
2043 return $count;
2044 }
2045
2046 /**
2047 * Actually run any "transaction listener" callbacks
2048 *
2049 * @internal This method should not be used outside of Database/LoadBalancer
2050 *
2051 * @since 1.20
2052 * @param int $trigger IDatabase::TRIGGER_* constant
2053 * @param DBError[] &$errors DB exceptions caught [returned]
2054 * @throws Throwable Any non-DBError exception thrown by a callback
2055 */
2056 public function runTransactionListenerCallbacks( $trigger, array &$errors = [] ) {
2057 if ( $this->transactionManager->isEndCallbacksSuppressed() ) {
2058 // Execution deferred by LoadBalancer for explicit execution later
2059 return;
2060 }
2061
2062 // These callbacks should only be registered in setup, thus no iteration is needed
2063 foreach ( $this->transactionManager->getRecurringCallbacks() as $callback ) {
2064 try {
2065 $callback( $trigger, $this );
2066 } catch ( DBError $ex ) {
2067 ( $this->errorLogger )( $ex );
2068 $errors[] = $ex;
2069 }
2070 }
2071 }
2072
2073 /**
2074 * Handle "on transaction idle/resolution" and "transaction listener" callbacks post-COMMIT
2075 *
2076 * @throws DBError The first DBError exception thrown by a callback
2077 * @throws Throwable Any non-DBError exception thrown by a callback
2078 */
2079 private function runTransactionPostCommitCallbacks() {
2080 $dbErrors = [];
2081 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT, $dbErrors );
2082 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT, $dbErrors );
2083 $this->lastEmulatedAffectedRows = 0; // for the sake of consistency
2084 if ( $dbErrors ) {
2085 throw $dbErrors[0];
2086 }
2087 }
2088
2089 /**
2090 * Handle "on transaction idle/resolution" and "transaction listener" callbacks post-ROLLBACK
2091 *
2092 * This will suppress and log any DBError exceptions
2093 *
2094 * @throws Throwable Any non-DBError exception thrown by a callback
2095 */
2096 private function runTransactionPostRollbackCallbacks() {
2097 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2098 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2099 $this->lastEmulatedAffectedRows = 0; // for the sake of consistency
2100 }
2101
2102 final public function startAtomic(
2103 $fname = __METHOD__,
2104 $cancelable = self::ATOMIC_NOT_CANCELABLE
2105 ) {
2106 $cs = $this->commenceCriticalSection( __METHOD__ );
2107
2108 if ( $this->trxLevel() ) {
2109 // This atomic section is only one part of a larger transaction
2110 $sectionOwnsTrx = false;
2111 } else {
2112 // Start an implicit transaction (sets trxAutomatic)
2113 try {
2114 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2115 } catch ( DBError $e ) {
2116 $this->completeCriticalSection( __METHOD__, $cs );
2117 throw $e;
2118 }
2119 if ( $this->flagsHolder->hasImplicitTrxFlag() ) {
2120 // This DB handle participates in LoadBalancer transaction rounds; all atomic
2121 // sections should be buffered into one transaction (e.g. to keep web requests
2122 // transactional). Note that an implicit transaction round is considered to be
2123 // active when no there is no explicit transaction round.
2124 $sectionOwnsTrx = false;
2125 } else {
2126 // This DB handle does not participate in LoadBalancer transaction rounds;
2127 // each topmost atomic section will use its own transaction.
2128 $sectionOwnsTrx = true;
2129 }
2130 $this->transactionManager->setAutomaticAtomic( $sectionOwnsTrx );
2131 }
2132
2133 if ( $cancelable === self::ATOMIC_CANCELABLE ) {
2134 if ( $sectionOwnsTrx ) {
2135 // This atomic section is synonymous with the whole transaction; just
2136 // use full COMMIT/ROLLBACK in endAtomic()/cancelAtomic(), respectively
2137 $savepointId = self::NOT_APPLICABLE;
2138 } else {
2139 // This atomic section is only part of the whole transaction; use a SAVEPOINT
2140 // query so that its changes can be cancelled without losing the rest of the
2141 // transaction (e.g. changes from other sections or from outside of sections)
2142 try {
2143 $savepointId = $this->transactionManager->nextSavePointId( $this, $fname );
2144 $sql = $this->platform->savepointSqlText( $savepointId );
2145 $query = new Query( $sql, self::QUERY_CHANGE_TRX, 'SAVEPOINT' );
2146 $this->query( $query, $fname );
2147 } catch ( DBError $e ) {
2148 $this->completeCriticalSection( __METHOD__, $cs, $e );
2149 throw $e;
2150 }
2151 }
2152 } else {
2153 $savepointId = null;
2154 }
2155
2156 $sectionId = new AtomicSectionIdentifier;
2157 $this->transactionManager->addToAtomicLevels( $fname, $sectionId, $savepointId );
2158
2159 $this->completeCriticalSection( __METHOD__, $cs );
2160
2161 return $sectionId;
2162 }
2163
2164 final public function endAtomic( $fname = __METHOD__ ) {
2165 [ $savepointId, $sectionId ] = $this->transactionManager->onEndAtomic( $this, $fname );
2166
2167 $runPostCommitCallbacks = false;
2168
2169 $cs = $this->commenceCriticalSection( __METHOD__ );
2170
2171 // Remove the last section (no need to re-index the array)
2172 $finalLevelOfImplicitTrxPopped = $this->transactionManager->popAtomicLevel();
2173
2174 try {
2175 if ( $finalLevelOfImplicitTrxPopped ) {
2176 $this->commit( $fname, self::FLUSHING_INTERNAL );
2177 $runPostCommitCallbacks = true;
2178 } elseif ( $savepointId !== null && $savepointId !== self::NOT_APPLICABLE ) {
2179 $sql = $this->platform->releaseSavepointSqlText( $savepointId );
2180 $query = new Query( $sql, self::QUERY_CHANGE_TRX, 'RELEASE SAVEPOINT' );
2181 $this->query( $query, $fname );
2182 }
2183 } catch ( DBError $e ) {
2184 $this->completeCriticalSection( __METHOD__, $cs, $e );
2185 throw $e;
2186 }
2187
2188 $this->transactionManager->onEndAtomicInCriticalSection( $sectionId );
2189
2190 $this->completeCriticalSection( __METHOD__, $cs );
2191
2192 if ( $runPostCommitCallbacks ) {
2193 $this->runTransactionPostCommitCallbacks();
2194 }
2195 }
2196
2197 final public function cancelAtomic(
2198 $fname = __METHOD__,
2199 ?AtomicSectionIdentifier $sectionId = null
2200 ) {
2201 $this->transactionManager->onCancelAtomicBeforeCriticalSection( $this, $fname );
2202 $pos = $this->transactionManager->getPositionFromSectionId( $sectionId );
2203 if ( $pos < 0 ) {
2204 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
2205 }
2206
2207 $cs = $this->commenceCriticalSection( __METHOD__ );
2208 $runPostRollbackCallbacks = false;
2209 [ $savedFname, $excisedSectionIds, $newTopSectionId, $savedSectionId, $savepointId ] =
2210 $this->transactionManager->cancelAtomic( $pos );
2211
2212 try {
2213 if ( $savedFname !== $fname ) {
2214 $e = new DBUnexpectedError(
2215 $this,
2216 "Invalid atomic section ended (got $fname but expected $savedFname)"
2217 );
2218 $this->completeCriticalSection( __METHOD__, $cs, $e );
2219 throw $e;
2220 }
2221
2222 // Remove the last section (no need to re-index the array)
2223 $this->transactionManager->popAtomicLevel();
2224 $excisedSectionIds[] = $savedSectionId;
2225 $newTopSectionId = $this->transactionManager->currentAtomicSectionId();
2226
2227 if ( $savepointId !== null ) {
2228 // Rollback the transaction changes proposed within this atomic section
2229 if ( $savepointId === self::NOT_APPLICABLE ) {
2230 // Atomic section started the transaction; rollback the whole transaction
2231 // and trigger cancellation callbacks for all active atomic sections
2232 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2233 $runPostRollbackCallbacks = true;
2234 } else {
2235 // Atomic section nested within the transaction; rollback the transaction
2236 // to the state prior to this section and trigger its cancellation callbacks
2237 $sql = $this->platform->rollbackToSavepointSqlText( $savepointId );
2238 $query = new Query( $sql, self::QUERY_CHANGE_TRX, 'ROLLBACK TO SAVEPOINT' );
2239 $this->query( $query, $fname );
2240 $this->transactionManager->setTrxStatusToOk(); // no exception; recovered
2241 $this->transactionManager->runOnAtomicSectionCancelCallbacks(
2242 $this,
2243 self::TRIGGER_CANCEL,
2244 $excisedSectionIds
2245 );
2246 }
2247 } else {
2248 // Put the transaction into an error state if it's not already in one
2249 $trxError = new DBUnexpectedError(
2250 $this,
2251 "Uncancelable atomic section canceled (got $fname)"
2252 );
2253 $this->transactionManager->setTransactionError( $trxError );
2254 }
2255 } finally {
2256 // Fix up callbacks owned by the sections that were just cancelled.
2257 // All callbacks should have an owner that is present in trxAtomicLevels.
2258 $this->transactionManager->modifyCallbacksForCancel(
2259 $excisedSectionIds,
2260 $newTopSectionId
2261 );
2262 }
2263
2264 $this->lastEmulatedAffectedRows = 0; // for the sake of consistency
2265
2266 $this->completeCriticalSection( __METHOD__, $cs );
2267
2268 if ( $runPostRollbackCallbacks ) {
2269 $this->runTransactionPostRollbackCallbacks();
2270 }
2271 }
2272
2273 final public function doAtomicSection(
2274 $fname,
2275 callable $callback,
2276 $cancelable = self::ATOMIC_NOT_CANCELABLE
2277 ) {
2278 $sectionId = $this->startAtomic( $fname, $cancelable );
2279 try {
2280 $res = $callback( $this, $fname );
2281 } catch ( Throwable $e ) {
2282 // Avoid confusing error reporting during critical section errors
2283 if ( !$this->csmError ) {
2284 $this->cancelAtomic( $fname, $sectionId );
2285 }
2286
2287 throw $e;
2288 }
2289 $this->endAtomic( $fname );
2290
2291 return $res;
2292 }
2293
2294 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2295 static $modes = [ self::TRANSACTION_EXPLICIT, self::TRANSACTION_INTERNAL ];
2296 if ( !in_array( $mode, $modes, true ) ) {
2297 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
2298 }
2299
2300 $this->transactionManager->onBegin( $this, $fname );
2301
2302 if ( $this->flagsHolder->hasImplicitTrxFlag() && $mode !== self::TRANSACTION_INTERNAL ) {
2303 $msg = "$fname: implicit transaction expected (DBO_TRX set)";
2304 throw new DBUnexpectedError( $this, $msg );
2305 }
2306
2307 $this->assertHasConnectionHandle();
2308
2309 $cs = $this->commenceCriticalSection( __METHOD__ );
2310 $timeStart = microtime( true );
2311 try {
2312 $this->doBegin( $fname );
2313 } catch ( DBError $e ) {
2314 $this->completeCriticalSection( __METHOD__, $cs );
2315 throw $e;
2316 }
2317 $timeEnd = microtime( true );
2318 // Treat "BEGIN" as a trivial query to gauge the RTT delay
2319 $rtt = max( $timeEnd - $timeStart, 0.0 );
2320 $this->transactionManager->onBeginInCriticalSection( $mode, $fname, $rtt );
2321 $this->replicationReporter->resetReplicationLagStatus( $this );
2322 $this->completeCriticalSection( __METHOD__, $cs );
2323 }
2324
2325 /**
2326 * Issues the BEGIN command to the database server.
2327 *
2328 * @see Database::begin()
2329 * @param string $fname
2330 * @throws DBError
2331 */
2332 protected function doBegin( $fname ) {
2333 $query = new Query( 'BEGIN', self::QUERY_CHANGE_TRX, 'BEGIN' );
2334 $this->query( $query, $fname );
2335 }
2336
2337 final public function commit( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
2338 static $modes = [ self::FLUSHING_ONE, self::FLUSHING_ALL_PEERS, self::FLUSHING_INTERNAL ];
2339 if ( !in_array( $flush, $modes, true ) ) {
2340 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
2341 }
2342
2343 if ( !$this->transactionManager->onCommit( $this, $fname, $flush ) ) {
2344 return;
2345 }
2346
2347 $this->assertHasConnectionHandle();
2348
2349 $this->runOnTransactionPreCommitCallbacks();
2350
2351 $cs = $this->commenceCriticalSection( __METHOD__ );
2352 try {
2353 if ( $this->trxLevel() ) {
2354 $query = new Query( 'COMMIT', self::QUERY_CHANGE_TRX, 'COMMIT' );
2355 $this->query( $query, $fname );
2356 }
2357 } catch ( DBError $e ) {
2358 $this->completeCriticalSection( __METHOD__, $cs );
2359 throw $e;
2360 }
2361 $lastWriteTime = $this->transactionManager->onCommitInCriticalSection( $this );
2362 if ( $lastWriteTime ) {
2363 $this->lastWriteTime = $lastWriteTime;
2364 }
2365 // With FLUSHING_ALL_PEERS, callbacks will run when requested by a dedicated phase
2366 // within LoadBalancer. With FLUSHING_INTERNAL, callbacks will run when requested by
2367 // the Database caller during a safe point. This avoids isolation and recursion issues.
2368 if ( $flush === self::FLUSHING_ONE ) {
2369 $this->runTransactionPostCommitCallbacks();
2370 }
2371 $this->completeCriticalSection( __METHOD__, $cs );
2372 }
2373
2374 final public function rollback( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
2375 if (
2376 $flush !== self::FLUSHING_INTERNAL &&
2377 $flush !== self::FLUSHING_ALL_PEERS &&
2378 $this->flagsHolder->hasImplicitTrxFlag()
2379 ) {
2380 throw new DBUnexpectedError(
2381 $this,
2382 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
2383 );
2384 }
2385
2386 if ( !$this->trxLevel() ) {
2387 $this->transactionManager->setTrxStatusToNone();
2388 $this->transactionManager->clearPreEndCallbacks();
2389 if ( $this->transactionManager->trxLevel() === TransactionManager::STATUS_TRX_ERROR ) {
2390 $this->logger->info(
2391 "$fname: acknowledged server-side transaction loss on {db_server}",
2392 $this->getLogContext()
2393 );
2394 }
2395
2396 return;
2397 }
2398
2399 $this->assertHasConnectionHandle();
2400
2401 if ( $this->csmError ) {
2402 // Since the session state is corrupt, we cannot just rollback the transaction
2403 // while preserving the non-transaction session state. The handle will remain
2404 // marked as corrupt until flushSession() is called to reset the connection
2405 // and deal with any remaining callbacks.
2406 $this->logger->info(
2407 "$fname: acknowledged client-side transaction loss on {db_server}",
2408 $this->getLogContext()
2409 );
2410
2411 return;
2412 }
2413
2414 $cs = $this->commenceCriticalSection( __METHOD__ );
2415 if ( $this->trxLevel() ) {
2416 // Disconnects cause rollback anyway, so ignore those errors
2417 $query = new Query(
2418 $this->platform->rollbackSqlText(),
2419 self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_TRX,
2420 'ROLLBACK'
2421 );
2422 $this->query( $query, $fname );
2423 }
2424 $this->transactionManager->onRollbackInCriticalSection( $this );
2425 // With FLUSHING_ALL_PEERS, callbacks will run when requested by a dedicated phase
2426 // within LoadBalancer. With FLUSHING_INTERNAL, callbacks will run when requested by
2427 // the Database caller during a safe point. This avoids isolation and recursion issues.
2428 if ( $flush === self::FLUSHING_ONE ) {
2429 $this->runTransactionPostRollbackCallbacks();
2430 }
2431 $this->completeCriticalSection( __METHOD__, $cs );
2432 }
2433
2434 /**
2435 * @internal Only for tests and highly discouraged
2436 * @param TransactionManager $transactionManager
2437 */
2438 public function setTransactionManager( TransactionManager $transactionManager ) {
2439 $this->transactionManager = $transactionManager;
2440 }
2441
2442 public function flushSession( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
2443 if (
2444 $flush !== self::FLUSHING_INTERNAL &&
2445 $flush !== self::FLUSHING_ALL_PEERS &&
2446 $this->flagsHolder->hasImplicitTrxFlag()
2447 ) {
2448 throw new DBUnexpectedError(
2449 $this,
2450 "$fname: Expected mass flush of all peer connections (DBO_TRX set)"
2451 );
2452 }
2453
2454 if ( $this->csmError ) {
2455 // If a critical section error occurred, such as Excimer timeout exceptions raised
2456 // before a query response was marshalled, destroy the connection handle and reset
2457 // the session state tracking variables. The value of trxLevel() is irrelevant here,
2458 // and, in fact, might be 1 due to rollback() deferring critical section recovery.
2459 $this->logger->info(
2460 "$fname: acknowledged client-side session loss on {db_server}",
2461 $this->getLogContext()
2462 );
2463 $this->csmError = null;
2464 $this->csmFname = null;
2465 $this->replaceLostConnection( 2048, __METHOD__ );
2466
2467 return;
2468 }
2469
2470 if ( $this->trxLevel() ) {
2471 // Any existing transaction should have been rolled back already
2472 throw new DBUnexpectedError(
2473 $this,
2474 "$fname: transaction still in progress (not yet rolled back)"
2475 );
2476 }
2477
2478 if ( $this->transactionManager->sessionStatus() === TransactionManager::STATUS_SESS_ERROR ) {
2479 // If the session state was already lost due to either an unacknowledged session
2480 // state loss error (e.g. dropped connection) or an explicit connection close call,
2481 // then there is nothing to do here. Note that in such cases, even temporary tables
2482 // and server-side config variables are lost (invocation of this method is assumed
2483 // to imply that such losses are tolerable).
2484 $this->logger->info(
2485 "$fname: acknowledged server-side session loss on {db_server}",
2486 $this->getLogContext()
2487 );
2488 } elseif ( $this->isOpen() ) {
2489 // Connection handle exists; server-side session state must be flushed
2490 $this->doFlushSession( $fname );
2491 $this->sessionNamedLocks = [];
2492 }
2493
2494 $this->transactionManager->clearSessionError();
2495 }
2496
2497 /**
2498 * Reset the server-side session state for named locks and table locks
2499 *
2500 * Connection and query errors will be suppressed and logged
2501 *
2502 * @param string $fname
2503 * @since 1.38
2504 */
2505 protected function doFlushSession( $fname ) {
2506 // no-op
2507 }
2508
2509 public function flushSnapshot( $fname = __METHOD__, $flush = self::FLUSHING_ONE ) {
2510 $this->transactionManager->onFlushSnapshot( $this, $fname, $flush, $this->getTransactionRoundId() );
2511 if (
2512 $this->transactionManager->sessionStatus() === TransactionManager::STATUS_SESS_ERROR ||
2513 $this->transactionManager->trxStatus() === TransactionManager::STATUS_TRX_ERROR
2514 ) {
2515 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2516 } else {
2517 $this->commit( $fname, self::FLUSHING_INTERNAL );
2518 }
2519 }
2520
2521 public function duplicateTableStructure(
2522 $oldName,
2523 $newName,
2524 $temporary = false,
2525 $fname = __METHOD__
2526 ) {
2527 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2528 }
2529
2530 public function listTables( $prefix = null, $fname = __METHOD__ ) {
2531 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2532 }
2533
2534 public function affectedRows() {
2535 $this->lastEmulatedAffectedRows ??= $this->lastQueryAffectedRows;
2536
2537 return $this->lastEmulatedAffectedRows;
2538 }
2539
2540 public function insertId() {
2541 if ( $this->lastEmulatedInsertId === null ) {
2542 // Guard against misuse of this method by checking affectedRows(). Note that calls
2543 // to insert() with "IGNORE" and calls to insertSelect() might not add any rows.
2544 if ( $this->affectedRows() ) {
2545 $this->lastEmulatedInsertId = $this->lastInsertId();
2546 } else {
2547 $this->lastEmulatedInsertId = 0;
2548 }
2549 }
2550
2551 return $this->lastEmulatedInsertId;
2552 }
2553
2554 /**
2555 * Get a row ID from the last insert statement to implicitly assign one within the session
2556 *
2557 * If the statement involved assigning sequence IDs to multiple rows, then the return value
2558 * will be any one of those values (database-specific). If the statement was an "UPSERT" and
2559 * some existing rows were updated, then the result will either reflect only IDs of created
2560 * rows or it will reflect IDs of both created and updated rows (this is database-specific).
2561 *
2562 * The result is unspecified if the statement gave an error.
2563 *
2564 * @return int Sequence ID, 0 (if none)
2565 * @throws DBError
2566 */
2567 abstract protected function lastInsertId();
2568
2569 public function ping() {
2570 if ( $this->isOpen() ) {
2571 // If the connection was recently used, assume that it is still good
2572 if ( ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
2573 return true;
2574 }
2575 // Send a trivial query to test the connection, triggering an automatic
2576 // reconnection attempt if the connection was lost
2577 $query = new Query(
2578 self::PING_QUERY,
2579 self::QUERY_IGNORE_DBO_TRX | self::QUERY_SILENCE_ERRORS | self::QUERY_CHANGE_NONE,
2580 'SELECT'
2581 );
2582 $res = $this->query( $query, __METHOD__ );
2583 $ok = ( $res !== false );
2584 } else {
2585 // Try to re-establish a connection
2586 $ok = $this->replaceLostConnection( null, __METHOD__ );
2587 }
2588
2589 return $ok;
2590 }
2591
2592 /**
2593 * Close any existing (dead) database connection and open a new connection
2594 *
2595 * @param int|null $lastErrno
2596 * @param string $fname
2597 * @return bool True if new connection is opened successfully, false if error
2598 */
2599 protected function replaceLostConnection( $lastErrno, $fname ) {
2600 if ( $this->conn ) {
2601 $this->closeConnection();
2602 $this->conn = null;
2603 $this->handleSessionLossPreconnect();
2604 }
2605
2606 try {
2607 $this->open(
2608 $this->connectionParams[self::CONN_HOST],
2609 $this->connectionParams[self::CONN_USER],
2610 $this->connectionParams[self::CONN_PASSWORD],
2611 $this->currentDomain->getDatabase(),
2612 $this->currentDomain->getSchema(),
2613 $this->tablePrefix()
2614 );
2615 $this->lastPing = microtime( true );
2616 $ok = true;
2617
2618 $this->logger->warning(
2619 $fname . ': lost connection to {db_server} with error {errno}; reconnected',
2620 $this->getLogContext( [
2621 'exception' => new RuntimeException(),
2622 'db_log_category' => 'connection',
2623 'errno' => $lastErrno
2624 ] )
2625 );
2626 } catch ( DBConnectionError $e ) {
2627 $ok = false;
2628
2629 $this->logger->error(
2630 $fname . ': lost connection to {db_server} with error {errno}; reconnection failed: {connect_msg}',
2631 $this->getLogContext( [
2632 'exception' => new RuntimeException(),
2633 'db_log_category' => 'connection',
2634 'errno' => $lastErrno,
2635 'connect_msg' => $e->getMessage()
2636 ] )
2637 );
2638 }
2639
2640 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
2641 // If callback suppression is set then the array will remain unhandled.
2642 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2643 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener().
2644 // If callback suppression is set then the array will remain unhandled.
2645 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2646
2647 return $ok;
2648 }
2649
2650 /**
2651 * Merge the result of getSessionLagStatus() for several DBs
2652 * using the most pessimistic values to estimate the lag of
2653 * any data derived from them in combination
2654 *
2655 * This is information is useful for caching modules
2656 *
2657 * @see WANObjectCache::set()
2658 * @see WANObjectCache::getWithSetCallback()
2659 *
2660 * @param IReadableDatabase|null ...$dbs
2661 * Note: For backward compatibility, it is allowed for null values
2662 * to be passed among the parameters. This is deprecated since 1.36,
2663 * only IReadableDatabase objects should be passed.
2664 *
2665 * @return array Map of values:
2666 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2667 * - since: oldest UNIX timestamp of any of the DB lag estimates
2668 * - pending: whether any of the DBs have uncommitted changes
2669 * @throws DBError
2670 * @since 1.27
2671 */
2672 public static function getCacheSetOptions( ?IReadableDatabase ...$dbs ) {
2673 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
2674
2675 foreach ( func_get_args() as $db ) {
2676 if ( $db instanceof IReadableDatabase ) {
2677 $status = $db->getSessionLagStatus();
2678
2679 if ( $status['lag'] === false ) {
2680 $res['lag'] = false;
2681 } elseif ( $res['lag'] !== false ) {
2682 $res['lag'] = max( $res['lag'], $status['lag'] );
2683 }
2684 $res['since'] = min( $res['since'], $status['since'] );
2685 }
2686
2687 if ( $db instanceof IDatabaseForOwner ) {
2688 $res['pending'] = $res['pending'] ?: $db->writesPending();
2689 }
2690 }
2691
2692 return $res;
2693 }
2694
2695 public function encodeBlob( $b ) {
2696 return $b;
2697 }
2698
2699 public function decodeBlob( $b ) {
2700 if ( $b instanceof Blob ) {
2701 $b = $b->fetch();
2702 }
2703 return $b;
2704 }
2705
2706 public function setSessionOptions( array $options ) {
2707 }
2708
2709 public function sourceFile(
2710 $filename,
2711 ?callable $lineCallback = null,
2712 ?callable $resultCallback = null,
2713 $fname = false,
2714 ?callable $inputCallback = null
2715 ) {
2716 AtEase::suppressWarnings();
2717 $fp = fopen( $filename, 'r' );
2718 AtEase::restoreWarnings();
2719
2720 if ( $fp === false ) {
2721 throw new RuntimeException( "Could not open \"{$filename}\"" );
2722 }
2723
2724 if ( !$fname ) {
2725 $fname = __METHOD__ . "( $filename )";
2726 }
2727
2728 try {
2729 return $this->sourceStream(
2730 $fp,
2731 $lineCallback,
2732 $resultCallback,
2733 $fname,
2734 $inputCallback
2735 );
2736 } finally {
2737 fclose( $fp );
2738 }
2739 }
2740
2741 public function sourceStream(
2742 $fp,
2743 ?callable $lineCallback = null,
2744 ?callable $resultCallback = null,
2745 $fname = __METHOD__,
2746 ?callable $inputCallback = null
2747 ) {
2748 $delimiterReset = new ScopedCallback(
2749 function ( $delimiter ) {
2750 $this->delimiter = $delimiter;
2751 },
2752 [ $this->delimiter ]
2753 );
2754 $cmd = '';
2755
2756 while ( !feof( $fp ) ) {
2757 if ( $lineCallback ) {
2758 call_user_func( $lineCallback );
2759 }
2760
2761 $line = trim( fgets( $fp ) );
2762
2763 if ( $line == '' ) {
2764 continue;
2765 }
2766
2767 if ( $line[0] == '-' && $line[1] == '-' ) {
2768 continue;
2769 }
2770
2771 if ( $cmd != '' ) {
2772 $cmd .= ' ';
2773 }
2774
2775 $done = $this->streamStatementEnd( $cmd, $line );
2776
2777 $cmd .= "$line\n";
2778
2779 if ( $done || feof( $fp ) ) {
2780 $cmd = $this->platform->replaceVars( $cmd );
2781
2782 if ( $inputCallback ) {
2783 $callbackResult = $inputCallback( $cmd );
2784
2785 if ( is_string( $callbackResult ) || !$callbackResult ) {
2786 $cmd = $callbackResult;
2787 }
2788 }
2789
2790 if ( $cmd ) {
2791 $res = $this->query( $cmd, $fname );
2792
2793 if ( $resultCallback ) {
2794 $resultCallback( $res, $this );
2795 }
2796
2797 if ( $res === false ) {
2798 $err = $this->lastError();
2799
2800 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2801 }
2802 }
2803 $cmd = '';
2804 }
2805 }
2806
2807 ScopedCallback::consume( $delimiterReset );
2808 return true;
2809 }
2810
2811 /**
2812 * Called by sourceStream() to check if we've reached a statement end
2813 *
2814 * @param string &$sql SQL assembled so far
2815 * @param string &$newLine New line about to be added to $sql
2816 * @return bool Whether $newLine contains end of the statement
2817 */
2818 public function streamStatementEnd( &$sql, &$newLine ) {
2819 if ( $this->delimiter ) {
2820 $prev = $newLine;
2821 $newLine = preg_replace(
2822 '/' . preg_quote( $this->delimiter, '/' ) . '$/',
2823 '',
2824 $newLine
2825 );
2826 if ( $newLine != $prev ) {
2827 return true;
2828 }
2829 }
2830
2831 return false;
2832 }
2833
2834 /**
2835 * @inheritDoc
2836 */
2837 public function lockIsFree( $lockName, $method ) {
2838 // RDBMs methods for checking named locks may or may not count this thread itself.
2839 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
2840 // the behavior chosen by the interface for this method.
2841 if ( isset( $this->sessionNamedLocks[$lockName] ) ) {
2842 $lockIsFree = false;
2843 } else {
2844 $lockIsFree = $this->doLockIsFree( $lockName, $method );
2845 }
2846
2847 return $lockIsFree;
2848 }
2849
2850 /**
2851 * @see lockIsFree()
2852 *
2853 * @param string $lockName
2854 * @param string $method
2855 * @return bool Success
2856 * @throws DBError
2857 */
2858 protected function doLockIsFree( string $lockName, string $method ) {
2859 return true; // not implemented
2860 }
2861
2862 /**
2863 * @inheritDoc
2864 */
2865 public function lock( $lockName, $method, $timeout = 5, $flags = 0 ) {
2866 $lockTsUnix = $this->doLock( $lockName, $method, $timeout );
2867 if ( $lockTsUnix !== null ) {
2868 $locked = true;
2869 $this->sessionNamedLocks[$lockName] = [
2870 'ts' => $lockTsUnix,
2871 'trxId' => $this->transactionManager->getTrxId()
2872 ];
2873 } else {
2874 $locked = false;
2875 $this->logger->info(
2876 __METHOD__ . ": failed to acquire lock '{lockname}'",
2877 [
2878 'lockname' => $lockName,
2879 'db_log_category' => 'locking'
2880 ]
2881 );
2882 }
2883
2884 return $this->flagsHolder::contains( $flags, self::LOCK_TIMESTAMP ) ? $lockTsUnix : $locked;
2885 }
2886
2887 /**
2888 * @see lock()
2889 *
2890 * @param string $lockName
2891 * @param string $method
2892 * @param int $timeout
2893 * @return float|null UNIX timestamp of lock acquisition; null on failure
2894 * @throws DBError
2895 */
2896 protected function doLock( string $lockName, string $method, int $timeout ) {
2897 return microtime( true ); // not implemented
2898 }
2899
2900 /**
2901 * @inheritDoc
2902 */
2903 public function unlock( $lockName, $method ) {
2904 if ( !isset( $this->sessionNamedLocks[$lockName] ) ) {
2905 $released = false;
2906 $this->logger->warning(
2907 __METHOD__ . ": trying to release unheld lock '$lockName'\n",
2908 [ 'db_log_category' => 'locking' ]
2909 );
2910 } else {
2911 $released = $this->doUnlock( $lockName, $method );
2912 if ( $released ) {
2913 unset( $this->sessionNamedLocks[$lockName] );
2914 } else {
2915 $this->logger->warning(
2916 __METHOD__ . ": failed to release lock '$lockName'\n",
2917 [ 'db_log_category' => 'locking' ]
2918 );
2919 }
2920 }
2921
2922 return $released;
2923 }
2924
2925 /**
2926 * @see unlock()
2927 *
2928 * @param string $lockName
2929 * @param string $method
2930 * @return bool Success
2931 * @throws DBError
2932 */
2933 protected function doUnlock( string $lockName, string $method ) {
2934 return true; // not implemented
2935 }
2936
2937 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
2938 $this->transactionManager->onGetScopedLockAndFlush( $this, $fname );
2939
2940 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
2941 return null;
2942 }
2943
2944 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
2945 // Note that the callback can be reached due to an exception making the calling
2946 // function end early. If the transaction/session is in an error state, avoid log
2947 // spam and confusing replacement of an original DBError with one about unlock().
2948 // Unlock query will fail anyway; avoid possibly triggering errors in rollback()
2949 if (
2950 $this->transactionManager->sessionStatus() === TransactionManager::STATUS_SESS_ERROR ||
2951 $this->transactionManager->trxStatus() === TransactionManager::STATUS_TRX_ERROR
2952 ) {
2953 return;
2954 }
2955 if ( $this->trxLevel() ) {
2956 $this->onTransactionResolution(
2957 function () use ( $lockKey, $fname ) {
2958 $this->unlock( $lockKey, $fname );
2959 },
2960 $fname
2961 );
2962 } else {
2963 $this->unlock( $lockKey, $fname );
2964 }
2965 } );
2966
2967 $this->commit( $fname, self::FLUSHING_INTERNAL );
2968
2969 return $unlocker;
2970 }
2971
2972 public function dropTable( $table, $fname = __METHOD__ ) {
2973 if ( !$this->tableExists( $table, $fname ) ) {
2974 return false;
2975 }
2976
2977 $query = new Query(
2978 $this->platform->dropTableSqlText( $table ),
2979 self::QUERY_CHANGE_SCHEMA,
2980 'DROP',
2981 $table
2982 );
2983 $this->query( $query, $fname );
2984
2985 return true;
2986 }
2987
2988 public function truncateTable( $table, $fname = __METHOD__ ) {
2989 $sql = "TRUNCATE TABLE " . $this->tableName( $table );
2990 $query = new Query( $sql, self::QUERY_CHANGE_SCHEMA, 'TRUNCATE', $table );
2991 $this->query( $query, $fname );
2992 }
2993
2994 public function isReadOnly() {
2995 return ( $this->getReadOnlyReason() !== null );
2996 }
2997
2998 /**
2999 * @return array|null Tuple of (reason string, "role" or "lb") if read-only; null otherwise
3000 */
3001 protected function getReadOnlyReason() {
3002 $reason = $this->replicationReporter->getTopologyBasedReadOnlyReason();
3003 if ( $reason ) {
3004 return $reason;
3005 }
3006
3007 $reason = $this->getLBInfo( self::LB_READ_ONLY_REASON );
3008 if ( is_string( $reason ) ) {
3009 return [ $reason, 'lb' ];
3010 }
3011
3012 return null;
3013 }
3014
3015 /**
3016 * Get the underlying binding connection handle
3017 *
3018 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3019 * This catches broken callers than catch and ignore disconnection exceptions.
3020 * Unlike checking isOpen(), this is safe to call inside of open().
3021 *
3022 * @return mixed
3023 * @throws DBUnexpectedError
3024 * @since 1.26
3025 */
3026 protected function getBindingHandle() {
3027 if ( !$this->conn ) {
3028 throw new DBUnexpectedError(
3029 $this,
3030 'DB connection was already closed or the connection dropped'
3031 );
3032 }
3033
3034 return $this->conn;
3035 }
3036
3037 /**
3038 * Demark the start of a critical section of session/transaction state changes
3039 *
3040 * Use this to disable potentially DB handles due to corruption from highly unexpected
3041 * exceptions (e.g. from zend timers or coding errors) preempting execution of methods.
3042 *
3043 * Callers must demark completion of the critical section with completeCriticalSection().
3044 * Callers should handle DBError exceptions that do not cause object state corruption by
3045 * catching them, calling completeCriticalSection(), and then rethrowing them.
3046 *
3047 * @code
3048 * $cs = $this->commenceCriticalSection( __METHOD__ );
3049 * try {
3050 * //...send a query that changes the session/transaction state...
3051 * } catch ( DBError $e ) {
3052 * $this->completeCriticalSection( __METHOD__, $cs );
3053 * throw $expectedException;
3054 * }
3055 * try {
3056 * //...send another query that changes the session/transaction state...
3057 * } catch ( DBError $trxError ) {
3058 * // Require ROLLBACK before allowing any other queries from outside callers
3059 * $this->completeCriticalSection( __METHOD__, $cs, $trxError );
3060 * throw $expectedException;
3061 * }
3062 * // ...update session state fields of $this...
3063 * $this->completeCriticalSection( __METHOD__, $cs );
3064 * @endcode
3065 *
3066 * @see Database::completeCriticalSection()
3067 *
3068 * @since 1.36
3069 * @param string $fname Caller name
3070 * @return CriticalSectionScope|null RAII-style monitor (topmost sections only)
3071 * @throws DBUnexpectedError If an unresolved critical section error already exists
3072 */
3073 protected function commenceCriticalSection( string $fname ) {
3074 if ( $this->csmError ) {
3075 throw new DBUnexpectedError(
3076 $this,
3077 "Cannot execute $fname critical section while session state is out of sync.\n\n" .
3078 $this->csmError->getMessage() . "\n" .
3079 $this->csmError->getTraceAsString()
3080 );
3081 }
3082
3083 if ( $this->csmId ) {
3084 $csm = null; // fold into the outer critical section
3085 } elseif ( $this->csProvider ) {
3086 $csm = $this->csProvider->scopedEnter(
3087 $fname,
3088 null, // emergency limit (default)
3089 null, // emergency callback (default)
3090 function () use ( $fname ) {
3091 // Mark a critical section as having been aborted by an error
3092 $e = new RuntimeException( "A critical section from {$fname} has failed" );
3093 $this->csmError = $e;
3094 $this->csmId = null;
3095 }
3096 );
3097 $this->csmId = $csm->getId();
3098 $this->csmFname = $fname;
3099 } else {
3100 $csm = null; // not supported
3101 }
3102
3103 return $csm;
3104 }
3105
3106 /**
3107 * Demark the completion of a critical section of session/transaction state changes
3108 *
3109 * @see Database::commenceCriticalSection()
3110 *
3111 * @since 1.36
3112 * @param string $fname Caller name
3113 * @param CriticalSectionScope|null $csm RAII-style monitor (topmost sections only)
3114 * @param Throwable|null $trxError Error that requires setting STATUS_TRX_ERROR (if any)
3115 */
3116 protected function completeCriticalSection(
3117 string $fname,
3118 ?CriticalSectionScope $csm,
3119 ?Throwable $trxError = null
3120 ) {
3121 if ( $csm !== null ) {
3122 if ( $this->csmId === null ) {
3123 throw new LogicException( "$fname critical section is not active" );
3124 } elseif ( $csm->getId() !== $this->csmId ) {
3125 throw new LogicException(
3126 "$fname critical section is not the active ({$this->csmFname}) one"
3127 );
3128 }
3129
3130 $csm->exit();
3131 $this->csmId = null;
3132 }
3133
3134 if ( $trxError ) {
3135 $this->transactionManager->setTransactionError( $trxError );
3136 }
3137 }
3138
3139 public function __toString() {
3140 $id = spl_object_id( $this );
3141
3142 $description = $this->getType() . ' object #' . $id;
3143 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.is_resource
3144 if ( is_resource( $this->conn ) ) {
3145 $description .= ' (' . (string)$this->conn . ')'; // "resource id #<ID>"
3146 } elseif ( is_object( $this->conn ) ) {
3147 $handleId = spl_object_id( $this->conn );
3148 $description .= " (handle id #$handleId)";
3149 }
3150
3151 return $description;
3152 }
3153
3154 /**
3155 * Make sure that copies do not share the same client binding handle
3156 * @throws DBConnectionError
3157 */
3158 public function __clone() {
3159 $this->logger->warning(
3160 "Cloning " . static::class . " is not recommended; forking connection",
3161 [
3162 'exception' => new RuntimeException(),
3163 'db_log_category' => 'connection'
3164 ]
3165 );
3166
3167 if ( $this->isOpen() ) {
3168 // Open a new connection resource without messing with the old one
3169 $this->conn = null;
3170 $this->transactionManager->clearEndCallbacks();
3171 $this->handleSessionLossPreconnect(); // no trx or locks anymore
3172 $this->open(
3173 $this->connectionParams[self::CONN_HOST],
3174 $this->connectionParams[self::CONN_USER],
3175 $this->connectionParams[self::CONN_PASSWORD],
3176 $this->currentDomain->getDatabase(),
3177 $this->currentDomain->getSchema(),
3178 $this->tablePrefix()
3179 );
3180 $this->lastPing = microtime( true );
3181 }
3182 }
3183
3184 /**
3185 * Called by serialize. Throw an exception when DB connection is serialized.
3186 * This causes problems on some database engines because the connection is
3187 * not restored on unserialize.
3188 * @return never
3189 */
3190 public function __sleep() {
3191 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3192 'the connection is not restored on wakeup' );
3193 }
3194
3195 /**
3196 * Run a few simple checks and close dangling connections
3197 */
3198 public function __destruct() {
3199 if ( $this->transactionManager ) {
3200 // Tests mock this class and disable constructor.
3201 $this->transactionManager->onDestruct();
3202 }
3203
3204 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3205 if ( $danglingWriters ) {
3206 $fnames = implode( ', ', $danglingWriters );
3207 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
3208 }
3209
3210 if ( $this->conn ) {
3211 // Avoid connection leaks. Normally, resources close at script completion.
3212 // The connection might already be closed in PHP by now, so suppress warnings.
3213 AtEase::suppressWarnings();
3214 $this->closeConnection();
3215 AtEase::restoreWarnings();
3216 $this->conn = null;
3217 }
3218 }
3219
3220 /* Start of methods delegated to DatabaseFlags. Avoid using them outside of rdbms library */
3221
3222 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
3223 $this->flagsHolder->setFlag( $flag, $remember );
3224 }
3225
3226 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
3227 $this->flagsHolder->clearFlag( $flag, $remember );
3228 }
3229
3230 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
3231 $this->flagsHolder->restoreFlags( $state );
3232 }
3233
3234 public function getFlag( $flag ) {
3235 return $this->flagsHolder->getFlag( $flag );
3236 }
3237
3238 /* End of methods delegated to DatabaseFlags. */
3239
3240 /* Start of methods delegated to TransactionManager. Avoid using them outside of rdbms library */
3241
3242 final public function trxLevel() {
3243 // FIXME: A lot of tests disable constructor leading to trx manager being
3244 // null and breaking, this is unacceptable but hopefully this should
3245 // happen less by moving these functions to the transaction manager class.
3246 if ( !$this->transactionManager ) {
3247 $this->transactionManager = new TransactionManager( new NullLogger() );
3248 }
3249 return $this->transactionManager->trxLevel();
3250 }
3251
3252 public function trxTimestamp() {
3253 return $this->transactionManager->trxTimestamp();
3254 }
3255
3256 public function trxStatus() {
3257 return $this->transactionManager->trxStatus();
3258 }
3259
3260 public function writesPending() {
3261 return $this->transactionManager->writesPending();
3262 }
3263
3264 public function writesOrCallbacksPending() {
3265 return $this->transactionManager->writesOrCallbacksPending();
3266 }
3267
3268 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
3269 return $this->transactionManager->pendingWriteQueryDuration( $type );
3270 }
3271
3272 public function pendingWriteCallers() {
3273 if ( !$this->transactionManager ) {
3274 return [];
3275 }
3276 return $this->transactionManager->pendingWriteCallers();
3277 }
3278
3279 public function pendingWriteAndCallbackCallers() {
3280 if ( !$this->transactionManager ) {
3281 return [];
3282 }
3283 return $this->transactionManager->pendingWriteAndCallbackCallers();
3284 }
3285
3286 public function runOnTransactionPreCommitCallbacks() {
3287 return $this->transactionManager->runOnTransactionPreCommitCallbacks( $this );
3288 }
3289
3290 public function explicitTrxActive() {
3291 return $this->transactionManager->explicitTrxActive();
3292 }
3293
3294 /* End of methods delegated to TransactionManager. */
3295
3296 /* Start of methods delegated to SQLPlatform. Avoid using them outside of rdbms library */
3297
3298 public function implicitOrderby() {
3299 return $this->platform->implicitOrderby();
3300 }
3301
3302 public function selectSQLText(
3303 $tables, $vars, $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
3304 ) {
3305 return $this->platform->selectSQLText( $tables, $vars, $conds, $fname, $options, $join_conds );
3306 }
3307
3308 public function buildComparison( string $op, array $conds ): string {
3309 return $this->platform->buildComparison( $op, $conds );
3310 }
3311
3312 public function makeList( array $a, $mode = self::LIST_COMMA ) {
3313 return $this->platform->makeList( $a, $mode );
3314 }
3315
3316 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
3317 return $this->platform->makeWhereFrom2d( $data, $baseKey, $subKey );
3318 }
3319
3320 public function factorConds( $condsArray ) {
3321 return $this->platform->factorConds( $condsArray );
3322 }
3323
3324 public function bitNot( $field ) {
3325 return $this->platform->bitNot( $field );
3326 }
3327
3328 public function bitAnd( $fieldLeft, $fieldRight ) {
3329 return $this->platform->bitAnd( $fieldLeft, $fieldRight );
3330 }
3331
3332 public function bitOr( $fieldLeft, $fieldRight ) {
3333 return $this->platform->bitOr( $fieldLeft, $fieldRight );
3334 }
3335
3336 public function buildConcat( $stringList ) {
3337 return $this->platform->buildConcat( $stringList );
3338 }
3339
3340 public function buildGreatest( $fields, $values ) {
3341 return $this->platform->buildGreatest( $fields, $values );
3342 }
3343
3344 public function buildLeast( $fields, $values ) {
3345 return $this->platform->buildLeast( $fields, $values );
3346 }
3347
3348 public function buildSubstring( $input, $startPosition, $length = null ) {
3349 return $this->platform->buildSubstring( $input, $startPosition, $length );
3350 }
3351
3352 public function buildStringCast( $field ) {
3353 return $this->platform->buildStringCast( $field );
3354 }
3355
3356 public function buildIntegerCast( $field ) {
3357 return $this->platform->buildIntegerCast( $field );
3358 }
3359
3360 public function tableName( string $name, $format = 'quoted' ) {
3361 return $this->platform->tableName( $name, $format );
3362 }
3363
3364 public function tableNames( ...$tables ) {
3365 return $this->platform->tableNames( ...$tables );
3366 }
3367
3368 public function tableNamesN( ...$tables ) {
3369 return $this->platform->tableNamesN( ...$tables );
3370 }
3371
3372 public function addIdentifierQuotes( $s ) {
3373 return $this->platform->addIdentifierQuotes( $s );
3374 }
3375
3376 public function isQuotedIdentifier( $name ) {
3377 return $this->platform->isQuotedIdentifier( $name );
3378 }
3379
3380 public function buildLike( $param, ...$params ) {
3381 return $this->platform->buildLike( $param, ...$params );
3382 }
3383
3384 public function anyChar() {
3385 return $this->platform->anyChar();
3386 }
3387
3388 public function anyString() {
3389 return $this->platform->anyString();
3390 }
3391
3392 public function limitResult( $sql, $limit, $offset = false ) {
3393 return $this->platform->limitResult( $sql, $limit, $offset );
3394 }
3395
3396 public function unionSupportsOrderAndLimit() {
3397 return $this->platform->unionSupportsOrderAndLimit();
3398 }
3399
3400 public function unionQueries( $sqls, $all, $options = [] ) {
3401 return $this->platform->unionQueries( $sqls, $all, $options );
3402 }
3403
3404 public function conditional( $cond, $caseTrueExpression, $caseFalseExpression ) {
3405 return $this->platform->conditional( $cond, $caseTrueExpression, $caseFalseExpression );
3406 }
3407
3408 public function strreplace( $orig, $old, $new ) {
3409 return $this->platform->strreplace( $orig, $old, $new );
3410 }
3411
3412 public function timestamp( $ts = 0 ) {
3413 return $this->platform->timestamp( $ts );
3414 }
3415
3416 public function timestampOrNull( $ts = null ) {
3417 return $this->platform->timestampOrNull( $ts );
3418 }
3419
3420 public function getInfinity() {
3421 return $this->platform->getInfinity();
3422 }
3423
3424 public function encodeExpiry( $expiry ) {
3425 return $this->platform->encodeExpiry( $expiry );
3426 }
3427
3428 public function decodeExpiry( $expiry, $format = TS_MW ) {
3429 return $this->platform->decodeExpiry( $expiry, $format );
3430 }
3431
3432 public function setTableAliases( array $aliases ) {
3433 $this->platform->setTableAliases( $aliases );
3434 }
3435
3436 public function getTableAliases() {
3437 return $this->platform->getTableAliases();
3438 }
3439
3440 public function setIndexAliases( array $aliases ) {
3441 $this->platform->setIndexAliases( $aliases );
3442 }
3443
3444 public function buildGroupConcatField(
3445 $delim, $tables, $field, $conds = '', $join_conds = []
3446 ) {
3447 return $this->platform->buildGroupConcatField( $delim, $tables, $field, $conds, $join_conds );
3448 }
3449
3450 public function buildSelectSubquery(
3451 $tables, $vars, $conds = '', $fname = __METHOD__,
3452 $options = [], $join_conds = []
3453 ) {
3454 return $this->platform->buildSelectSubquery( $tables, $vars, $conds, $fname, $options, $join_conds );
3455 }
3456
3457 public function buildExcludedValue( $column ) {
3458 return $this->platform->buildExcludedValue( $column );
3459 }
3460
3461 public function setSchemaVars( $vars ) {
3462 $this->platform->setSchemaVars( $vars );
3463 }
3464
3465 /* End of methods delegated to SQLPlatform. */
3466
3467 /* Start of methods delegated to ReplicationReporter. */
3468 public function primaryPosWait( DBPrimaryPos $pos, $timeout ) {
3469 return $this->replicationReporter->primaryPosWait( $this, $pos, $timeout );
3470 }
3471
3472 public function getPrimaryPos() {
3473 return $this->replicationReporter->getPrimaryPos( $this );
3474 }
3475
3476 public function getLag() {
3477 return $this->replicationReporter->getLag( $this );
3478 }
3479
3480 public function getSessionLagStatus() {
3481 return $this->replicationReporter->getSessionLagStatus( $this );
3482 }
3483
3484 /* End of methods delegated to ReplicationReporter. */
3485 }