9e9b7ab4afb265f9e230a309357ad5215f78e431
[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 InvalidArgumentException;
37 use Exception;
38 use RuntimeException;
39
40 /**
41 * Relational database abstraction object
42 *
43 * @ingroup Database
44 * @since 1.28
45 */
46 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
47 /** Number of times to re-try an operation in case of deadlock */
48 const DEADLOCK_TRIES = 4;
49 /** Minimum time to wait before retry, in microseconds */
50 const DEADLOCK_DELAY_MIN = 500000;
51 /** Maximum time to wait before retry */
52 const DEADLOCK_DELAY_MAX = 1500000;
53
54 /** How long before it is worth doing a dummy query to test the connection */
55 const PING_TTL = 1.0;
56 const PING_QUERY = 'SELECT 1 AS ping';
57
58 const TINY_WRITE_SEC = 0.010;
59 const SLOW_WRITE_SEC = 0.500;
60 const SMALL_WRITE_ROWS = 100;
61
62 /** @var string SQL query */
63 protected $lastQuery = '';
64 /** @var float|bool UNIX timestamp of last write query */
65 protected $lastWriteTime = false;
66 /** @var string|bool */
67 protected $phpError = false;
68 /** @var string */
69 protected $server;
70 /** @var string */
71 protected $user;
72 /** @var string */
73 protected $password;
74 /** @var string */
75 protected $dbName;
76 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
77 protected $tableAliases = [];
78 /** @var bool Whether this PHP instance is for a CLI script */
79 protected $cliMode;
80 /** @var string Agent name for query profiling */
81 protected $agent;
82
83 /** @var BagOStuff APC cache */
84 protected $srvCache;
85 /** @var LoggerInterface */
86 protected $connLogger;
87 /** @var LoggerInterface */
88 protected $queryLogger;
89 /** @var callback Error logging callback */
90 protected $errorLogger;
91
92 /** @var resource|null Database connection */
93 protected $conn = null;
94 /** @var bool */
95 protected $opened = false;
96
97 /** @var array[] List of (callable, method name) */
98 protected $trxIdleCallbacks = [];
99 /** @var array[] List of (callable, method name) */
100 protected $trxPreCommitCallbacks = [];
101 /** @var array[] List of (callable, method name) */
102 protected $trxEndCallbacks = [];
103 /** @var callable[] Map of (name => callable) */
104 protected $trxRecurringCallbacks = [];
105 /** @var bool Whether to suppress triggering of transaction end callbacks */
106 protected $trxEndCallbacksSuppressed = false;
107
108 /** @var string */
109 protected $tablePrefix = '';
110 /** @var string */
111 protected $schema = '';
112 /** @var int */
113 protected $flags;
114 /** @var array */
115 protected $lbInfo = [];
116 /** @var array|bool */
117 protected $schemaVars = false;
118 /** @var array */
119 protected $sessionVars = [];
120 /** @var array|null */
121 protected $preparedArgs;
122 /** @var string|bool|null Stashed value of html_errors INI setting */
123 protected $htmlErrors;
124 /** @var string */
125 protected $delimiter = ';';
126 /** @var DatabaseDomain */
127 protected $currentDomain;
128 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
129 protected $affectedRowCount;
130
131 /**
132 * Either 1 if a transaction is active or 0 otherwise.
133 * The other Trx fields may not be meaningfull if this is 0.
134 *
135 * @var int
136 */
137 protected $trxLevel = 0;
138 /**
139 * Either a short hexidecimal string if a transaction is active or ""
140 *
141 * @var string
142 * @see Database::trxLevel
143 */
144 protected $trxShortId = '';
145 /**
146 * The UNIX time that the transaction started. Callers can assume that if
147 * snapshot isolation is used, then the data is *at least* up to date to that
148 * point (possibly more up-to-date since the first SELECT defines the snapshot).
149 *
150 * @var float|null
151 * @see Database::trxLevel
152 */
153 private $trxTimestamp = null;
154 /** @var float Lag estimate at the time of BEGIN */
155 private $trxReplicaLag = null;
156 /**
157 * Remembers the function name given for starting the most recent transaction via begin().
158 * Used to provide additional context for error reporting.
159 *
160 * @var string
161 * @see Database::trxLevel
162 */
163 private $trxFname = null;
164 /**
165 * Record if possible write queries were done in the last transaction started
166 *
167 * @var bool
168 * @see Database::trxLevel
169 */
170 private $trxDoneWrites = false;
171 /**
172 * Record if the current transaction was started implicitly due to DBO_TRX being set.
173 *
174 * @var bool
175 * @see Database::trxLevel
176 */
177 private $trxAutomatic = false;
178 /**
179 * Array of levels of atomicity within transactions
180 *
181 * @var array
182 */
183 private $trxAtomicLevels = [];
184 /**
185 * Record if the current transaction was started implicitly by Database::startAtomic
186 *
187 * @var bool
188 */
189 private $trxAutomaticAtomic = false;
190 /**
191 * Track the write query callers of the current transaction
192 *
193 * @var string[]
194 */
195 private $trxWriteCallers = [];
196 /**
197 * @var float Seconds spent in write queries for the current transaction
198 */
199 private $trxWriteDuration = 0.0;
200 /**
201 * @var int Number of write queries for the current transaction
202 */
203 private $trxWriteQueryCount = 0;
204 /**
205 * @var int Number of rows affected by write queries for the current transaction
206 */
207 private $trxWriteAffectedRows = 0;
208 /**
209 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
210 */
211 private $trxWriteAdjDuration = 0.0;
212 /**
213 * @var int Number of write queries counted in trxWriteAdjDuration
214 */
215 private $trxWriteAdjQueryCount = 0;
216 /**
217 * @var float RTT time estimate
218 */
219 private $rttEstimate = 0.0;
220
221 /** @var array Map of (name => 1) for locks obtained via lock() */
222 private $namedLocksHeld = [];
223 /** @var array Map of (table name => 1) for TEMPORARY tables */
224 protected $sessionTempTables = [];
225
226 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
227 private $lazyMasterHandle;
228
229 /** @var float UNIX timestamp */
230 protected $lastPing = 0.0;
231
232 /** @var int[] Prior flags member variable values */
233 private $priorFlags = [];
234
235 /** @var object|string Class name or object With profileIn/profileOut methods */
236 protected $profiler;
237 /** @var TransactionProfiler */
238 protected $trxProfiler;
239
240 /** @var int */
241 protected $nonNativeInsertSelectBatchSize = 10000;
242
243 /**
244 * Constructor and database handle and attempt to connect to the DB server
245 *
246 * IDatabase classes should not be constructed directly in external
247 * code. Database::factory() should be used instead.
248 *
249 * @param array $params Parameters passed from Database::factory()
250 */
251 function __construct( array $params ) {
252 $server = $params['host'];
253 $user = $params['user'];
254 $password = $params['password'];
255 $dbName = $params['dbname'];
256
257 $this->schema = $params['schema'];
258 $this->tablePrefix = $params['tablePrefix'];
259
260 $this->cliMode = $params['cliMode'];
261 // Agent name is added to SQL queries in a comment, so make sure it can't break out
262 $this->agent = str_replace( '/', '-', $params['agent'] );
263
264 $this->flags = $params['flags'];
265 if ( $this->flags & self::DBO_DEFAULT ) {
266 if ( $this->cliMode ) {
267 $this->flags &= ~self::DBO_TRX;
268 } else {
269 $this->flags |= self::DBO_TRX;
270 }
271 }
272
273 $this->sessionVars = $params['variables'];
274
275 $this->srvCache = isset( $params['srvCache'] )
276 ? $params['srvCache']
277 : new HashBagOStuff();
278
279 $this->profiler = $params['profiler'];
280 $this->trxProfiler = $params['trxProfiler'];
281 $this->connLogger = $params['connLogger'];
282 $this->queryLogger = $params['queryLogger'];
283 $this->errorLogger = $params['errorLogger'];
284
285 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
286 $this->nonNativeInsertSelectBatchSize = $params['nonNativeInsertSelectBatchSize'];
287 }
288
289 // Set initial dummy domain until open() sets the final DB/prefix
290 $this->currentDomain = DatabaseDomain::newUnspecified();
291
292 if ( $user ) {
293 $this->open( $server, $user, $password, $dbName );
294 } elseif ( $this->requiresDatabaseUser() ) {
295 throw new InvalidArgumentException( "No database user provided." );
296 }
297
298 // Set the domain object after open() sets the relevant fields
299 if ( $this->dbName != '' ) {
300 // Domains with server scope but a table prefix are not used by IDatabase classes
301 $this->currentDomain = new DatabaseDomain( $this->dbName, null, $this->tablePrefix );
302 }
303 }
304
305 /**
306 * Construct a Database subclass instance given a database type and parameters
307 *
308 * This also connects to the database immediately upon object construction
309 *
310 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
311 * @param array $p Parameter map with keys:
312 * - host : The hostname of the DB server
313 * - user : The name of the database user the client operates under
314 * - password : The password for the database user
315 * - dbname : The name of the database to use where queries do not specify one.
316 * The database must exist or an error might be thrown. Setting this to the empty string
317 * will avoid any such errors and make the handle have no implicit database scope. This is
318 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
319 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
320 * in which user names and such are defined, e.g. users are database-specific in Postgres.
321 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
322 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
323 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
324 * recognized in queries. This can be used in place of schemas for handle site farms.
325 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
326 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
327 * flag in place UNLESS this this database simply acts as a key/value store.
328 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
329 * 'mysqli' driver; the old one 'mysql' has been removed.
330 * - variables: Optional map of session variables to set after connecting. This can be
331 * used to adjust lock timeouts or encoding modes and the like.
332 * - connLogger: Optional PSR-3 logger interface instance.
333 * - queryLogger: Optional PSR-3 logger interface instance.
334 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
335 * These will be called in query(), using a simplified version of the SQL that also
336 * includes the agent as a SQL comment.
337 * - trxProfiler: Optional TransactionProfiler instance.
338 * - errorLogger: Optional callback that takes an Exception and logs it.
339 * - cliMode: Whether to consider the execution context that of a CLI script.
340 * - agent: Optional name used to identify the end-user in query profiling/logging.
341 * - srvCache: Optional BagOStuff instance to an APC-style cache.
342 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
343 * @return Database|null If the database driver or extension cannot be found
344 * @throws InvalidArgumentException If the database driver or extension cannot be found
345 * @since 1.18
346 */
347 final public static function factory( $dbType, $p = [] ) {
348 $class = self::getClass( $dbType, isset( $p['driver'] ) ? $p['driver'] : null );
349
350 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
351 // Resolve some defaults for b/c
352 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
353 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
354 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
355 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
356 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
357 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
358 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
359 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
360 $p['cliMode'] = isset( $p['cliMode'] )
361 ? $p['cliMode']
362 : ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' );
363 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
364 if ( !isset( $p['connLogger'] ) ) {
365 $p['connLogger'] = new NullLogger();
366 }
367 if ( !isset( $p['queryLogger'] ) ) {
368 $p['queryLogger'] = new NullLogger();
369 }
370 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
371 if ( !isset( $p['trxProfiler'] ) ) {
372 $p['trxProfiler'] = new TransactionProfiler();
373 }
374 if ( !isset( $p['errorLogger'] ) ) {
375 $p['errorLogger'] = function ( Exception $e ) {
376 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
377 };
378 }
379
380 $conn = new $class( $p );
381 } else {
382 $conn = null;
383 }
384
385 return $conn;
386 }
387
388 /**
389 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
390 * @param string|null $driver Optional name of a specific DB client driver
391 * @return string Database subclass name to use
392 * @throws InvalidArgumentException
393 */
394 private static function getClass( $dbType, $driver = null ) {
395 // For database types with built-in support, the below maps type to IDatabase
396 // implementations. For types with multipe driver implementations (PHP extensions),
397 // an array can be used, keyed by extension name. In case of an array, the
398 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
399 // we auto-detect the first available driver. For types without built-in support,
400 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
401 static $builtinTypes = [
402 'mssql' => DatabaseMssql::class,
403 'mysql' => [ 'mysqli' => DatabaseMysqli::class ],
404 'sqlite' => DatabaseSqlite::class,
405 'postgres' => DatabasePostgres::class,
406 ];
407
408 $dbType = strtolower( $dbType );
409 $class = false;
410
411 if ( isset( $builtinTypes[$dbType] ) ) {
412 $possibleDrivers = $builtinTypes[$dbType];
413 if ( is_string( $possibleDrivers ) ) {
414 $class = $possibleDrivers;
415 } else {
416 if ( (string)$driver !== '' ) {
417 if ( !isset( $possibleDrivers[$driver] ) ) {
418 throw new InvalidArgumentException( __METHOD__ .
419 " type '$dbType' does not support driver '{$driver}'" );
420 } else {
421 $class = $possibleDrivers[$driver];
422 }
423 } else {
424 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
425 if ( extension_loaded( $posDriver ) ) {
426 $class = $possibleClass;
427 break;
428 }
429 }
430 }
431 }
432 } else {
433 $class = 'Database' . ucfirst( $dbType );
434 }
435
436 if ( $class === false ) {
437 throw new InvalidArgumentException( __METHOD__ .
438 " no viable database extension found for type '$dbType'" );
439 }
440
441 return $class;
442 }
443
444 /**
445 * Set the PSR-3 logger interface to use for query logging. (The logger
446 * interfaces for connection logging and error logging can be set with the
447 * constructor.)
448 *
449 * @param LoggerInterface $logger
450 */
451 public function setLogger( LoggerInterface $logger ) {
452 $this->queryLogger = $logger;
453 }
454
455 public function getServerInfo() {
456 return $this->getServerVersion();
457 }
458
459 public function bufferResults( $buffer = null ) {
460 $res = !$this->getFlag( self::DBO_NOBUFFER );
461 if ( $buffer !== null ) {
462 $buffer
463 ? $this->clearFlag( self::DBO_NOBUFFER )
464 : $this->setFlag( self::DBO_NOBUFFER );
465 }
466
467 return $res;
468 }
469
470 /**
471 * Turns on (false) or off (true) the automatic generation and sending
472 * of a "we're sorry, but there has been a database error" page on
473 * database errors. Default is on (false). When turned off, the
474 * code should use lastErrno() and lastError() to handle the
475 * situation as appropriate.
476 *
477 * Do not use this function outside of the Database classes.
478 *
479 * @param null|bool $ignoreErrors
480 * @return bool The previous value of the flag.
481 */
482 protected function ignoreErrors( $ignoreErrors = null ) {
483 $res = $this->getFlag( self::DBO_IGNORE );
484 if ( $ignoreErrors !== null ) {
485 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
486 if ( $ignoreErrors ) {
487 $this->flags |= self::DBO_IGNORE;
488 } else {
489 $this->flags &= ~self::DBO_IGNORE;
490 }
491 }
492
493 return $res;
494 }
495
496 public function trxLevel() {
497 return $this->trxLevel;
498 }
499
500 public function trxTimestamp() {
501 return $this->trxLevel ? $this->trxTimestamp : null;
502 }
503
504 public function tablePrefix( $prefix = null ) {
505 $old = $this->tablePrefix;
506 if ( $prefix !== null ) {
507 $this->tablePrefix = $prefix;
508 $this->currentDomain = ( $this->dbName != '' )
509 ? new DatabaseDomain( $this->dbName, null, $this->tablePrefix )
510 : DatabaseDomain::newUnspecified();
511 }
512
513 return $old;
514 }
515
516 public function dbSchema( $schema = null ) {
517 $old = $this->schema;
518 if ( $schema !== null ) {
519 $this->schema = $schema;
520 }
521
522 return $old;
523 }
524
525 public function getLBInfo( $name = null ) {
526 if ( is_null( $name ) ) {
527 return $this->lbInfo;
528 } else {
529 if ( array_key_exists( $name, $this->lbInfo ) ) {
530 return $this->lbInfo[$name];
531 } else {
532 return null;
533 }
534 }
535 }
536
537 public function setLBInfo( $name, $value = null ) {
538 if ( is_null( $value ) ) {
539 $this->lbInfo = $name;
540 } else {
541 $this->lbInfo[$name] = $value;
542 }
543 }
544
545 public function setLazyMasterHandle( IDatabase $conn ) {
546 $this->lazyMasterHandle = $conn;
547 }
548
549 /**
550 * @return IDatabase|null
551 * @see setLazyMasterHandle()
552 * @since 1.27
553 */
554 protected function getLazyMasterHandle() {
555 return $this->lazyMasterHandle;
556 }
557
558 public function implicitGroupby() {
559 return true;
560 }
561
562 public function implicitOrderby() {
563 return true;
564 }
565
566 public function lastQuery() {
567 return $this->lastQuery;
568 }
569
570 public function doneWrites() {
571 return (bool)$this->lastWriteTime;
572 }
573
574 public function lastDoneWrites() {
575 return $this->lastWriteTime ?: false;
576 }
577
578 public function writesPending() {
579 return $this->trxLevel && $this->trxDoneWrites;
580 }
581
582 public function writesOrCallbacksPending() {
583 return $this->trxLevel && (
584 $this->trxDoneWrites || $this->trxIdleCallbacks || $this->trxPreCommitCallbacks
585 );
586 }
587
588 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
589 if ( !$this->trxLevel ) {
590 return false;
591 } elseif ( !$this->trxDoneWrites ) {
592 return 0.0;
593 }
594
595 switch ( $type ) {
596 case self::ESTIMATE_DB_APPLY:
597 $this->ping( $rtt );
598 $rttAdjTotal = $this->trxWriteAdjQueryCount * $rtt;
599 $applyTime = max( $this->trxWriteAdjDuration - $rttAdjTotal, 0 );
600 // For omitted queries, make them count as something at least
601 $omitted = $this->trxWriteQueryCount - $this->trxWriteAdjQueryCount;
602 $applyTime += self::TINY_WRITE_SEC * $omitted;
603
604 return $applyTime;
605 default: // everything
606 return $this->trxWriteDuration;
607 }
608 }
609
610 public function pendingWriteCallers() {
611 return $this->trxLevel ? $this->trxWriteCallers : [];
612 }
613
614 public function pendingWriteRowsAffected() {
615 return $this->trxWriteAffectedRows;
616 }
617
618 /**
619 * Get the list of method names that have pending write queries or callbacks
620 * for this transaction
621 *
622 * @return array
623 */
624 protected function pendingWriteAndCallbackCallers() {
625 if ( !$this->trxLevel ) {
626 return [];
627 }
628
629 $fnames = $this->trxWriteCallers;
630 foreach ( [
631 $this->trxIdleCallbacks,
632 $this->trxPreCommitCallbacks,
633 $this->trxEndCallbacks
634 ] as $callbacks ) {
635 foreach ( $callbacks as $callback ) {
636 $fnames[] = $callback[1];
637 }
638 }
639
640 return $fnames;
641 }
642
643 public function isOpen() {
644 return $this->opened;
645 }
646
647 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
648 if ( ( $flag & self::DBO_IGNORE ) ) {
649 throw new \UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
650 }
651
652 if ( $remember === self::REMEMBER_PRIOR ) {
653 array_push( $this->priorFlags, $this->flags );
654 }
655 $this->flags |= $flag;
656 }
657
658 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
659 if ( ( $flag & self::DBO_IGNORE ) ) {
660 throw new \UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
661 }
662
663 if ( $remember === self::REMEMBER_PRIOR ) {
664 array_push( $this->priorFlags, $this->flags );
665 }
666 $this->flags &= ~$flag;
667 }
668
669 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
670 if ( !$this->priorFlags ) {
671 return;
672 }
673
674 if ( $state === self::RESTORE_INITIAL ) {
675 $this->flags = reset( $this->priorFlags );
676 $this->priorFlags = [];
677 } else {
678 $this->flags = array_pop( $this->priorFlags );
679 }
680 }
681
682 public function getFlag( $flag ) {
683 return !!( $this->flags & $flag );
684 }
685
686 /**
687 * @param string $name Class field name
688 * @return mixed
689 * @deprecated Since 1.28
690 */
691 public function getProperty( $name ) {
692 return $this->$name;
693 }
694
695 public function getDomainID() {
696 return $this->currentDomain->getId();
697 }
698
699 final public function getWikiID() {
700 return $this->getDomainID();
701 }
702
703 /**
704 * Get information about an index into an object
705 * @param string $table Table name
706 * @param string $index Index name
707 * @param string $fname Calling function name
708 * @return mixed Database-specific index description class or false if the index does not exist
709 */
710 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
711
712 /**
713 * Wrapper for addslashes()
714 *
715 * @param string $s String to be slashed.
716 * @return string Slashed string.
717 */
718 abstract function strencode( $s );
719
720 /**
721 * Set a custom error handler for logging errors during database connection
722 */
723 protected function installErrorHandler() {
724 $this->phpError = false;
725 $this->htmlErrors = ini_set( 'html_errors', '0' );
726 set_error_handler( [ $this, 'connectionErrorLogger' ] );
727 }
728
729 /**
730 * Restore the previous error handler and return the last PHP error for this DB
731 *
732 * @return bool|string
733 */
734 protected function restoreErrorHandler() {
735 restore_error_handler();
736 if ( $this->htmlErrors !== false ) {
737 ini_set( 'html_errors', $this->htmlErrors );
738 }
739
740 return $this->getLastPHPError();
741 }
742
743 /**
744 * @return string|bool Last PHP error for this DB (typically connection errors)
745 */
746 protected function getLastPHPError() {
747 if ( $this->phpError ) {
748 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError );
749 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
750
751 return $error;
752 }
753
754 return false;
755 }
756
757 /**
758 * Error handler for logging errors during database connection
759 * This method should not be used outside of Database classes
760 *
761 * @param int $errno
762 * @param string $errstr
763 */
764 public function connectionErrorLogger( $errno, $errstr ) {
765 $this->phpError = $errstr;
766 }
767
768 /**
769 * Create a log context to pass to PSR-3 logger functions.
770 *
771 * @param array $extras Additional data to add to context
772 * @return array
773 */
774 protected function getLogContext( array $extras = [] ) {
775 return array_merge(
776 [
777 'db_server' => $this->server,
778 'db_name' => $this->dbName,
779 'db_user' => $this->user,
780 ],
781 $extras
782 );
783 }
784
785 public function close() {
786 if ( $this->conn ) {
787 if ( $this->trxLevel() ) {
788 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
789 }
790
791 $closed = $this->closeConnection();
792 $this->conn = false;
793 } elseif (
794 $this->trxIdleCallbacks ||
795 $this->trxPreCommitCallbacks ||
796 $this->trxEndCallbacks
797 ) { // sanity
798 throw new RuntimeException( "Transaction callbacks still pending." );
799 } else {
800 $closed = true;
801 }
802 $this->opened = false;
803
804 return $closed;
805 }
806
807 /**
808 * Make sure isOpen() returns true as a sanity check
809 *
810 * @throws DBUnexpectedError
811 */
812 protected function assertOpen() {
813 if ( !$this->isOpen() ) {
814 throw new DBUnexpectedError( $this, "DB connection was already closed." );
815 }
816 }
817
818 /**
819 * Closes underlying database connection
820 * @since 1.20
821 * @return bool Whether connection was closed successfully
822 */
823 abstract protected function closeConnection();
824
825 public function reportConnectionError( $error = 'Unknown error' ) {
826 $myError = $this->lastError();
827 if ( $myError ) {
828 $error = $myError;
829 }
830
831 # New method
832 throw new DBConnectionError( $this, $error );
833 }
834
835 /**
836 * The DBMS-dependent part of query()
837 *
838 * @param string $sql SQL query.
839 * @return ResultWrapper|bool Result object to feed to fetchObject,
840 * fetchRow, ...; or false on failure
841 */
842 abstract protected function doQuery( $sql );
843
844 /**
845 * Determine whether a query writes to the DB.
846 * Should return true if unsure.
847 *
848 * @param string $sql
849 * @return bool
850 */
851 protected function isWriteQuery( $sql ) {
852 return !preg_match(
853 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
854 }
855
856 /**
857 * @param string $sql
858 * @return string|null
859 */
860 protected function getQueryVerb( $sql ) {
861 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
862 }
863
864 /**
865 * Determine whether a SQL statement is sensitive to isolation level.
866 * A SQL statement is considered transactable if its result could vary
867 * depending on the transaction isolation level. Operational commands
868 * such as 'SET' and 'SHOW' are not considered to be transactable.
869 *
870 * @param string $sql
871 * @return bool
872 */
873 protected function isTransactableQuery( $sql ) {
874 return !in_array(
875 $this->getQueryVerb( $sql ),
876 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
877 true
878 );
879 }
880
881 /**
882 * @param string $sql A SQL query
883 * @return bool Whether $sql is SQL for TEMPORARY table operation
884 */
885 protected function registerTempTableOperation( $sql ) {
886 if ( preg_match(
887 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
888 $sql,
889 $matches
890 ) ) {
891 $this->sessionTempTables[$matches[1]] = 1;
892
893 return true;
894 } elseif ( preg_match(
895 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
896 $sql,
897 $matches
898 ) ) {
899 $isTemp = isset( $this->sessionTempTables[$matches[1]] );
900 unset( $this->sessionTempTables[$matches[1]] );
901
902 return $isTemp;
903 } elseif ( preg_match(
904 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
905 $sql,
906 $matches
907 ) ) {
908 return isset( $this->sessionTempTables[$matches[1]] );
909 } elseif ( preg_match(
910 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
911 $sql,
912 $matches
913 ) ) {
914 return isset( $this->sessionTempTables[$matches[1]] );
915 }
916
917 return false;
918 }
919
920 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
921 $priorWritesPending = $this->writesOrCallbacksPending();
922 $this->lastQuery = $sql;
923
924 $isWrite = $this->isWriteQuery( $sql );
925 if ( $isWrite ) {
926 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
927 } else {
928 $isNonTempWrite = false;
929 }
930
931 if ( $isWrite ) {
932 if ( $this->getLBInfo( 'replica' ) === true ) {
933 throw new DBError(
934 $this,
935 'Write operations are not allowed on replica database connections.'
936 );
937 }
938 # In theory, non-persistent writes are allowed in read-only mode, but due to things
939 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
940 $reason = $this->getReadOnlyReason();
941 if ( $reason !== false ) {
942 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
943 }
944 # Set a flag indicating that writes have been done
945 $this->lastWriteTime = microtime( true );
946 }
947
948 # Add trace comment to the begin of the sql string, right after the operator.
949 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
950 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
951
952 # Start implicit transactions that wrap the request if DBO_TRX is enabled
953 if ( !$this->trxLevel && $this->getFlag( self::DBO_TRX )
954 && $this->isTransactableQuery( $sql )
955 ) {
956 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
957 $this->trxAutomatic = true;
958 }
959
960 # Keep track of whether the transaction has write queries pending
961 if ( $this->trxLevel && !$this->trxDoneWrites && $isWrite ) {
962 $this->trxDoneWrites = true;
963 $this->trxProfiler->transactionWritingIn(
964 $this->server, $this->dbName, $this->trxShortId );
965 }
966
967 if ( $this->getFlag( self::DBO_DEBUG ) ) {
968 $this->queryLogger->debug( "{$this->dbName} {$commentedSql}" );
969 }
970
971 # Avoid fatals if close() was called
972 $this->assertOpen();
973
974 # Send the query to the server
975 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
976
977 # Try reconnecting if the connection was lost
978 if ( false === $ret && $this->wasErrorReissuable() ) {
979 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
980 # Stash the last error values before anything might clear them
981 $lastError = $this->lastError();
982 $lastErrno = $this->lastErrno();
983 # Update state tracking to reflect transaction loss due to disconnection
984 $this->handleSessionLoss();
985 if ( $this->reconnect() ) {
986 $msg = __METHOD__ . ': lost connection to {dbserver}; reconnected';
987 $params = [ 'dbserver' => $this->getServer() ];
988 $this->connLogger->warning( $msg, $params );
989 $this->queryLogger->warning( $msg, $params +
990 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
991
992 if ( !$recoverable ) {
993 # Callers may catch the exception and continue to use the DB
994 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
995 } else {
996 # Should be safe to silently retry the query
997 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
998 }
999 } else {
1000 $msg = __METHOD__ . ': lost connection to {dbserver} permanently';
1001 $this->connLogger->error( $msg, [ 'dbserver' => $this->getServer() ] );
1002 }
1003 }
1004
1005 if ( false === $ret ) {
1006 # Deadlocks cause the entire transaction to abort, not just the statement.
1007 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1008 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1009 if ( $this->wasDeadlock() ) {
1010 if ( $this->explicitTrxActive() || $priorWritesPending ) {
1011 $tempIgnore = false; // not recoverable
1012 }
1013 # Update state tracking to reflect transaction loss
1014 $this->handleSessionLoss();
1015 }
1016
1017 $this->reportQueryError(
1018 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1019 }
1020
1021 $res = $this->resultObject( $ret );
1022
1023 return $res;
1024 }
1025
1026 /**
1027 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1028 *
1029 * @param string $sql Original SQL query
1030 * @param string $commentedSql SQL query with debugging/trace comment
1031 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1032 * @param string $fname Name of the calling function
1033 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1034 * object for a successful read query, or false on failure
1035 */
1036 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1037 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1038 # generalizeSQL() will probably cut down the query to reasonable
1039 # logging size most of the time. The substr is really just a sanity check.
1040 if ( $isMaster ) {
1041 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1042 } else {
1043 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1044 }
1045
1046 # Include query transaction state
1047 $queryProf .= $this->trxShortId ? " [TRX#{$this->trxShortId}]" : "";
1048
1049 $startTime = microtime( true );
1050 if ( $this->profiler ) {
1051 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
1052 }
1053 $this->affectedRowCount = null;
1054 $ret = $this->doQuery( $commentedSql );
1055 $this->affectedRowCount = $this->affectedRows();
1056 if ( $this->profiler ) {
1057 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
1058 }
1059 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1060
1061 unset( $queryProfSection ); // profile out (if set)
1062
1063 if ( $ret !== false ) {
1064 $this->lastPing = $startTime;
1065 if ( $isWrite && $this->trxLevel ) {
1066 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1067 $this->trxWriteCallers[] = $fname;
1068 }
1069 }
1070
1071 if ( $sql === self::PING_QUERY ) {
1072 $this->rttEstimate = $queryRuntime;
1073 }
1074
1075 $this->trxProfiler->recordQueryCompletion(
1076 $queryProf, $startTime, $isWrite, $this->affectedRows()
1077 );
1078 $this->queryLogger->debug( $sql, [
1079 'method' => $fname,
1080 'master' => $isMaster,
1081 'runtime' => $queryRuntime,
1082 ] );
1083
1084 return $ret;
1085 }
1086
1087 /**
1088 * Update the estimated run-time of a query, not counting large row lock times
1089 *
1090 * LoadBalancer can be set to rollback transactions that will create huge replication
1091 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1092 * queries, like inserting a row can take a long time due to row locking. This method
1093 * uses some simple heuristics to discount those cases.
1094 *
1095 * @param string $sql A SQL write query
1096 * @param float $runtime Total runtime, including RTT
1097 * @param int $affected Affected row count
1098 */
1099 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1100 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1101 $indicativeOfReplicaRuntime = true;
1102 if ( $runtime > self::SLOW_WRITE_SEC ) {
1103 $verb = $this->getQueryVerb( $sql );
1104 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1105 if ( $verb === 'INSERT' ) {
1106 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1107 } elseif ( $verb === 'REPLACE' ) {
1108 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1109 }
1110 }
1111
1112 $this->trxWriteDuration += $runtime;
1113 $this->trxWriteQueryCount += 1;
1114 $this->trxWriteAffectedRows += $affected;
1115 if ( $indicativeOfReplicaRuntime ) {
1116 $this->trxWriteAdjDuration += $runtime;
1117 $this->trxWriteAdjQueryCount += 1;
1118 }
1119 }
1120
1121 /**
1122 * Determine whether or not it is safe to retry queries after a database
1123 * connection is lost
1124 *
1125 * @param string $sql SQL query
1126 * @param bool $priorWritesPending Whether there is a transaction open with
1127 * possible write queries or transaction pre-commit/idle callbacks
1128 * waiting on it to finish.
1129 * @return bool True if it is safe to retry the query, false otherwise
1130 */
1131 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1132 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1133 # Dropped connections also mean that named locks are automatically released.
1134 # Only allow error suppression in autocommit mode or when the lost transaction
1135 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1136 if ( $this->namedLocksHeld ) {
1137 return false; // possible critical section violation
1138 } elseif ( $sql === 'COMMIT' ) {
1139 return !$priorWritesPending; // nothing written anyway? (T127428)
1140 } elseif ( $sql === 'ROLLBACK' ) {
1141 return true; // transaction lost...which is also what was requested :)
1142 } elseif ( $this->explicitTrxActive() ) {
1143 return false; // don't drop atomocity
1144 } elseif ( $priorWritesPending ) {
1145 return false; // prior writes lost from implicit transaction
1146 }
1147
1148 return true;
1149 }
1150
1151 /**
1152 * Clean things up after transaction loss due to disconnection
1153 *
1154 * @return null|Exception
1155 */
1156 private function handleSessionLoss() {
1157 $this->trxLevel = 0;
1158 $this->trxIdleCallbacks = []; // T67263
1159 $this->trxPreCommitCallbacks = []; // T67263
1160 $this->sessionTempTables = [];
1161 $this->namedLocksHeld = [];
1162 try {
1163 // Handle callbacks in trxEndCallbacks
1164 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1165 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1166 return null;
1167 } catch ( Exception $e ) {
1168 // Already logged; move on...
1169 return $e;
1170 }
1171 }
1172
1173 /**
1174 * Checks whether the cause of the error is detected to be a timeout.
1175 *
1176 * It returns false by default, and not all engines support detecting this yet.
1177 * If this returns false, it will be treated as a generic query error.
1178 *
1179 * @param string $error Error text
1180 * @param int $errno Error number
1181 * @return bool
1182 */
1183 protected function wasQueryTimeout( $error, $errno ) {
1184 return false;
1185 }
1186
1187 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1188 if ( $this->ignoreErrors() || $tempIgnore ) {
1189 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1190 } else {
1191 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1192 $this->queryLogger->error(
1193 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1194 $this->getLogContext( [
1195 'method' => __METHOD__,
1196 'errno' => $errno,
1197 'error' => $error,
1198 'sql1line' => $sql1line,
1199 'fname' => $fname,
1200 ] )
1201 );
1202 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1203 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1204 if ( $wasQueryTimeout ) {
1205 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1206 } else {
1207 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1208 }
1209 }
1210 }
1211
1212 public function freeResult( $res ) {
1213 }
1214
1215 public function selectField(
1216 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1217 ) {
1218 if ( $var === '*' ) { // sanity
1219 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1220 }
1221
1222 if ( !is_array( $options ) ) {
1223 $options = [ $options ];
1224 }
1225
1226 $options['LIMIT'] = 1;
1227
1228 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1229 if ( $res === false || !$this->numRows( $res ) ) {
1230 return false;
1231 }
1232
1233 $row = $this->fetchRow( $res );
1234
1235 if ( $row !== false ) {
1236 return reset( $row );
1237 } else {
1238 return false;
1239 }
1240 }
1241
1242 public function selectFieldValues(
1243 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1244 ) {
1245 if ( $var === '*' ) { // sanity
1246 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1247 } elseif ( !is_string( $var ) ) { // sanity
1248 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1249 }
1250
1251 if ( !is_array( $options ) ) {
1252 $options = [ $options ];
1253 }
1254
1255 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1256 if ( $res === false ) {
1257 return false;
1258 }
1259
1260 $values = [];
1261 foreach ( $res as $row ) {
1262 $values[] = $row->$var;
1263 }
1264
1265 return $values;
1266 }
1267
1268 /**
1269 * Returns an optional USE INDEX clause to go after the table, and a
1270 * string to go at the end of the query.
1271 *
1272 * @param array $options Associative array of options to be turned into
1273 * an SQL query, valid keys are listed in the function.
1274 * @return array
1275 * @see Database::select()
1276 */
1277 protected function makeSelectOptions( $options ) {
1278 $preLimitTail = $postLimitTail = '';
1279 $startOpts = '';
1280
1281 $noKeyOptions = [];
1282
1283 foreach ( $options as $key => $option ) {
1284 if ( is_numeric( $key ) ) {
1285 $noKeyOptions[$option] = true;
1286 }
1287 }
1288
1289 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1290
1291 $preLimitTail .= $this->makeOrderBy( $options );
1292
1293 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1294 $postLimitTail .= ' FOR UPDATE';
1295 }
1296
1297 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1298 $postLimitTail .= ' LOCK IN SHARE MODE';
1299 }
1300
1301 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1302 $startOpts .= 'DISTINCT';
1303 }
1304
1305 # Various MySQL extensions
1306 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1307 $startOpts .= ' /*! STRAIGHT_JOIN */';
1308 }
1309
1310 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1311 $startOpts .= ' HIGH_PRIORITY';
1312 }
1313
1314 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1315 $startOpts .= ' SQL_BIG_RESULT';
1316 }
1317
1318 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1319 $startOpts .= ' SQL_BUFFER_RESULT';
1320 }
1321
1322 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1323 $startOpts .= ' SQL_SMALL_RESULT';
1324 }
1325
1326 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1327 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1328 }
1329
1330 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1331 $startOpts .= ' SQL_CACHE';
1332 }
1333
1334 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1335 $startOpts .= ' SQL_NO_CACHE';
1336 }
1337
1338 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1339 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1340 } else {
1341 $useIndex = '';
1342 }
1343 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1344 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1345 } else {
1346 $ignoreIndex = '';
1347 }
1348
1349 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1350 }
1351
1352 /**
1353 * Returns an optional GROUP BY with an optional HAVING
1354 *
1355 * @param array $options Associative array of options
1356 * @return string
1357 * @see Database::select()
1358 * @since 1.21
1359 */
1360 protected function makeGroupByWithHaving( $options ) {
1361 $sql = '';
1362 if ( isset( $options['GROUP BY'] ) ) {
1363 $gb = is_array( $options['GROUP BY'] )
1364 ? implode( ',', $options['GROUP BY'] )
1365 : $options['GROUP BY'];
1366 $sql .= ' GROUP BY ' . $gb;
1367 }
1368 if ( isset( $options['HAVING'] ) ) {
1369 $having = is_array( $options['HAVING'] )
1370 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1371 : $options['HAVING'];
1372 $sql .= ' HAVING ' . $having;
1373 }
1374
1375 return $sql;
1376 }
1377
1378 /**
1379 * Returns an optional ORDER BY
1380 *
1381 * @param array $options Associative array of options
1382 * @return string
1383 * @see Database::select()
1384 * @since 1.21
1385 */
1386 protected function makeOrderBy( $options ) {
1387 if ( isset( $options['ORDER BY'] ) ) {
1388 $ob = is_array( $options['ORDER BY'] )
1389 ? implode( ',', $options['ORDER BY'] )
1390 : $options['ORDER BY'];
1391
1392 return ' ORDER BY ' . $ob;
1393 }
1394
1395 return '';
1396 }
1397
1398 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1399 $options = [], $join_conds = [] ) {
1400 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1401
1402 return $this->query( $sql, $fname );
1403 }
1404
1405 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1406 $options = [], $join_conds = []
1407 ) {
1408 if ( is_array( $vars ) ) {
1409 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1410 }
1411
1412 $options = (array)$options;
1413 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1414 ? $options['USE INDEX']
1415 : [];
1416 $ignoreIndexes = (
1417 isset( $options['IGNORE INDEX'] ) &&
1418 is_array( $options['IGNORE INDEX'] )
1419 )
1420 ? $options['IGNORE INDEX']
1421 : [];
1422
1423 if ( is_array( $table ) ) {
1424 $from = ' FROM ' .
1425 $this->tableNamesWithIndexClauseOrJOIN(
1426 $table, $useIndexes, $ignoreIndexes, $join_conds );
1427 } elseif ( $table != '' ) {
1428 $from = ' FROM ' .
1429 $this->tableNamesWithIndexClauseOrJOIN(
1430 [ $table ], $useIndexes, $ignoreIndexes, [] );
1431 } else {
1432 $from = '';
1433 }
1434
1435 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1436 $this->makeSelectOptions( $options );
1437
1438 if ( !empty( $conds ) ) {
1439 if ( is_array( $conds ) ) {
1440 $conds = $this->makeList( $conds, self::LIST_AND );
1441 }
1442 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1443 "WHERE $conds $preLimitTail";
1444 } else {
1445 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1446 }
1447
1448 if ( isset( $options['LIMIT'] ) ) {
1449 $sql = $this->limitResult( $sql, $options['LIMIT'],
1450 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1451 }
1452 $sql = "$sql $postLimitTail";
1453
1454 if ( isset( $options['EXPLAIN'] ) ) {
1455 $sql = 'EXPLAIN ' . $sql;
1456 }
1457
1458 return $sql;
1459 }
1460
1461 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1462 $options = [], $join_conds = []
1463 ) {
1464 $options = (array)$options;
1465 $options['LIMIT'] = 1;
1466 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1467
1468 if ( $res === false ) {
1469 return false;
1470 }
1471
1472 if ( !$this->numRows( $res ) ) {
1473 return false;
1474 }
1475
1476 $obj = $this->fetchObject( $res );
1477
1478 return $obj;
1479 }
1480
1481 public function estimateRowCount(
1482 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1483 ) {
1484 $rows = 0;
1485 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1486
1487 if ( $res ) {
1488 $row = $this->fetchRow( $res );
1489 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1490 }
1491
1492 return $rows;
1493 }
1494
1495 public function selectRowCount(
1496 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1497 ) {
1498 $rows = 0;
1499 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1500 // The identifier quotes is primarily for MSSQL.
1501 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1502 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1503 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1504
1505 if ( $res ) {
1506 $row = $this->fetchRow( $res );
1507 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1508 }
1509
1510 return $rows;
1511 }
1512
1513 /**
1514 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1515 * It's only slightly flawed. Don't use for anything important.
1516 *
1517 * @param string $sql A SQL Query
1518 *
1519 * @return string
1520 */
1521 protected static function generalizeSQL( $sql ) {
1522 # This does the same as the regexp below would do, but in such a way
1523 # as to avoid crashing php on some large strings.
1524 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1525
1526 $sql = str_replace( "\\\\", '', $sql );
1527 $sql = str_replace( "\\'", '', $sql );
1528 $sql = str_replace( "\\\"", '', $sql );
1529 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1530 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1531
1532 # All newlines, tabs, etc replaced by single space
1533 $sql = preg_replace( '/\s+/', ' ', $sql );
1534
1535 # All numbers => N,
1536 # except the ones surrounded by characters, e.g. l10n
1537 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1538 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1539
1540 return $sql;
1541 }
1542
1543 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1544 $info = $this->fieldInfo( $table, $field );
1545
1546 return (bool)$info;
1547 }
1548
1549 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1550 if ( !$this->tableExists( $table ) ) {
1551 return null;
1552 }
1553
1554 $info = $this->indexInfo( $table, $index, $fname );
1555 if ( is_null( $info ) ) {
1556 return null;
1557 } else {
1558 return $info !== false;
1559 }
1560 }
1561
1562 public function tableExists( $table, $fname = __METHOD__ ) {
1563 $tableRaw = $this->tableName( $table, 'raw' );
1564 if ( isset( $this->sessionTempTables[$tableRaw] ) ) {
1565 return true; // already known to exist
1566 }
1567
1568 $table = $this->tableName( $table );
1569 $ignoreErrors = true;
1570 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1571
1572 return (bool)$res;
1573 }
1574
1575 public function indexUnique( $table, $index ) {
1576 $indexInfo = $this->indexInfo( $table, $index );
1577
1578 if ( !$indexInfo ) {
1579 return null;
1580 }
1581
1582 return !$indexInfo[0]->Non_unique;
1583 }
1584
1585 /**
1586 * Helper for Database::insert().
1587 *
1588 * @param array $options
1589 * @return string
1590 */
1591 protected function makeInsertOptions( $options ) {
1592 return implode( ' ', $options );
1593 }
1594
1595 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1596 # No rows to insert, easy just return now
1597 if ( !count( $a ) ) {
1598 return true;
1599 }
1600
1601 $table = $this->tableName( $table );
1602
1603 if ( !is_array( $options ) ) {
1604 $options = [ $options ];
1605 }
1606
1607 $fh = null;
1608 if ( isset( $options['fileHandle'] ) ) {
1609 $fh = $options['fileHandle'];
1610 }
1611 $options = $this->makeInsertOptions( $options );
1612
1613 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1614 $multi = true;
1615 $keys = array_keys( $a[0] );
1616 } else {
1617 $multi = false;
1618 $keys = array_keys( $a );
1619 }
1620
1621 $sql = 'INSERT ' . $options .
1622 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1623
1624 if ( $multi ) {
1625 $first = true;
1626 foreach ( $a as $row ) {
1627 if ( $first ) {
1628 $first = false;
1629 } else {
1630 $sql .= ',';
1631 }
1632 $sql .= '(' . $this->makeList( $row ) . ')';
1633 }
1634 } else {
1635 $sql .= '(' . $this->makeList( $a ) . ')';
1636 }
1637
1638 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1639 return false;
1640 } elseif ( $fh !== null ) {
1641 return true;
1642 }
1643
1644 return (bool)$this->query( $sql, $fname );
1645 }
1646
1647 /**
1648 * Make UPDATE options array for Database::makeUpdateOptions
1649 *
1650 * @param array $options
1651 * @return array
1652 */
1653 protected function makeUpdateOptionsArray( $options ) {
1654 if ( !is_array( $options ) ) {
1655 $options = [ $options ];
1656 }
1657
1658 $opts = [];
1659
1660 if ( in_array( 'IGNORE', $options ) ) {
1661 $opts[] = 'IGNORE';
1662 }
1663
1664 return $opts;
1665 }
1666
1667 /**
1668 * Make UPDATE options for the Database::update function
1669 *
1670 * @param array $options The options passed to Database::update
1671 * @return string
1672 */
1673 protected function makeUpdateOptions( $options ) {
1674 $opts = $this->makeUpdateOptionsArray( $options );
1675
1676 return implode( ' ', $opts );
1677 }
1678
1679 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1680 $table = $this->tableName( $table );
1681 $opts = $this->makeUpdateOptions( $options );
1682 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1683
1684 if ( $conds !== [] && $conds !== '*' ) {
1685 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1686 }
1687
1688 return (bool)$this->query( $sql, $fname );
1689 }
1690
1691 public function makeList( $a, $mode = self::LIST_COMMA ) {
1692 if ( !is_array( $a ) ) {
1693 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1694 }
1695
1696 $first = true;
1697 $list = '';
1698
1699 foreach ( $a as $field => $value ) {
1700 if ( !$first ) {
1701 if ( $mode == self::LIST_AND ) {
1702 $list .= ' AND ';
1703 } elseif ( $mode == self::LIST_OR ) {
1704 $list .= ' OR ';
1705 } else {
1706 $list .= ',';
1707 }
1708 } else {
1709 $first = false;
1710 }
1711
1712 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1713 $list .= "($value)";
1714 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1715 $list .= "$value";
1716 } elseif (
1717 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1718 ) {
1719 // Remove null from array to be handled separately if found
1720 $includeNull = false;
1721 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1722 $includeNull = true;
1723 unset( $value[$nullKey] );
1724 }
1725 if ( count( $value ) == 0 && !$includeNull ) {
1726 throw new InvalidArgumentException(
1727 __METHOD__ . ": empty input for field $field" );
1728 } elseif ( count( $value ) == 0 ) {
1729 // only check if $field is null
1730 $list .= "$field IS NULL";
1731 } else {
1732 // IN clause contains at least one valid element
1733 if ( $includeNull ) {
1734 // Group subconditions to ensure correct precedence
1735 $list .= '(';
1736 }
1737 if ( count( $value ) == 1 ) {
1738 // Special-case single values, as IN isn't terribly efficient
1739 // Don't necessarily assume the single key is 0; we don't
1740 // enforce linear numeric ordering on other arrays here.
1741 $value = array_values( $value )[0];
1742 $list .= $field . " = " . $this->addQuotes( $value );
1743 } else {
1744 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1745 }
1746 // if null present in array, append IS NULL
1747 if ( $includeNull ) {
1748 $list .= " OR $field IS NULL)";
1749 }
1750 }
1751 } elseif ( $value === null ) {
1752 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1753 $list .= "$field IS ";
1754 } elseif ( $mode == self::LIST_SET ) {
1755 $list .= "$field = ";
1756 }
1757 $list .= 'NULL';
1758 } else {
1759 if (
1760 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1761 ) {
1762 $list .= "$field = ";
1763 }
1764 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1765 }
1766 }
1767
1768 return $list;
1769 }
1770
1771 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1772 $conds = [];
1773
1774 foreach ( $data as $base => $sub ) {
1775 if ( count( $sub ) ) {
1776 $conds[] = $this->makeList(
1777 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1778 self::LIST_AND );
1779 }
1780 }
1781
1782 if ( $conds ) {
1783 return $this->makeList( $conds, self::LIST_OR );
1784 } else {
1785 // Nothing to search for...
1786 return false;
1787 }
1788 }
1789
1790 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1791 return $valuename;
1792 }
1793
1794 public function bitNot( $field ) {
1795 return "(~$field)";
1796 }
1797
1798 public function bitAnd( $fieldLeft, $fieldRight ) {
1799 return "($fieldLeft & $fieldRight)";
1800 }
1801
1802 public function bitOr( $fieldLeft, $fieldRight ) {
1803 return "($fieldLeft | $fieldRight)";
1804 }
1805
1806 public function buildConcat( $stringList ) {
1807 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1808 }
1809
1810 public function buildGroupConcatField(
1811 $delim, $table, $field, $conds = '', $join_conds = []
1812 ) {
1813 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1814
1815 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1816 }
1817
1818 public function buildStringCast( $field ) {
1819 return $field;
1820 }
1821
1822 public function databasesAreIndependent() {
1823 return false;
1824 }
1825
1826 public function selectDB( $db ) {
1827 # Stub. Shouldn't cause serious problems if it's not overridden, but
1828 # if your database engine supports a concept similar to MySQL's
1829 # databases you may as well.
1830 $this->dbName = $db;
1831
1832 return true;
1833 }
1834
1835 public function getDBname() {
1836 return $this->dbName;
1837 }
1838
1839 public function getServer() {
1840 return $this->server;
1841 }
1842
1843 public function tableName( $name, $format = 'quoted' ) {
1844 # Skip the entire process when we have a string quoted on both ends.
1845 # Note that we check the end so that we will still quote any use of
1846 # use of `database`.table. But won't break things if someone wants
1847 # to query a database table with a dot in the name.
1848 if ( $this->isQuotedIdentifier( $name ) ) {
1849 return $name;
1850 }
1851
1852 # Lets test for any bits of text that should never show up in a table
1853 # name. Basically anything like JOIN or ON which are actually part of
1854 # SQL queries, but may end up inside of the table value to combine
1855 # sql. Such as how the API is doing.
1856 # Note that we use a whitespace test rather than a \b test to avoid
1857 # any remote case where a word like on may be inside of a table name
1858 # surrounded by symbols which may be considered word breaks.
1859 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1860 return $name;
1861 }
1862
1863 # Split database and table into proper variables.
1864 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1865
1866 # Quote $table and apply the prefix if not quoted.
1867 # $tableName might be empty if this is called from Database::replaceVars()
1868 $tableName = "{$prefix}{$table}";
1869 if ( $format === 'quoted'
1870 && !$this->isQuotedIdentifier( $tableName )
1871 && $tableName !== ''
1872 ) {
1873 $tableName = $this->addIdentifierQuotes( $tableName );
1874 }
1875
1876 # Quote $schema and $database and merge them with the table name if needed
1877 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1878 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1879
1880 return $tableName;
1881 }
1882
1883 /**
1884 * Get the table components needed for a query given the currently selected database
1885 *
1886 * @param string $name Table name in the form of db.schema.table, db.table, or table
1887 * @return array (DB name or "" for default, schema name, table prefix, table name)
1888 */
1889 protected function qualifiedTableComponents( $name ) {
1890 # We reverse the explode so that database.table and table both output the correct table.
1891 $dbDetails = explode( '.', $name, 3 );
1892 if ( count( $dbDetails ) == 3 ) {
1893 list( $database, $schema, $table ) = $dbDetails;
1894 # We don't want any prefix added in this case
1895 $prefix = '';
1896 } elseif ( count( $dbDetails ) == 2 ) {
1897 list( $database, $table ) = $dbDetails;
1898 # We don't want any prefix added in this case
1899 $prefix = '';
1900 # In dbs that support it, $database may actually be the schema
1901 # but that doesn't affect any of the functionality here
1902 $schema = '';
1903 } else {
1904 list( $table ) = $dbDetails;
1905 if ( isset( $this->tableAliases[$table] ) ) {
1906 $database = $this->tableAliases[$table]['dbname'];
1907 $schema = is_string( $this->tableAliases[$table]['schema'] )
1908 ? $this->tableAliases[$table]['schema']
1909 : $this->schema;
1910 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1911 ? $this->tableAliases[$table]['prefix']
1912 : $this->tablePrefix;
1913 } else {
1914 $database = '';
1915 $schema = $this->schema; # Default schema
1916 $prefix = $this->tablePrefix; # Default prefix
1917 }
1918 }
1919
1920 return [ $database, $schema, $prefix, $table ];
1921 }
1922
1923 /**
1924 * @param string|null $namespace Database or schema
1925 * @param string $relation Name of table, view, sequence, etc...
1926 * @param string $format One of (raw, quoted)
1927 * @return string Relation name with quoted and merged $namespace as needed
1928 */
1929 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1930 if ( strlen( $namespace ) ) {
1931 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1932 $namespace = $this->addIdentifierQuotes( $namespace );
1933 }
1934 $relation = $namespace . '.' . $relation;
1935 }
1936
1937 return $relation;
1938 }
1939
1940 public function tableNames() {
1941 $inArray = func_get_args();
1942 $retVal = [];
1943
1944 foreach ( $inArray as $name ) {
1945 $retVal[$name] = $this->tableName( $name );
1946 }
1947
1948 return $retVal;
1949 }
1950
1951 public function tableNamesN() {
1952 $inArray = func_get_args();
1953 $retVal = [];
1954
1955 foreach ( $inArray as $name ) {
1956 $retVal[] = $this->tableName( $name );
1957 }
1958
1959 return $retVal;
1960 }
1961
1962 /**
1963 * Get an aliased table name
1964 * e.g. tableName AS newTableName
1965 *
1966 * @param string $name Table name, see tableName()
1967 * @param string|bool $alias Alias (optional)
1968 * @return string SQL name for aliased table. Will not alias a table to its own name
1969 */
1970 protected function tableNameWithAlias( $name, $alias = false ) {
1971 if ( !$alias || $alias == $name ) {
1972 return $this->tableName( $name );
1973 } else {
1974 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1975 }
1976 }
1977
1978 /**
1979 * Gets an array of aliased table names
1980 *
1981 * @param array $tables [ [alias] => table ]
1982 * @return string[] See tableNameWithAlias()
1983 */
1984 protected function tableNamesWithAlias( $tables ) {
1985 $retval = [];
1986 foreach ( $tables as $alias => $table ) {
1987 if ( is_numeric( $alias ) ) {
1988 $alias = $table;
1989 }
1990 $retval[] = $this->tableNameWithAlias( $table, $alias );
1991 }
1992
1993 return $retval;
1994 }
1995
1996 /**
1997 * Get an aliased field name
1998 * e.g. fieldName AS newFieldName
1999 *
2000 * @param string $name Field name
2001 * @param string|bool $alias Alias (optional)
2002 * @return string SQL name for aliased field. Will not alias a field to its own name
2003 */
2004 protected function fieldNameWithAlias( $name, $alias = false ) {
2005 if ( !$alias || (string)$alias === (string)$name ) {
2006 return $name;
2007 } else {
2008 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2009 }
2010 }
2011
2012 /**
2013 * Gets an array of aliased field names
2014 *
2015 * @param array $fields [ [alias] => field ]
2016 * @return string[] See fieldNameWithAlias()
2017 */
2018 protected function fieldNamesWithAlias( $fields ) {
2019 $retval = [];
2020 foreach ( $fields as $alias => $field ) {
2021 if ( is_numeric( $alias ) ) {
2022 $alias = $field;
2023 }
2024 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2025 }
2026
2027 return $retval;
2028 }
2029
2030 /**
2031 * Get the aliased table name clause for a FROM clause
2032 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2033 *
2034 * @param array $tables ( [alias] => table )
2035 * @param array $use_index Same as for select()
2036 * @param array $ignore_index Same as for select()
2037 * @param array $join_conds Same as for select()
2038 * @return string
2039 */
2040 protected function tableNamesWithIndexClauseOrJOIN(
2041 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2042 ) {
2043 $ret = [];
2044 $retJOIN = [];
2045 $use_index = (array)$use_index;
2046 $ignore_index = (array)$ignore_index;
2047 $join_conds = (array)$join_conds;
2048
2049 foreach ( $tables as $alias => $table ) {
2050 if ( !is_string( $alias ) ) {
2051 // No alias? Set it equal to the table name
2052 $alias = $table;
2053 }
2054
2055 if ( is_array( $table ) ) {
2056 // A parenthesized group
2057 if ( count( $table ) > 1 ) {
2058 $joinedTable = '('
2059 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2060 . ')';
2061 } else {
2062 // Degenerate case
2063 $innerTable = reset( $table );
2064 $innerAlias = key( $table );
2065 $joinedTable = $this->tableNameWithAlias(
2066 $innerTable,
2067 is_string( $innerAlias ) ? $innerAlias : $innerTable
2068 );
2069 }
2070 } else {
2071 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2072 }
2073
2074 // Is there a JOIN clause for this table?
2075 if ( isset( $join_conds[$alias] ) ) {
2076 list( $joinType, $conds ) = $join_conds[$alias];
2077 $tableClause = $joinType;
2078 $tableClause .= ' ' . $joinedTable;
2079 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2080 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2081 if ( $use != '' ) {
2082 $tableClause .= ' ' . $use;
2083 }
2084 }
2085 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2086 $ignore = $this->ignoreIndexClause(
2087 implode( ',', (array)$ignore_index[$alias] ) );
2088 if ( $ignore != '' ) {
2089 $tableClause .= ' ' . $ignore;
2090 }
2091 }
2092 $on = $this->makeList( (array)$conds, self::LIST_AND );
2093 if ( $on != '' ) {
2094 $tableClause .= ' ON (' . $on . ')';
2095 }
2096
2097 $retJOIN[] = $tableClause;
2098 } elseif ( isset( $use_index[$alias] ) ) {
2099 // Is there an INDEX clause for this table?
2100 $tableClause = $joinedTable;
2101 $tableClause .= ' ' . $this->useIndexClause(
2102 implode( ',', (array)$use_index[$alias] )
2103 );
2104
2105 $ret[] = $tableClause;
2106 } elseif ( isset( $ignore_index[$alias] ) ) {
2107 // Is there an INDEX clause for this table?
2108 $tableClause = $joinedTable;
2109 $tableClause .= ' ' . $this->ignoreIndexClause(
2110 implode( ',', (array)$ignore_index[$alias] )
2111 );
2112
2113 $ret[] = $tableClause;
2114 } else {
2115 $tableClause = $joinedTable;
2116
2117 $ret[] = $tableClause;
2118 }
2119 }
2120
2121 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2122 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2123 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2124
2125 // Compile our final table clause
2126 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2127 }
2128
2129 /**
2130 * Allows for index remapping in queries where this is not consistent across DBMS
2131 *
2132 * @param string $index
2133 * @return string
2134 */
2135 protected function indexName( $index ) {
2136 return $index;
2137 }
2138
2139 public function addQuotes( $s ) {
2140 if ( $s instanceof Blob ) {
2141 $s = $s->fetch();
2142 }
2143 if ( $s === null ) {
2144 return 'NULL';
2145 } elseif ( is_bool( $s ) ) {
2146 return (int)$s;
2147 } else {
2148 # This will also quote numeric values. This should be harmless,
2149 # and protects against weird problems that occur when they really
2150 # _are_ strings such as article titles and string->number->string
2151 # conversion is not 1:1.
2152 return "'" . $this->strencode( $s ) . "'";
2153 }
2154 }
2155
2156 /**
2157 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2158 * MySQL uses `backticks` while basically everything else uses double quotes.
2159 * Since MySQL is the odd one out here the double quotes are our generic
2160 * and we implement backticks in DatabaseMysqlBase.
2161 *
2162 * @param string $s
2163 * @return string
2164 */
2165 public function addIdentifierQuotes( $s ) {
2166 return '"' . str_replace( '"', '""', $s ) . '"';
2167 }
2168
2169 /**
2170 * Returns if the given identifier looks quoted or not according to
2171 * the database convention for quoting identifiers .
2172 *
2173 * @note Do not use this to determine if untrusted input is safe.
2174 * A malicious user can trick this function.
2175 * @param string $name
2176 * @return bool
2177 */
2178 public function isQuotedIdentifier( $name ) {
2179 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2180 }
2181
2182 /**
2183 * @param string $s
2184 * @param string $escapeChar
2185 * @return string
2186 */
2187 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2188 return str_replace( [ $escapeChar, '%', '_' ],
2189 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2190 $s );
2191 }
2192
2193 public function buildLike() {
2194 $params = func_get_args();
2195
2196 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2197 $params = $params[0];
2198 }
2199
2200 $s = '';
2201
2202 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2203 // may escape backslashes, creating problems of double escaping. The `
2204 // character has good cross-DBMS compatibility, avoiding special operators
2205 // in MS SQL like ^ and %
2206 $escapeChar = '`';
2207
2208 foreach ( $params as $value ) {
2209 if ( $value instanceof LikeMatch ) {
2210 $s .= $value->toString();
2211 } else {
2212 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2213 }
2214 }
2215
2216 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2217 }
2218
2219 public function anyChar() {
2220 return new LikeMatch( '_' );
2221 }
2222
2223 public function anyString() {
2224 return new LikeMatch( '%' );
2225 }
2226
2227 public function nextSequenceValue( $seqName ) {
2228 return null;
2229 }
2230
2231 /**
2232 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2233 * is only needed because a) MySQL must be as efficient as possible due to
2234 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2235 * which index to pick. Anyway, other databases might have different
2236 * indexes on a given table. So don't bother overriding this unless you're
2237 * MySQL.
2238 * @param string $index
2239 * @return string
2240 */
2241 public function useIndexClause( $index ) {
2242 return '';
2243 }
2244
2245 /**
2246 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2247 * is only needed because a) MySQL must be as efficient as possible due to
2248 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2249 * which index to pick. Anyway, other databases might have different
2250 * indexes on a given table. So don't bother overriding this unless you're
2251 * MySQL.
2252 * @param string $index
2253 * @return string
2254 */
2255 public function ignoreIndexClause( $index ) {
2256 return '';
2257 }
2258
2259 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2260 if ( count( $rows ) == 0 ) {
2261 return;
2262 }
2263
2264 // Single row case
2265 if ( !is_array( reset( $rows ) ) ) {
2266 $rows = [ $rows ];
2267 }
2268
2269 $useTrx = !$this->trxLevel;
2270 if ( $useTrx ) {
2271 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2272 }
2273 try {
2274 $affectedRowCount = 0;
2275 foreach ( $rows as $row ) {
2276 // Delete rows which collide with this one
2277 $indexWhereClauses = [];
2278 foreach ( $uniqueIndexes as $index ) {
2279 $indexColumns = (array)$index;
2280 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2281 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2282 throw new DBUnexpectedError(
2283 $this,
2284 'New record does not provide all values for unique key (' .
2285 implode( ', ', $indexColumns ) . ')'
2286 );
2287 } elseif ( in_array( null, $indexRowValues, true ) ) {
2288 throw new DBUnexpectedError(
2289 $this,
2290 'New record has a null value for unique key (' .
2291 implode( ', ', $indexColumns ) . ')'
2292 );
2293 }
2294 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND );
2295 }
2296
2297 if ( $indexWhereClauses ) {
2298 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR ), $fname );
2299 $affectedRowCount += $this->affectedRows();
2300 }
2301
2302 // Now insert the row
2303 $this->insert( $table, $row, $fname );
2304 $affectedRowCount += $this->affectedRows();
2305 }
2306 } catch ( Exception $e ) {
2307 if ( $useTrx ) {
2308 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2309 }
2310 throw $e;
2311 }
2312 if ( $useTrx ) {
2313 $this->commit( $fname, self::FLUSHING_INTERNAL );
2314 }
2315
2316 $this->affectedRowCount = $affectedRowCount;
2317 }
2318
2319 /**
2320 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2321 * statement.
2322 *
2323 * @param string $table Table name
2324 * @param array|string $rows Row(s) to insert
2325 * @param string $fname Caller function name
2326 *
2327 * @return ResultWrapper
2328 */
2329 protected function nativeReplace( $table, $rows, $fname ) {
2330 $table = $this->tableName( $table );
2331
2332 # Single row case
2333 if ( !is_array( reset( $rows ) ) ) {
2334 $rows = [ $rows ];
2335 }
2336
2337 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2338 $first = true;
2339
2340 foreach ( $rows as $row ) {
2341 if ( $first ) {
2342 $first = false;
2343 } else {
2344 $sql .= ',';
2345 }
2346
2347 $sql .= '(' . $this->makeList( $row ) . ')';
2348 }
2349
2350 return $this->query( $sql, $fname );
2351 }
2352
2353 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2354 $fname = __METHOD__
2355 ) {
2356 if ( !count( $rows ) ) {
2357 return true; // nothing to do
2358 }
2359
2360 if ( !is_array( reset( $rows ) ) ) {
2361 $rows = [ $rows ];
2362 }
2363
2364 if ( count( $uniqueIndexes ) ) {
2365 $clauses = []; // list WHERE clauses that each identify a single row
2366 foreach ( $rows as $row ) {
2367 foreach ( $uniqueIndexes as $index ) {
2368 $index = is_array( $index ) ? $index : [ $index ]; // columns
2369 $rowKey = []; // unique key to this row
2370 foreach ( $index as $column ) {
2371 $rowKey[$column] = $row[$column];
2372 }
2373 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2374 }
2375 }
2376 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2377 } else {
2378 $where = false;
2379 }
2380
2381 $affectedRowCount = 0;
2382 $useTrx = !$this->trxLevel;
2383 if ( $useTrx ) {
2384 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2385 }
2386 try {
2387 # Update any existing conflicting row(s)
2388 if ( $where !== false ) {
2389 $ok = $this->update( $table, $set, $where, $fname );
2390 $affectedRowCount += $this->affectedRows();
2391 } else {
2392 $ok = true;
2393 }
2394 # Now insert any non-conflicting row(s)
2395 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2396 $affectedRowCount += $this->affectedRows();
2397 } catch ( Exception $e ) {
2398 if ( $useTrx ) {
2399 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2400 }
2401 throw $e;
2402 }
2403 if ( $useTrx ) {
2404 $this->commit( $fname, self::FLUSHING_INTERNAL );
2405 }
2406 $this->affectedRowCount = $affectedRowCount;
2407
2408 return $ok;
2409 }
2410
2411 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2412 $fname = __METHOD__
2413 ) {
2414 if ( !$conds ) {
2415 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2416 }
2417
2418 $delTable = $this->tableName( $delTable );
2419 $joinTable = $this->tableName( $joinTable );
2420 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2421 if ( $conds != '*' ) {
2422 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2423 }
2424 $sql .= ')';
2425
2426 $this->query( $sql, $fname );
2427 }
2428
2429 public function textFieldSize( $table, $field ) {
2430 $table = $this->tableName( $table );
2431 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2432 $res = $this->query( $sql, __METHOD__ );
2433 $row = $this->fetchObject( $res );
2434
2435 $m = [];
2436
2437 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2438 $size = $m[1];
2439 } else {
2440 $size = -1;
2441 }
2442
2443 return $size;
2444 }
2445
2446 public function delete( $table, $conds, $fname = __METHOD__ ) {
2447 if ( !$conds ) {
2448 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2449 }
2450
2451 $table = $this->tableName( $table );
2452 $sql = "DELETE FROM $table";
2453
2454 if ( $conds != '*' ) {
2455 if ( is_array( $conds ) ) {
2456 $conds = $this->makeList( $conds, self::LIST_AND );
2457 }
2458 $sql .= ' WHERE ' . $conds;
2459 }
2460
2461 return $this->query( $sql, $fname );
2462 }
2463
2464 public function insertSelect(
2465 $destTable, $srcTable, $varMap, $conds,
2466 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2467 ) {
2468 if ( $this->cliMode ) {
2469 // For massive migrations with downtime, we don't want to select everything
2470 // into memory and OOM, so do all this native on the server side if possible.
2471 return $this->nativeInsertSelect(
2472 $destTable,
2473 $srcTable,
2474 $varMap,
2475 $conds,
2476 $fname,
2477 $insertOptions,
2478 $selectOptions,
2479 $selectJoinConds
2480 );
2481 }
2482
2483 return $this->nonNativeInsertSelect(
2484 $destTable,
2485 $srcTable,
2486 $varMap,
2487 $conds,
2488 $fname,
2489 $insertOptions,
2490 $selectOptions,
2491 $selectJoinConds
2492 );
2493 }
2494
2495 /**
2496 * Implementation of insertSelect() based on select() and insert()
2497 *
2498 * @see IDatabase::insertSelect()
2499 * @since 1.30
2500 * @param string $destTable
2501 * @param string|array $srcTable
2502 * @param array $varMap
2503 * @param array $conds
2504 * @param string $fname
2505 * @param array $insertOptions
2506 * @param array $selectOptions
2507 * @param array $selectJoinConds
2508 * @return bool
2509 */
2510 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2511 $fname = __METHOD__,
2512 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2513 ) {
2514 $insertOptions = array_diff( (array)$insertOptions, [ 'NO_AUTO_COLUMNS' ] );
2515
2516 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2517 // on only the master (without needing row-based-replication). It also makes it easy to
2518 // know how big the INSERT is going to be.
2519 $fields = [];
2520 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2521 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2522 }
2523 $selectOptions[] = 'FOR UPDATE';
2524 $res = $this->select(
2525 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2526 );
2527 if ( !$res ) {
2528 return false;
2529 }
2530
2531 try {
2532 $affectedRowCount = 0;
2533 $this->startAtomic( $fname );
2534 $rows = [];
2535 $ok = true;
2536 foreach ( $res as $row ) {
2537 $rows[] = (array)$row;
2538
2539 // Avoid inserts that are too huge
2540 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize ) {
2541 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2542 if ( !$ok ) {
2543 break;
2544 }
2545 $affectedRowCount += $this->affectedRows();
2546 $rows = [];
2547 }
2548 }
2549 if ( $rows && $ok ) {
2550 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2551 if ( $ok ) {
2552 $affectedRowCount += $this->affectedRows();
2553 }
2554 }
2555 if ( $ok ) {
2556 $this->endAtomic( $fname );
2557 $this->affectedRowCount = $affectedRowCount;
2558 } else {
2559 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2560 $this->affectedRowCount = 0;
2561 }
2562 return $ok;
2563 } catch ( Exception $e ) {
2564 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2565 $this->affectedRowCount = 0;
2566 throw $e;
2567 }
2568 }
2569
2570 /**
2571 * Native server-side implementation of insertSelect() for situations where
2572 * we don't want to select everything into memory
2573 *
2574 * @see IDatabase::insertSelect()
2575 * @param string $destTable
2576 * @param string|array $srcTable
2577 * @param array $varMap
2578 * @param array $conds
2579 * @param string $fname
2580 * @param array $insertOptions
2581 * @param array $selectOptions
2582 * @param array $selectJoinConds
2583 * @return bool
2584 */
2585 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2586 $fname = __METHOD__,
2587 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2588 ) {
2589 $destTable = $this->tableName( $destTable );
2590
2591 if ( !is_array( $insertOptions ) ) {
2592 $insertOptions = [ $insertOptions ];
2593 }
2594 $insertOptions = array_diff( (array)$insertOptions, [ 'NO_AUTO_COLUMNS' ] );
2595
2596 $insertOptions = $this->makeInsertOptions( $insertOptions );
2597
2598 $selectSql = $this->selectSQLText(
2599 $srcTable,
2600 array_values( $varMap ),
2601 $conds,
2602 $fname,
2603 $selectOptions,
2604 $selectJoinConds
2605 );
2606
2607 $sql = "INSERT $insertOptions" .
2608 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2609 $selectSql;
2610
2611 return $this->query( $sql, $fname );
2612 }
2613
2614 /**
2615 * Construct a LIMIT query with optional offset. This is used for query
2616 * pages. The SQL should be adjusted so that only the first $limit rows
2617 * are returned. If $offset is provided as well, then the first $offset
2618 * rows should be discarded, and the next $limit rows should be returned.
2619 * If the result of the query is not ordered, then the rows to be returned
2620 * are theoretically arbitrary.
2621 *
2622 * $sql is expected to be a SELECT, if that makes a difference.
2623 *
2624 * The version provided by default works in MySQL and SQLite. It will very
2625 * likely need to be overridden for most other DBMSes.
2626 *
2627 * @param string $sql SQL query we will append the limit too
2628 * @param int $limit The SQL limit
2629 * @param int|bool $offset The SQL offset (default false)
2630 * @throws DBUnexpectedError
2631 * @return string
2632 */
2633 public function limitResult( $sql, $limit, $offset = false ) {
2634 if ( !is_numeric( $limit ) ) {
2635 throw new DBUnexpectedError( $this,
2636 "Invalid non-numeric limit passed to limitResult()\n" );
2637 }
2638
2639 return "$sql LIMIT "
2640 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2641 . "{$limit} ";
2642 }
2643
2644 public function unionSupportsOrderAndLimit() {
2645 return true; // True for almost every DB supported
2646 }
2647
2648 public function unionQueries( $sqls, $all ) {
2649 $glue = $all ? ') UNION ALL (' : ') UNION (';
2650
2651 return '(' . implode( $glue, $sqls ) . ')';
2652 }
2653
2654 public function unionConditionPermutations(
2655 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
2656 $options = [], $join_conds = []
2657 ) {
2658 // First, build the Cartesian product of $permute_conds
2659 $conds = [ [] ];
2660 foreach ( $permute_conds as $field => $values ) {
2661 if ( !$values ) {
2662 // Skip empty $values
2663 continue;
2664 }
2665 $values = array_unique( $values ); // For sanity
2666 $newConds = [];
2667 foreach ( $conds as $cond ) {
2668 foreach ( $values as $value ) {
2669 $cond[$field] = $value;
2670 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2671 }
2672 }
2673 $conds = $newConds;
2674 }
2675
2676 $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
2677
2678 // If there's just one condition and no subordering, hand off to
2679 // selectSQLText directly.
2680 if ( count( $conds ) === 1 &&
2681 ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
2682 ) {
2683 return $this->selectSQLText(
2684 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
2685 );
2686 }
2687
2688 // Otherwise, we need to pull out the order and limit to apply after
2689 // the union. Then build the SQL queries for each set of conditions in
2690 // $conds. Then union them together (using UNION ALL, because the
2691 // product *should* already be distinct).
2692 $orderBy = $this->makeOrderBy( $options );
2693 $limit = isset( $options['LIMIT'] ) ? $options['LIMIT'] : null;
2694 $offset = isset( $options['OFFSET'] ) ? $options['OFFSET'] : false;
2695 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2696 if ( !$this->unionSupportsOrderAndLimit() ) {
2697 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2698 } else {
2699 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2700 $options['ORDER BY'] = $options['INNER ORDER BY'];
2701 }
2702 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2703 // We need to increase the limit by the offset rather than
2704 // using the offset directly, otherwise it'll skip incorrectly
2705 // in the subqueries.
2706 $options['LIMIT'] = $limit + $offset;
2707 unset( $options['OFFSET'] );
2708 }
2709 }
2710
2711 $sqls = [];
2712 foreach ( $conds as $cond ) {
2713 $sqls[] = $this->selectSQLText(
2714 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
2715 );
2716 }
2717 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2718 if ( $limit !== null ) {
2719 $sql = $this->limitResult( $sql, $limit, $offset );
2720 }
2721
2722 return $sql;
2723 }
2724
2725 public function conditional( $cond, $trueVal, $falseVal ) {
2726 if ( is_array( $cond ) ) {
2727 $cond = $this->makeList( $cond, self::LIST_AND );
2728 }
2729
2730 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2731 }
2732
2733 public function strreplace( $orig, $old, $new ) {
2734 return "REPLACE({$orig}, {$old}, {$new})";
2735 }
2736
2737 public function getServerUptime() {
2738 return 0;
2739 }
2740
2741 public function wasDeadlock() {
2742 return false;
2743 }
2744
2745 public function wasLockTimeout() {
2746 return false;
2747 }
2748
2749 public function wasErrorReissuable() {
2750 return false;
2751 }
2752
2753 public function wasReadOnlyError() {
2754 return false;
2755 }
2756
2757 /**
2758 * Do not use this method outside of Database/DBError classes
2759 *
2760 * @param int|string $errno
2761 * @return bool Whether the given query error was a connection drop
2762 */
2763 public function wasConnectionError( $errno ) {
2764 return false;
2765 }
2766
2767 public function deadlockLoop() {
2768 $args = func_get_args();
2769 $function = array_shift( $args );
2770 $tries = self::DEADLOCK_TRIES;
2771
2772 $this->begin( __METHOD__ );
2773
2774 $retVal = null;
2775 /** @var Exception $e */
2776 $e = null;
2777 do {
2778 try {
2779 $retVal = call_user_func_array( $function, $args );
2780 break;
2781 } catch ( DBQueryError $e ) {
2782 if ( $this->wasDeadlock() ) {
2783 // Retry after a randomized delay
2784 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2785 } else {
2786 // Throw the error back up
2787 throw $e;
2788 }
2789 }
2790 } while ( --$tries > 0 );
2791
2792 if ( $tries <= 0 ) {
2793 // Too many deadlocks; give up
2794 $this->rollback( __METHOD__ );
2795 throw $e;
2796 } else {
2797 $this->commit( __METHOD__ );
2798
2799 return $retVal;
2800 }
2801 }
2802
2803 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2804 # Real waits are implemented in the subclass.
2805 return 0;
2806 }
2807
2808 public function getReplicaPos() {
2809 # Stub
2810 return false;
2811 }
2812
2813 public function getMasterPos() {
2814 # Stub
2815 return false;
2816 }
2817
2818 public function serverIsReadOnly() {
2819 return false;
2820 }
2821
2822 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2823 if ( !$this->trxLevel ) {
2824 throw new DBUnexpectedError( $this, "No transaction is active." );
2825 }
2826 $this->trxEndCallbacks[] = [ $callback, $fname ];
2827 }
2828
2829 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2830 $this->trxIdleCallbacks[] = [ $callback, $fname ];
2831 if ( !$this->trxLevel ) {
2832 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2833 }
2834 }
2835
2836 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2837 if ( $this->trxLevel || $this->getFlag( self::DBO_TRX ) ) {
2838 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2839 // an implicit commit of all peer databases. This is true even if a transaction has
2840 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2841 $this->trxPreCommitCallbacks[] = [ $callback, $fname ];
2842 } else {
2843 // No transaction is active nor will start implicitly, so make one for this callback
2844 $this->startAtomic( __METHOD__ );
2845 try {
2846 call_user_func( $callback );
2847 $this->endAtomic( __METHOD__ );
2848 } catch ( Exception $e ) {
2849 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2850 throw $e;
2851 }
2852 }
2853 }
2854
2855 final public function setTransactionListener( $name, callable $callback = null ) {
2856 if ( $callback ) {
2857 $this->trxRecurringCallbacks[$name] = $callback;
2858 } else {
2859 unset( $this->trxRecurringCallbacks[$name] );
2860 }
2861 }
2862
2863 /**
2864 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2865 *
2866 * This method should not be used outside of Database/LoadBalancer
2867 *
2868 * @param bool $suppress
2869 * @since 1.28
2870 */
2871 final public function setTrxEndCallbackSuppression( $suppress ) {
2872 $this->trxEndCallbacksSuppressed = $suppress;
2873 }
2874
2875 /**
2876 * Actually run and consume any "on transaction idle/resolution" callbacks.
2877 *
2878 * This method should not be used outside of Database/LoadBalancer
2879 *
2880 * @param int $trigger IDatabase::TRIGGER_* constant
2881 * @since 1.20
2882 * @throws Exception
2883 */
2884 public function runOnTransactionIdleCallbacks( $trigger ) {
2885 if ( $this->trxEndCallbacksSuppressed ) {
2886 return;
2887 }
2888
2889 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2890 /** @var Exception $e */
2891 $e = null; // first exception
2892 do { // callbacks may add callbacks :)
2893 $callbacks = array_merge(
2894 $this->trxIdleCallbacks,
2895 $this->trxEndCallbacks // include "transaction resolution" callbacks
2896 );
2897 $this->trxIdleCallbacks = []; // consumed (and recursion guard)
2898 $this->trxEndCallbacks = []; // consumed (recursion guard)
2899 foreach ( $callbacks as $callback ) {
2900 try {
2901 list( $phpCallback ) = $callback;
2902 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2903 call_user_func_array( $phpCallback, [ $trigger ] );
2904 if ( $autoTrx ) {
2905 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2906 } else {
2907 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2908 }
2909 } catch ( Exception $ex ) {
2910 call_user_func( $this->errorLogger, $ex );
2911 $e = $e ?: $ex;
2912 // Some callbacks may use startAtomic/endAtomic, so make sure
2913 // their transactions are ended so other callbacks don't fail
2914 if ( $this->trxLevel() ) {
2915 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2916 }
2917 }
2918 }
2919 } while ( count( $this->trxIdleCallbacks ) );
2920
2921 if ( $e instanceof Exception ) {
2922 throw $e; // re-throw any first exception
2923 }
2924 }
2925
2926 /**
2927 * Actually run and consume any "on transaction pre-commit" callbacks.
2928 *
2929 * This method should not be used outside of Database/LoadBalancer
2930 *
2931 * @since 1.22
2932 * @throws Exception
2933 */
2934 public function runOnTransactionPreCommitCallbacks() {
2935 $e = null; // first exception
2936 do { // callbacks may add callbacks :)
2937 $callbacks = $this->trxPreCommitCallbacks;
2938 $this->trxPreCommitCallbacks = []; // consumed (and recursion guard)
2939 foreach ( $callbacks as $callback ) {
2940 try {
2941 list( $phpCallback ) = $callback;
2942 call_user_func( $phpCallback );
2943 } catch ( Exception $ex ) {
2944 call_user_func( $this->errorLogger, $ex );
2945 $e = $e ?: $ex;
2946 }
2947 }
2948 } while ( count( $this->trxPreCommitCallbacks ) );
2949
2950 if ( $e instanceof Exception ) {
2951 throw $e; // re-throw any first exception
2952 }
2953 }
2954
2955 /**
2956 * Actually run any "transaction listener" callbacks.
2957 *
2958 * This method should not be used outside of Database/LoadBalancer
2959 *
2960 * @param int $trigger IDatabase::TRIGGER_* constant
2961 * @throws Exception
2962 * @since 1.20
2963 */
2964 public function runTransactionListenerCallbacks( $trigger ) {
2965 if ( $this->trxEndCallbacksSuppressed ) {
2966 return;
2967 }
2968
2969 /** @var Exception $e */
2970 $e = null; // first exception
2971
2972 foreach ( $this->trxRecurringCallbacks as $phpCallback ) {
2973 try {
2974 $phpCallback( $trigger, $this );
2975 } catch ( Exception $ex ) {
2976 call_user_func( $this->errorLogger, $ex );
2977 $e = $e ?: $ex;
2978 }
2979 }
2980
2981 if ( $e instanceof Exception ) {
2982 throw $e; // re-throw any first exception
2983 }
2984 }
2985
2986 final public function startAtomic( $fname = __METHOD__ ) {
2987 if ( !$this->trxLevel ) {
2988 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2989 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2990 // in all changes being in one transaction to keep requests transactional.
2991 if ( !$this->getFlag( self::DBO_TRX ) ) {
2992 $this->trxAutomaticAtomic = true;
2993 }
2994 }
2995
2996 $this->trxAtomicLevels[] = $fname;
2997 }
2998
2999 final public function endAtomic( $fname = __METHOD__ ) {
3000 if ( !$this->trxLevel ) {
3001 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3002 }
3003 if ( !$this->trxAtomicLevels ||
3004 array_pop( $this->trxAtomicLevels ) !== $fname
3005 ) {
3006 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3007 }
3008
3009 if ( !$this->trxAtomicLevels && $this->trxAutomaticAtomic ) {
3010 $this->commit( $fname, self::FLUSHING_INTERNAL );
3011 }
3012 }
3013
3014 final public function doAtomicSection( $fname, callable $callback ) {
3015 $this->startAtomic( $fname );
3016 try {
3017 $res = call_user_func_array( $callback, [ $this, $fname ] );
3018 } catch ( Exception $e ) {
3019 $this->rollback( $fname, self::FLUSHING_INTERNAL );
3020 throw $e;
3021 }
3022 $this->endAtomic( $fname );
3023
3024 return $res;
3025 }
3026
3027 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
3028 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3029 if ( $this->trxLevel ) {
3030 if ( $this->trxAtomicLevels ) {
3031 $levels = implode( ', ', $this->trxAtomicLevels );
3032 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3033 throw new DBUnexpectedError( $this, $msg );
3034 } elseif ( !$this->trxAutomatic ) {
3035 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3036 throw new DBUnexpectedError( $this, $msg );
3037 } else {
3038 // @TODO: make this an exception at some point
3039 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3040 $this->queryLogger->error( $msg );
3041 return; // join the main transaction set
3042 }
3043 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
3044 // @TODO: make this an exception at some point
3045 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3046 $this->queryLogger->error( $msg );
3047 return; // let any writes be in the main transaction
3048 }
3049
3050 // Avoid fatals if close() was called
3051 $this->assertOpen();
3052
3053 $this->doBegin( $fname );
3054 $this->trxTimestamp = microtime( true );
3055 $this->trxFname = $fname;
3056 $this->trxDoneWrites = false;
3057 $this->trxAutomaticAtomic = false;
3058 $this->trxAtomicLevels = [];
3059 $this->trxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3060 $this->trxWriteDuration = 0.0;
3061 $this->trxWriteQueryCount = 0;
3062 $this->trxWriteAffectedRows = 0;
3063 $this->trxWriteAdjDuration = 0.0;
3064 $this->trxWriteAdjQueryCount = 0;
3065 $this->trxWriteCallers = [];
3066 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3067 // Get an estimate of the replica DB lag before then, treating estimate staleness
3068 // as lag itself just to be safe
3069 $status = $this->getApproximateLagStatus();
3070 $this->trxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3071 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3072 // caller will think its OK to muck around with the transaction just because startAtomic()
3073 // has not yet completed (e.g. setting trxAtomicLevels).
3074 $this->trxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
3075 }
3076
3077 /**
3078 * Issues the BEGIN command to the database server.
3079 *
3080 * @see Database::begin()
3081 * @param string $fname
3082 */
3083 protected function doBegin( $fname ) {
3084 $this->query( 'BEGIN', $fname );
3085 $this->trxLevel = 1;
3086 }
3087
3088 final public function commit( $fname = __METHOD__, $flush = '' ) {
3089 if ( $this->trxLevel && $this->trxAtomicLevels ) {
3090 // There are still atomic sections open. This cannot be ignored
3091 $levels = implode( ', ', $this->trxAtomicLevels );
3092 throw new DBUnexpectedError(
3093 $this,
3094 "$fname: Got COMMIT while atomic sections $levels are still open."
3095 );
3096 }
3097
3098 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3099 if ( !$this->trxLevel ) {
3100 return; // nothing to do
3101 } elseif ( !$this->trxAutomatic ) {
3102 throw new DBUnexpectedError(
3103 $this,
3104 "$fname: Flushing an explicit transaction, getting out of sync."
3105 );
3106 }
3107 } else {
3108 if ( !$this->trxLevel ) {
3109 $this->queryLogger->error(
3110 "$fname: No transaction to commit, something got out of sync." );
3111 return; // nothing to do
3112 } elseif ( $this->trxAutomatic ) {
3113 // @TODO: make this an exception at some point
3114 $msg = "$fname: Explicit commit of implicit transaction.";
3115 $this->queryLogger->error( $msg );
3116 return; // wait for the main transaction set commit round
3117 }
3118 }
3119
3120 // Avoid fatals if close() was called
3121 $this->assertOpen();
3122
3123 $this->runOnTransactionPreCommitCallbacks();
3124 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
3125 $this->doCommit( $fname );
3126 if ( $this->trxDoneWrites ) {
3127 $this->lastWriteTime = microtime( true );
3128 $this->trxProfiler->transactionWritingOut(
3129 $this->server,
3130 $this->dbName,
3131 $this->trxShortId,
3132 $writeTime,
3133 $this->trxWriteAffectedRows
3134 );
3135 }
3136
3137 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
3138 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
3139 }
3140
3141 /**
3142 * Issues the COMMIT command to the database server.
3143 *
3144 * @see Database::commit()
3145 * @param string $fname
3146 */
3147 protected function doCommit( $fname ) {
3148 if ( $this->trxLevel ) {
3149 $this->query( 'COMMIT', $fname );
3150 $this->trxLevel = 0;
3151 }
3152 }
3153
3154 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3155 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3156 if ( !$this->trxLevel ) {
3157 return; // nothing to do
3158 }
3159 } else {
3160 if ( !$this->trxLevel ) {
3161 $this->queryLogger->error(
3162 "$fname: No transaction to rollback, something got out of sync." );
3163 return; // nothing to do
3164 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
3165 throw new DBUnexpectedError(
3166 $this,
3167 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3168 );
3169 }
3170 }
3171
3172 // Avoid fatals if close() was called
3173 $this->assertOpen();
3174
3175 $this->doRollback( $fname );
3176 $this->trxAtomicLevels = [];
3177 if ( $this->trxDoneWrites ) {
3178 $this->trxProfiler->transactionWritingOut(
3179 $this->server,
3180 $this->dbName,
3181 $this->trxShortId
3182 );
3183 }
3184
3185 $this->trxIdleCallbacks = []; // clear