rdbms: make Database query error handling more strict
[lhc/web/wiklou.git] / includes / libs / rdbms / database / Database.php
1 <?php
2 /**
3 * @defgroup Database Database
4 *
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @ingroup Database
25 */
26 namespace Wikimedia\Rdbms;
27
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Psr\Log\NullLogger;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\Timestamp\ConvertibleTimestamp;
33 use Wikimedia;
34 use BagOStuff;
35 use HashBagOStuff;
36 use LogicException;
37 use InvalidArgumentException;
38 use UnexpectedValueException;
39 use Exception;
40 use RuntimeException;
41
42 /**
43 * Relational database abstraction object
44 *
45 * @ingroup Database
46 * @since 1.28
47 */
48 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
49 /** Number of times to re-try an operation in case of deadlock */
50 const DEADLOCK_TRIES = 4;
51 /** Minimum time to wait before retry, in microseconds */
52 const DEADLOCK_DELAY_MIN = 500000;
53 /** Maximum time to wait before retry */
54 const DEADLOCK_DELAY_MAX = 1500000;
55
56 /** How long before it is worth doing a dummy query to test the connection */
57 const PING_TTL = 1.0;
58 const PING_QUERY = 'SELECT 1 AS ping';
59
60 const TINY_WRITE_SEC = 0.010;
61 const SLOW_WRITE_SEC = 0.500;
62 const SMALL_WRITE_ROWS = 100;
63
64 /** @var string Whether lock granularity is on the level of the entire database */
65 const ATTR_DB_LEVEL_LOCKING = 'db-level-locking';
66
67 /** @var int New Database instance will not be connected yet when returned */
68 const NEW_UNCONNECTED = 0;
69 /** @var int New Database instance will already be connected when returned */
70 const NEW_CONNECTED = 1;
71
72 /** @var string SQL query */
73 protected $lastQuery = '';
74 /** @var float|bool UNIX timestamp of last write query */
75 protected $lastWriteTime = false;
76 /** @var string|bool */
77 protected $phpError = false;
78 /** @var string Server that this instance is currently connected to */
79 protected $server;
80 /** @var string User that this instance is currently connected under the name of */
81 protected $user;
82 /** @var string Password used to establish the current connection */
83 protected $password;
84 /** @var string Database that this instance is currently connected to */
85 protected $dbName;
86 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
87 protected $tableAliases = [];
88 /** @var string[] Map of (index alias => index) */
89 protected $indexAliases = [];
90 /** @var bool Whether this PHP instance is for a CLI script */
91 protected $cliMode;
92 /** @var string Agent name for query profiling */
93 protected $agent;
94 /** @var array Parameters used by initConnection() to establish a connection */
95 protected $connectionParams = [];
96 /** @var BagOStuff APC cache */
97 protected $srvCache;
98 /** @var LoggerInterface */
99 protected $connLogger;
100 /** @var LoggerInterface */
101 protected $queryLogger;
102 /** @var callback Error logging callback */
103 protected $errorLogger;
104
105 /** @var resource|null Database connection */
106 protected $conn = null;
107 /** @var bool */
108 protected $opened = false;
109
110 /** @var array[] List of (callable, method name) */
111 protected $trxIdleCallbacks = [];
112 /** @var array[] List of (callable, method name) */
113 protected $trxPreCommitCallbacks = [];
114 /** @var array[] List of (callable, method name) */
115 protected $trxEndCallbacks = [];
116 /** @var callable[] Map of (name => callable) */
117 protected $trxRecurringCallbacks = [];
118 /** @var bool Whether to suppress triggering of transaction end callbacks */
119 protected $trxEndCallbacksSuppressed = false;
120
121 /** @var string */
122 protected $tablePrefix = '';
123 /** @var string */
124 protected $schema = '';
125 /** @var int */
126 protected $flags;
127 /** @var array */
128 protected $lbInfo = [];
129 /** @var array|bool */
130 protected $schemaVars = false;
131 /** @var array */
132 protected $sessionVars = [];
133 /** @var array|null */
134 protected $preparedArgs;
135 /** @var string|bool|null Stashed value of html_errors INI setting */
136 protected $htmlErrors;
137 /** @var string */
138 protected $delimiter = ';';
139 /** @var DatabaseDomain */
140 protected $currentDomain;
141 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
142 protected $affectedRowCount;
143
144 /**
145 * @var int Transaction status
146 */
147 protected $trxStatus = self::STATUS_TRX_NONE;
148 /**
149 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
150 */
151 protected $trxStatusCause;
152 /**
153 * Either 1 if a transaction is active or 0 otherwise.
154 * The other Trx fields may not be meaningfull if this is 0.
155 *
156 * @var int
157 */
158 protected $trxLevel = 0;
159 /**
160 * Either a short hexidecimal string if a transaction is active or ""
161 *
162 * @var string
163 * @see Database::trxLevel
164 */
165 protected $trxShortId = '';
166 /**
167 * The UNIX time that the transaction started. Callers can assume that if
168 * snapshot isolation is used, then the data is *at least* up to date to that
169 * point (possibly more up-to-date since the first SELECT defines the snapshot).
170 *
171 * @var float|null
172 * @see Database::trxLevel
173 */
174 private $trxTimestamp = null;
175 /** @var float Lag estimate at the time of BEGIN */
176 private $trxReplicaLag = null;
177 /**
178 * Remembers the function name given for starting the most recent transaction via begin().
179 * Used to provide additional context for error reporting.
180 *
181 * @var string
182 * @see Database::trxLevel
183 */
184 private $trxFname = null;
185 /**
186 * Record if possible write queries were done in the last transaction started
187 *
188 * @var bool
189 * @see Database::trxLevel
190 */
191 private $trxDoneWrites = false;
192 /**
193 * Record if the current transaction was started implicitly due to DBO_TRX being set.
194 *
195 * @var bool
196 * @see Database::trxLevel
197 */
198 private $trxAutomatic = false;
199 /**
200 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
201 *
202 * @var int
203 */
204 private $trxAtomicCounter = 0;
205 /**
206 * Array of levels of atomicity within transactions
207 *
208 * @var array
209 */
210 private $trxAtomicLevels = [];
211 /**
212 * Record if the current transaction was started implicitly by Database::startAtomic
213 *
214 * @var bool
215 */
216 private $trxAutomaticAtomic = false;
217 /**
218 * Track the write query callers of the current transaction
219 *
220 * @var string[]
221 */
222 private $trxWriteCallers = [];
223 /**
224 * @var float Seconds spent in write queries for the current transaction
225 */
226 private $trxWriteDuration = 0.0;
227 /**
228 * @var int Number of write queries for the current transaction
229 */
230 private $trxWriteQueryCount = 0;
231 /**
232 * @var int Number of rows affected by write queries for the current transaction
233 */
234 private $trxWriteAffectedRows = 0;
235 /**
236 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
237 */
238 private $trxWriteAdjDuration = 0.0;
239 /**
240 * @var int Number of write queries counted in trxWriteAdjDuration
241 */
242 private $trxWriteAdjQueryCount = 0;
243 /**
244 * @var float RTT time estimate
245 */
246 private $rttEstimate = 0.0;
247
248 /** @var array Map of (name => 1) for locks obtained via lock() */
249 private $namedLocksHeld = [];
250 /** @var array Map of (table name => 1) for TEMPORARY tables */
251 protected $sessionTempTables = [];
252
253 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
254 private $lazyMasterHandle;
255
256 /** @var float UNIX timestamp */
257 protected $lastPing = 0.0;
258
259 /** @var int[] Prior flags member variable values */
260 private $priorFlags = [];
261
262 /** @var object|string Class name or object With profileIn/profileOut methods */
263 protected $profiler;
264 /** @var TransactionProfiler */
265 protected $trxProfiler;
266
267 /** @var int */
268 protected $nonNativeInsertSelectBatchSize = 10000;
269
270 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
271 const STATUS_TRX_ERROR = 1;
272 /** @var int Transaction is active and in a normal state */
273 const STATUS_TRX_OK = 2;
274 /** @var int No transaction is active */
275 const STATUS_TRX_NONE = 3;
276
277 /**
278 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
279 * @param array $params Parameters passed from Database::factory()
280 */
281 protected function __construct( array $params ) {
282 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
283 $this->connectionParams[$name] = $params[$name];
284 }
285
286 $this->schema = $params['schema'];
287 $this->tablePrefix = $params['tablePrefix'];
288
289 $this->cliMode = $params['cliMode'];
290 // Agent name is added to SQL queries in a comment, so make sure it can't break out
291 $this->agent = str_replace( '/', '-', $params['agent'] );
292
293 $this->flags = $params['flags'];
294 if ( $this->flags & self::DBO_DEFAULT ) {
295 if ( $this->cliMode ) {
296 $this->flags &= ~self::DBO_TRX;
297 } else {
298 $this->flags |= self::DBO_TRX;
299 }
300 }
301 // Disregard deprecated DBO_IGNORE flag (T189999)
302 $this->flags &= ~self::DBO_IGNORE;
303
304 $this->sessionVars = $params['variables'];
305
306 $this->srvCache = isset( $params['srvCache'] )
307 ? $params['srvCache']
308 : new HashBagOStuff();
309
310 $this->profiler = $params['profiler'];
311 $this->trxProfiler = $params['trxProfiler'];
312 $this->connLogger = $params['connLogger'];
313 $this->queryLogger = $params['queryLogger'];
314 $this->errorLogger = $params['errorLogger'];
315
316 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
317 $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'];
318 }
319
320 // Set initial dummy domain until open() sets the final DB/prefix
321 $this->currentDomain = DatabaseDomain::newUnspecified();
322 }
323
324 /**
325 * Initialize the connection to the database over the wire (or to local files)
326 *
327 * @throws LogicException
328 * @throws InvalidArgumentException
329 * @throws DBConnectionError
330 * @since 1.31
331 */
332 final public function initConnection() {
333 if ( $this->isOpen() ) {
334 throw new LogicException( __METHOD__ . ': already connected.' );
335 }
336 // Establish the connection
337 $this->doInitConnection();
338 // Set the domain object after open() sets the relevant fields
339 if ( $this->dbName != '' ) {
340 // Domains with server scope but a table prefix are not used by IDatabase classes
341 $this->currentDomain = new DatabaseDomain( $this->dbName, null, $this->tablePrefix );
342 }
343 }
344
345 /**
346 * Actually connect to the database over the wire (or to local files)
347 *
348 * @throws InvalidArgumentException
349 * @throws DBConnectionError
350 * @since 1.31
351 */
352 protected function doInitConnection() {
353 if ( strlen( $this->connectionParams['user'] ) ) {
354 $this->open(
355 $this->connectionParams['host'],
356 $this->connectionParams['user'],
357 $this->connectionParams['password'],
358 $this->connectionParams['dbname']
359 );
360 } else {
361 throw new InvalidArgumentException( "No database user provided." );
362 }
363 }
364
365 /**
366 * Construct a Database subclass instance given a database type and parameters
367 *
368 * This also connects to the database immediately upon object construction
369 *
370 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
371 * @param array $p Parameter map with keys:
372 * - host : The hostname of the DB server
373 * - user : The name of the database user the client operates under
374 * - password : The password for the database user
375 * - dbname : The name of the database to use where queries do not specify one.
376 * The database must exist or an error might be thrown. Setting this to the empty string
377 * will avoid any such errors and make the handle have no implicit database scope. This is
378 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
379 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
380 * in which user names and such are defined, e.g. users are database-specific in Postgres.
381 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
382 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
383 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
384 * recognized in queries. This can be used in place of schemas for handle site farms.
385 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
386 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
387 * flag in place UNLESS this this database simply acts as a key/value store.
388 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
389 * 'mysqli' driver; the old one 'mysql' has been removed.
390 * - variables: Optional map of session variables to set after connecting. This can be
391 * used to adjust lock timeouts or encoding modes and the like.
392 * - connLogger: Optional PSR-3 logger interface instance.
393 * - queryLogger: Optional PSR-3 logger interface instance.
394 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
395 * These will be called in query(), using a simplified version of the SQL that also
396 * includes the agent as a SQL comment.
397 * - trxProfiler: Optional TransactionProfiler instance.
398 * - errorLogger: Optional callback that takes an Exception and logs it.
399 * - cliMode: Whether to consider the execution context that of a CLI script.
400 * - agent: Optional name used to identify the end-user in query profiling/logging.
401 * - srvCache: Optional BagOStuff instance to an APC-style cache.
402 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
403 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
404 * @return Database|null If the database driver or extension cannot be found
405 * @throws InvalidArgumentException If the database driver or extension cannot be found
406 * @since 1.18
407 */
408 final public static function factory( $dbType, $p = [], $connect = self::NEW_CONNECTED ) {
409 $class = self::getClass( $dbType, isset( $p['driver'] ) ? $p['driver'] : null );
410
411 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
412 // Resolve some defaults for b/c
413 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
414 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
415 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
416 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
417 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
418 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
419 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
420 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
421 $p['cliMode'] = isset( $p['cliMode'] )
422 ? $p['cliMode']
423 : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
424 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
425 if ( !isset( $p['connLogger'] ) ) {
426 $p['connLogger'] = new NullLogger();
427 }
428 if ( !isset( $p['queryLogger'] ) ) {
429 $p['queryLogger'] = new NullLogger();
430 }
431 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
432 if ( !isset( $p['trxProfiler'] ) ) {
433 $p['trxProfiler'] = new TransactionProfiler();
434 }
435 if ( !isset( $p['errorLogger'] ) ) {
436 $p['errorLogger'] = function ( Exception $e ) {
437 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
438 };
439 }
440
441 /** @var Database $conn */
442 $conn = new $class( $p );
443 if ( $connect == self::NEW_CONNECTED ) {
444 $conn->initConnection();
445 }
446 } else {
447 $conn = null;
448 }
449
450 return $conn;
451 }
452
453 /**
454 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
455 * @param string|null $driver Optional name of a specific DB client driver
456 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
457 * @throws InvalidArgumentException
458 * @since 1.31
459 */
460 final public static function attributesFromType( $dbType, $driver = null ) {
461 static $defaults = [ self::ATTR_DB_LEVEL_LOCKING => false ];
462
463 $class = self::getClass( $dbType, $driver );
464
465 return call_user_func( [ $class, 'getAttributes' ] ) + $defaults;
466 }
467
468 /**
469 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
470 * @param string|null $driver Optional name of a specific DB client driver
471 * @return string Database subclass name to use
472 * @throws InvalidArgumentException
473 */
474 private static function getClass( $dbType, $driver = null ) {
475 // For database types with built-in support, the below maps type to IDatabase
476 // implementations. For types with multipe driver implementations (PHP extensions),
477 // an array can be used, keyed by extension name. In case of an array, the
478 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
479 // we auto-detect the first available driver. For types without built-in support,
480 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
481 static $builtinTypes = [
482 'mssql' => DatabaseMssql::class,
483 'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
484 'sqlite' => DatabaseSqlite::class,
485 'postgres' => DatabasePostgres::class,
486 ];
487
488 $dbType = strtolower( $dbType );
489 $class = false;
490
491 if ( isset( $builtinTypes[$dbType] ) ) {
492 $possibleDrivers = $builtinTypes[$dbType];
493 if ( is_string( $possibleDrivers ) ) {
494 $class = $possibleDrivers;
495 } else {
496 if ( (string)$driver !== '' ) {
497 if ( !isset( $possibleDrivers[$driver] ) ) {
498 throw new InvalidArgumentException( __METHOD__ .
499 " type '$dbType' does not support driver '{$driver}'" );
500 } else {
501 $class = $possibleDrivers[$driver];
502 }
503 } else {
504 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
505 if ( extension_loaded( $posDriver ) ) {
506 $class = $possibleClass;
507 break;
508 }
509 }
510 }
511 }
512 } else {
513 $class = 'Database' . ucfirst( $dbType );
514 }
515
516 if ( $class === false ) {
517 throw new InvalidArgumentException( __METHOD__ .
518 " no viable database extension found for type '$dbType'" );
519 }
520
521 return $class;
522 }
523
524 /**
525 * @return array Map of (Database::ATTRIBUTE_* constant => value
526 * @since 1.31
527 */
528 protected static function getAttributes() {
529 return [];
530 }
531
532 /**
533 * Set the PSR-3 logger interface to use for query logging. (The logger
534 * interfaces for connection logging and error logging can be set with the
535 * constructor.)
536 *
537 * @param LoggerInterface $logger
538 */
539 public function setLogger( LoggerInterface $logger ) {
540 $this->queryLogger = $logger;
541 }
542
543 public function getServerInfo() {
544 return $this->getServerVersion();
545 }
546
547 public function bufferResults( $buffer = null ) {
548 $res = !$this->getFlag( self::DBO_NOBUFFER );
549 if ( $buffer !== null ) {
550 $buffer
551 ? $this->clearFlag( self::DBO_NOBUFFER )
552 : $this->setFlag( self::DBO_NOBUFFER );
553 }
554
555 return $res;
556 }
557
558 public function trxLevel() {
559 return $this->trxLevel;
560 }
561
562 public function trxTimestamp() {
563 return $this->trxLevel ? $this->trxTimestamp : null;
564 }
565
566 /**
567 * @return int One of the STATUS_TRX_* class constants
568 * @since 1.31
569 */
570 public function trxStatus() {
571 return $this->trxStatus;
572 }
573
574 public function tablePrefix( $prefix = null ) {
575 $old = $this->tablePrefix;
576 if ( $prefix !== null ) {
577 $this->tablePrefix = $prefix;
578 $this->currentDomain = ( $this->dbName != '' )
579 ? new DatabaseDomain( $this->dbName, null, $this->tablePrefix )
580 : DatabaseDomain::newUnspecified();
581 }
582
583 return $old;
584 }
585
586 public function dbSchema( $schema = null ) {
587 $old = $this->schema;
588 if ( $schema !== null ) {
589 $this->schema = $schema;
590 }
591
592 return $old;
593 }
594
595 public function getLBInfo( $name = null ) {
596 if ( is_null( $name ) ) {
597 return $this->lbInfo;
598 } else {
599 if ( array_key_exists( $name, $this->lbInfo ) ) {
600 return $this->lbInfo[$name];
601 } else {
602 return null;
603 }
604 }
605 }
606
607 public function setLBInfo( $name, $value = null ) {
608 if ( is_null( $value ) ) {
609 $this->lbInfo = $name;
610 } else {
611 $this->lbInfo[$name] = $value;
612 }
613 }
614
615 public function setLazyMasterHandle( IDatabase $conn ) {
616 $this->lazyMasterHandle = $conn;
617 }
618
619 /**
620 * @return IDatabase|null
621 * @see setLazyMasterHandle()
622 * @since 1.27
623 */
624 protected function getLazyMasterHandle() {
625 return $this->lazyMasterHandle;
626 }
627
628 public function implicitGroupby() {
629 return true;
630 }
631
632 public function implicitOrderby() {
633 return true;
634 }
635
636 public function lastQuery() {
637 return $this->lastQuery;
638 }
639
640 public function doneWrites() {
641 return (bool)$this->lastWriteTime;
642 }
643
644 public function lastDoneWrites() {
645 return $this->lastWriteTime ?: false;
646 }
647
648 public function writesPending() {
649 return $this->trxLevel && $this->trxDoneWrites;
650 }
651
652 public function writesOrCallbacksPending() {
653 return $this->trxLevel && (
654 $this->trxDoneWrites ||
655 $this->trxIdleCallbacks ||
656 $this->trxPreCommitCallbacks ||
657 $this->trxEndCallbacks
658 );
659 }
660
661 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
662 if ( !$this->trxLevel ) {
663 return false;
664 } elseif ( !$this->trxDoneWrites ) {
665 return 0.0;
666 }
667
668 switch ( $type ) {
669 case self::ESTIMATE_DB_APPLY:
670 $this->ping( $rtt );
671 $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
672 $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
673 // For omitted queries, make them count as something at least
674 $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
675 $applyTime += self::TINY_WRITE_SEC * $omitted;
676
677 return $applyTime;
678 default: // everything
679 return $this->trxWriteDuration;
680 }
681 }
682
683 public function pendingWriteCallers() {
684 return $this->trxLevel ? $this->trxWriteCallers : [];
685 }
686
687 public function pendingWriteRowsAffected() {
688 return $this->trxWriteAffectedRows;
689 }
690
691 /**
692 * Get the list of method names that have pending write queries or callbacks
693 * for this transaction
694 *
695 * @return array
696 */
697 protected function pendingWriteAndCallbackCallers() {
698 if ( !$this->trxLevel ) {
699 return [];
700 }
701
702 $fnames = $this->trxWriteCallers;
703 foreach ( [
704 $this->trxIdleCallbacks,
705 $this->trxPreCommitCallbacks,
706 $this->trxEndCallbacks
707 ] as $callbacks ) {
708 foreach ( $callbacks as $callback ) {
709 $fnames[] = $callback[1];
710 }
711 }
712
713 return $fnames;
714 }
715
716 /**
717 * @return string
718 */
719 private function flatAtomicSectionList() {
720 return array_reduce( $this->trxAtomicLevels, function ( $accum, $v ) {
721 return $accum === null ? $v[0] : "$accum, " . $v[0];
722 } );
723 }
724
725 public function isOpen() {
726 return $this->opened;
727 }
728
729 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
730 if ( ( $flag & self::DBO_IGNORE ) ) {
731 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
732 }
733
734 if ( $remember === self::REMEMBER_PRIOR ) {
735 array_push( $this->priorFlags, $this->flags );
736 }
737 $this->flags |= $flag;
738 }
739
740 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
741 if ( ( $flag & self::DBO_IGNORE ) ) {
742 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
743 }
744
745 if ( $remember === self::REMEMBER_PRIOR ) {
746 array_push( $this->priorFlags, $this->flags );
747 }
748 $this->flags &= ~$flag;
749 }
750
751 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
752 if ( !$this->priorFlags ) {
753 return;
754 }
755
756 if ( $state === self::RESTORE_INITIAL ) {
757 $this->flags = reset( $this->priorFlags );
758 $this->priorFlags = [];
759 } else {
760 $this->flags = array_pop( $this->priorFlags );
761 }
762 }
763
764 public function getFlag( $flag ) {
765 return !!( $this->flags & $flag );
766 }
767
768 /**
769 * @param string $name Class field name
770 * @return mixed
771 * @deprecated Since 1.28
772 */
773 public function getProperty( $name ) {
774 return $this->$name;
775 }
776
777 public function getDomainID() {
778 return $this->currentDomain->getId();
779 }
780
781 final public function getWikiID() {
782 return $this->getDomainID();
783 }
784
785 /**
786 * Get information about an index into an object
787 * @param string $table Table name
788 * @param string $index Index name
789 * @param string $fname Calling function name
790 * @return mixed Database-specific index description class or false if the index does not exist
791 */
792 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
793
794 /**
795 * Wrapper for addslashes()
796 *
797 * @param string $s String to be slashed.
798 * @return string Slashed string.
799 */
800 abstract function strencode( $s );
801
802 /**
803 * Set a custom error handler for logging errors during database connection
804 */
805 protected function installErrorHandler() {
806 $this->phpError = false;
807 $this->htmlErrors = ini_set( 'html_errors', '0' );
808 set_error_handler( [ $this, 'connectionErrorLogger' ] );
809 }
810
811 /**
812 * Restore the previous error handler and return the last PHP error for this DB
813 *
814 * @return bool|string
815 */
816 protected function restoreErrorHandler() {
817 restore_error_handler();
818 if ( $this->htmlErrors !== false ) {
819 ini_set( 'html_errors', $this->htmlErrors );
820 }
821
822 return $this->getLastPHPError();
823 }
824
825 /**
826 * @return string|bool Last PHP error for this DB (typically connection errors)
827 */
828 protected function getLastPHPError() {
829 if ( $this->phpError ) {
830 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError );
831 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
832
833 return $error;
834 }
835
836 return false;
837 }
838
839 /**
840 * Error handler for logging errors during database connection
841 * This method should not be used outside of Database classes
842 *
843 * @param int $errno
844 * @param string $errstr
845 */
846 public function connectionErrorLogger( $errno, $errstr ) {
847 $this->phpError = $errstr;
848 }
849
850 /**
851 * Create a log context to pass to PSR-3 logger functions.
852 *
853 * @param array $extras Additional data to add to context
854 * @return array
855 */
856 protected function getLogContext( array $extras = [] ) {
857 return array_merge(
858 [
859 'db_server' => $this->server,
860 'db_name' => $this->dbName,
861 'db_user' => $this->user,
862 ],
863 $extras
864 );
865 }
866
867 final public function close() {
868 $exception = null; // error to throw after disconnecting
869
870 if ( $this->conn ) {
871 // Resolve any dangling transaction first
872 if ( $this->trxLevel ) {
873 // Meaningful transactions should ideally have been resolved by now
874 if ( $this->writesOrCallbacksPending() ) {
875 $this->queryLogger->warning(
876 __METHOD__ . ": writes or callbacks still pending.",
877 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
878 );
879 // Cannot let incomplete atomic sections be committed
880 if ( $this->trxAtomicLevels ) {
881 $levels = $this->flatAtomicSectionList();
882 $exception = new DBUnexpectedError(
883 $this,
884 __METHOD__ . ": atomic sections $levels are still open."
885 );
886 // Check if it is possible to properly commit and trigger callbacks
887 } elseif ( $this->trxEndCallbacksSuppressed ) {
888 $exception = new DBUnexpectedError(
889 $this,
890 __METHOD__ . ': callbacks are suppressed; cannot properly commit.'
891 );
892 }
893 }
894 // Commit or rollback the changes and run any callbacks as needed
895 if ( $this->trxStatus === self::STATUS_TRX_OK && !$exception ) {
896 $this->commit( __METHOD__, self::TRANSACTION_INTERNAL );
897 } else {
898 $this->rollback( __METHOD__, self::TRANSACTION_INTERNAL );
899 }
900 }
901 // Close the actual connection in the binding handle
902 $closed = $this->closeConnection();
903 $this->conn = false;
904 } else {
905 $closed = true; // already closed; nothing to do
906 }
907
908 $this->opened = false;
909
910 // Throw any unexpected errors after having disconnected
911 if ( $exception instanceof Exception ) {
912 throw $exception;
913 }
914
915 // Sanity check that no callbacks are dangling
916 if (
917 $this->trxIdleCallbacks || $this->trxPreCommitCallbacks || $this->trxEndCallbacks
918 ) {
919 throw new RuntimeException(
920 "Transaction callbacks are still pending:\n" .
921 implode( ', ', $this->pendingWriteAndCallbackCallers() )
922 );
923 }
924
925 return $closed;
926 }
927
928 /**
929 * Make sure isOpen() returns true as a sanity check
930 *
931 * @throws DBUnexpectedError
932 */
933 protected function assertOpen() {
934 if ( !$this->isOpen() ) {
935 throw new DBUnexpectedError( $this, "DB connection was already closed." );
936 }
937 }
938
939 /**
940 * Closes underlying database connection
941 * @since 1.20
942 * @return bool Whether connection was closed successfully
943 */
944 abstract protected function closeConnection();
945
946 /**
947 * @param string $error Fallback error message, used if none is given by DB
948 * @throws DBConnectionError
949 */
950 public function reportConnectionError( $error = 'Unknown error' ) {
951 $myError = $this->lastError();
952 if ( $myError ) {
953 $error = $myError;
954 }
955
956 # New method
957 throw new DBConnectionError( $this, $error );
958 }
959
960 /**
961 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
962 *
963 * This might return things, such as mysqli_result, that do not formally implement
964 * IResultWrapper, but nonetheless implement all of its methods correctly
965 *
966 * @param string $sql SQL query.
967 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
968 */
969 abstract protected function doQuery( $sql );
970
971 /**
972 * Determine whether a query writes to the DB.
973 * Should return true if unsure.
974 *
975 * @param string $sql
976 * @return bool
977 */
978 protected function isWriteQuery( $sql ) {
979 return !preg_match(
980 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
981 }
982
983 /**
984 * @param string $sql
985 * @return string|null
986 */
987 protected function getQueryVerb( $sql ) {
988 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
989 }
990
991 /**
992 * Determine whether a SQL statement is sensitive to isolation level.
993 * A SQL statement is considered transactable if its result could vary
994 * depending on the transaction isolation level. Operational commands
995 * such as 'SET' and 'SHOW' are not considered to be transactable.
996 *
997 * @param string $sql
998 * @return bool
999 */
1000 protected function isTransactableQuery( $sql ) {
1001 return !in_array(
1002 $this->getQueryVerb( $sql ),
1003 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
1004 true
1005 );
1006 }
1007
1008 /**
1009 * @param string $sql A SQL query
1010 * @return bool Whether $sql is SQL for TEMPORARY table operation
1011 */
1012 protected function registerTempTableOperation( $sql ) {
1013 if ( preg_match(
1014 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1015 $sql,
1016 $matches
1017 ) ) {
1018 $this->sessionTempTables[$matches[1]] = 1;
1019
1020 return true;
1021 } elseif ( preg_match(
1022 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1023 $sql,
1024 $matches
1025 ) ) {
1026 $isTemp = isset( $this->sessionTempTables[$matches[1]] );
1027 unset( $this->sessionTempTables[$matches[1]] );
1028
1029 return $isTemp;
1030 } elseif ( preg_match(
1031 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1032 $sql,
1033 $matches
1034 ) ) {
1035 return isset( $this->sessionTempTables[$matches[1]] );
1036 } elseif ( preg_match(
1037 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1038 $sql,
1039 $matches
1040 ) ) {
1041 return isset( $this->sessionTempTables[$matches[1]] );
1042 }
1043
1044 return false;
1045 }
1046
1047 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
1048 $this->assertTransactionStatus( $sql, $fname );
1049
1050 $priorWritesPending = $this->writesOrCallbacksPending();
1051 $this->lastQuery = $sql;
1052
1053 $isWrite = $this->isWriteQuery( $sql );
1054 if ( $isWrite ) {
1055 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1056 } else {
1057 $isNonTempWrite = false;
1058 }
1059
1060 if ( $isWrite ) {
1061 if ( $this->getLBInfo( 'replica' ) === true ) {
1062 throw new DBError(
1063 $this,
1064 'Write operations are not allowed on replica database connections.'
1065 );
1066 }
1067 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1068 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1069 $reason = $this->getReadOnlyReason();
1070 if ( $reason !== false ) {
1071 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1072 }
1073 # Set a flag indicating that writes have been done
1074 $this->lastWriteTime = microtime( true );
1075 }
1076
1077 # Add trace comment to the begin of the sql string, right after the operator.
1078 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1079 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1080
1081 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1082 if ( !$this->trxLevel && $this->getFlag( self::DBO_TRX )
1083 && $this->isTransactableQuery( $sql )
1084 ) {
1085 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
1086 $this->trxAutomatic = true;
1087 }
1088
1089 # Keep track of whether the transaction has write queries pending
1090 if ( $this->trxLevel && !$this->trxDoneWrites && $isWrite ) {
1091 $this->trxDoneWrites = true;
1092 $this->trxProfiler->transactionWritingIn(
1093 $this->server, $this->dbName, $this->trxShortId );
1094 }
1095
1096 if ( $this->getFlag( self::DBO_DEBUG ) ) {
1097 $this->queryLogger->debug( "{$this->dbName} {$commentedSql}" );
1098 }
1099
1100 # Avoid fatals if close() was called
1101 $this->assertOpen();
1102
1103 # Send the query to the server and fetch any corresponding errors
1104 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1105 $lastError = $this->lastError();
1106 $lastErrno = $this->lastErrno();
1107
1108 # Try reconnecting if the connection was lost
1109 if ( $ret === false && $this->wasConnectionLoss() ) {
1110 # Check if any meaningful session state was lost
1111 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1112 # Update session state tracking and try to restore the connection
1113 $reconnected = $this->replaceLostConnection( __METHOD__ );
1114 # Silently resend the query to the server if it is safe and possible
1115 if ( $reconnected && $recoverable ) {
1116 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1117 $lastError = $this->lastError();
1118 $lastErrno = $this->lastErrno();
1119
1120 if ( $ret === false && $this->wasConnectionLoss() ) {
1121 # Query probably causes disconnects; reconnect and do not re-run it
1122 $this->replaceLostConnection( __METHOD__ );
1123 }
1124 }
1125 }
1126
1127 if ( $ret === false ) {
1128 if ( $this->trxLevel && !$this->wasKnownStatementRollbackError() ) {
1129 # Either the query was aborted or all queries after BEGIN where aborted.
1130 if ( $this->explicitTrxActive() || $priorWritesPending ) {
1131 # In the first case, the only options going forward are (a) ROLLBACK, or
1132 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1133 # option is ROLLBACK, since the snapshots would have been released.
1134 if ( is_object( $tempIgnore ) ) {
1135 // Ugly hack to know that savepoints are in use for postgres
1136 // FIXME: remove this and make DatabasePostgres use ATOMIC_CANCELABLE
1137 } else {
1138 $this->trxStatus = self::STATUS_TRX_ERROR;
1139 $this->trxStatusCause =
1140 $this->makeQueryException( $lastError, $lastErrno, $sql, $fname );
1141 $tempIgnore = false; // cannot recover
1142 }
1143 } else {
1144 # Nothing prior was there to lose from the transaction
1145 $this->trxStatus = self::STATUS_TRX_OK;
1146 }
1147 }
1148
1149 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1150 }
1151
1152 return $this->resultObject( $ret );
1153 }
1154
1155 /**
1156 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1157 *
1158 * @param string $sql Original SQL query
1159 * @param string $commentedSql SQL query with debugging/trace comment
1160 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1161 * @param string $fname Name of the calling function
1162 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1163 * object for a successful read query, or false on failure
1164 */
1165 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1166 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1167 # generalizeSQL() will probably cut down the query to reasonable
1168 # logging size most of the time. The substr is really just a sanity check.
1169 if ( $isMaster ) {
1170 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1171 } else {
1172 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1173 }
1174
1175 # Include query transaction state
1176 $queryProf .= $this->trxShortId ? " [TRX#{$this->trxShortId}]" : "";
1177
1178 $startTime = microtime( true );
1179 if ( $this->profiler ) {
1180 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
1181 }
1182 $this->affectedRowCount = null;
1183 $ret = $this->doQuery( $commentedSql );
1184 $this->affectedRowCount = $this->affectedRows();
1185 if ( $this->profiler ) {
1186 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
1187 }
1188 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1189
1190 unset( $queryProfSection ); // profile out (if set)
1191
1192 if ( $ret !== false ) {
1193 $this->lastPing = $startTime;
1194 if ( $isWrite && $this->trxLevel ) {
1195 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1196 $this->trxWriteCallers[] = $fname;
1197 }
1198 }
1199
1200 if ( $sql === self::PING_QUERY ) {
1201 $this->rttEstimate = $queryRuntime;
1202 }
1203
1204 $this->trxProfiler->recordQueryCompletion(
1205 $queryProf, $startTime, $isWrite, $this->affectedRows()
1206 );
1207 $this->queryLogger->debug( $sql, [
1208 'method' => $fname,
1209 'master' => $isMaster,
1210 'runtime' => $queryRuntime,
1211 ] );
1212
1213 return $ret;
1214 }
1215
1216 /**
1217 * Update the estimated run-time of a query, not counting large row lock times
1218 *
1219 * LoadBalancer can be set to rollback transactions that will create huge replication
1220 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1221 * queries, like inserting a row can take a long time due to row locking. This method
1222 * uses some simple heuristics to discount those cases.
1223 *
1224 * @param string $sql A SQL write query
1225 * @param float $runtime Total runtime, including RTT
1226 * @param int $affected Affected row count
1227 */
1228 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1229 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1230 $indicativeOfReplicaRuntime = true;
1231 if ( $runtime > self::SLOW_WRITE_SEC ) {
1232 $verb = $this->getQueryVerb( $sql );
1233 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1234 if ( $verb === 'INSERT' ) {
1235 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1236 } elseif ( $verb === 'REPLACE' ) {
1237 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1238 }
1239 }
1240
1241 $this->trxWriteDuration += $runtime;
1242 $this->trxWriteQueryCount += 1;
1243 $this->trxWriteAffectedRows += $affected;
1244 if ( $indicativeOfReplicaRuntime ) {
1245 $this->trxWriteAdjDuration += $runtime;
1246 $this->trxWriteAdjQueryCount += 1;
1247 }
1248 }
1249
1250 /**
1251 * @param string $sql
1252 * @param string $fname
1253 * @throws DBTransactionStateError
1254 */
1255 private function assertTransactionStatus( $sql, $fname ) {
1256 if (
1257 $this->trxStatus < self::STATUS_TRX_OK &&
1258 $this->getQueryVerb( $sql ) !== 'ROLLBACK' // transaction/savepoint
1259 ) {
1260 throw new DBTransactionStateError(
1261 $this,
1262 "Cannot execute query from $fname while transaction status is ERROR. ",
1263 [],
1264 $this->trxStatusCause
1265 );
1266 }
1267 }
1268
1269 /**
1270 * Determine whether or not it is safe to retry queries after a database
1271 * connection is lost
1272 *
1273 * @param string $sql SQL query
1274 * @param bool $priorWritesPending Whether there is a transaction open with
1275 * possible write queries or transaction pre-commit/idle callbacks
1276 * waiting on it to finish.
1277 * @return bool True if it is safe to retry the query, false otherwise
1278 */
1279 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1280 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1281 # Dropped connections also mean that named locks are automatically released.
1282 # Only allow error suppression in autocommit mode or when the lost transaction
1283 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1284 if ( $this->namedLocksHeld ) {
1285 return false; // possible critical section violation
1286 } elseif ( $this->sessionTempTables ) {
1287 return false; // tables might be queried latter
1288 } elseif ( $sql === 'COMMIT' ) {
1289 return !$priorWritesPending; // nothing written anyway? (T127428)
1290 } elseif ( $sql === 'ROLLBACK' ) {
1291 return true; // transaction lost...which is also what was requested :)
1292 } elseif ( $this->explicitTrxActive() ) {
1293 return false; // don't drop atomocity and explicit snapshots
1294 } elseif ( $priorWritesPending ) {
1295 return false; // prior writes lost from implicit transaction
1296 }
1297
1298 return true;
1299 }
1300
1301 /**
1302 * Clean things up after session (and thus transaction) loss
1303 */
1304 private function handleSessionLoss() {
1305 // Clean up tracking of session-level things...
1306 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1307 // https://www.postgresql.org/docs/9.1/static/sql-createtable.html (ignoring ON COMMIT)
1308 $this->sessionTempTables = [];
1309 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1310 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1311 $this->namedLocksHeld = [];
1312 // Session loss implies transaction loss
1313 $this->handleTransactionLoss();
1314 }
1315
1316 /**
1317 * Clean things up after transaction loss
1318 */
1319 private function handleTransactionLoss() {
1320 $this->trxLevel = 0;
1321 $this->trxAtomicCounter = 0;
1322 $this->trxIdleCallbacks = []; // T67263; transaction already lost
1323 $this->trxPreCommitCallbacks = []; // T67263; transaction already lost
1324 try {
1325 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1326 // If callback suppression is set then the array will remain unhandled.
1327 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1328 } catch ( Exception $ex ) {
1329 // Already logged; move on...
1330 }
1331 try {
1332 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1333 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1334 } catch ( Exception $ex ) {
1335 // Already logged; move on...
1336 }
1337 }
1338
1339 /**
1340 * Checks whether the cause of the error is detected to be a timeout.
1341 *
1342 * It returns false by default, and not all engines support detecting this yet.
1343 * If this returns false, it will be treated as a generic query error.
1344 *
1345 * @param string $error Error text
1346 * @param int $errno Error number
1347 * @return bool
1348 */
1349 protected function wasQueryTimeout( $error, $errno ) {
1350 return false;
1351 }
1352
1353 /**
1354 * Report a query error. Log the error, and if neither the object ignore
1355 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1356 *
1357 * @param string $error
1358 * @param int $errno
1359 * @param string $sql
1360 * @param string $fname
1361 * @param bool $tempIgnore
1362 * @throws DBQueryError
1363 */
1364 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1365 if ( $tempIgnore ) {
1366 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1367 } else {
1368 $exception = $this->makeQueryException( $error, $errno, $sql, $fname );
1369
1370 throw $exception;
1371 }
1372 }
1373
1374 /**
1375 * @param string $error
1376 * @param string|int $errno
1377 * @param string $sql
1378 * @param string $fname
1379 * @return DBError
1380 */
1381 private function makeQueryException( $error, $errno, $sql, $fname ) {
1382 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1383 $this->queryLogger->error(
1384 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1385 $this->getLogContext( [
1386 'method' => __METHOD__,
1387 'errno' => $errno,
1388 'error' => $error,
1389 'sql1line' => $sql1line,
1390 'fname' => $fname,
1391 ] )
1392 );
1393 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1394 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1395 if ( $wasQueryTimeout ) {
1396 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1397 } else {
1398 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1399 }
1400
1401 return $e;
1402 }
1403
1404 public function freeResult( $res ) {
1405 }
1406
1407 public function selectField(
1408 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1409 ) {
1410 if ( $var === '*' ) { // sanity
1411 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1412 }
1413
1414 if ( !is_array( $options ) ) {
1415 $options = [ $options ];
1416 }
1417
1418 $options['LIMIT'] = 1;
1419
1420 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1421 if ( $res === false || !$this->numRows( $res ) ) {
1422 return false;
1423 }
1424
1425 $row = $this->fetchRow( $res );
1426
1427 if ( $row !== false ) {
1428 return reset( $row );
1429 } else {
1430 return false;
1431 }
1432 }
1433
1434 public function selectFieldValues(
1435 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1436 ) {
1437 if ( $var === '*' ) { // sanity
1438 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1439 } elseif ( !is_string( $var ) ) { // sanity
1440 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1441 }
1442
1443 if ( !is_array( $options ) ) {
1444 $options = [ $options ];
1445 }
1446
1447 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1448 if ( $res === false ) {
1449 return false;
1450 }
1451
1452 $values = [];
1453 foreach ( $res as $row ) {
1454 $values[] = $row->$var;
1455 }
1456
1457 return $values;
1458 }
1459
1460 /**
1461 * Returns an optional USE INDEX clause to go after the table, and a
1462 * string to go at the end of the query.
1463 *
1464 * @param array $options Associative array of options to be turned into
1465 * an SQL query, valid keys are listed in the function.
1466 * @return array
1467 * @see Database::select()
1468 */
1469 protected function makeSelectOptions( $options ) {
1470 $preLimitTail = $postLimitTail = '';
1471 $startOpts = '';
1472
1473 $noKeyOptions = [];
1474
1475 foreach ( $options as $key => $option ) {
1476 if ( is_numeric( $key ) ) {
1477 $noKeyOptions[$option] = true;
1478 }
1479 }
1480
1481 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1482
1483 $preLimitTail .= $this->makeOrderBy( $options );
1484
1485 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1486 $postLimitTail .= ' FOR UPDATE';
1487 }
1488
1489 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1490 $postLimitTail .= ' LOCK IN SHARE MODE';
1491 }
1492
1493 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1494 $startOpts .= 'DISTINCT';
1495 }
1496
1497 # Various MySQL extensions
1498 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1499 $startOpts .= ' /*! STRAIGHT_JOIN */';
1500 }
1501
1502 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1503 $startOpts .= ' HIGH_PRIORITY';
1504 }
1505
1506 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1507 $startOpts .= ' SQL_BIG_RESULT';
1508 }
1509
1510 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1511 $startOpts .= ' SQL_BUFFER_RESULT';
1512 }
1513
1514 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1515 $startOpts .= ' SQL_SMALL_RESULT';
1516 }
1517
1518 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1519 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1520 }
1521
1522 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1523 $startOpts .= ' SQL_CACHE';
1524 }
1525
1526 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1527 $startOpts .= ' SQL_NO_CACHE';
1528 }
1529
1530 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1531 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1532 } else {
1533 $useIndex = '';
1534 }
1535 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1536 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1537 } else {
1538 $ignoreIndex = '';
1539 }
1540
1541 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1542 }
1543
1544 /**
1545 * Returns an optional GROUP BY with an optional HAVING
1546 *
1547 * @param array $options Associative array of options
1548 * @return string
1549 * @see Database::select()
1550 * @since 1.21
1551 */
1552 protected function makeGroupByWithHaving( $options ) {
1553 $sql = '';
1554 if ( isset( $options['GROUP BY'] ) ) {
1555 $gb = is_array( $options['GROUP BY'] )
1556 ? implode( ',', $options['GROUP BY'] )
1557 : $options['GROUP BY'];
1558 $sql .= ' GROUP BY ' . $gb;
1559 }
1560 if ( isset( $options['HAVING'] ) ) {
1561 $having = is_array( $options['HAVING'] )
1562 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1563 : $options['HAVING'];
1564 $sql .= ' HAVING ' . $having;
1565 }
1566
1567 return $sql;
1568 }
1569
1570 /**
1571 * Returns an optional ORDER BY
1572 *
1573 * @param array $options Associative array of options
1574 * @return string
1575 * @see Database::select()
1576 * @since 1.21
1577 */
1578 protected function makeOrderBy( $options ) {
1579 if ( isset( $options['ORDER BY'] ) ) {
1580 $ob = is_array( $options['ORDER BY'] )
1581 ? implode( ',', $options['ORDER BY'] )
1582 : $options['ORDER BY'];
1583
1584 return ' ORDER BY ' . $ob;
1585 }
1586
1587 return '';
1588 }
1589
1590 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1591 $options = [], $join_conds = [] ) {
1592 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1593
1594 return $this->query( $sql, $fname );
1595 }
1596
1597 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1598 $options = [], $join_conds = []
1599 ) {
1600 if ( is_array( $vars ) ) {
1601 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1602 }
1603
1604 $options = (array)$options;
1605 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1606 ? $options['USE INDEX']
1607 : [];
1608 $ignoreIndexes = (
1609 isset( $options['IGNORE INDEX'] ) &&
1610 is_array( $options['IGNORE INDEX'] )
1611 )
1612 ? $options['IGNORE INDEX']
1613 : [];
1614
1615 if ( is_array( $table ) ) {
1616 $from = ' FROM ' .
1617 $this->tableNamesWithIndexClauseOrJOIN(
1618 $table, $useIndexes, $ignoreIndexes, $join_conds );
1619 } elseif ( $table != '' ) {
1620 $from = ' FROM ' .
1621 $this->tableNamesWithIndexClauseOrJOIN(
1622 [ $table ], $useIndexes, $ignoreIndexes, [] );
1623 } else {
1624 $from = '';
1625 }
1626
1627 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1628 $this->makeSelectOptions( $options );
1629
1630 if ( is_array( $conds ) ) {
1631 $conds = $this->makeList( $conds, self::LIST_AND );
1632 }
1633
1634 if ( $conds === null || $conds === false ) {
1635 $this->queryLogger->warning(
1636 __METHOD__
1637 . ' called from '
1638 . $fname
1639 . ' with incorrect parameters: $conds must be a string or an array'
1640 );
1641 $conds = '';
1642 }
1643
1644 if ( $conds === '' ) {
1645 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1646 } elseif ( is_string( $conds ) ) {
1647 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1648 "WHERE $conds $preLimitTail";
1649 } else {
1650 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1651 }
1652
1653 if ( isset( $options['LIMIT'] ) ) {
1654 $sql = $this->limitResult( $sql, $options['LIMIT'],
1655 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1656 }
1657 $sql = "$sql $postLimitTail";
1658
1659 if ( isset( $options['EXPLAIN'] ) ) {
1660 $sql = 'EXPLAIN ' . $sql;
1661 }
1662
1663 return $sql;
1664 }
1665
1666 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1667 $options = [], $join_conds = []
1668 ) {
1669 $options = (array)$options;
1670 $options['LIMIT'] = 1;
1671 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1672
1673 if ( $res === false ) {
1674 return false;
1675 }
1676
1677 if ( !$this->numRows( $res ) ) {
1678 return false;
1679 }
1680
1681 $obj = $this->fetchObject( $res );
1682
1683 return $obj;
1684 }
1685
1686 public function estimateRowCount(
1687 $table, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1688 ) {
1689 $conds = $this->normalizeConditions( $conds, $fname );
1690 $column = $this->extractSingleFieldFromList( $var );
1691 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1692 $conds[] = "$column IS NOT NULL";
1693 }
1694
1695 $res = $this->select(
1696 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1697 );
1698 $row = $res ? $this->fetchRow( $res ) : [];
1699
1700 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1701 }
1702
1703 public function selectRowCount(
1704 $tables, $var = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1705 ) {
1706 $conds = $this->normalizeConditions( $conds, $fname );
1707 $column = $this->extractSingleFieldFromList( $var );
1708 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1709 $conds[] = "$column IS NOT NULL";
1710 }
1711
1712 $res = $this->select(
1713 [
1714 'tmp_count' => $this->buildSelectSubquery(
1715 $tables,
1716 '1',
1717 $conds,
1718 $fname,
1719 $options,
1720 $join_conds
1721 )
1722 ],
1723 [ 'rowcount' => 'COUNT(*)' ],
1724 [],
1725 $fname
1726 );
1727 $row = $res ? $this->fetchRow( $res ) : [];
1728
1729 return isset( $row['rowcount'] ) ? (int)$row['rowcount'] : 0;
1730 }
1731
1732 /**
1733 * @param array|string $conds
1734 * @param string $fname
1735 * @return array
1736 */
1737 final protected function normalizeConditions( $conds, $fname ) {
1738 if ( $conds === null || $conds === false ) {
1739 $this->queryLogger->warning(
1740 __METHOD__
1741 . ' called from '
1742 . $fname
1743 . ' with incorrect parameters: $conds must be a string or an array'
1744 );
1745 $conds = '';
1746 }
1747
1748 if ( !is_array( $conds ) ) {
1749 $conds = ( $conds === '' ) ? [] : [ $conds ];
1750 }
1751
1752 return $conds;
1753 }
1754
1755 /**
1756 * @param array|string $var Field parameter in the style of select()
1757 * @return string|null Column name or null; ignores aliases
1758 * @throws DBUnexpectedError Errors out if multiple columns are given
1759 */
1760 final protected function extractSingleFieldFromList( $var ) {
1761 if ( is_array( $var ) ) {
1762 if ( !$var ) {
1763 $column = null;
1764 } elseif ( count( $var ) == 1 ) {
1765 $column = isset( $var[0] ) ? $var[0] : reset( $var );
1766 } else {
1767 throw new DBUnexpectedError( $this, __METHOD__ . ': got multiple columns.' );
1768 }
1769 } else {
1770 $column = $var;
1771 }
1772
1773 return $column;
1774 }
1775
1776 /**
1777 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1778 * It's only slightly flawed. Don't use for anything important.
1779 *
1780 * @param string $sql A SQL Query
1781 *
1782 * @return string
1783 */
1784 protected static function generalizeSQL( $sql ) {
1785 # This does the same as the regexp below would do, but in such a way
1786 # as to avoid crashing php on some large strings.
1787 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1788
1789 $sql = str_replace( "\\\\", '', $sql );
1790 $sql = str_replace( "\\'", '', $sql );
1791 $sql = str_replace( "\\\"", '', $sql );
1792 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1793 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1794
1795 # All newlines, tabs, etc replaced by single space
1796 $sql = preg_replace( '/\s+/', ' ', $sql );
1797
1798 # All numbers => N,
1799 # except the ones surrounded by characters, e.g. l10n
1800 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1801 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1802
1803 return $sql;
1804 }
1805
1806 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1807 $info = $this->fieldInfo( $table, $field );
1808
1809 return (bool)$info;
1810 }
1811
1812 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1813 if ( !$this->tableExists( $table ) ) {
1814 return null;
1815 }
1816
1817 $info = $this->indexInfo( $table, $index, $fname );
1818 if ( is_null( $info ) ) {
1819 return null;
1820 } else {
1821 return $info !== false;
1822 }
1823 }
1824
1825 public function tableExists( $table, $fname = __METHOD__ ) {
1826 $tableRaw = $this->tableName( $table, 'raw' );
1827 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
1828 return true; // already known to exist
1829 }
1830
1831 $table = $this->tableName( $table );
1832 $ignoreErrors = true;
1833 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1834
1835 return (bool)$res;
1836 }
1837
1838 public function indexUnique( $table, $index ) {
1839 $indexInfo = $this->indexInfo( $table, $index );
1840
1841 if ( !$indexInfo ) {
1842 return null;
1843 }
1844
1845 return !$indexInfo[0]->Non_unique;
1846 }
1847
1848 /**
1849 * Helper for Database::insert().
1850 *
1851 * @param array $options
1852 * @return string
1853 */
1854 protected function makeInsertOptions( $options ) {
1855 return implode( ' ', $options );
1856 }
1857
1858 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1859 # No rows to insert, easy just return now
1860 if ( !count( $a ) ) {
1861 return true;
1862 }
1863
1864 $table = $this->tableName( $table );
1865
1866 if ( !is_array( $options ) ) {
1867 $options = [ $options ];
1868 }
1869
1870 $fh = null;
1871 if ( isset( $options['fileHandle'] ) ) {
1872 $fh = $options['fileHandle'];
1873 }
1874 $options = $this->makeInsertOptions( $options );
1875
1876 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1877 $multi = true;
1878 $keys = array_keys( $a[0] );
1879 } else {
1880 $multi = false;
1881 $keys = array_keys( $a );
1882 }
1883
1884 $sql = 'INSERT ' . $options .
1885 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1886
1887 if ( $multi ) {
1888 $first = true;
1889 foreach ( $a as $row ) {
1890 if ( $first ) {
1891 $first = false;
1892 } else {
1893 $sql .= ',';
1894 }
1895 $sql .= '(' . $this->makeList( $row ) . ')';
1896 }
1897 } else {
1898 $sql .= '(' . $this->makeList( $a ) . ')';
1899 }
1900
1901 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1902 return false;
1903 } elseif ( $fh !== null ) {
1904 return true;
1905 }
1906
1907 return (bool)$this->query( $sql, $fname );
1908 }
1909
1910 /**
1911 * Make UPDATE options array for Database::makeUpdateOptions
1912 *
1913 * @param array $options
1914 * @return array
1915 */
1916 protected function makeUpdateOptionsArray( $options ) {
1917 if ( !is_array( $options ) ) {
1918 $options = [ $options ];
1919 }
1920
1921 $opts = [];
1922
1923 if ( in_array( 'IGNORE', $options ) ) {
1924 $opts[] = 'IGNORE';
1925 }
1926
1927 return $opts;
1928 }
1929
1930 /**
1931 * Make UPDATE options for the Database::update function
1932 *
1933 * @param array $options The options passed to Database::update
1934 * @return string
1935 */
1936 protected function makeUpdateOptions( $options ) {
1937 $opts = $this->makeUpdateOptionsArray( $options );
1938
1939 return implode( ' ', $opts );
1940 }
1941
1942 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1943 $table = $this->tableName( $table );
1944 $opts = $this->makeUpdateOptions( $options );
1945 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1946
1947 if ( $conds !== [] && $conds !== '*' ) {
1948 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1949 }
1950
1951 return (bool)$this->query( $sql, $fname );
1952 }
1953
1954 public function makeList( $a, $mode = self::LIST_COMMA ) {
1955 if ( !is_array( $a ) ) {
1956 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1957 }
1958
1959 $first = true;
1960 $list = '';
1961
1962 foreach ( $a as $field => $value ) {
1963 if ( !$first ) {
1964 if ( $mode == self::LIST_AND ) {
1965 $list .= ' AND ';
1966 } elseif ( $mode == self::LIST_OR ) {
1967 $list .= ' OR ';
1968 } else {
1969 $list .= ',';
1970 }
1971 } else {
1972 $first = false;
1973 }
1974
1975 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1976 $list .= "($value)";
1977 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1978 $list .= "$value";
1979 } elseif (
1980 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1981 ) {
1982 // Remove null from array to be handled separately if found
1983 $includeNull = false;
1984 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1985 $includeNull = true;
1986 unset( $value[$nullKey] );
1987 }
1988 if ( count( $value ) == 0 && !$includeNull ) {
1989 throw new InvalidArgumentException(
1990 __METHOD__ . ": empty input for field $field" );
1991 } elseif ( count( $value ) == 0 ) {
1992 // only check if $field is null
1993 $list .= "$field IS NULL";
1994 } else {
1995 // IN clause contains at least one valid element
1996 if ( $includeNull ) {
1997 // Group subconditions to ensure correct precedence
1998 $list .= '(';
1999 }
2000 if ( count( $value ) == 1 ) {
2001 // Special-case single values, as IN isn't terribly efficient
2002 // Don't necessarily assume the single key is 0; we don't
2003 // enforce linear numeric ordering on other arrays here.
2004 $value = array_values( $value )[0];
2005 $list .= $field . " = " . $this->addQuotes( $value );
2006 } else {
2007 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2008 }
2009 // if null present in array, append IS NULL
2010 if ( $includeNull ) {
2011 $list .= " OR $field IS NULL)";
2012 }
2013 }
2014 } elseif ( $value === null ) {
2015 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
2016 $list .= "$field IS ";
2017 } elseif ( $mode == self::LIST_SET ) {
2018 $list .= "$field = ";
2019 }
2020 $list .= 'NULL';
2021 } else {
2022 if (
2023 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
2024 ) {
2025 $list .= "$field = ";
2026 }
2027 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
2028 }
2029 }
2030
2031 return $list;
2032 }
2033
2034 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2035 $conds = [];
2036
2037 foreach ( $data as $base => $sub ) {
2038 if ( count( $sub ) ) {
2039 $conds[] = $this->makeList(
2040 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2041 self::LIST_AND );
2042 }
2043 }
2044
2045 if ( $conds ) {
2046 return $this->makeList( $conds, self::LIST_OR );
2047 } else {
2048 // Nothing to search for...
2049 return false;
2050 }
2051 }
2052
2053 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2054 return $valuename;
2055 }
2056
2057 public function bitNot( $field ) {
2058 return "(~$field)";
2059 }
2060
2061 public function bitAnd( $fieldLeft, $fieldRight ) {
2062 return "($fieldLeft & $fieldRight)";
2063 }
2064
2065 public function bitOr( $fieldLeft, $fieldRight ) {
2066 return "($fieldLeft | $fieldRight)";
2067 }
2068
2069 public function buildConcat( $stringList ) {
2070 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2071 }
2072
2073 public function buildGroupConcatField(
2074 $delim, $table, $field, $conds = '', $join_conds = []
2075 ) {
2076 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2077
2078 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2079 }
2080
2081 public function buildSubstring( $input, $startPosition, $length = null ) {
2082 $this->assertBuildSubstringParams( $startPosition, $length );
2083 $functionBody = "$input FROM $startPosition";
2084 if ( $length !== null ) {
2085 $functionBody .= " FOR $length";
2086 }
2087 return 'SUBSTRING(' . $functionBody . ')';
2088 }
2089
2090 /**
2091 * Check type and bounds for parameters to self::buildSubstring()
2092 *
2093 * All supported databases have substring functions that behave the same for
2094 * positive $startPosition and non-negative $length, but behaviors differ when
2095 * given 0 or negative $startPosition or negative $length. The simplest
2096 * solution to that is to just forbid those values.
2097 *
2098 * @param int $startPosition
2099 * @param int|null $length
2100 * @since 1.31
2101 */
2102 protected function assertBuildSubstringParams( $startPosition, $length ) {
2103 if ( !is_int( $startPosition ) || $startPosition <= 0 ) {
2104 throw new InvalidArgumentException(
2105 '$startPosition must be a positive integer'
2106 );
2107 }
2108 if ( !( is_int( $length ) && $length >= 0 || $length === null ) ) {
2109 throw new InvalidArgumentException(
2110 '$length must be null or an integer greater than or equal to 0'
2111 );
2112 }
2113 }
2114
2115 public function buildStringCast( $field ) {
2116 return $field;
2117 }
2118
2119 public function buildIntegerCast( $field ) {
2120 return 'CAST( ' . $field . ' AS INTEGER )';
2121 }
2122
2123 public function buildSelectSubquery(
2124 $table, $vars, $conds = '', $fname = __METHOD__,
2125 $options = [], $join_conds = []
2126 ) {
2127 return new Subquery(
2128 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2129 );
2130 }
2131
2132 public function databasesAreIndependent() {
2133 return false;
2134 }
2135
2136 public function selectDB( $db ) {
2137 # Stub. Shouldn't cause serious problems if it's not overridden, but
2138 # if your database engine supports a concept similar to MySQL's
2139 # databases you may as well.
2140 $this->dbName = $db;
2141
2142 return true;
2143 }
2144
2145 public function getDBname() {
2146 return $this->dbName;
2147 }
2148
2149 public function getServer() {
2150 return $this->server;
2151 }
2152
2153 public function tableName( $name, $format = 'quoted' ) {
2154 if ( $name instanceof Subquery ) {
2155 throw new DBUnexpectedError(
2156 $this,
2157 __METHOD__ . ': got Subquery instance when expecting a string.'
2158 );
2159 }
2160
2161 # Skip the entire process when we have a string quoted on both ends.
2162 # Note that we check the end so that we will still quote any use of
2163 # use of `database`.table. But won't break things if someone wants
2164 # to query a database table with a dot in the name.
2165 if ( $this->isQuotedIdentifier( $name ) ) {
2166 return $name;
2167 }
2168
2169 # Lets test for any bits of text that should never show up in a table
2170 # name. Basically anything like JOIN or ON which are actually part of
2171 # SQL queries, but may end up inside of the table value to combine
2172 # sql. Such as how the API is doing.
2173 # Note that we use a whitespace test rather than a \b test to avoid
2174 # any remote case where a word like on may be inside of a table name
2175 # surrounded by symbols which may be considered word breaks.
2176 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2177 $this->queryLogger->warning(
2178 __METHOD__ . ": use of subqueries is not supported this way.",
2179 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2180 );
2181
2182 return $name;
2183 }
2184
2185 # Split database and table into proper variables.
2186 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2187
2188 # Quote $table and apply the prefix if not quoted.
2189 # $tableName might be empty if this is called from Database::replaceVars()
2190 $tableName = "{$prefix}{$table}";
2191 if ( $format === 'quoted'
2192 && !$this->isQuotedIdentifier( $tableName )
2193 && $tableName !== ''
2194 ) {
2195 $tableName = $this->addIdentifierQuotes( $tableName );
2196 }
2197
2198 # Quote $schema and $database and merge them with the table name if needed
2199 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2200 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2201
2202 return $tableName;
2203 }
2204
2205 /**
2206 * Get the table components needed for a query given the currently selected database
2207 *
2208 * @param string $name Table name in the form of db.schema.table, db.table, or table
2209 * @return array (DB name or "" for default, schema name, table prefix, table name)
2210 */
2211 protected function qualifiedTableComponents( $name ) {
2212 # We reverse the explode so that database.table and table both output the correct table.
2213 $dbDetails = explode( '.', $name, 3 );
2214 if ( count( $dbDetails ) == 3 ) {
2215 list( $database, $schema, $table ) = $dbDetails;
2216 # We don't want any prefix added in this case
2217 $prefix = '';
2218 } elseif ( count( $dbDetails ) == 2 ) {
2219 list( $database, $table ) = $dbDetails;
2220 # We don't want any prefix added in this case
2221 $prefix = '';
2222 # In dbs that support it, $database may actually be the schema
2223 # but that doesn't affect any of the functionality here
2224 $schema = '';
2225 } else {
2226 list( $table ) = $dbDetails;
2227 if ( isset( $this->tableAliases[$table] ) ) {
2228 $database = $this->tableAliases[$table]['dbname'];
2229 $schema = is_string( $this->tableAliases[$table]['schema'] )
2230 ? $this->tableAliases[$table]['schema']
2231 : $this->schema;
2232 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
2233 ? $this->tableAliases[$table]['prefix']
2234 : $this->tablePrefix;
2235 } else {
2236 $database = '';
2237 $schema = $this->schema; # Default schema
2238 $prefix = $this->tablePrefix; # Default prefix
2239 }
2240 }
2241
2242 return [ $database, $schema, $prefix, $table ];
2243 }
2244
2245 /**
2246 * @param string|null $namespace Database or schema
2247 * @param string $relation Name of table, view, sequence, etc...
2248 * @param string $format One of (raw, quoted)
2249 * @return string Relation name with quoted and merged $namespace as needed
2250 */
2251 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2252 if ( strlen( $namespace ) ) {
2253 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2254 $namespace = $this->addIdentifierQuotes( $namespace );
2255 }
2256 $relation = $namespace . '.' . $relation;
2257 }
2258
2259 return $relation;
2260 }
2261
2262 public function tableNames() {
2263 $inArray = func_get_args();
2264 $retVal = [];
2265
2266 foreach ( $inArray as $name ) {
2267 $retVal[$name] = $this->tableName( $name );
2268 }
2269
2270 return $retVal;
2271 }
2272
2273 public function tableNamesN() {
2274 $inArray = func_get_args();
2275 $retVal = [];
2276
2277 foreach ( $inArray as $name ) {
2278 $retVal[] = $this->tableName( $name );
2279 }
2280
2281 return $retVal;
2282 }
2283
2284 /**
2285 * Get an aliased table name
2286 *
2287 * This returns strings like "tableName AS newTableName" for aliased tables
2288 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2289 *
2290 * @see Database::tableName()
2291 * @param string|Subquery $table Table name or object with a 'sql' field
2292 * @param string|bool $alias Table alias (optional)
2293 * @return string SQL name for aliased table. Will not alias a table to its own name
2294 */
2295 protected function tableNameWithAlias( $table, $alias = false ) {
2296 if ( is_string( $table ) ) {
2297 $quotedTable = $this->tableName( $table );
2298 } elseif ( $table instanceof Subquery ) {
2299 $quotedTable = (string)$table;
2300 } else {
2301 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2302 }
2303
2304 if ( !strlen( $alias ) || $alias === $table ) {
2305 if ( $table instanceof Subquery ) {
2306 throw new InvalidArgumentException( "Subquery table missing alias." );
2307 }
2308
2309 return $quotedTable;
2310 } else {
2311 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2312 }
2313 }
2314
2315 /**
2316 * Gets an array of aliased table names
2317 *
2318 * @param array $tables [ [alias] => table ]
2319 * @return string[] See tableNameWithAlias()
2320 */
2321 protected function tableNamesWithAlias( $tables ) {
2322 $retval = [];
2323 foreach ( $tables as $alias => $table ) {
2324 if ( is_numeric( $alias ) ) {
2325 $alias = $table;
2326 }
2327 $retval[] = $this->tableNameWithAlias( $table, $alias );
2328 }
2329
2330 return $retval;
2331 }
2332
2333 /**
2334 * Get an aliased field name
2335 * e.g. fieldName AS newFieldName
2336 *
2337 * @param string $name Field name
2338 * @param string|bool $alias Alias (optional)
2339 * @return string SQL name for aliased field. Will not alias a field to its own name
2340 */
2341 protected function fieldNameWithAlias( $name, $alias = false ) {
2342 if ( !$alias || (string)$alias === (string)$name ) {
2343 return $name;
2344 } else {
2345 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2346 }
2347 }
2348
2349 /**
2350 * Gets an array of aliased field names
2351 *
2352 * @param array $fields [ [alias] => field ]
2353 * @return string[] See fieldNameWithAlias()
2354 */
2355 protected function fieldNamesWithAlias( $fields ) {
2356 $retval = [];
2357 foreach ( $fields as $alias => $field ) {
2358 if ( is_numeric( $alias ) ) {
2359 $alias = $field;
2360 }
2361 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2362 }
2363
2364 return $retval;
2365 }
2366
2367 /**
2368 * Get the aliased table name clause for a FROM clause
2369 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2370 *
2371 * @param array $tables ( [alias] => table )
2372 * @param array $use_index Same as for select()
2373 * @param array $ignore_index Same as for select()
2374 * @param array $join_conds Same as for select()
2375 * @return string
2376 */
2377 protected function tableNamesWithIndexClauseOrJOIN(
2378 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2379 ) {
2380 $ret = [];
2381 $retJOIN = [];
2382 $use_index = (array)$use_index;
2383 $ignore_index = (array)$ignore_index;
2384 $join_conds = (array)$join_conds;
2385
2386 foreach ( $tables as $alias => $table ) {
2387 if ( !is_string( $alias ) ) {
2388 // No alias? Set it equal to the table name
2389 $alias = $table;
2390 }
2391
2392 if ( is_array( $table ) ) {
2393 // A parenthesized group
2394 if ( count( $table ) > 1 ) {
2395 $joinedTable = '(' .
2396 $this->tableNamesWithIndexClauseOrJOIN(
2397 $table, $use_index, $ignore_index, $join_conds ) . ')';
2398 } else {
2399 // Degenerate case
2400 $innerTable = reset( $table );
2401 $innerAlias = key( $table );
2402 $joinedTable = $this->tableNameWithAlias(
2403 $innerTable,
2404 is_string( $innerAlias ) ? $innerAlias : $innerTable
2405 );
2406 }
2407 } else {
2408 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2409 }
2410
2411 // Is there a JOIN clause for this table?
2412 if ( isset( $join_conds[$alias] ) ) {
2413 list( $joinType, $conds ) = $join_conds[$alias];
2414 $tableClause = $joinType;
2415 $tableClause .= ' ' . $joinedTable;
2416 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2417 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2418 if ( $use != '' ) {
2419 $tableClause .= ' ' . $use;
2420 }
2421 }
2422 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2423 $ignore = $this->ignoreIndexClause(
2424 implode( ',', (array)$ignore_index[$alias] ) );
2425 if ( $ignore != '' ) {
2426 $tableClause .= ' ' . $ignore;
2427 }
2428 }
2429 $on = $this->makeList( (array)$conds, self::LIST_AND );
2430 if ( $on != '' ) {
2431 $tableClause .= ' ON (' . $on . ')';
2432 }
2433
2434 $retJOIN[] = $tableClause;
2435 } elseif ( isset( $use_index[$alias] ) ) {
2436 // Is there an INDEX clause for this table?
2437 $tableClause = $joinedTable;
2438 $tableClause .= ' ' . $this->useIndexClause(
2439 implode( ',', (array)$use_index[$alias] )
2440 );
2441
2442 $ret[] = $tableClause;
2443 } elseif ( isset( $ignore_index[$alias] ) ) {
2444 // Is there an INDEX clause for this table?
2445 $tableClause = $joinedTable;
2446 $tableClause .= ' ' . $this->ignoreIndexClause(
2447 implode( ',', (array)$ignore_index[$alias] )
2448 );
2449
2450 $ret[] = $tableClause;
2451 } else {
2452 $tableClause = $joinedTable;
2453
2454 $ret[] = $tableClause;
2455 }
2456 }
2457
2458 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2459 $implicitJoins = $ret ? implode( ',', $ret ) : "";
2460 $explicitJoins = $retJOIN ? implode( ' ', $retJOIN ) : "";
2461
2462 // Compile our final table clause
2463 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2464 }
2465
2466 /**
2467 * Allows for index remapping in queries where this is not consistent across DBMS
2468 *
2469 * @param string $index
2470 * @return string
2471 */
2472 protected function indexName( $index ) {
2473 return isset( $this->indexAliases[$index] )
2474 ? $this->indexAliases[$index]
2475 : $index;
2476 }
2477
2478 public function addQuotes( $s ) {
2479 if ( $s instanceof Blob ) {
2480 $s = $s->fetch();
2481 }
2482 if ( $s === null ) {
2483 return 'NULL';
2484 } elseif ( is_bool( $s ) ) {
2485 return (int)$s;
2486 } else {
2487 # This will also quote numeric values. This should be harmless,
2488 # and protects against weird problems that occur when they really
2489 # _are_ strings such as article titles and string->number->string
2490 # conversion is not 1:1.
2491 return "'" . $this->strencode( $s ) . "'";
2492 }
2493 }
2494
2495 /**
2496 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2497 * MySQL uses `backticks` while basically everything else uses double quotes.
2498 * Since MySQL is the odd one out here the double quotes are our generic
2499 * and we implement backticks in DatabaseMysqlBase.
2500 *
2501 * @param string $s
2502 * @return string
2503 */
2504 public function addIdentifierQuotes( $s ) {
2505 return '"' . str_replace( '"', '""', $s ) . '"';
2506 }
2507
2508 /**
2509 * Returns if the given identifier looks quoted or not according to
2510 * the database convention for quoting identifiers .
2511 *
2512 * @note Do not use this to determine if untrusted input is safe.
2513 * A malicious user can trick this function.
2514 * @param string $name
2515 * @return bool
2516 */
2517 public function isQuotedIdentifier( $name ) {
2518 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2519 }
2520
2521 /**
2522 * @param string $s
2523 * @param string $escapeChar
2524 * @return string
2525 */
2526 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2527 return str_replace( [ $escapeChar, '%', '_' ],
2528 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2529 $s );
2530 }
2531
2532 public function buildLike() {
2533 $params = func_get_args();
2534
2535 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2536 $params = $params[0];
2537 }
2538
2539 $s = '';
2540
2541 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2542 // may escape backslashes, creating problems of double escaping. The `
2543 // character has good cross-DBMS compatibility, avoiding special operators
2544 // in MS SQL like ^ and %
2545 $escapeChar = '`';
2546
2547 foreach ( $params as $value ) {
2548 if ( $value instanceof LikeMatch ) {
2549 $s .= $value->toString();
2550 } else {
2551 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2552 }
2553 }
2554
2555 return ' LIKE ' .
2556 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2557 }
2558
2559 public function anyChar() {
2560 return new LikeMatch( '_' );
2561 }
2562
2563 public function anyString() {
2564 return new LikeMatch( '%' );
2565 }
2566
2567 public function nextSequenceValue( $seqName ) {
2568 return null;
2569 }
2570
2571 /**
2572 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2573 * is only needed because a) MySQL must be as efficient as possible due to
2574 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2575 * which index to pick. Anyway, other databases might have different
2576 * indexes on a given table. So don't bother overriding this unless you're
2577 * MySQL.
2578 * @param string $index
2579 * @return string
2580 */
2581 public function useIndexClause( $index ) {
2582 return '';
2583 }
2584
2585 /**
2586 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2587 * is only needed because a) MySQL must be as efficient as possible due to
2588 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2589 * which index to pick. Anyway, other databases might have different
2590 * indexes on a given table. So don't bother overriding this unless you're
2591 * MySQL.
2592 * @param string $index
2593 * @return string
2594 */
2595 public function ignoreIndexClause( $index ) {
2596 return '';
2597 }
2598
2599 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2600 if ( count( $rows ) == 0 ) {
2601 return;
2602 }
2603
2604 // Single row case
2605 if ( !is_array( reset( $rows ) ) ) {
2606 $rows = [ $rows ];
2607 }
2608
2609 try {
2610 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2611 $affectedRowCount = 0;
2612 foreach ( $rows as $row ) {
2613 // Delete rows which collide with this one
2614 $indexWhereClauses = [];
2615 foreach ( $uniqueIndexes as $index ) {
2616 $indexColumns = (array)$index;
2617 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2618 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2619 throw new DBUnexpectedError(
2620 $this,
2621 'New record does not provide all values for unique key (' .
2622 implode( ', ', $indexColumns ) . ')'
2623 );
2624 } elseif ( in_array( null, $indexRowValues, true ) ) {
2625 throw new DBUnexpectedError(
2626 $this,
2627 'New record has a null value for unique key (' .
2628 implode( ', ', $indexColumns ) . ')'
2629 );
2630 }
2631 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2632 }
2633
2634 if ( $indexWhereClauses ) {
2635 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2636 $affectedRowCount += $this->affectedRows();
2637 }
2638
2639 // Now insert the row
2640 $this->insert( $table, $row, $fname );
2641 $affectedRowCount += $this->affectedRows();
2642 }
2643 $this->endAtomic( $fname );
2644 $this->affectedRowCount = $affectedRowCount;
2645 } catch ( Exception $e ) {
2646 $this->cancelAtomic( $fname );
2647 throw $e;
2648 }
2649 }
2650
2651 /**
2652 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2653 * statement.
2654 *
2655 * @param string $table Table name
2656 * @param array|string $rows Row(s) to insert
2657 * @param string $fname Caller function name
2658 *
2659 * @return ResultWrapper
2660 */
2661 protected function nativeReplace( $table, $rows, $fname ) {
2662 $table = $this->tableName( $table );
2663
2664 # Single row case
2665 if ( !is_array( reset( $rows ) ) ) {
2666 $rows = [ $rows ];
2667 }
2668
2669 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2670 $first = true;
2671
2672 foreach ( $rows as $row ) {
2673 if ( $first ) {
2674 $first = false;
2675 } else {
2676 $sql .= ',';
2677 }
2678
2679 $sql .= '(' . $this->makeList( $row ) . ')';
2680 }
2681
2682 return $this->query( $sql, $fname );
2683 }
2684
2685 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2686 $fname = __METHOD__
2687 ) {
2688 if ( !count( $rows ) ) {
2689 return true; // nothing to do
2690 }
2691
2692 if ( !is_array( reset( $rows ) ) ) {
2693 $rows = [ $rows ];
2694 }
2695
2696 if ( count( $uniqueIndexes ) ) {
2697 $clauses = []; // list WHERE clauses that each identify a single row
2698 foreach ( $rows as $row ) {
2699 foreach ( $uniqueIndexes as $index ) {
2700 $index = is_array( $index ) ? $index : [ $index ]; // columns
2701 $rowKey = []; // unique key to this row
2702 foreach ( $index as $column ) {
2703 $rowKey[$column] = $row[$column];
2704 }
2705 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2706 }
2707 }
2708 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2709 } else {
2710 $where = false;
2711 }
2712
2713 $affectedRowCount = 0;
2714 try {
2715 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2716 # Update any existing conflicting row(s)
2717 if ( $where !== false ) {
2718 $ok = $this->update( $table, $set, $where, $fname );
2719 $affectedRowCount += $this->affectedRows();
2720 } else {
2721 $ok = true;
2722 }
2723 # Now insert any non-conflicting row(s)
2724 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2725 $affectedRowCount += $this->affectedRows();
2726 $this->endAtomic( $fname );
2727 $this->affectedRowCount = $affectedRowCount;
2728 } catch ( Exception $e ) {
2729 $this->cancelAtomic( $fname );
2730 throw $e;
2731 }
2732
2733 return $ok;
2734 }
2735
2736 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2737 $fname = __METHOD__
2738 ) {
2739 if ( !$conds ) {
2740 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2741 }
2742
2743 $delTable = $this->tableName( $delTable );
2744 $joinTable = $this->tableName( $joinTable );
2745 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2746 if ( $conds != '*' ) {
2747 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2748 }
2749 $sql .= ')';
2750
2751 $this->query( $sql, $fname );
2752 }
2753
2754 public function textFieldSize( $table, $field ) {
2755 $table = $this->tableName( $table );
2756 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2757 $res = $this->query( $sql, __METHOD__ );
2758 $row = $this->fetchObject( $res );
2759
2760 $m = [];
2761
2762 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2763 $size = $m[1];
2764 } else {
2765 $size = -1;
2766 }
2767
2768 return $size;
2769 }
2770
2771 public function delete( $table, $conds, $fname = __METHOD__ ) {
2772 if ( !$conds ) {
2773 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2774 }
2775
2776 $table = $this->tableName( $table );
2777 $sql = "DELETE FROM $table";
2778
2779 if ( $conds != '*' ) {
2780 if ( is_array( $conds ) ) {
2781 $conds = $this->makeList( $conds, self::LIST_AND );
2782 }
2783 $sql .= ' WHERE ' . $conds;
2784 }
2785
2786 return $this->query( $sql, $fname );
2787 }
2788
2789 final public function insertSelect(
2790 $destTable, $srcTable, $varMap, $conds,
2791 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2792 ) {
2793 static $hints = [ 'NO_AUTO_COLUMNS' ];
2794
2795 $insertOptions = (array)$insertOptions;
2796 $selectOptions = (array)$selectOptions;
2797
2798 if ( $this->cliMode && $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2799 // For massive migrations with downtime, we don't want to select everything
2800 // into memory and OOM, so do all this native on the server side if possible.
2801 return $this->nativeInsertSelect(
2802 $destTable,
2803 $srcTable,
2804 $varMap,
2805 $conds,
2806 $fname,
2807 array_diff( $insertOptions, $hints ),
2808 $selectOptions,
2809 $selectJoinConds
2810 );
2811 }
2812
2813 return $this->nonNativeInsertSelect(
2814 $destTable,
2815 $srcTable,
2816 $varMap,
2817 $conds,
2818 $fname,
2819 array_diff( $insertOptions, $hints ),
2820 $selectOptions,
2821 $selectJoinConds
2822 );
2823 }
2824
2825 /**
2826 * @param array $insertOptions INSERT options
2827 * @param array $selectOptions SELECT options
2828 * @return bool Whether an INSERT SELECT with these options will be replication safe
2829 * @since 1.31
2830 */
2831 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2832 return true;
2833 }
2834
2835 /**
2836 * Implementation of insertSelect() based on select() and insert()
2837 *
2838 * @see IDatabase::insertSelect()
2839 * @since 1.30
2840 * @param string $destTable
2841 * @param string|array $srcTable
2842 * @param array $varMap
2843 * @param array $conds
2844 * @param string $fname
2845 * @param array $insertOptions
2846 * @param array $selectOptions
2847 * @param array $selectJoinConds
2848 * @return bool
2849 */
2850 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2851 $fname = __METHOD__,
2852 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2853 ) {
2854 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2855 // on only the master (without needing row-based-replication). It also makes it easy to
2856 // know how big the INSERT is going to be.
2857 $fields = [];
2858 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2859 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2860 }
2861 $selectOptions[] = 'FOR UPDATE';
2862 $res = $this->select(
2863 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2864 );
2865 if ( !$res ) {
2866 return false;
2867 }
2868
2869 try {
2870 $affectedRowCount = 0;
2871 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
2872 $rows = [];
2873 $ok = true;
2874 foreach ( $res as $row ) {
2875 $rows[] = (array)$row;
2876
2877 // Avoid inserts that are too huge
2878 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
2879 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2880 if ( !$ok ) {
2881 break;
2882 }
2883 $affectedRowCount += $this->affectedRows();
2884 $rows = [];
2885 }
2886 }
2887 if ( $rows && $ok ) {
2888 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2889 if ( $ok ) {
2890 $affectedRowCount += $this->affectedRows();
2891 }
2892 }
2893 if ( $ok ) {
2894 $this->endAtomic( $fname );
2895 $this->affectedRowCount = $affectedRowCount;
2896 } else {
2897 $this->cancelAtomic( $fname );
2898 }
2899 return $ok;
2900 } catch ( Exception $e ) {
2901 $this->cancelAtomic( $fname );
2902 throw $e;
2903 }
2904 }
2905
2906 /**
2907 * Native server-side implementation of insertSelect() for situations where
2908 * we don't want to select everything into memory
2909 *
2910 * @see IDatabase::insertSelect()
2911 * @param string $destTable
2912 * @param string|array $srcTable
2913 * @param array $varMap
2914 * @param array $conds
2915 * @param string $fname
2916 * @param array $insertOptions
2917 * @param array $selectOptions
2918 * @param array $selectJoinConds
2919 * @return bool
2920 */
2921 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2922 $fname = __METHOD__,
2923 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2924 ) {
2925 $destTable = $this->tableName( $destTable );
2926
2927 if ( !is_array( $insertOptions ) ) {
2928 $insertOptions = [ $insertOptions ];
2929 }
2930
2931 $insertOptions = $this->makeInsertOptions( $insertOptions );
2932
2933 $selectSql = $this->selectSQLText(
2934 $srcTable,
2935 array_values( $varMap ),
2936 $conds,
2937 $fname,
2938 $selectOptions,
2939 $selectJoinConds
2940 );
2941
2942 $sql = "INSERT $insertOptions" .
2943 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2944 $selectSql;
2945
2946 return $this->query( $sql, $fname );
2947 }
2948
2949 /**
2950 * Construct a LIMIT query with optional offset. This is used for query
2951 * pages. The SQL should be adjusted so that only the first $limit rows
2952 * are returned. If $offset is provided as well, then the first $offset
2953 * rows should be discarded, and the next $limit rows should be returned.
2954 * If the result of the query is not ordered, then the rows to be returned
2955 * are theoretically arbitrary.
2956 *
2957 * $sql is expected to be a SELECT, if that makes a difference.
2958 *
2959 * The version provided by default works in MySQL and SQLite. It will very
2960 * likely need to be overridden for most other DBMSes.
2961 *
2962 * @param string $sql SQL query we will append the limit too
2963 * @param int $limit The SQL limit
2964 * @param int|bool $offset The SQL offset (default false)
2965 * @throws DBUnexpectedError
2966 * @return string
2967 */
2968 public function limitResult( $sql, $limit, $offset = false ) {
2969 if ( !is_numeric( $limit ) ) {
2970 throw new DBUnexpectedError( $this,
2971 "Invalid non-numeric limit passed to limitResult()\n" );
2972 }
2973
2974 return "$sql LIMIT "
2975 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2976 . "{$limit} ";
2977 }
2978
2979 public function unionSupportsOrderAndLimit() {
2980 return true; // True for almost every DB supported
2981 }
2982
2983 public function unionQueries( $sqls, $all ) {
2984 $glue = $all ? ') UNION ALL (' : ') UNION (';
2985
2986 return '(' . implode( $glue, $sqls ) . ')';
2987 }
2988
2989 public function unionConditionPermutations(
2990 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
2991 $options = [], $join_conds = []
2992 ) {
2993 // First, build the Cartesian product of $permute_conds
2994 $conds = [ [] ];
2995 foreach ( $permute_conds as $field => $values ) {
2996 if ( !$values ) {
2997 // Skip empty $values
2998 continue;
2999 }
3000 $values = array_unique( $values ); // For sanity
3001 $newConds = [];
3002 foreach ( $conds as $cond ) {
3003 foreach ( $values as $value ) {
3004 $cond[$field] = $value;
3005 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3006 }
3007 }
3008 $conds = $newConds;
3009 }
3010
3011 $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
3012
3013 // If there's just one condition and no subordering, hand off to
3014 // selectSQLText directly.
3015 if ( count( $conds ) === 1 &&
3016 ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
3017 ) {
3018 return $this->selectSQLText(
3019 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
3020 );
3021 }
3022
3023 // Otherwise, we need to pull out the order and limit to apply after
3024 // the union. Then build the SQL queries for each set of conditions in
3025 // $conds. Then union them together (using UNION ALL, because the
3026 // product *should* already be distinct).
3027 $orderBy = $this->makeOrderBy( $options );
3028 $limit = isset( $options['LIMIT'] ) ? $options['LIMIT'] : null;
3029 $offset = isset( $options['OFFSET'] ) ? $options['OFFSET'] : false;
3030 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3031 if ( !$this->unionSupportsOrderAndLimit() ) {
3032 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3033 } else {
3034 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3035 $options['ORDER BY'] = $options['INNER ORDER BY'];
3036 }
3037 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3038 // We need to increase the limit by the offset rather than
3039 // using the offset directly, otherwise it'll skip incorrectly
3040 // in the subqueries.
3041 $options['LIMIT'] = $limit + $offset;
3042 unset( $options['OFFSET'] );
3043 }
3044 }
3045
3046 $sqls = [];
3047 foreach ( $conds as $cond ) {
3048 $sqls[] = $this->selectSQLText(
3049 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
3050 );
3051 }
3052 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3053 if ( $limit !== null ) {
3054 $sql = $this->limitResult( $sql, $limit, $offset );
3055 }
3056
3057 return $sql;
3058 }
3059
3060 public function conditional( $cond, $trueVal, $falseVal ) {
3061 if ( is_array( $cond ) ) {
3062 $cond = $this->makeList( $cond, self::LIST_AND );
3063 }
3064
3065 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3066 }
3067
3068 public function strreplace( $orig, $old, $new ) {
3069 return "REPLACE({$orig}, {$old}, {$new})";
3070 }
3071
3072 public function getServerUptime() {
3073 return 0;
3074 }
3075
3076 public function wasDeadlock() {
3077 return false;
3078 }
3079
3080 public function wasLockTimeout() {
3081 return false;
3082 }
3083
3084 public function wasConnectionLoss() {
3085 return $this->wasConnectionError( $this->lastErrno() );
3086 }
3087
3088 public function wasReadOnlyError() {
3089 return false;
3090 }
3091
3092 public function wasErrorReissuable() {
3093 return (
3094 $this->wasDeadlock() ||
3095 $this->wasLockTimeout() ||
3096 $this->wasConnectionLoss()
3097 );
3098 }
3099
3100 /**
3101 * Do not use this method outside of Database/DBError classes
3102 *
3103 * @param int|string $errno
3104 * @return bool Whether the given query error was a connection drop
3105 */
3106 public function wasConnectionError( $errno ) {
3107 return false;
3108 }
3109
3110 /**
3111 * @return bool Whether it is safe to assume the given error only caused statement rollback
3112 * @note This is for backwards compatibility for callers catching DBError exceptions in
3113 * order to ignore problems like duplicate key errors or foriegn key violations
3114 * @since 1.31
3115 */
3116 protected function wasKnownStatementRollbackError() {
3117 return false; // don't know; it could have caused a transaction rollback
3118 }
3119
3120 public function deadlockLoop() {
3121 $args = func_get_args();
3122 $function = array_shift( $args );
3123 $tries = self::DEADLOCK_TRIES;
3124
3125 $this->begin( __METHOD__ );
3126
3127 $retVal = null;
3128 /** @var Exception $e */
3129 $e = null;
3130 do {
3131 try {
3132 $retVal = call_user_func_array( $function, $args );
3133 break;
3134 } catch ( DBQueryError $e ) {
3135 if ( $this->wasDeadlock() ) {
3136 // Retry after a randomized delay
3137 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3138 } else {
3139 // Throw the error back up
3140 throw $e;
3141 }
3142 }
3143 } while ( --$tries > 0 );
3144
3145 if ( $tries <= 0 ) {
3146 // Too many deadlocks; give up
3147 $this->rollback( __METHOD__ );
3148 throw $e;
3149 } else {
3150 $this->commit( __METHOD__ );
3151
3152 return $retVal;
3153 }
3154 }
3155
3156 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3157 # Real waits are implemented in the subclass.
3158 return 0;
3159 }
3160
3161 public function getReplicaPos() {
3162 # Stub
3163 return false;
3164 }
3165
3166 public function getMasterPos() {
3167 # Stub
3168 return false;
3169 }
3170
3171 public function serverIsReadOnly() {
3172 return false;
3173 }
3174
3175 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
3176 if ( !$this->trxLevel ) {
3177 throw new DBUnexpectedError( $this, "No transaction is active." );
3178 }
3179 $this->trxEndCallbacks[] = [ $callback, $fname ];
3180 }
3181
3182 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
3183 $this->trxIdleCallbacks[] = [ $callback, $fname ];
3184 if ( !$this->trxLevel ) {
3185 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
3186 }
3187 }
3188
3189 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
3190 if ( $this->trxLevel || $this->getFlag( self::DBO_TRX ) ) {
3191 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3192 // an implicit commit of all peer databases. This is true even if a transaction has
3193 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3194 $this->trxPreCommitCallbacks[] = [ $callback, $fname ];
3195 } else {
3196 // No transaction is active nor will start implicitly, so make one for this callback
3197 $this->startAtomic( __METHOD__, self::ATOMIC_CANCELABLE );
3198 try {
3199 call_user_func( $callback );
3200 $this->endAtomic( __METHOD__ );
3201 } catch ( Exception $e ) {
3202 $this->cancelAtomic( __METHOD__ );
3203 throw $e;
3204 }
3205 }
3206 }
3207
3208 final public function setTransactionListener( $name, callable $callback = null ) {
3209 if ( $callback ) {
3210 $this->trxRecurringCallbacks[$name] = $callback;
3211 } else {
3212 unset( $this->trxRecurringCallbacks[$name] );
3213 }
3214 }
3215
3216 /**
3217 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3218 *
3219 * This method should not be used outside of Database/LoadBalancer
3220 *
3221 * @param bool $suppress
3222 * @since 1.28
3223 */
3224 final public function setTrxEndCallbackSuppression( $suppress ) {
3225 $this->trxEndCallbacksSuppressed = $suppress;
3226 }
3227
3228 /**
3229 * Actually run and consume any "on transaction idle/resolution" callbacks.
3230 *
3231 * This method should not be used outside of Database/LoadBalancer
3232 *
3233 * @param int $trigger IDatabase::TRIGGER_* constant
3234 * @since 1.20
3235 * @throws Exception
3236 */
3237 public function runOnTransactionIdleCallbacks( $trigger ) {
3238 if ( $this->trxEndCallbacksSuppressed ) {
3239 return;
3240 }
3241
3242 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
3243 /** @var Exception $e */
3244 $e = null; // first exception
3245 do { // callbacks may add callbacks :)
3246 $callbacks = array_merge(
3247 $this->trxIdleCallbacks,
3248 $this->trxEndCallbacks // include "transaction resolution" callbacks
3249 );
3250 $this->trxIdleCallbacks = []; // consumed (and recursion guard)
3251 $this->trxEndCallbacks = []; // consumed (recursion guard)
3252 foreach ( $callbacks as $callback ) {
3253 try {
3254 list( $phpCallback ) = $callback;
3255 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
3256 call_user_func_array( $phpCallback, [ $trigger ] );
3257 if ( $autoTrx ) {
3258 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
3259 } else {
3260 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
3261 }
3262 } catch ( Exception $ex ) {
3263 call_user_func( $this->errorLogger, $ex );
3264 $e = $e ?: $ex;
3265 // Some callbacks may use startAtomic/endAtomic, so make sure
3266 // their transactions are ended so other callbacks don't fail
3267 if ( $this->trxLevel() ) {
3268 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
3269 }
3270 }
3271 }
3272 } while ( count( $this->trxIdleCallbacks ) );
3273
3274 if ( $e instanceof Exception ) {
3275 throw $e; // re-throw any first exception
3276 }
3277 }
3278
3279 /**
3280 * Actually run and consume any "on transaction pre-commit" callbacks.
3281 *
3282 * This method should not be used outside of Database/LoadBalancer
3283 *
3284 * @since 1.22
3285 * @throws Exception
3286 */
3287 public function runOnTransactionPreCommitCallbacks() {
3288 $e = null; // first exception
3289 do { // callbacks may add callbacks :)
3290 $callbacks = $this->trxPreCommitCallbacks;
3291 $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
3292 foreach ( $callbacks as $callback ) {
3293 try {
3294 list( $phpCallback ) = $callback;
3295 call_user_func( $phpCallback );
3296 } catch ( Exception $ex ) {
3297 call_user_func( $this->errorLogger, $ex );
3298 $e = $e ?: $ex;
3299 }
3300 }
3301 } while ( count( $this->trxPreCommitCallbacks ) );
3302
3303 if ( $e instanceof Exception ) {
3304 throw $e; // re-throw any first exception
3305 }
3306 }
3307
3308 /**
3309 * Actually run any "transaction listener" callbacks.
3310 *
3311 * This method should not be used outside of Database/LoadBalancer
3312 *
3313 * @param int $trigger IDatabase::TRIGGER_* constant
3314 * @throws Exception
3315 * @since 1.20
3316 */
3317 public function runTransactionListenerCallbacks( $trigger ) {
3318 if ( $this->trxEndCallbacksSuppressed ) {
3319 return;
3320 }
3321
3322 /** @var Exception $e */
3323 $e = null; // first exception
3324
3325 foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
3326 try {
3327 $phpCallback( $trigger, $this );
3328 } catch ( Exception $ex ) {
3329 call_user_func( $this->errorLogger, $ex );
3330 $e = $e ?: $ex;
3331 }
3332 }
3333
3334 if ( $e instanceof Exception ) {
3335 throw $e; // re-throw any first exception
3336 }
3337 }
3338
3339 /**
3340 * Create a savepoint
3341 *
3342 * This is used internally to implement atomic sections. It should not be
3343 * used otherwise.
3344 *
3345 * @since 1.31
3346 * @param string $identifier Identifier for the savepoint
3347 * @param string $fname Calling function name
3348 */
3349 protected function doSavepoint( $identifier, $fname ) {
3350 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3351 }
3352
3353 /**
3354 * Release a savepoint
3355 *
3356 * This is used internally to implement atomic sections. It should not be
3357 * used otherwise.
3358 *
3359 * @since 1.31
3360 * @param string $identifier Identifier for the savepoint
3361 * @param string $fname Calling function name
3362 */
3363 protected function doReleaseSavepoint( $identifier, $fname ) {
3364 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3365 }
3366
3367 /**
3368 * Rollback to a savepoint
3369 *
3370 * This is used internally to implement atomic sections. It should not be
3371 * used otherwise.
3372 *
3373 * @since 1.31
3374 * @param string $identifier Identifier for the savepoint
3375 * @param string $fname Calling function name
3376 */
3377 protected function doRollbackToSavepoint( $identifier, $fname ) {
3378 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3379 }
3380
3381 final public function startAtomic(
3382 $fname = __METHOD__, $cancelable = self::ATOMIC_NOT_CANCELABLE
3383 ) {
3384 $savepointId = $cancelable === self::ATOMIC_CANCELABLE ? 'n/a' : null;
3385 if ( !$this->trxLevel ) {
3386 $this->begin( $fname, self::TRANSACTION_INTERNAL );
3387 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3388 // in all changes being in one transaction to keep requests transactional.
3389 if ( !$this->getFlag( self::DBO_TRX ) ) {
3390 $this->trxAutomaticAtomic = true;
3391 }
3392 } elseif ( $cancelable === self::ATOMIC_CANCELABLE ) {
3393 $savepointId = 'wikimedia_rdbms_atomic' . ++$this->trxAtomicCounter;
3394 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3395 $this->queryLogger->warning(
3396 'There have been an excessively large number of atomic sections in a transaction'
3397 . " started by $this->trxFname, reusing IDs (at $fname)",
3398 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3399 );
3400 $this->trxAtomicCounter = 0;
3401 $savepointId = 'wikimedia_rdbms_atomic' . ++$this->trxAtomicCounter;
3402 }
3403 $this->doSavepoint( $savepointId, $fname );
3404 }
3405
3406 $this->trxAtomicLevels[] = [ $fname, $savepointId ];
3407 }
3408
3409 final public function endAtomic( $fname = __METHOD__ ) {
3410 if ( !$this->trxLevel ) {
3411 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3412 }
3413
3414 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3415 ? array_pop( $this->trxAtomicLevels ) : [ null, null ];
3416 if ( $savedFname !== $fname ) {
3417 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3418 }
3419
3420 if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3421 $this->commit( $fname, self::FLUSHING_INTERNAL );
3422 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3423 $this->doReleaseSavepoint( $savepointId, $fname );
3424 }
3425 }
3426
3427 final public function cancelAtomic( $fname = __METHOD__ ) {
3428 if ( !$this->trxLevel ) {
3429 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3430 }
3431
3432 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3433 ? array_pop( $this->trxAtomicLevels ) : [ null, null ];
3434 if ( $savedFname !== $fname ) {
3435 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3436 }
3437 if ( !$savepointId ) {
3438 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3439 }
3440
3441 if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3442 $this->rollback( $fname, self::FLUSHING_INTERNAL );
3443 } elseif ( $savepointId !== 'n/a' ) {
3444 $this->doRollbackToSavepoint( $savepointId, $fname );
3445 $this->trxStatus = self::STATUS_TRX_OK; // no exception; recovered
3446 }
3447
3448 $this->affectedRowCount = 0; // for the sake of consistency
3449 }
3450
3451 final public function doAtomicSection( $fname, callable $callback ) {
3452 $this->startAtomic( $fname, self::ATOMIC_CANCELABLE );
3453 try {
3454 $res = call_user_func_array( $callback, [ $this, $fname ] );
3455 } catch ( Exception $e ) {
3456 $this->cancelAtomic( $fname );
3457 throw $e;
3458 }
3459 $this->endAtomic( $fname );
3460
3461 return $res;
3462 }
3463
3464 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3465 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3466 if ( $this->trxLevel ) {
3467 if ( $this->trxAtomicLevels ) {
3468 $levels = $this->flatAtomicSectionList();
3469 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3470 throw new DBUnexpectedError( $this, $msg );
3471 } elseif ( !$this->trxAutomatic ) {
3472 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3473 throw new DBUnexpectedError( $this, $msg );
3474 } else {
3475 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3476 throw new DBUnexpectedError( $this, $msg );
3477 }
3478 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
3479 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3480 throw new DBUnexpectedError( $this, $msg );
3481 }
3482
3483 // Avoid fatals if close() was called
3484 $this->assertOpen();
3485
3486 $this->doBegin( $fname );
3487 $this->trxStatus = self::STATUS_TRX_OK;
3488 $this->trxAtomicCounter = 0;
3489 $this->trxTimestamp = microtime( true );
3490 $this->trxFname = $fname;
3491 $this->trxDoneWrites = false;
3492 $this->trxAutomaticAtomic = false;
3493 $this->trxAtomicLevels = [];
3494 $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3495 $this->trxWriteDuration = 0.0;
3496 $this->trxWriteQueryCount = 0;
3497 $this->trxWriteAffectedRows = 0;
3498 $this->trxWriteAdjDuration = 0.0;
3499 $this->trxWriteAdjQueryCount = 0;
3500 $this->trxWriteCallers = [];
3501 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3502 // Get an estimate of the replication lag before any such queries.
3503 $this->trxReplicaLag = $this->getApproximateLagStatus()['lag'];
3504 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3505 // caller will think its OK to muck around with the transaction just because startAtomic()
3506 // has not yet completed (e.g. setting trxAtomicLevels).
3507 $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
3508 }
3509
3510 /**
3511 * Issues the BEGIN command to the database server.
3512 *
3513 * @see Database::begin()
3514 * @param string $fname
3515 */
3516 protected function doBegin( $fname ) {
3517 $this->query( 'BEGIN', $fname );
3518 $this->trxLevel = 1;
3519 }
3520
3521 final public function commit( $fname = __METHOD__, $flush = '' ) {
3522 if ( $this->trxLevel && $this->trxAtomicLevels ) {
3523 // There are still atomic sections open. This cannot be ignored
3524 $levels = $this->flatAtomicSectionList();
3525 throw new DBUnexpectedError(
3526 $this,
3527 "$fname: Got COMMIT while atomic sections $levels are still open."
3528 );
3529 }
3530
3531 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3532 if ( !$this->trxLevel ) {
3533 return; // nothing to do
3534 } elseif ( !$this->trxAutomatic ) {
3535 throw new DBUnexpectedError(
3536 $this,
3537 "$fname: Flushing an explicit transaction, getting out of sync."
3538 );
3539 }
3540 } else {
3541 if ( !$this->trxLevel ) {
3542 $this->queryLogger->error(
3543 "$fname: No transaction to commit, something got out of sync." );
3544 return; // nothing to do
3545 } elseif ( $this->trxAutomatic ) {
3546 throw new DBUnexpectedError(
3547 $this,
3548 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3549 );
3550 }
3551 }
3552
3553 // Avoid fatals if close() was called
3554 $this->assertOpen();
3555
3556 $this->runOnTransactionPreCommitCallbacks();
3557 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
3558 $this->doCommit( $fname );
3559 $this->trxStatus = self::STATUS_TRX_NONE;
3560 if ( $this->trxDoneWrites ) {
3561 $this->lastWriteTime = microtime( true );
3562 $this->trxProfiler->transactionWritingOut(
3563 $this->server,
3564 $this->dbName,
3565 $this->trxShortId,
3566 $writeTime,
3567 $this->trxWriteAffectedRows
3568 );
3569 }
3570
3571 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
3572 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
3573 }
3574
3575 /**
3576 * Issues the COMMIT command to the database server.
3577 *
3578 * @see Database::commit()
3579 * @param string $fname
3580 */
3581 protected function doCommit( $fname ) {
3582 if ( $this->trxLevel ) {
3583 $this->query( 'COMMIT', $fname );
3584 $this->trxLevel = 0;
3585 }
3586 }
3587
3588 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3589 $trxActive = $this->trxLevel;
3590
3591 if ( $flush !== self::FLUSHING_INTERNAL && $flush !== self::FLUSHING_ALL_PEERS ) {
3592 if ( $this->getFlag( self::DBO_TRX ) ) {
3593 throw new DBUnexpectedError(
3594 $this,
3595 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3596 );
3597 }
3598 }
3599
3600 if ( $trxActive ) {
3601 // Avoid fatals if close() was called
3602 $this->assertOpen();
3603
3604 $this->doRollback( $fname );
3605 $this->trxStatus = self::STATUS_TRX_NONE;
3606 $this->trxAtomicLevels = [];
3607 if ( $this->trxDoneWrites ) {
3608 $this->trxProfiler->transactionWritingOut(
3609 $this->server,
3610 $this->dbName,
3611 $this->trxShortId
3612 );
3613 }
3614 }
3615
3616 // Clear any commit-dependant callbacks. They might even be present
3617 // only due to transaction rounds, with no SQL transaction being active
3618 $this->trxIdleCallbacks = [];
3619 $this->trxPreCommitCallbacks = [];
3620
3621 if ( $trxActive ) {
3622 try {
3623 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3624 } catch ( Exception $e ) {
3625 // already logged; finish and let LoadBalancer move on during mass-rollback
3626 }
3627 try {
3628 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3629 } catch ( Exception $e ) {
3630 // already logged; let LoadBalancer move on during mass-rollback
3631 }
3632
3633 $this->affectedRowCount = 0; // for the sake of consistency
3634 }
3635 }
3636
3637 /**
3638 * Issues the ROLLBACK command to the database server.
3639 *
3640 * @see Database::rollback()
3641 * @param string $fname
3642 */
3643 protected function doRollback( $fname ) {
3644 if ( $this->trxLevel ) {
3645 # Disconnects cause rollback anyway, so ignore those errors
3646 $ignoreErrors = true;
3647 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3648 $this->trxLevel = 0;
3649 }
3650 }
3651
3652 public function flushSnapshot( $fname = __METHOD__ ) {
3653 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3654 // This only flushes transactions to clear snapshots, not to write data
3655 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3656 throw new DBUnexpectedError(
3657 $this,
3658 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3659 );
3660 }
3661
3662 $this->commit( $fname, self::FLUSHING_INTERNAL );
3663 }
3664
3665 public function explicitTrxActive() {
3666 return $this->trxLevel && ( $this->trxAtomicLevels || !$this->trxAutomatic );
3667 }
3668
3669 public function duplicateTableStructure(
3670 $oldName, $newName, $temporary = false, $fname = __METHOD__
3671 ) {
3672 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3673 }
3674
3675 public function listTables( $prefix = null, $fname = __METHOD__ ) {
3676 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3677 }
3678
3679 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3680 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3681 }
3682
3683 public function timestamp( $ts = 0 ) {
3684 $t = new ConvertibleTimestamp( $ts );
3685 // Let errors bubble up to avoid putting garbage in the DB
3686 return $t->getTimestamp( TS_MW );
3687 }
3688
3689 public function timestampOrNull( $ts = null ) {
3690 if ( is_null( $ts ) ) {
3691 return null;
3692 } else {
3693 return $this->timestamp( $ts );
3694 }
3695 }
3696
3697 public function affectedRows() {
3698 return ( $this->affectedRowCount === null )
3699 ? $this->fetchAffectedRowCount() // default to driver value
3700 : $this->affectedRowCount;
3701 }
3702
3703 /**
3704 * @return int Number of retrieved rows according to the driver
3705 */
3706 abstract protected function fetchAffectedRowCount();
3707
3708 /**
3709 * Take the result from a query, and wrap it in a ResultWrapper if
3710 * necessary. Boolean values are passed through as is, to indicate success
3711 * of write queries or failure.
3712 *
3713 * Once upon a time, Database::query() returned a bare MySQL result
3714 * resource, and it was necessary to call this function to convert it to
3715 * a wrapper. Nowadays, raw database objects are never exposed to external
3716 * callers, so this is unnecessary in external code.
3717 *
3718 * @param bool|ResultWrapper|resource|object $result
3719 * @return bool|ResultWrapper
3720 */
3721 protected function resultObject( $result ) {
3722 if ( !$result ) {
3723 return false;
3724 } elseif ( $result instanceof ResultWrapper ) {
3725 return $result;
3726 } elseif ( $result === true ) {
3727 // Successful write query
3728 return $result;
3729 } else {
3730 return new ResultWrapper( $this, $result );
3731 }
3732 }
3733
3734 public function ping( &$rtt = null ) {
3735 // Avoid hitting the server if it was hit recently
3736 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3737 if ( !func_num_args() || $this->rttEstimate > 0 ) {
3738 $rtt = $this->rttEstimate;
3739 return true; // don't care about $rtt
3740 }
3741 }
3742
3743 // This will reconnect if possible or return false if not
3744 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
3745 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3746 $this->restoreFlags( self::RESTORE_PRIOR );
3747
3748 if ( $ok ) {
3749 $rtt = $this->rttEstimate;
3750 }
3751
3752 return $ok;
3753 }
3754
3755 /**
3756 * Close any existing (dead) database connection and open a new connection
3757 *
3758 * @param string $fname
3759 * @return bool True if new connection is opened successfully, false if error
3760 */
3761 protected function replaceLostConnection( $fname ) {
3762 $this->closeConnection();
3763 $this->opened = false;
3764 $this->conn = false;
3765 try {
3766 $this->open( $this->server, $this->user, $this->password, $this->dbName );
3767 $this->lastPing = microtime( true );
3768 $ok = true;
3769
3770 $this->connLogger->warning(
3771 $fname . ': lost connection to {dbserver}; reconnected',
3772 [
3773 'dbserver' => $this->getServer(),
3774 'trace' => ( new RuntimeException() )->getTraceAsString()
3775 ]
3776 );
3777 } catch ( DBConnectionError $e ) {
3778 $ok = false;
3779
3780 $this->connLogger->error(
3781 $fname . ': lost connection to {dbserver} permanently',
3782 [ 'dbserver' => $this->getServer() ]
3783 );
3784 }
3785
3786 $this->handleSessionLoss();
3787
3788 return $ok;
3789 }
3790
3791 public function getSessionLagStatus() {
3792 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3793 }
3794
3795 /**
3796 * Get the replica DB lag when the current transaction started
3797 *
3798 * This is useful when transactions might use snapshot isolation
3799 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3800 * is this lag plus transaction duration. If they don't, it is still
3801 * safe to be pessimistic. This returns null if there is no transaction.
3802 *
3803 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3804 * @since 1.27
3805 */
3806 final protected function getTransactionLagStatus() {
3807 return $this->trxLevel
3808 ? [ 'lag' => $this->trxReplicaLag, 'since' => $this->trxTimestamp() ]
3809 : null;
3810 }
3811
3812 /**
3813 * Get a replica DB lag estimate for this server
3814 *
3815 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3816 * @since 1.27
3817 */
3818 protected function getApproximateLagStatus() {
3819 return [
3820 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3821 'since' => microtime( true )
3822 ];
3823 }
3824
3825 /**
3826 * Merge the result of getSessionLagStatus() for several DBs
3827 * using the most pessimistic values to estimate the lag of
3828 * any data derived from them in combination
3829 *
3830 * This is information is useful for caching modules
3831 *
3832 * @see WANObjectCache::set()
3833 * @see WANObjectCache::getWithSetCallback()
3834 *
3835 * @param IDatabase $db1
3836 * @param IDatabase $db2 [optional]
3837 * @return array Map of values:
3838 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3839 * - since: oldest UNIX timestamp of any of the DB lag estimates
3840 * - pending: whether any of the DBs have uncommitted changes
3841 * @throws DBError
3842 * @since 1.27
3843 */
3844 public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
3845 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3846 foreach ( func_get_args() as $db ) {
3847 /** @var IDatabase $db */
3848 $status = $db->getSessionLagStatus();
3849 if ( $status['lag'] === false ) {
3850 $res['lag'] = false;
3851 } elseif ( $res['lag'] !== false ) {
3852 $res['lag'] = max( $res['lag'], $status['lag'] );
3853 }
3854 $res['since'] = min( $res['since'], $status['since'] );
3855 $res['pending'] = $res['pending'] ?: $db->writesPending();
3856 }
3857
3858 return $res;
3859 }
3860
3861 public function getLag() {
3862 return 0;
3863 }
3864
3865 public function maxListLen() {
3866 return 0;
3867 }
3868
3869 public function encodeBlob( $b ) {
3870 return $b;
3871 }
3872
3873 public function decodeBlob( $b ) {
3874 if ( $b instanceof Blob ) {
3875 $b = $b->fetch();
3876 }
3877 return $b;
3878 }
3879
3880 public function setSessionOptions( array $options ) {
3881 }
3882
3883 public function sourceFile(
3884 $filename,
3885 callable $lineCallback = null,
3886 callable $resultCallback = null,
3887 $fname = false,
3888 callable $inputCallback = null
3889 ) {
3890 Wikimedia\suppressWarnings();
3891 $fp = fopen( $filename, 'r' );
3892 Wikimedia\restoreWarnings();
3893
3894 if ( false === $fp ) {
3895 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3896 }
3897
3898 if ( !$fname ) {
3899 $fname = __METHOD__ . "( $filename )";
3900 }
3901
3902 try {
3903 $error = $this->sourceStream(
3904 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3905 } catch ( Exception $e ) {
3906 fclose( $fp );
3907 throw $e;
3908 }
3909
3910 fclose( $fp );
3911
3912 return $error;
3913 }
3914
3915 public function setSchemaVars( $vars ) {
3916 $this->schemaVars = $vars;
3917 }
3918
3919 public function sourceStream(
3920 $fp,
3921 callable $lineCallback = null,
3922 callable $resultCallback = null,
3923 $fname = __METHOD__,
3924 callable $inputCallback = null
3925 ) {
3926 $delimiterReset = new ScopedCallback(
3927 function ( $delimiter ) {
3928 $this->delimiter = $delimiter;
3929 },
3930 [ $this->delimiter ]
3931 );
3932 $cmd = '';
3933
3934 while ( !feof( $fp ) ) {
3935 if ( $lineCallback ) {
3936 call_user_func( $lineCallback );
3937 }
3938
3939 $line = trim( fgets( $fp ) );
3940
3941 if ( $line == '' ) {
3942 continue;
3943 }
3944
3945 if ( '-' == $line[0] && '-' == $line[1] ) {
3946 continue;
3947 }
3948
3949 if ( $cmd != '' ) {
3950 $cmd .= ' ';
3951 }
3952
3953 $done = $this->streamStatementEnd( $cmd, $line );
3954
3955 $cmd .= "$line\n";
3956
3957 if ( $done || feof( $fp ) ) {
3958 $cmd = $this->replaceVars( $cmd );
3959
3960 if ( $inputCallback ) {
3961 $callbackResult = call_user_func( $inputCallback, $cmd );
3962
3963 if ( is_string( $callbackResult ) || !$callbackResult ) {
3964 $cmd = $callbackResult;
3965 }
3966 }
3967
3968 if ( $cmd ) {
3969 $res = $this->query( $cmd, $fname );
3970
3971 if ( $resultCallback ) {
3972 call_user_func( $resultCallback, $res, $this );
3973 }
3974
3975 if ( false === $res ) {
3976 $err = $this->lastError();
3977
3978 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3979 }
3980 }
3981 $cmd = '';
3982 }
3983 }
3984
3985 ScopedCallback::consume( $delimiterReset );
3986 return true;
3987 }
3988
3989 /**
3990 * Called by sourceStream() to check if we've reached a statement end
3991 *
3992 * @param string &$sql SQL assembled so far
3993 * @param string &$newLine New line about to be added to $sql
3994 * @return bool Whether $newLine contains end of the statement
3995 */
3996 public function streamStatementEnd( &$sql, &$newLine ) {
3997 if ( $this->delimiter ) {
3998 $prev = $newLine;
3999 $newLine = preg_replace(
4000 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4001 if ( $newLine != $prev ) {
4002 return true;
4003 }
4004 }
4005
4006 return false;
4007 }
4008
4009 /**
4010 * Database independent variable replacement. Replaces a set of variables
4011 * in an SQL statement with their contents as given by $this->getSchemaVars().
4012 *
4013 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4014 *
4015 * - '{$var}' should be used for text and is passed through the database's
4016 * addQuotes method.
4017 * - `{$var}` should be used for identifiers (e.g. table and database names).
4018 * It is passed through the database's addIdentifierQuotes method which
4019 * can be overridden if the database uses something other than backticks.
4020 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4021 * database's tableName method.
4022 * - / *i* / passes the name that follows through the database's indexName method.
4023 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4024 * its use should be avoided. In 1.24 and older, string encoding was applied.
4025 *
4026 * @param string $ins SQL statement to replace variables in
4027 * @return string The new SQL statement with variables replaced
4028 */
4029 protected function replaceVars( $ins ) {
4030 $vars = $this->getSchemaVars();
4031 return preg_replace_callback(
4032 '!
4033 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4034 \'\{\$ (\w+) }\' | # 3. addQuotes
4035 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4036 /\*\$ (\w+) \*/ # 5. leave unencoded
4037 !x',
4038 function ( $m ) use ( $vars ) {
4039 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4040 // check for both nonexistent keys *and* the empty string.
4041 if ( isset( $m[1] ) && $m[1] !== '' ) {
4042 if ( $m[1] === 'i' ) {
4043 return $this->indexName( $m[2] );
4044 } else {
4045 return $this->tableName( $m[2] );
4046 }
4047 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4048 return $this->addQuotes( $vars[$m[3]] );
4049 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4050 return $this->addIdentifierQuotes( $vars[$m[4]] );
4051 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4052 return $vars[$m[5]];
4053 } else {
4054 return $m[0];
4055 }
4056 },
4057 $ins
4058 );
4059 }
4060
4061 /**
4062 * Get schema variables. If none have been set via setSchemaVars(), then
4063 * use some defaults from the current object.
4064 *
4065 * @return array
4066 */
4067 protected function getSchemaVars() {
4068 if ( $this->schemaVars ) {
4069 return $this->schemaVars;
4070 } else {
4071 return $this->getDefaultSchemaVars();
4072 }
4073 }
4074
4075 /**
4076 * Get schema variables to use if none have been set via setSchemaVars().
4077 *
4078 * Override this in derived classes to provide variables for tables.sql
4079 * and SQL patch files.
4080 *
4081 * @return array
4082 */
4083 protected function getDefaultSchemaVars() {
4084 return [];
4085 }
4086
4087 public function lockIsFree( $lockName, $method ) {
4088 // RDBMs methods for checking named locks may or may not count this thread itself.
4089 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4090 // the behavior choosen by the interface for this method.
4091 return !isset( $this->namedLocksHeld[$lockName] );
4092 }
4093
4094 public function lock( $lockName, $method, $timeout = 5 ) {
4095 $this->namedLocksHeld[$lockName] = 1;
4096
4097 return true;
4098 }
4099
4100 public function unlock( $lockName, $method ) {
4101 unset( $this->namedLocksHeld[$lockName] );
4102
4103 return true;
4104 }
4105
4106 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4107 if ( $this->writesOrCallbacksPending() ) {
4108 // This only flushes transactions to clear snapshots, not to write data
4109 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4110 throw new DBUnexpectedError(
4111 $this,
4112 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4113 );
4114 }
4115
4116 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4117 return null;
4118 }
4119
4120 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4121 if ( $this->trxLevel() ) {
4122 // There is a good chance an exception was thrown, causing any early return
4123 // from the caller. Let any error handler get a chance to issue rollback().
4124 // If there isn't one, let the error bubble up and trigger server-side rollback.
4125 $this->onTransactionResolution(
4126 function () use ( $lockKey, $fname ) {
4127 $this->unlock( $lockKey, $fname );
4128 },
4129 $fname
4130 );
4131 } else {
4132 $this->unlock( $lockKey, $fname );
4133 }
4134 } );
4135
4136 $this->commit( $fname, self::FLUSHING_INTERNAL );
4137
4138 return $unlocker;
4139 }
4140
4141 public function namedLocksEnqueue() {
4142 return false;
4143 }
4144
4145 public function tableLocksHaveTransactionScope() {
4146 return true;
4147 }
4148
4149 final public function lockTables( array $read, array $write, $method ) {
4150 if ( $this->writesOrCallbacksPending() ) {
4151 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4152 }
4153
4154 if ( $this->tableLocksHaveTransactionScope() ) {
4155 $this->startAtomic( $method );
4156 }
4157
4158 return $this->doLockTables( $read, $write, $method );
4159 }
4160
4161 /**
4162 * Helper function for lockTables() that handles the actual table locking
4163 *
4164 * @param array $read Array of tables to lock for read access
4165 * @param array $write Array of tables to lock for write access
4166 * @param string $method Name of caller
4167 * @return true
4168 */
4169 protected function doLockTables( array $read, array $write, $method ) {
4170 return true;
4171 }
4172
4173 final public function unlockTables( $method ) {
4174 if ( $this->tableLocksHaveTransactionScope() ) {
4175 $this->endAtomic( $method );
4176
4177 return true; // locks released on COMMIT/ROLLBACK
4178 }
4179
4180 return $this->doUnlockTables( $method );
4181 }
4182
4183 /**
4184 * Helper function for unlockTables() that handles the actual table unlocking
4185 *
4186 * @param string $method Name of caller
4187 * @return true
4188 */
4189 protected function doUnlockTables( $method ) {
4190 return true;
4191 }
4192
4193 /**
4194 * Delete a table
4195 * @param string $tableName
4196 * @param string $fName
4197 * @return bool|ResultWrapper
4198 * @since 1.18
4199 */
4200 public function dropTable( $tableName, $fName = __METHOD__ ) {
4201 if ( !$this->tableExists( $tableName, $fName ) ) {
4202 return false;
4203 }
4204 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4205
4206 return $this->query( $sql, $fName );
4207 }
4208
4209 public function getInfinity() {
4210 return 'infinity';
4211 }
4212
4213 public function encodeExpiry( $expiry ) {
4214 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4215 ? $this->getInfinity()
4216 : $this->timestamp( $expiry );
4217 }
4218
4219 public function decodeExpiry( $expiry, $format = TS_MW ) {
4220 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
4221 return 'infinity';
4222 }
4223
4224 return ConvertibleTimestamp::convert( $format, $expiry );
4225 }
4226
4227 public function setBigSelects( $value = true ) {
4228 // no-op
4229 }
4230
4231 public function isReadOnly() {
4232 return ( $this->getReadOnlyReason() !== false );
4233 }
4234
4235 /**
4236 * @return string|bool Reason this DB is read-only or false if it is not
4237 */
4238 protected function getReadOnlyReason() {
4239 $reason = $this->getLBInfo( 'readOnlyReason' );
4240
4241 return is_string( $reason ) ? $reason : false;
4242 }
4243
4244 public function setTableAliases( array $aliases ) {
4245 $this->tableAliases = $aliases;
4246 }
4247
4248 public function setIndexAliases( array $aliases ) {
4249 $this->indexAliases = $aliases;
4250 }
4251
4252 /**
4253 * Get the underlying binding connection handle
4254 *
4255 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4256 * This catches broken callers than catch and ignore disconnection exceptions.
4257 * Unlike checking isOpen(), this is safe to call inside of open().
4258 *
4259 * @return mixed
4260 * @throws DBUnexpectedError
4261 * @since 1.26
4262 */
4263 protected function getBindingHandle() {
4264 if ( !$this->conn ) {
4265 throw new DBUnexpectedError(
4266 $this,
4267 'DB connection was already closed or the connection dropped.'
4268 );
4269 }
4270
4271 return $this->conn;
4272 }
4273
4274 /**
4275 * @since 1.19
4276 * @return string
4277 */
4278 public function __toString() {
4279 return (string)$this->conn;
4280 }
4281
4282 /**
4283 * Make sure that copies do not share the same client binding handle
4284 * @throws DBConnectionError
4285 */
4286 public function __clone() {
4287 $this->connLogger->warning(
4288 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4289 ( new RuntimeException() )->getTraceAsString()
4290 );
4291
4292 if ( $this->isOpen() ) {
4293 // Open a new connection resource without messing with the old one
4294 $this->opened = false;
4295 $this->conn = false;
4296 $this->trxEndCallbacks = []; // don't copy
4297 $this->handleSessionLoss(); // no trx or locks anymore
4298 $this->open( $this->server, $this->user, $this->password, $this->dbName );
4299 $this->lastPing = microtime( true );
4300 }
4301 }
4302
4303 /**
4304 * Called by serialize. Throw an exception when DB connection is serialized.
4305 * This causes problems on some database engines because the connection is
4306 * not restored on unserialize.
4307 */
4308 public function __sleep() {
4309 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4310 'the connection is not restored on wakeup.' );
4311 }
4312
4313 /**
4314 * Run a few simple sanity checks and close dangling connections
4315 */
4316 public function __destruct() {
4317 if ( $this->trxLevel && $this->trxDoneWrites ) {
4318 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4319 }
4320
4321 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4322 if ( $danglingWriters ) {
4323 $fnames = implode( ', ', $danglingWriters );
4324 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4325 }
4326
4327 if ( $this->conn ) {
4328 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4329 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4330 Wikimedia\suppressWarnings();
4331 $this->closeConnection();
4332 Wikimedia\restoreWarnings();
4333 $this->conn = false;
4334 $this->opened = false;
4335 }
4336 }
4337 }
4338
4339 class_alias( Database::class, 'DatabaseBase' ); // b/c for old name
4340 class_alias( Database::class, 'Database' ); // b/c global alias