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