15e02ad0857e98caae07fb46b771278039349c71
[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 if ( $this->getLBInfo( 'replica' ) === true ) {
912 throw new DBError(
913 $this,
914 'Write operations are not allowed on replica database connections.'
915 );
916 }
917 # In theory, non-persistent writes are allowed in read-only mode, but due to things
918 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
919 $reason = $this->getReadOnlyReason();
920 if ( $reason !== false ) {
921 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
922 }
923 # Set a flag indicating that writes have been done
924 $this->mLastWriteTime = microtime( true );
925 }
926
927 # Add trace comment to the begin of the sql string, right after the operator.
928 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
929 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
930
931 # Start implicit transactions that wrap the request if DBO_TRX is enabled
932 if ( !$this->mTrxLevel && $this->getFlag( self::DBO_TRX )
933 && $this->isTransactableQuery( $sql )
934 ) {
935 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
936 $this->mTrxAutomatic = true;
937 }
938
939 # Keep track of whether the transaction has write queries pending
940 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
941 $this->mTrxDoneWrites = true;
942 $this->trxProfiler->transactionWritingIn(
943 $this->mServer, $this->mDBname, $this->mTrxShortId );
944 }
945
946 if ( $this->getFlag( self::DBO_DEBUG ) ) {
947 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
948 }
949
950 # Avoid fatals if close() was called
951 $this->assertOpen();
952
953 # Send the query to the server
954 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
955
956 # Try reconnecting if the connection was lost
957 if ( false === $ret && $this->wasErrorReissuable() ) {
958 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
959 # Stash the last error values before anything might clear them
960 $lastError = $this->lastError();
961 $lastErrno = $this->lastErrno();
962 # Update state tracking to reflect transaction loss due to disconnection
963 $this->handleSessionLoss();
964 if ( $this->reconnect() ) {
965 $msg = __METHOD__ . ': lost connection to {dbserver}; reconnected';
966 $params = [ 'dbserver' => $this->getServer() ];
967 $this->connLogger->warning( $msg, $params );
968 $this->queryLogger->warning( $msg, $params +
969 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
970
971 if ( !$recoverable ) {
972 # Callers may catch the exception and continue to use the DB
973 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
974 } else {
975 # Should be safe to silently retry the query
976 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
977 }
978 } else {
979 $msg = __METHOD__ . ': lost connection to {dbserver} permanently';
980 $this->connLogger->error( $msg, [ 'dbserver' => $this->getServer() ] );
981 }
982 }
983
984 if ( false === $ret ) {
985 # Deadlocks cause the entire transaction to abort, not just the statement.
986 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
987 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
988 if ( $this->wasDeadlock() ) {
989 if ( $this->explicitTrxActive() || $priorWritesPending ) {
990 $tempIgnore = false; // not recoverable
991 }
992 # Update state tracking to reflect transaction loss
993 $this->handleSessionLoss();
994 }
995
996 $this->reportQueryError(
997 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
998 }
999
1000 $res = $this->resultObject( $ret );
1001
1002 return $res;
1003 }
1004
1005 /**
1006 * Helper method for query() that handles profiling and logging and sends
1007 * the query to doQuery()
1008 *
1009 * @param string $sql Original SQL query
1010 * @param string $commentedSql SQL query with debugging/trace comment
1011 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1012 * @param string $fname Name of the calling function
1013 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1014 * object for a successful read query, or false on failure
1015 */
1016 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1017 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1018 # generalizeSQL() will probably cut down the query to reasonable
1019 # logging size most of the time. The substr is really just a sanity check.
1020 if ( $isMaster ) {
1021 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1022 } else {
1023 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
1024 }
1025
1026 # Include query transaction state
1027 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
1028
1029 $startTime = microtime( true );
1030 if ( $this->profiler ) {
1031 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
1032 }
1033 $ret = $this->doQuery( $commentedSql );
1034 if ( $this->profiler ) {
1035 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
1036 }
1037 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1038
1039 unset( $queryProfSection ); // profile out (if set)
1040
1041 if ( $ret !== false ) {
1042 $this->lastPing = $startTime;
1043 if ( $isWrite && $this->mTrxLevel ) {
1044 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1045 $this->mTrxWriteCallers[] = $fname;
1046 }
1047 }
1048
1049 if ( $sql === self::PING_QUERY ) {
1050 $this->mRTTEstimate = $queryRuntime;
1051 }
1052
1053 $this->trxProfiler->recordQueryCompletion(
1054 $queryProf, $startTime, $isWrite, $this->affectedRows()
1055 );
1056 $this->queryLogger->debug( $sql, [
1057 'method' => $fname,
1058 'master' => $isMaster,
1059 'runtime' => $queryRuntime,
1060 ] );
1061
1062 return $ret;
1063 }
1064
1065 /**
1066 * Update the estimated run-time of a query, not counting large row lock times
1067 *
1068 * LoadBalancer can be set to rollback transactions that will create huge replication
1069 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1070 * queries, like inserting a row can take a long time due to row locking. This method
1071 * uses some simple heuristics to discount those cases.
1072 *
1073 * @param string $sql A SQL write query
1074 * @param float $runtime Total runtime, including RTT
1075 * @param int $affected Affected row count
1076 */
1077 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1078 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1079 $indicativeOfReplicaRuntime = true;
1080 if ( $runtime > self::SLOW_WRITE_SEC ) {
1081 $verb = $this->getQueryVerb( $sql );
1082 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1083 if ( $verb === 'INSERT' ) {
1084 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1085 } elseif ( $verb === 'REPLACE' ) {
1086 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1087 }
1088 }
1089
1090 $this->mTrxWriteDuration += $runtime;
1091 $this->mTrxWriteQueryCount += 1;
1092 $this->mTrxWriteAffectedRows += $affected;
1093 if ( $indicativeOfReplicaRuntime ) {
1094 $this->mTrxWriteAdjDuration += $runtime;
1095 $this->mTrxWriteAdjQueryCount += 1;
1096 }
1097 }
1098
1099 /**
1100 * Determine whether or not it is safe to retry queries after a database
1101 * connection is lost
1102 *
1103 * @param string $sql SQL query
1104 * @param bool $priorWritesPending Whether there is a transaction open with
1105 * possible write queries or transaction pre-commit/idle callbacks
1106 * waiting on it to finish.
1107 * @return bool True if it is safe to retry the query, false otherwise
1108 */
1109 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1110 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1111 # Dropped connections also mean that named locks are automatically released.
1112 # Only allow error suppression in autocommit mode or when the lost transaction
1113 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1114 if ( $this->mNamedLocksHeld ) {
1115 return false; // possible critical section violation
1116 } elseif ( $sql === 'COMMIT' ) {
1117 return !$priorWritesPending; // nothing written anyway? (T127428)
1118 } elseif ( $sql === 'ROLLBACK' ) {
1119 return true; // transaction lost...which is also what was requested :)
1120 } elseif ( $this->explicitTrxActive() ) {
1121 return false; // don't drop atomocity
1122 } elseif ( $priorWritesPending ) {
1123 return false; // prior writes lost from implicit transaction
1124 }
1125
1126 return true;
1127 }
1128
1129 /**
1130 * Clean things up after transaction loss due to disconnection
1131 *
1132 * @return null|Exception
1133 */
1134 private function handleSessionLoss() {
1135 $this->mTrxLevel = 0;
1136 $this->mTrxIdleCallbacks = []; // T67263
1137 $this->mTrxPreCommitCallbacks = []; // T67263
1138 $this->mSessionTempTables = [];
1139 $this->mNamedLocksHeld = [];
1140 try {
1141 // Handle callbacks in mTrxEndCallbacks
1142 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1143 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1144 return null;
1145 } catch ( Exception $e ) {
1146 // Already logged; move on...
1147 return $e;
1148 }
1149 }
1150
1151 /**
1152 * Checks whether the cause of the error is detected to be a timeout.
1153 *
1154 * It returns false by default, and not all engines support detecting this yet.
1155 * If this returns false, it will be treated as a generic query error.
1156 *
1157 * @param string $error Error text
1158 * @param int $errno Error number
1159 * @return bool
1160 */
1161 protected function wasQueryTimeout( $error, $errno ) {
1162 return false;
1163 }
1164
1165 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1166 if ( $this->ignoreErrors() || $tempIgnore ) {
1167 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1168 } else {
1169 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1170 $this->queryLogger->error(
1171 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1172 $this->getLogContext( [
1173 'method' => __METHOD__,
1174 'errno' => $errno,
1175 'error' => $error,
1176 'sql1line' => $sql1line,
1177 'fname' => $fname,
1178 ] )
1179 );
1180 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1181 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1182 if ( $wasQueryTimeout ) {
1183 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1184 } else {
1185 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1186 }
1187 }
1188 }
1189
1190 public function freeResult( $res ) {
1191 }
1192
1193 public function selectField(
1194 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1195 ) {
1196 if ( $var === '*' ) { // sanity
1197 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1198 }
1199
1200 if ( !is_array( $options ) ) {
1201 $options = [ $options ];
1202 }
1203
1204 $options['LIMIT'] = 1;
1205
1206 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1207 if ( $res === false || !$this->numRows( $res ) ) {
1208 return false;
1209 }
1210
1211 $row = $this->fetchRow( $res );
1212
1213 if ( $row !== false ) {
1214 return reset( $row );
1215 } else {
1216 return false;
1217 }
1218 }
1219
1220 public function selectFieldValues(
1221 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1222 ) {
1223 if ( $var === '*' ) { // sanity
1224 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1225 } elseif ( !is_string( $var ) ) { // sanity
1226 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1227 }
1228
1229 if ( !is_array( $options ) ) {
1230 $options = [ $options ];
1231 }
1232
1233 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1234 if ( $res === false ) {
1235 return false;
1236 }
1237
1238 $values = [];
1239 foreach ( $res as $row ) {
1240 $values[] = $row->$var;
1241 }
1242
1243 return $values;
1244 }
1245
1246 /**
1247 * Returns an optional USE INDEX clause to go after the table, and a
1248 * string to go at the end of the query.
1249 *
1250 * @param array $options Associative array of options to be turned into
1251 * an SQL query, valid keys are listed in the function.
1252 * @return array
1253 * @see Database::select()
1254 */
1255 protected function makeSelectOptions( $options ) {
1256 $preLimitTail = $postLimitTail = '';
1257 $startOpts = '';
1258
1259 $noKeyOptions = [];
1260
1261 foreach ( $options as $key => $option ) {
1262 if ( is_numeric( $key ) ) {
1263 $noKeyOptions[$option] = true;
1264 }
1265 }
1266
1267 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1268
1269 $preLimitTail .= $this->makeOrderBy( $options );
1270
1271 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1272 $postLimitTail .= ' FOR UPDATE';
1273 }
1274
1275 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1276 $postLimitTail .= ' LOCK IN SHARE MODE';
1277 }
1278
1279 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1280 $startOpts .= 'DISTINCT';
1281 }
1282
1283 # Various MySQL extensions
1284 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1285 $startOpts .= ' /*! STRAIGHT_JOIN */';
1286 }
1287
1288 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1289 $startOpts .= ' HIGH_PRIORITY';
1290 }
1291
1292 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1293 $startOpts .= ' SQL_BIG_RESULT';
1294 }
1295
1296 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1297 $startOpts .= ' SQL_BUFFER_RESULT';
1298 }
1299
1300 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1301 $startOpts .= ' SQL_SMALL_RESULT';
1302 }
1303
1304 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1305 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1306 }
1307
1308 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1309 $startOpts .= ' SQL_CACHE';
1310 }
1311
1312 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1313 $startOpts .= ' SQL_NO_CACHE';
1314 }
1315
1316 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1317 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1318 } else {
1319 $useIndex = '';
1320 }
1321 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1322 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1323 } else {
1324 $ignoreIndex = '';
1325 }
1326
1327 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1328 }
1329
1330 /**
1331 * Returns an optional GROUP BY with an optional HAVING
1332 *
1333 * @param array $options Associative array of options
1334 * @return string
1335 * @see Database::select()
1336 * @since 1.21
1337 */
1338 protected function makeGroupByWithHaving( $options ) {
1339 $sql = '';
1340 if ( isset( $options['GROUP BY'] ) ) {
1341 $gb = is_array( $options['GROUP BY'] )
1342 ? implode( ',', $options['GROUP BY'] )
1343 : $options['GROUP BY'];
1344 $sql .= ' GROUP BY ' . $gb;
1345 }
1346 if ( isset( $options['HAVING'] ) ) {
1347 $having = is_array( $options['HAVING'] )
1348 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1349 : $options['HAVING'];
1350 $sql .= ' HAVING ' . $having;
1351 }
1352
1353 return $sql;
1354 }
1355
1356 /**
1357 * Returns an optional ORDER BY
1358 *
1359 * @param array $options Associative array of options
1360 * @return string
1361 * @see Database::select()
1362 * @since 1.21
1363 */
1364 protected function makeOrderBy( $options ) {
1365 if ( isset( $options['ORDER BY'] ) ) {
1366 $ob = is_array( $options['ORDER BY'] )
1367 ? implode( ',', $options['ORDER BY'] )
1368 : $options['ORDER BY'];
1369
1370 return ' ORDER BY ' . $ob;
1371 }
1372
1373 return '';
1374 }
1375
1376 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1377 $options = [], $join_conds = [] ) {
1378 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1379
1380 return $this->query( $sql, $fname );
1381 }
1382
1383 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1384 $options = [], $join_conds = []
1385 ) {
1386 if ( is_array( $vars ) ) {
1387 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1388 }
1389
1390 $options = (array)$options;
1391 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1392 ? $options['USE INDEX']
1393 : [];
1394 $ignoreIndexes = (
1395 isset( $options['IGNORE INDEX'] ) &&
1396 is_array( $options['IGNORE INDEX'] )
1397 )
1398 ? $options['IGNORE INDEX']
1399 : [];
1400
1401 if ( is_array( $table ) ) {
1402 $from = ' FROM ' .
1403 $this->tableNamesWithIndexClauseOrJOIN(
1404 $table, $useIndexes, $ignoreIndexes, $join_conds );
1405 } elseif ( $table != '' ) {
1406 if ( $table[0] == ' ' ) {
1407 $from = ' FROM ' . $table;
1408 } else {
1409 $from = ' FROM ' .
1410 $this->tableNamesWithIndexClauseOrJOIN(
1411 [ $table ], $useIndexes, $ignoreIndexes, [] );
1412 }
1413 } else {
1414 $from = '';
1415 }
1416
1417 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1418 $this->makeSelectOptions( $options );
1419
1420 if ( !empty( $conds ) ) {
1421 if ( is_array( $conds ) ) {
1422 $conds = $this->makeList( $conds, self::LIST_AND );
1423 }
1424 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1425 "WHERE $conds $preLimitTail";
1426 } else {
1427 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1428 }
1429
1430 if ( isset( $options['LIMIT'] ) ) {
1431 $sql = $this->limitResult( $sql, $options['LIMIT'],
1432 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1433 }
1434 $sql = "$sql $postLimitTail";
1435
1436 if ( isset( $options['EXPLAIN'] ) ) {
1437 $sql = 'EXPLAIN ' . $sql;
1438 }
1439
1440 return $sql;
1441 }
1442
1443 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1444 $options = [], $join_conds = []
1445 ) {
1446 $options = (array)$options;
1447 $options['LIMIT'] = 1;
1448 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1449
1450 if ( $res === false ) {
1451 return false;
1452 }
1453
1454 if ( !$this->numRows( $res ) ) {
1455 return false;
1456 }
1457
1458 $obj = $this->fetchObject( $res );
1459
1460 return $obj;
1461 }
1462
1463 public function estimateRowCount(
1464 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1465 ) {
1466 $rows = 0;
1467 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1468
1469 if ( $res ) {
1470 $row = $this->fetchRow( $res );
1471 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1472 }
1473
1474 return $rows;
1475 }
1476
1477 public function selectRowCount(
1478 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1479 ) {
1480 $rows = 0;
1481 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1482 // The identifier quotes is primarily for MSSQL.
1483 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1484 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1485 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1486
1487 if ( $res ) {
1488 $row = $this->fetchRow( $res );
1489 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1490 }
1491
1492 return $rows;
1493 }
1494
1495 /**
1496 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1497 * It's only slightly flawed. Don't use for anything important.
1498 *
1499 * @param string $sql A SQL Query
1500 *
1501 * @return string
1502 */
1503 protected static function generalizeSQL( $sql ) {
1504 # This does the same as the regexp below would do, but in such a way
1505 # as to avoid crashing php on some large strings.
1506 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1507
1508 $sql = str_replace( "\\\\", '', $sql );
1509 $sql = str_replace( "\\'", '', $sql );
1510 $sql = str_replace( "\\\"", '', $sql );
1511 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1512 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1513
1514 # All newlines, tabs, etc replaced by single space
1515 $sql = preg_replace( '/\s+/', ' ', $sql );
1516
1517 # All numbers => N,
1518 # except the ones surrounded by characters, e.g. l10n
1519 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1520 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1521
1522 return $sql;
1523 }
1524
1525 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1526 $info = $this->fieldInfo( $table, $field );
1527
1528 return (bool)$info;
1529 }
1530
1531 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1532 if ( !$this->tableExists( $table ) ) {
1533 return null;
1534 }
1535
1536 $info = $this->indexInfo( $table, $index, $fname );
1537 if ( is_null( $info ) ) {
1538 return null;
1539 } else {
1540 return $info !== false;
1541 }
1542 }
1543
1544 public function tableExists( $table, $fname = __METHOD__ ) {
1545 $tableRaw = $this->tableName( $table, 'raw' );
1546 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1547 return true; // already known to exist
1548 }
1549
1550 $table = $this->tableName( $table );
1551 $ignoreErrors = true;
1552 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1553
1554 return (bool)$res;
1555 }
1556
1557 public function indexUnique( $table, $index ) {
1558 $indexInfo = $this->indexInfo( $table, $index );
1559
1560 if ( !$indexInfo ) {
1561 return null;
1562 }
1563
1564 return !$indexInfo[0]->Non_unique;
1565 }
1566
1567 /**
1568 * Helper for Database::insert().
1569 *
1570 * @param array $options
1571 * @return string
1572 */
1573 protected function makeInsertOptions( $options ) {
1574 return implode( ' ', $options );
1575 }
1576
1577 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1578 # No rows to insert, easy just return now
1579 if ( !count( $a ) ) {
1580 return true;
1581 }
1582
1583 $table = $this->tableName( $table );
1584
1585 if ( !is_array( $options ) ) {
1586 $options = [ $options ];
1587 }
1588
1589 $fh = null;
1590 if ( isset( $options['fileHandle'] ) ) {
1591 $fh = $options['fileHandle'];
1592 }
1593 $options = $this->makeInsertOptions( $options );
1594
1595 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1596 $multi = true;
1597 $keys = array_keys( $a[0] );
1598 } else {
1599 $multi = false;
1600 $keys = array_keys( $a );
1601 }
1602
1603 $sql = 'INSERT ' . $options .
1604 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1605
1606 if ( $multi ) {
1607 $first = true;
1608 foreach ( $a as $row ) {
1609 if ( $first ) {
1610 $first = false;
1611 } else {
1612 $sql .= ',';
1613 }
1614 $sql .= '(' . $this->makeList( $row ) . ')';
1615 }
1616 } else {
1617 $sql .= '(' . $this->makeList( $a ) . ')';
1618 }
1619
1620 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1621 return false;
1622 } elseif ( $fh !== null ) {
1623 return true;
1624 }
1625
1626 return (bool)$this->query( $sql, $fname );
1627 }
1628
1629 /**
1630 * Make UPDATE options array for Database::makeUpdateOptions
1631 *
1632 * @param array $options
1633 * @return array
1634 */
1635 protected function makeUpdateOptionsArray( $options ) {
1636 if ( !is_array( $options ) ) {
1637 $options = [ $options ];
1638 }
1639
1640 $opts = [];
1641
1642 if ( in_array( 'IGNORE', $options ) ) {
1643 $opts[] = 'IGNORE';
1644 }
1645
1646 return $opts;
1647 }
1648
1649 /**
1650 * Make UPDATE options for the Database::update function
1651 *
1652 * @param array $options The options passed to Database::update
1653 * @return string
1654 */
1655 protected function makeUpdateOptions( $options ) {
1656 $opts = $this->makeUpdateOptionsArray( $options );
1657
1658 return implode( ' ', $opts );
1659 }
1660
1661 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1662 $table = $this->tableName( $table );
1663 $opts = $this->makeUpdateOptions( $options );
1664 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1665
1666 if ( $conds !== [] && $conds !== '*' ) {
1667 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1668 }
1669
1670 return (bool)$this->query( $sql, $fname );
1671 }
1672
1673 public function makeList( $a, $mode = self::LIST_COMMA ) {
1674 if ( !is_array( $a ) ) {
1675 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1676 }
1677
1678 $first = true;
1679 $list = '';
1680
1681 foreach ( $a as $field => $value ) {
1682 if ( !$first ) {
1683 if ( $mode == self::LIST_AND ) {
1684 $list .= ' AND ';
1685 } elseif ( $mode == self::LIST_OR ) {
1686 $list .= ' OR ';
1687 } else {
1688 $list .= ',';
1689 }
1690 } else {
1691 $first = false;
1692 }
1693
1694 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1695 $list .= "($value)";
1696 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1697 $list .= "$value";
1698 } elseif (
1699 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1700 ) {
1701 // Remove null from array to be handled separately if found
1702 $includeNull = false;
1703 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1704 $includeNull = true;
1705 unset( $value[$nullKey] );
1706 }
1707 if ( count( $value ) == 0 && !$includeNull ) {
1708 throw new InvalidArgumentException(
1709 __METHOD__ . ": empty input for field $field" );
1710 } elseif ( count( $value ) == 0 ) {
1711 // only check if $field is null
1712 $list .= "$field IS NULL";
1713 } else {
1714 // IN clause contains at least one valid element
1715 if ( $includeNull ) {
1716 // Group subconditions to ensure correct precedence
1717 $list .= '(';
1718 }
1719 if ( count( $value ) == 1 ) {
1720 // Special-case single values, as IN isn't terribly efficient
1721 // Don't necessarily assume the single key is 0; we don't
1722 // enforce linear numeric ordering on other arrays here.
1723 $value = array_values( $value )[0];
1724 $list .= $field . " = " . $this->addQuotes( $value );
1725 } else {
1726 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1727 }
1728 // if null present in array, append IS NULL
1729 if ( $includeNull ) {
1730 $list .= " OR $field IS NULL)";
1731 }
1732 }
1733 } elseif ( $value === null ) {
1734 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1735 $list .= "$field IS ";
1736 } elseif ( $mode == self::LIST_SET ) {
1737 $list .= "$field = ";
1738 }
1739 $list .= 'NULL';
1740 } else {
1741 if (
1742 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1743 ) {
1744 $list .= "$field = ";
1745 }
1746 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1747 }
1748 }
1749
1750 return $list;
1751 }
1752
1753 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1754 $conds = [];
1755
1756 foreach ( $data as $base => $sub ) {
1757 if ( count( $sub ) ) {
1758 $conds[] = $this->makeList(
1759 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1760 self::LIST_AND );
1761 }
1762 }
1763
1764 if ( $conds ) {
1765 return $this->makeList( $conds, self::LIST_OR );
1766 } else {
1767 // Nothing to search for...
1768 return false;
1769 }
1770 }
1771
1772 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1773 return $valuename;
1774 }
1775
1776 public function bitNot( $field ) {
1777 return "(~$field)";
1778 }
1779
1780 public function bitAnd( $fieldLeft, $fieldRight ) {
1781 return "($fieldLeft & $fieldRight)";
1782 }
1783
1784 public function bitOr( $fieldLeft, $fieldRight ) {
1785 return "($fieldLeft | $fieldRight)";
1786 }
1787
1788 public function buildConcat( $stringList ) {
1789 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1790 }
1791
1792 public function buildGroupConcatField(
1793 $delim, $table, $field, $conds = '', $join_conds = []
1794 ) {
1795 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1796
1797 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1798 }
1799
1800 public function buildStringCast( $field ) {
1801 return $field;
1802 }
1803
1804 public function databasesAreIndependent() {
1805 return false;
1806 }
1807
1808 public function selectDB( $db ) {
1809 # Stub. Shouldn't cause serious problems if it's not overridden, but
1810 # if your database engine supports a concept similar to MySQL's
1811 # databases you may as well.
1812 $this->mDBname = $db;
1813
1814 return true;
1815 }
1816
1817 public function getDBname() {
1818 return $this->mDBname;
1819 }
1820
1821 public function getServer() {
1822 return $this->mServer;
1823 }
1824
1825 public function tableName( $name, $format = 'quoted' ) {
1826 # Skip the entire process when we have a string quoted on both ends.
1827 # Note that we check the end so that we will still quote any use of
1828 # use of `database`.table. But won't break things if someone wants
1829 # to query a database table with a dot in the name.
1830 if ( $this->isQuotedIdentifier( $name ) ) {
1831 return $name;
1832 }
1833
1834 # Lets test for any bits of text that should never show up in a table
1835 # name. Basically anything like JOIN or ON which are actually part of
1836 # SQL queries, but may end up inside of the table value to combine
1837 # sql. Such as how the API is doing.
1838 # Note that we use a whitespace test rather than a \b test to avoid
1839 # any remote case where a word like on may be inside of a table name
1840 # surrounded by symbols which may be considered word breaks.
1841 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1842 return $name;
1843 }
1844
1845 # Split database and table into proper variables.
1846 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1847
1848 # Quote $table and apply the prefix if not quoted.
1849 # $tableName might be empty if this is called from Database::replaceVars()
1850 $tableName = "{$prefix}{$table}";
1851 if ( $format === 'quoted'
1852 && !$this->isQuotedIdentifier( $tableName )
1853 && $tableName !== ''
1854 ) {
1855 $tableName = $this->addIdentifierQuotes( $tableName );
1856 }
1857
1858 # Quote $schema and $database and merge them with the table name if needed
1859 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1860 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1861
1862 return $tableName;
1863 }
1864
1865 /**
1866 * Get the table components needed for a query given the currently selected database
1867 *
1868 * @param string $name Table name in the form of db.schema.table, db.table, or table
1869 * @return array (DB name or "" for default, schema name, table prefix, table name)
1870 */
1871 protected function qualifiedTableComponents( $name ) {
1872 # We reverse the explode so that database.table and table both output the correct table.
1873 $dbDetails = explode( '.', $name, 3 );
1874 if ( count( $dbDetails ) == 3 ) {
1875 list( $database, $schema, $table ) = $dbDetails;
1876 # We don't want any prefix added in this case
1877 $prefix = '';
1878 } elseif ( count( $dbDetails ) == 2 ) {
1879 list( $database, $table ) = $dbDetails;
1880 # We don't want any prefix added in this case
1881 $prefix = '';
1882 # In dbs that support it, $database may actually be the schema
1883 # but that doesn't affect any of the functionality here
1884 $schema = '';
1885 } else {
1886 list( $table ) = $dbDetails;
1887 if ( isset( $this->tableAliases[$table] ) ) {
1888 $database = $this->tableAliases[$table]['dbname'];
1889 $schema = is_string( $this->tableAliases[$table]['schema'] )
1890 ? $this->tableAliases[$table]['schema']
1891 : $this->mSchema;
1892 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1893 ? $this->tableAliases[$table]['prefix']
1894 : $this->mTablePrefix;
1895 } else {
1896 $database = '';
1897 $schema = $this->mSchema; # Default schema
1898 $prefix = $this->mTablePrefix; # Default prefix
1899 }
1900 }
1901
1902 return [ $database, $schema, $prefix, $table ];
1903 }
1904
1905 /**
1906 * @param string|null $namespace Database or schema
1907 * @param string $relation Name of table, view, sequence, etc...
1908 * @param string $format One of (raw, quoted)
1909 * @return string Relation name with quoted and merged $namespace as needed
1910 */
1911 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1912 if ( strlen( $namespace ) ) {
1913 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1914 $namespace = $this->addIdentifierQuotes( $namespace );
1915 }
1916 $relation = $namespace . '.' . $relation;
1917 }
1918
1919 return $relation;
1920 }
1921
1922 public function tableNames() {
1923 $inArray = func_get_args();
1924 $retVal = [];
1925
1926 foreach ( $inArray as $name ) {
1927 $retVal[$name] = $this->tableName( $name );
1928 }
1929
1930 return $retVal;
1931 }
1932
1933 public function tableNamesN() {
1934 $inArray = func_get_args();
1935 $retVal = [];
1936
1937 foreach ( $inArray as $name ) {
1938 $retVal[] = $this->tableName( $name );
1939 }
1940
1941 return $retVal;
1942 }
1943
1944 /**
1945 * Get an aliased table name
1946 * e.g. tableName AS newTableName
1947 *
1948 * @param string $name Table name, see tableName()
1949 * @param string|bool $alias Alias (optional)
1950 * @return string SQL name for aliased table. Will not alias a table to its own name
1951 */
1952 protected function tableNameWithAlias( $name, $alias = false ) {
1953 if ( !$alias || $alias == $name ) {
1954 return $this->tableName( $name );
1955 } else {
1956 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1957 }
1958 }
1959
1960 /**
1961 * Gets an array of aliased table names
1962 *
1963 * @param array $tables [ [alias] => table ]
1964 * @return string[] See tableNameWithAlias()
1965 */
1966 protected function tableNamesWithAlias( $tables ) {
1967 $retval = [];
1968 foreach ( $tables as $alias => $table ) {
1969 if ( is_numeric( $alias ) ) {
1970 $alias = $table;
1971 }
1972 $retval[] = $this->tableNameWithAlias( $table, $alias );
1973 }
1974
1975 return $retval;
1976 }
1977
1978 /**
1979 * Get an aliased field name
1980 * e.g. fieldName AS newFieldName
1981 *
1982 * @param string $name Field name
1983 * @param string|bool $alias Alias (optional)
1984 * @return string SQL name for aliased field. Will not alias a field to its own name
1985 */
1986 protected function fieldNameWithAlias( $name, $alias = false ) {
1987 if ( !$alias || (string)$alias === (string)$name ) {
1988 return $name;
1989 } else {
1990 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1991 }
1992 }
1993
1994 /**
1995 * Gets an array of aliased field names
1996 *
1997 * @param array $fields [ [alias] => field ]
1998 * @return string[] See fieldNameWithAlias()
1999 */
2000 protected function fieldNamesWithAlias( $fields ) {
2001 $retval = [];
2002 foreach ( $fields as $alias => $field ) {
2003 if ( is_numeric( $alias ) ) {
2004 $alias = $field;
2005 }
2006 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2007 }
2008
2009 return $retval;
2010 }
2011
2012 /**
2013 * Get the aliased table name clause for a FROM clause
2014 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2015 *
2016 * @param array $tables ( [alias] => table )
2017 * @param array $use_index Same as for select()
2018 * @param array $ignore_index Same as for select()
2019 * @param array $join_conds Same as for select()
2020 * @return string
2021 */
2022 protected function tableNamesWithIndexClauseOrJOIN(
2023 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2024 ) {
2025 $ret = [];
2026 $retJOIN = [];
2027 $use_index = (array)$use_index;
2028 $ignore_index = (array)$ignore_index;
2029 $join_conds = (array)$join_conds;
2030
2031 foreach ( $tables as $alias => $table ) {
2032 if ( !is_string( $alias ) ) {
2033 // No alias? Set it equal to the table name
2034 $alias = $table;
2035 }
2036
2037 if ( is_array( $table ) ) {
2038 // A parenthesized group
2039 if ( count( $table ) > 1 ) {
2040 $joinedTable = '('
2041 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2042 . ')';
2043 } else {
2044 // Degenerate case
2045 $innerTable = reset( $table );
2046 $innerAlias = key( $table );
2047 $joinedTable = $this->tableNameWithAlias(
2048 $innerTable,
2049 is_string( $innerAlias ) ? $innerAlias : $innerTable
2050 );
2051 }
2052 } else {
2053 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2054 }
2055
2056 // Is there a JOIN clause for this table?
2057 if ( isset( $join_conds[$alias] ) ) {
2058 list( $joinType, $conds ) = $join_conds[$alias];
2059 $tableClause = $joinType;
2060 $tableClause .= ' ' . $joinedTable;
2061 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2062 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2063 if ( $use != '' ) {
2064 $tableClause .= ' ' . $use;
2065 }
2066 }
2067 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2068 $ignore = $this->ignoreIndexClause(
2069 implode( ',', (array)$ignore_index[$alias] ) );
2070 if ( $ignore != '' ) {
2071 $tableClause .= ' ' . $ignore;
2072 }
2073 }
2074 $on = $this->makeList( (array)$conds, self::LIST_AND );
2075 if ( $on != '' ) {
2076 $tableClause .= ' ON (' . $on . ')';
2077 }
2078
2079 $retJOIN[] = $tableClause;
2080 } elseif ( isset( $use_index[$alias] ) ) {
2081 // Is there an INDEX clause for this table?
2082 $tableClause = $joinedTable;
2083 $tableClause .= ' ' . $this->useIndexClause(
2084 implode( ',', (array)$use_index[$alias] )
2085 );
2086
2087 $ret[] = $tableClause;
2088 } elseif ( isset( $ignore_index[$alias] ) ) {
2089 // Is there an INDEX clause for this table?
2090 $tableClause = $joinedTable;
2091 $tableClause .= ' ' . $this->ignoreIndexClause(
2092 implode( ',', (array)$ignore_index[$alias] )
2093 );
2094
2095 $ret[] = $tableClause;
2096 } else {
2097 $tableClause = $joinedTable;
2098
2099 $ret[] = $tableClause;
2100 }
2101 }
2102
2103 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2104 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2105 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2106
2107 // Compile our final table clause
2108 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2109 }
2110
2111 /**
2112 * Allows for index remapping in queries where this is not consistent across DBMS
2113 *
2114 * @param string $index
2115 * @return string
2116 */
2117 protected function indexName( $index ) {
2118 return $index;
2119 }
2120
2121 public function addQuotes( $s ) {
2122 if ( $s instanceof Blob ) {
2123 $s = $s->fetch();
2124 }
2125 if ( $s === null ) {
2126 return 'NULL';
2127 } elseif ( is_bool( $s ) ) {
2128 return (int)$s;
2129 } else {
2130 # This will also quote numeric values. This should be harmless,
2131 # and protects against weird problems that occur when they really
2132 # _are_ strings such as article titles and string->number->string
2133 # conversion is not 1:1.
2134 return "'" . $this->strencode( $s ) . "'";
2135 }
2136 }
2137
2138 /**
2139 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2140 * MySQL uses `backticks` while basically everything else uses double quotes.
2141 * Since MySQL is the odd one out here the double quotes are our generic
2142 * and we implement backticks in DatabaseMysqlBase.
2143 *
2144 * @param string $s
2145 * @return string
2146 */
2147 public function addIdentifierQuotes( $s ) {
2148 return '"' . str_replace( '"', '""', $s ) . '"';
2149 }
2150
2151 /**
2152 * Returns if the given identifier looks quoted or not according to
2153 * the database convention for quoting identifiers .
2154 *
2155 * @note Do not use this to determine if untrusted input is safe.
2156 * A malicious user can trick this function.
2157 * @param string $name
2158 * @return bool
2159 */
2160 public function isQuotedIdentifier( $name ) {
2161 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2162 }
2163
2164 /**
2165 * @param string $s
2166 * @param string $escapeChar
2167 * @return string
2168 */
2169 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2170 return str_replace( [ $escapeChar, '%', '_' ],
2171 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2172 $s );
2173 }
2174
2175 public function buildLike() {
2176 $params = func_get_args();
2177
2178 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2179 $params = $params[0];
2180 }
2181
2182 $s = '';
2183
2184 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2185 // may escape backslashes, creating problems of double escaping. The `
2186 // character has good cross-DBMS compatibility, avoiding special operators
2187 // in MS SQL like ^ and %
2188 $escapeChar = '`';
2189
2190 foreach ( $params as $value ) {
2191 if ( $value instanceof LikeMatch ) {
2192 $s .= $value->toString();
2193 } else {
2194 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2195 }
2196 }
2197
2198 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2199 }
2200
2201 public function anyChar() {
2202 return new LikeMatch( '_' );
2203 }
2204
2205 public function anyString() {
2206 return new LikeMatch( '%' );
2207 }
2208
2209 public function nextSequenceValue( $seqName ) {
2210 return null;
2211 }
2212
2213 /**
2214 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2215 * is only needed because a) MySQL must be as efficient as possible due to
2216 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2217 * which index to pick. Anyway, other databases might have different
2218 * indexes on a given table. So don't bother overriding this unless you're
2219 * MySQL.
2220 * @param string $index
2221 * @return string
2222 */
2223 public function useIndexClause( $index ) {
2224 return '';
2225 }
2226
2227 /**
2228 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2229 * is only needed because a) MySQL must be as efficient as possible due to
2230 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2231 * which index to pick. Anyway, other databases might have different
2232 * indexes on a given table. So don't bother overriding this unless you're
2233 * MySQL.
2234 * @param string $index
2235 * @return string
2236 */
2237 public function ignoreIndexClause( $index ) {
2238 return '';
2239 }
2240
2241 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2242 $quotedTable = $this->tableName( $table );
2243
2244 if ( count( $rows ) == 0 ) {
2245 return;
2246 }
2247
2248 # Single row case
2249 if ( !is_array( reset( $rows ) ) ) {
2250 $rows = [ $rows ];
2251 }
2252
2253 // @FXIME: this is not atomic, but a trx would break affectedRows()
2254 foreach ( $rows as $row ) {
2255 # Delete rows which collide
2256 if ( $uniqueIndexes ) {
2257 $sql = "DELETE FROM $quotedTable WHERE ";
2258 $first = true;
2259 foreach ( $uniqueIndexes as $index ) {
2260 if ( $first ) {
2261 $first = false;
2262 $sql .= '( ';
2263 } else {
2264 $sql .= ' ) OR ( ';
2265 }
2266 if ( is_array( $index ) ) {
2267 $first2 = true;
2268 foreach ( $index as $col ) {
2269 if ( $first2 ) {
2270 $first2 = false;
2271 } else {
2272 $sql .= ' AND ';
2273 }
2274 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2275 }
2276 } else {
2277 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2278 }
2279 }
2280 $sql .= ' )';
2281 $this->query( $sql, $fname );
2282 }
2283
2284 # Now insert the row
2285 $this->insert( $table, $row, $fname );
2286 }
2287 }
2288
2289 /**
2290 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2291 * statement.
2292 *
2293 * @param string $table Table name
2294 * @param array|string $rows Row(s) to insert
2295 * @param string $fname Caller function name
2296 *
2297 * @return ResultWrapper
2298 */
2299 protected function nativeReplace( $table, $rows, $fname ) {
2300 $table = $this->tableName( $table );
2301
2302 # Single row case
2303 if ( !is_array( reset( $rows ) ) ) {
2304 $rows = [ $rows ];
2305 }
2306
2307 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2308 $first = true;
2309
2310 foreach ( $rows as $row ) {
2311 if ( $first ) {
2312 $first = false;
2313 } else {
2314 $sql .= ',';
2315 }
2316
2317 $sql .= '(' . $this->makeList( $row ) . ')';
2318 }
2319
2320 return $this->query( $sql, $fname );
2321 }
2322
2323 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2324 $fname = __METHOD__
2325 ) {
2326 if ( !count( $rows ) ) {
2327 return true; // nothing to do
2328 }
2329
2330 if ( !is_array( reset( $rows ) ) ) {
2331 $rows = [ $rows ];
2332 }
2333
2334 if ( count( $uniqueIndexes ) ) {
2335 $clauses = []; // list WHERE clauses that each identify a single row
2336 foreach ( $rows as $row ) {
2337 foreach ( $uniqueIndexes as $index ) {
2338 $index = is_array( $index ) ? $index : [ $index ]; // columns
2339 $rowKey = []; // unique key to this row
2340 foreach ( $index as $column ) {
2341 $rowKey[$column] = $row[$column];
2342 }
2343 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2344 }
2345 }
2346 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2347 } else {
2348 $where = false;
2349 }
2350
2351 $useTrx = !$this->mTrxLevel;
2352 if ( $useTrx ) {
2353 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2354 }
2355 try {
2356 # Update any existing conflicting row(s)
2357 if ( $where !== false ) {
2358 $ok = $this->update( $table, $set, $where, $fname );
2359 } else {
2360 $ok = true;
2361 }
2362 # Now insert any non-conflicting row(s)
2363 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2364 } catch ( Exception $e ) {
2365 if ( $useTrx ) {
2366 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2367 }
2368 throw $e;
2369 }
2370 if ( $useTrx ) {
2371 $this->commit( $fname, self::FLUSHING_INTERNAL );
2372 }
2373
2374 return $ok;
2375 }
2376
2377 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2378 $fname = __METHOD__
2379 ) {
2380 if ( !$conds ) {
2381 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2382 }
2383
2384 $delTable = $this->tableName( $delTable );
2385 $joinTable = $this->tableName( $joinTable );
2386 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2387 if ( $conds != '*' ) {
2388 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2389 }
2390 $sql .= ')';
2391
2392 $this->query( $sql, $fname );
2393 }
2394
2395 public function textFieldSize( $table, $field ) {
2396 $table = $this->tableName( $table );
2397 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2398 $res = $this->query( $sql, __METHOD__ );
2399 $row = $this->fetchObject( $res );
2400
2401 $m = [];
2402
2403 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2404 $size = $m[1];
2405 } else {
2406 $size = -1;
2407 }
2408
2409 return $size;
2410 }
2411
2412 public function delete( $table, $conds, $fname = __METHOD__ ) {
2413 if ( !$conds ) {
2414 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2415 }
2416
2417 $table = $this->tableName( $table );
2418 $sql = "DELETE FROM $table";
2419
2420 if ( $conds != '*' ) {
2421 if ( is_array( $conds ) ) {
2422 $conds = $this->makeList( $conds, self::LIST_AND );
2423 }
2424 $sql .= ' WHERE ' . $conds;
2425 }
2426
2427 return $this->query( $sql, $fname );
2428 }
2429
2430 public function insertSelect(
2431 $destTable, $srcTable, $varMap, $conds,
2432 $fname = __METHOD__, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2433 ) {
2434 if ( $this->cliMode ) {
2435 // For massive migrations with downtime, we don't want to select everything
2436 // into memory and OOM, so do all this native on the server side if possible.
2437 return $this->nativeInsertSelect(
2438 $destTable,
2439 $srcTable,
2440 $varMap,
2441 $conds,
2442 $fname,
2443 $insertOptions,
2444 $selectOptions,
2445 $selectJoinConds
2446 );
2447 }
2448
2449 return $this->nonNativeInsertSelect(
2450 $destTable,
2451 $srcTable,
2452 $varMap,
2453 $conds,
2454 $fname,
2455 $insertOptions,
2456 $selectOptions,
2457 $selectJoinConds
2458 );
2459 }
2460
2461 /**
2462 * Implementation of insertSelect() based on select() and insert()
2463 *
2464 * @see IDatabase::insertSelect()
2465 * @since 1.30
2466 * @param string $destTable
2467 * @param string|array $srcTable
2468 * @param array $varMap
2469 * @param array $conds
2470 * @param string $fname
2471 * @param array $insertOptions
2472 * @param array $selectOptions
2473 * @param array $selectJoinConds
2474 * @return bool
2475 */
2476 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2477 $fname = __METHOD__,
2478 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2479 ) {
2480 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2481 // on only the master (without needing row-based-replication). It also makes it easy to
2482 // know how big the INSERT is going to be.
2483 $fields = [];
2484 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2485 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2486 }
2487 $selectOptions[] = 'FOR UPDATE';
2488 $res = $this->select(
2489 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2490 );
2491 if ( !$res ) {
2492 return false;
2493 }
2494
2495 $rows = [];
2496 foreach ( $res as $row ) {
2497 $rows[] = (array)$row;
2498 }
2499
2500 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2501 }
2502
2503 /**
2504 * Native server-side implementation of insertSelect() for situations where
2505 * we don't want to select everything into memory
2506 *
2507 * @see IDatabase::insertSelect()
2508 * @param string $destTable
2509 * @param string|array $srcTable
2510 * @param array $varMap
2511 * @param array $conds
2512 * @param string $fname
2513 * @param array $insertOptions
2514 * @param array $selectOptions
2515 * @param array $selectJoinConds
2516 * @return bool
2517 */
2518 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2519 $fname = __METHOD__,
2520 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2521 ) {
2522 $destTable = $this->tableName( $destTable );
2523
2524 if ( !is_array( $insertOptions ) ) {
2525 $insertOptions = [ $insertOptions ];
2526 }
2527
2528 $insertOptions = $this->makeInsertOptions( $insertOptions );
2529
2530 $selectSql = $this->selectSQLText(
2531 $srcTable,
2532 array_values( $varMap ),
2533 $conds,
2534 $fname,
2535 $selectOptions,
2536 $selectJoinConds
2537 );
2538
2539 $sql = "INSERT $insertOptions" .
2540 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2541 $selectSql;
2542
2543 return $this->query( $sql, $fname );
2544 }
2545
2546 /**
2547 * Construct a LIMIT query with optional offset. This is used for query
2548 * pages. The SQL should be adjusted so that only the first $limit rows
2549 * are returned. If $offset is provided as well, then the first $offset
2550 * rows should be discarded, and the next $limit rows should be returned.
2551 * If the result of the query is not ordered, then the rows to be returned
2552 * are theoretically arbitrary.
2553 *
2554 * $sql is expected to be a SELECT, if that makes a difference.
2555 *
2556 * The version provided by default works in MySQL and SQLite. It will very
2557 * likely need to be overridden for most other DBMSes.
2558 *
2559 * @param string $sql SQL query we will append the limit too
2560 * @param int $limit The SQL limit
2561 * @param int|bool $offset The SQL offset (default false)
2562 * @throws DBUnexpectedError
2563 * @return string
2564 */
2565 public function limitResult( $sql, $limit, $offset = false ) {
2566 if ( !is_numeric( $limit ) ) {
2567 throw new DBUnexpectedError( $this,
2568 "Invalid non-numeric limit passed to limitResult()\n" );
2569 }
2570
2571 return "$sql LIMIT "
2572 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2573 . "{$limit} ";
2574 }
2575
2576 public function unionSupportsOrderAndLimit() {
2577 return true; // True for almost every DB supported
2578 }
2579
2580 public function unionQueries( $sqls, $all ) {
2581 $glue = $all ? ') UNION ALL (' : ') UNION (';
2582
2583 return '(' . implode( $glue, $sqls ) . ')';
2584 }
2585
2586 public function unionConditionPermutations(
2587 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__,
2588 $options = [], $join_conds = []
2589 ) {
2590 // First, build the Cartesian product of $permute_conds
2591 $conds = [ [] ];
2592 foreach ( $permute_conds as $field => $values ) {
2593 if ( !$values ) {
2594 // Skip empty $values
2595 continue;
2596 }
2597 $values = array_unique( $values ); // For sanity
2598 $newConds = [];
2599 foreach ( $conds as $cond ) {
2600 foreach ( $values as $value ) {
2601 $cond[$field] = $value;
2602 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2603 }
2604 }
2605 $conds = $newConds;
2606 }
2607
2608 $extra_conds = $extra_conds === '' ? [] : (array)$extra_conds;
2609
2610 // If there's just one condition and no subordering, hand off to
2611 // selectSQLText directly.
2612 if ( count( $conds ) === 1 &&
2613 ( !isset( $options['INNER ORDER BY'] ) || !$this->unionSupportsOrderAndLimit() )
2614 ) {
2615 return $this->selectSQLText(
2616 $table, $vars, $conds[0] + $extra_conds, $fname, $options, $join_conds
2617 );
2618 }
2619
2620 // Otherwise, we need to pull out the order and limit to apply after
2621 // the union. Then build the SQL queries for each set of conditions in
2622 // $conds. Then union them together (using UNION ALL, because the
2623 // product *should* already be distinct).
2624 $orderBy = $this->makeOrderBy( $options );
2625 $limit = isset( $options['LIMIT'] ) ? $options['LIMIT'] : null;
2626 $offset = isset( $options['OFFSET'] ) ? $options['OFFSET'] : false;
2627 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2628 if ( !$this->unionSupportsOrderAndLimit() ) {
2629 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2630 } else {
2631 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2632 $options['ORDER BY'] = $options['INNER ORDER BY'];
2633 }
2634 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2635 // We need to increase the limit by the offset rather than
2636 // using the offset directly, otherwise it'll skip incorrectly
2637 // in the subqueries.
2638 $options['LIMIT'] = $limit + $offset;
2639 unset( $options['OFFSET'] );
2640 }
2641 }
2642
2643 $sqls = [];
2644 foreach ( $conds as $cond ) {
2645 $sqls[] = $this->selectSQLText(
2646 $table, $vars, $cond + $extra_conds, $fname, $options, $join_conds
2647 );
2648 }
2649 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2650 if ( $limit !== null ) {
2651 $sql = $this->limitResult( $sql, $limit, $offset );
2652 }
2653
2654 return $sql;
2655 }
2656
2657 public function conditional( $cond, $trueVal, $falseVal ) {
2658 if ( is_array( $cond ) ) {
2659 $cond = $this->makeList( $cond, self::LIST_AND );
2660 }
2661
2662 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2663 }
2664
2665 public function strreplace( $orig, $old, $new ) {
2666 return "REPLACE({$orig}, {$old}, {$new})";
2667 }
2668
2669 public function getServerUptime() {
2670 return 0;
2671 }
2672
2673 public function wasDeadlock() {
2674 return false;
2675 }
2676
2677 public function wasLockTimeout() {
2678 return false;
2679 }
2680
2681 public function wasErrorReissuable() {
2682 return false;
2683 }
2684
2685 public function wasReadOnlyError() {
2686 return false;
2687 }
2688
2689 /**
2690 * Do not use this method outside of Database/DBError classes
2691 *
2692 * @param int|string $errno
2693 * @return bool Whether the given query error was a connection drop
2694 */
2695 public function wasConnectionError( $errno ) {
2696 return false;
2697 }
2698
2699 public function deadlockLoop() {
2700 $args = func_get_args();
2701 $function = array_shift( $args );
2702 $tries = self::DEADLOCK_TRIES;
2703
2704 $this->begin( __METHOD__ );
2705
2706 $retVal = null;
2707 /** @var Exception $e */
2708 $e = null;
2709 do {
2710 try {
2711 $retVal = call_user_func_array( $function, $args );
2712 break;
2713 } catch ( DBQueryError $e ) {
2714 if ( $this->wasDeadlock() ) {
2715 // Retry after a randomized delay
2716 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2717 } else {
2718 // Throw the error back up
2719 throw $e;
2720 }
2721 }
2722 } while ( --$tries > 0 );
2723
2724 if ( $tries <= 0 ) {
2725 // Too many deadlocks; give up
2726 $this->rollback( __METHOD__ );
2727 throw $e;
2728 } else {
2729 $this->commit( __METHOD__ );
2730
2731 return $retVal;
2732 }
2733 }
2734
2735 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2736 # Real waits are implemented in the subclass.
2737 return 0;
2738 }
2739
2740 public function getReplicaPos() {
2741 # Stub
2742 return false;
2743 }
2744
2745 public function getMasterPos() {
2746 # Stub
2747 return false;
2748 }
2749
2750 public function serverIsReadOnly() {
2751 return false;
2752 }
2753
2754 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2755 if ( !$this->mTrxLevel ) {
2756 throw new DBUnexpectedError( $this, "No transaction is active." );
2757 }
2758 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2759 }
2760
2761 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2762 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2763 if ( !$this->mTrxLevel ) {
2764 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2765 }
2766 }
2767
2768 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2769 if ( $this->mTrxLevel || $this->getFlag( self::DBO_TRX ) ) {
2770 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2771 // an implicit commit of all peer databases. This is true even if a transaction has
2772 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2773 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2774 } else {
2775 // No transaction is active nor will start implicitly, so make one for this callback
2776 $this->startAtomic( __METHOD__ );
2777 try {
2778 call_user_func( $callback );
2779 $this->endAtomic( __METHOD__ );
2780 } catch ( Exception $e ) {
2781 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2782 throw $e;
2783 }
2784 }
2785 }
2786
2787 final public function setTransactionListener( $name, callable $callback = null ) {
2788 if ( $callback ) {
2789 $this->mTrxRecurringCallbacks[$name] = $callback;
2790 } else {
2791 unset( $this->mTrxRecurringCallbacks[$name] );
2792 }
2793 }
2794
2795 /**
2796 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2797 *
2798 * This method should not be used outside of Database/LoadBalancer
2799 *
2800 * @param bool $suppress
2801 * @since 1.28
2802 */
2803 final public function setTrxEndCallbackSuppression( $suppress ) {
2804 $this->mTrxEndCallbacksSuppressed = $suppress;
2805 }
2806
2807 /**
2808 * Actually run and consume any "on transaction idle/resolution" callbacks.
2809 *
2810 * This method should not be used outside of Database/LoadBalancer
2811 *
2812 * @param int $trigger IDatabase::TRIGGER_* constant
2813 * @since 1.20
2814 * @throws Exception
2815 */
2816 public function runOnTransactionIdleCallbacks( $trigger ) {
2817 if ( $this->mTrxEndCallbacksSuppressed ) {
2818 return;
2819 }
2820
2821 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2822 /** @var Exception $e */
2823 $e = null; // first exception
2824 do { // callbacks may add callbacks :)
2825 $callbacks = array_merge(
2826 $this->mTrxIdleCallbacks,
2827 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2828 );
2829 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2830 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2831 foreach ( $callbacks as $callback ) {
2832 try {
2833 list( $phpCallback ) = $callback;
2834 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2835 call_user_func_array( $phpCallback, [ $trigger ] );
2836 if ( $autoTrx ) {
2837 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2838 } else {
2839 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2840 }
2841 } catch ( Exception $ex ) {
2842 call_user_func( $this->errorLogger, $ex );
2843 $e = $e ?: $ex;
2844 // Some callbacks may use startAtomic/endAtomic, so make sure
2845 // their transactions are ended so other callbacks don't fail
2846 if ( $this->trxLevel() ) {
2847 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2848 }
2849 }
2850 }
2851 } while ( count( $this->mTrxIdleCallbacks ) );
2852
2853 if ( $e instanceof Exception ) {
2854 throw $e; // re-throw any first exception
2855 }
2856 }
2857
2858 /**
2859 * Actually run and consume any "on transaction pre-commit" callbacks.
2860 *
2861 * This method should not be used outside of Database/LoadBalancer
2862 *
2863 * @since 1.22
2864 * @throws Exception
2865 */
2866 public function runOnTransactionPreCommitCallbacks() {
2867 $e = null; // first exception
2868 do { // callbacks may add callbacks :)
2869 $callbacks = $this->mTrxPreCommitCallbacks;
2870 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2871 foreach ( $callbacks as $callback ) {
2872 try {
2873 list( $phpCallback ) = $callback;
2874 call_user_func( $phpCallback );
2875 } catch ( Exception $ex ) {
2876 call_user_func( $this->errorLogger, $ex );
2877 $e = $e ?: $ex;
2878 }
2879 }
2880 } while ( count( $this->mTrxPreCommitCallbacks ) );
2881
2882 if ( $e instanceof Exception ) {
2883 throw $e; // re-throw any first exception
2884 }
2885 }
2886
2887 /**
2888 * Actually run any "transaction listener" callbacks.
2889 *
2890 * This method should not be used outside of Database/LoadBalancer
2891 *
2892 * @param int $trigger IDatabase::TRIGGER_* constant
2893 * @throws Exception
2894 * @since 1.20
2895 */
2896 public function runTransactionListenerCallbacks( $trigger ) {
2897 if ( $this->mTrxEndCallbacksSuppressed ) {
2898 return;
2899 }
2900
2901 /** @var Exception $e */
2902 $e = null; // first exception
2903
2904 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2905 try {
2906 $phpCallback( $trigger, $this );
2907 } catch ( Exception $ex ) {
2908 call_user_func( $this->errorLogger, $ex );
2909 $e = $e ?: $ex;
2910 }
2911 }
2912
2913 if ( $e instanceof Exception ) {
2914 throw $e; // re-throw any first exception
2915 }
2916 }
2917
2918 final public function startAtomic( $fname = __METHOD__ ) {
2919 if ( !$this->mTrxLevel ) {
2920 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2921 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2922 // in all changes being in one transaction to keep requests transactional.
2923 if ( !$this->getFlag( self::DBO_TRX ) ) {
2924 $this->mTrxAutomaticAtomic = true;
2925 }
2926 }
2927
2928 $this->mTrxAtomicLevels[] = $fname;
2929 }
2930
2931 final public function endAtomic( $fname = __METHOD__ ) {
2932 if ( !$this->mTrxLevel ) {
2933 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2934 }
2935 if ( !$this->mTrxAtomicLevels ||
2936 array_pop( $this->mTrxAtomicLevels ) !== $fname
2937 ) {
2938 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2939 }
2940
2941 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2942 $this->commit( $fname, self::FLUSHING_INTERNAL );
2943 }
2944 }
2945
2946 final public function doAtomicSection( $fname, callable $callback ) {
2947 $this->startAtomic( $fname );
2948 try {
2949 $res = call_user_func_array( $callback, [ $this, $fname ] );
2950 } catch ( Exception $e ) {
2951 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2952 throw $e;
2953 }
2954 $this->endAtomic( $fname );
2955
2956 return $res;
2957 }
2958
2959 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2960 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2961 if ( $this->mTrxLevel ) {
2962 if ( $this->mTrxAtomicLevels ) {
2963 $levels = implode( ', ', $this->mTrxAtomicLevels );
2964 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2965 throw new DBUnexpectedError( $this, $msg );
2966 } elseif ( !$this->mTrxAutomatic ) {
2967 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2968 throw new DBUnexpectedError( $this, $msg );
2969 } else {
2970 // @TODO: make this an exception at some point
2971 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2972 $this->queryLogger->error( $msg );
2973 return; // join the main transaction set
2974 }
2975 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2976 // @TODO: make this an exception at some point
2977 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2978 $this->queryLogger->error( $msg );
2979 return; // let any writes be in the main transaction
2980 }
2981
2982 // Avoid fatals if close() was called
2983 $this->assertOpen();
2984
2985 $this->doBegin( $fname );
2986 $this->mTrxTimestamp = microtime( true );
2987 $this->mTrxFname = $fname;
2988 $this->mTrxDoneWrites = false;
2989 $this->mTrxAutomaticAtomic = false;
2990 $this->mTrxAtomicLevels = [];
2991 $this->mTrxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2992 $this->mTrxWriteDuration = 0.0;
2993 $this->mTrxWriteQueryCount = 0;
2994 $this->mTrxWriteAffectedRows = 0;
2995 $this->mTrxWriteAdjDuration = 0.0;
2996 $this->mTrxWriteAdjQueryCount = 0;
2997 $this->mTrxWriteCallers = [];
2998 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2999 // Get an estimate of the replica DB lag before then, treating estimate staleness
3000 // as lag itself just to be safe
3001 $status = $this->getApproximateLagStatus();
3002 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3003 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3004 // caller will think its OK to muck around with the transaction just because startAtomic()
3005 // has not yet completed (e.g. setting mTrxAtomicLevels).
3006 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
3007 }
3008
3009 /**
3010 * Issues the BEGIN command to the database server.
3011 *
3012 * @see Database::begin()
3013 * @param string $fname
3014 */
3015 protected function doBegin( $fname ) {
3016 $this->query( 'BEGIN', $fname );
3017 $this->mTrxLevel = 1;
3018 }
3019
3020 final public function commit( $fname = __METHOD__, $flush = '' ) {
3021 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
3022 // There are still atomic sections open. This cannot be ignored
3023 $levels = implode( ', ', $this->mTrxAtomicLevels );
3024 throw new DBUnexpectedError(
3025 $this,
3026 "$fname: Got COMMIT while atomic sections $levels are still open."
3027 );
3028 }
3029
3030 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3031 if ( !$this->mTrxLevel ) {
3032 return; // nothing to do
3033 } elseif ( !$this->mTrxAutomatic ) {
3034 throw new DBUnexpectedError(
3035 $this,
3036 "$fname: Flushing an explicit transaction, getting out of sync."
3037 );
3038 }
3039 } else {
3040 if ( !$this->mTrxLevel ) {
3041 $this->queryLogger->error(
3042 "$fname: No transaction to commit, something got out of sync." );
3043 return; // nothing to do
3044 } elseif ( $this->mTrxAutomatic ) {
3045 // @TODO: make this an exception at some point
3046 $msg = "$fname: Explicit commit of implicit transaction.";
3047 $this->queryLogger->error( $msg );
3048 return; // wait for the main transaction set commit round
3049 }
3050 }
3051
3052 // Avoid fatals if close() was called
3053 $this->assertOpen();
3054
3055 $this->runOnTransactionPreCommitCallbacks();
3056 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
3057 $this->doCommit( $fname );
3058 if ( $this->mTrxDoneWrites ) {
3059 $this->mLastWriteTime = microtime( true );
3060 $this->trxProfiler->transactionWritingOut(
3061 $this->mServer,
3062 $this->mDBname,
3063 $this->mTrxShortId,
3064 $writeTime,
3065 $this->mTrxWriteAffectedRows
3066 );
3067 }
3068
3069 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
3070 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
3071 }
3072
3073 /**
3074 * Issues the COMMIT command to the database server.
3075 *
3076 * @see Database::commit()
3077 * @param string $fname
3078 */
3079 protected function doCommit( $fname ) {
3080 if ( $this->mTrxLevel ) {
3081 $this->query( 'COMMIT', $fname );
3082 $this->mTrxLevel = 0;
3083 }
3084 }
3085
3086 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3087 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
3088 if ( !$this->mTrxLevel ) {
3089 return; // nothing to do
3090 }
3091 } else {
3092 if ( !$this->mTrxLevel ) {
3093 $this->queryLogger->error(
3094 "$fname: No transaction to rollback, something got out of sync." );
3095 return; // nothing to do
3096 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
3097 throw new DBUnexpectedError(
3098 $this,
3099 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3100 );
3101 }
3102 }
3103
3104 // Avoid fatals if close() was called
3105 $this->assertOpen();
3106
3107 $this->doRollback( $fname );
3108 $this->mTrxAtomicLevels = [];
3109 if ( $this->mTrxDoneWrites ) {
3110 $this->trxProfiler->transactionWritingOut(
3111 $this->mServer,
3112 $this->mDBname,
3113 $this->mTrxShortId
3114 );
3115 }
3116
3117 $this->mTrxIdleCallbacks = []; // clear
3118 $this->mTrxPreCommitCallbacks = []; // clear
3119 try {
3120 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
3121 } catch ( Exception $e ) {
3122 // already logged; finish and let LoadBalancer move on during mass-rollback
3123 }
3124 try {
3125 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
3126 } catch ( Exception $e ) {
3127 // already logged; let LoadBalancer move on during mass-rollback
3128 }
3129 }
3130
3131 /**
3132 * Issues the ROLLBACK command to the database server.
3133 *
3134 * @see Database::rollback()
3135 * @param string $fname
3136 */
3137 protected function doRollback( $fname ) {
3138 if ( $this->mTrxLevel ) {
3139 # Disconnects cause rollback anyway, so ignore those errors
3140 $ignoreErrors = true;
3141 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3142 $this->mTrxLevel = 0;
3143 }
3144 }
3145
3146 public function flushSnapshot( $fname = __METHOD__ ) {
3147 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
3148 // This only flushes transactions to clear snapshots, not to write data
3149 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3150 throw new DBUnexpectedError(
3151 $this,
3152 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3153 );
3154 }
3155
3156 $this->commit( $fname, self::FLUSHING_INTERNAL );
3157 }
3158
3159 public function explicitTrxActive() {
3160 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
3161 }
3162
3163 public function duplicateTableStructure(
3164 $oldName, $newName, $temporary = false, $fname = __METHOD__
3165 ) {
3166 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3167 }
3168
3169 public function listTables( $prefix = null, $fname = __METHOD__ ) {
3170 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3171 }
3172
3173 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3174 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
3175 }
3176
3177 public function timestamp( $ts = 0 ) {
3178 $t = new ConvertibleTimestamp( $ts );
3179 // Let errors bubble up to avoid putting garbage in the DB
3180 return $t->getTimestamp( TS_MW );
3181 }
3182
3183 public function timestampOrNull( $ts = null ) {
3184 if ( is_null( $ts ) ) {
3185 return null;
3186 } else {
3187 return $this->timestamp( $ts );
3188 }
3189 }
3190
3191 /**
3192 * Take the result from a query, and wrap it in a ResultWrapper if
3193 * necessary. Boolean values are passed through as is, to indicate success
3194 * of write queries or failure.
3195 *
3196 * Once upon a time, Database::query() returned a bare MySQL result
3197 * resource, and it was necessary to call this function to convert it to
3198 * a wrapper. Nowadays, raw database objects are never exposed to external
3199 * callers, so this is unnecessary in external code.
3200 *
3201 * @param bool|ResultWrapper|resource|object $result
3202 * @return bool|ResultWrapper
3203 */
3204 protected function resultObject( $result ) {
3205 if ( !$result ) {
3206 return false;
3207 } elseif ( $result instanceof ResultWrapper ) {
3208 return $result;
3209 } elseif ( $result === true ) {
3210 // Successful write query
3211 return $result;
3212 } else {
3213 return new ResultWrapper( $this, $result );
3214 }
3215 }
3216
3217 public function ping( &$rtt = null ) {
3218 // Avoid hitting the server if it was hit recently
3219 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
3220 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
3221 $rtt = $this->mRTTEstimate;
3222 return true; // don't care about $rtt
3223 }
3224 }
3225
3226 // This will reconnect if possible or return false if not
3227 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
3228 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
3229 $this->restoreFlags( self::RESTORE_PRIOR );
3230
3231 if ( $ok ) {
3232 $rtt = $this->mRTTEstimate;
3233 }
3234
3235 return $ok;
3236 }
3237
3238 /**
3239 * Close existing database connection and open a new connection
3240 *
3241 * @return bool True if new connection is opened successfully, false if error
3242 */
3243 protected function reconnect() {
3244 $this->closeConnection();
3245 $this->mOpened = false;
3246 $this->mConn = false;
3247 try {
3248 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3249 $this->lastPing = microtime( true );
3250 $ok = true;
3251 } catch ( DBConnectionError $e ) {
3252 $ok = false;
3253 }
3254
3255 return $ok;
3256 }
3257
3258 public function getSessionLagStatus() {
3259 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3260 }
3261
3262 /**
3263 * Get the replica DB lag when the current transaction started
3264 *
3265 * This is useful when transactions might use snapshot isolation
3266 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3267 * is this lag plus transaction duration. If they don't, it is still
3268 * safe to be pessimistic. This returns null if there is no transaction.
3269 *
3270 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3271 * @since 1.27
3272 */
3273 protected function getTransactionLagStatus() {
3274 return $this->mTrxLevel
3275 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3276 : null;
3277 }
3278
3279 /**
3280 * Get a replica DB lag estimate for this server
3281 *
3282 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3283 * @since 1.27
3284 */
3285 protected function getApproximateLagStatus() {
3286 return [
3287 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3288 'since' => microtime( true )
3289 ];
3290 }
3291
3292 /**
3293 * Merge the result of getSessionLagStatus() for several DBs
3294 * using the most pessimistic values to estimate the lag of
3295 * any data derived from them in combination
3296 *
3297 * This is information is useful for caching modules
3298 *
3299 * @see WANObjectCache::set()
3300 * @see WANObjectCache::getWithSetCallback()
3301 *
3302 * @param IDatabase $db1
3303 * @param IDatabase $db2 [optional]
3304 * @return array Map of values:
3305 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3306 * - since: oldest UNIX timestamp of any of the DB lag estimates
3307 * - pending: whether any of the DBs have uncommitted changes
3308 * @throws DBError
3309 * @since 1.27
3310 */
3311 public static function getCacheSetOptions( IDatabase $db1, IDatabase $db2 = null ) {
3312 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3313 foreach ( func_get_args() as $db ) {
3314 /** @var IDatabase $db */
3315 $status = $db->getSessionLagStatus();
3316 if ( $status['lag'] === false ) {
3317 $res['lag'] = false;
3318 } elseif ( $res['lag'] !== false ) {
3319 $res['lag'] = max( $res['lag'], $status['lag'] );
3320 }
3321 $res['since'] = min( $res['since'], $status['since'] );
3322 $res['pending'] = $res['pending'] ?: $db->writesPending();
3323 }
3324
3325 return $res;
3326 }
3327
3328 public function getLag() {
3329 return 0;
3330 }
3331
3332 public function maxListLen() {
3333 return 0;
3334 }
3335
3336 public function encodeBlob( $b ) {
3337 return $b;
3338 }
3339
3340 public function decodeBlob( $b ) {
3341 if ( $b instanceof Blob ) {
3342 $b = $b->fetch();
3343 }
3344 return $b;
3345 }
3346
3347 public function setSessionOptions( array $options ) {
3348 }
3349
3350 public function sourceFile(
3351 $filename,
3352 callable $lineCallback = null,
3353 callable $resultCallback = null,
3354 $fname = false,
3355 callable $inputCallback = null
3356 ) {
3357 MediaWiki\suppressWarnings();
3358 $fp = fopen( $filename, 'r' );
3359 MediaWiki\restoreWarnings();
3360
3361 if ( false === $fp ) {
3362 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3363 }
3364
3365 if ( !$fname ) {
3366 $fname = __METHOD__ . "( $filename )";
3367 }
3368
3369 try {
3370 $error = $this->sourceStream(
3371 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3372 } catch ( Exception $e ) {
3373 fclose( $fp );
3374 throw $e;
3375 }
3376
3377 fclose( $fp );
3378
3379 return $error;
3380 }
3381
3382 public function setSchemaVars( $vars ) {
3383 $this->mSchemaVars = $vars;
3384 }
3385
3386 public function sourceStream(
3387 $fp,
3388 callable $lineCallback = null,
3389 callable $resultCallback = null,
3390 $fname = __METHOD__,
3391 callable $inputCallback = null
3392 ) {
3393 $cmd = '';
3394
3395 while ( !feof( $fp ) ) {
3396 if ( $lineCallback ) {
3397 call_user_func( $lineCallback );
3398 }
3399
3400 $line = trim( fgets( $fp ) );
3401
3402 if ( $line == '' ) {
3403 continue;
3404 }
3405
3406 if ( '-' == $line[0] && '-' == $line[1] ) {
3407 continue;
3408 }
3409
3410 if ( $cmd != '' ) {
3411 $cmd .= ' ';
3412 }
3413
3414 $done = $this->streamStatementEnd( $cmd, $line );
3415
3416 $cmd .= "$line\n";
3417
3418 if ( $done || feof( $fp ) ) {
3419 $cmd = $this->replaceVars( $cmd );
3420
3421 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3422 $res = $this->query( $cmd, $fname );
3423
3424 if ( $resultCallback ) {
3425 call_user_func( $resultCallback, $res, $this );
3426 }
3427
3428 if ( false === $res ) {
3429 $err = $this->lastError();
3430
3431 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3432 }
3433 }
3434 $cmd = '';
3435 }
3436 }
3437
3438 return true;
3439 }
3440
3441 /**
3442 * Called by sourceStream() to check if we've reached a statement end
3443 *
3444 * @param string &$sql SQL assembled so far
3445 * @param string &$newLine New line about to be added to $sql
3446 * @return bool Whether $newLine contains end of the statement
3447 */
3448 public function streamStatementEnd( &$sql, &$newLine ) {
3449 if ( $this->delimiter ) {
3450 $prev = $newLine;
3451 $newLine = preg_replace(
3452 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3453 if ( $newLine != $prev ) {
3454 return true;
3455 }
3456 }
3457
3458 return false;
3459 }
3460
3461 /**
3462 * Database independent variable replacement. Replaces a set of variables
3463 * in an SQL statement with their contents as given by $this->getSchemaVars().
3464 *
3465 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3466 *
3467 * - '{$var}' should be used for text and is passed through the database's
3468 * addQuotes method.
3469 * - `{$var}` should be used for identifiers (e.g. table and database names).
3470 * It is passed through the database's addIdentifierQuotes method which
3471 * can be overridden if the database uses something other than backticks.
3472 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3473 * database's tableName method.
3474 * - / *i* / passes the name that follows through the database's indexName method.
3475 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3476 * its use should be avoided. In 1.24 and older, string encoding was applied.
3477 *
3478 * @param string $ins SQL statement to replace variables in
3479 * @return string The new SQL statement with variables replaced
3480 */
3481 protected function replaceVars( $ins ) {
3482 $vars = $this->getSchemaVars();
3483 return preg_replace_callback(
3484 '!
3485 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3486 \'\{\$ (\w+) }\' | # 3. addQuotes
3487 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3488 /\*\$ (\w+) \*/ # 5. leave unencoded
3489 !x',
3490 function ( $m ) use ( $vars ) {
3491 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3492 // check for both nonexistent keys *and* the empty string.
3493 if ( isset( $m[1] ) && $m[1] !== '' ) {
3494 if ( $m[1] === 'i' ) {
3495 return $this->indexName( $m[2] );
3496 } else {
3497 return $this->tableName( $m[2] );
3498 }
3499 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3500 return $this->addQuotes( $vars[$m[3]] );
3501 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3502 return $this->addIdentifierQuotes( $vars[$m[4]] );
3503 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3504 return $vars[$m[5]];
3505 } else {
3506 return $m[0];
3507 }
3508 },
3509 $ins
3510 );
3511 }
3512
3513 /**
3514 * Get schema variables. If none have been set via setSchemaVars(), then
3515 * use some defaults from the current object.
3516 *
3517 * @return array
3518 */
3519 protected function getSchemaVars() {
3520 if ( $this->mSchemaVars ) {
3521 return $this->mSchemaVars;
3522 } else {
3523 return $this->getDefaultSchemaVars();
3524 }
3525 }
3526
3527 /**
3528 * Get schema variables to use if none have been set via setSchemaVars().
3529 *
3530 * Override this in derived classes to provide variables for tables.sql
3531 * and SQL patch files.
3532 *
3533 * @return array
3534 */
3535 protected function getDefaultSchemaVars() {
3536 return [];
3537 }
3538
3539 public function lockIsFree( $lockName, $method ) {
3540 return true;
3541 }
3542
3543 public function lock( $lockName, $method, $timeout = 5 ) {
3544 $this->mNamedLocksHeld[$lockName] = 1;
3545
3546 return true;
3547 }
3548
3549 public function unlock( $lockName, $method ) {
3550 unset( $this->mNamedLocksHeld[$lockName] );
3551
3552 return true;
3553 }
3554
3555 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3556 if ( $this->writesOrCallbacksPending() ) {
3557 // This only flushes transactions to clear snapshots, not to write data
3558 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3559 throw new DBUnexpectedError(
3560 $this,
3561 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3562 );
3563 }
3564
3565 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3566 return null;
3567 }
3568
3569 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3570 if ( $this->trxLevel() ) {
3571 // There is a good chance an exception was thrown, causing any early return
3572 // from the caller. Let any error handler get a chance to issue rollback().
3573 // If there isn't one, let the error bubble up and trigger server-side rollback.
3574 $this->onTransactionResolution(
3575 function () use ( $lockKey, $fname ) {
3576 $this->unlock( $lockKey, $fname );
3577 },
3578 $fname
3579 );
3580 } else {
3581 $this->unlock( $lockKey, $fname );
3582 }
3583 } );
3584
3585 $this->commit( $fname, self::FLUSHING_INTERNAL );
3586
3587 return $unlocker;
3588 }
3589
3590 public function namedLocksEnqueue() {
3591 return false;
3592 }
3593
3594 public function tableLocksHaveTransactionScope() {
3595 return true;
3596 }
3597
3598 final public function lockTables( array $read, array $write, $method ) {
3599 if ( $this->writesOrCallbacksPending() ) {
3600 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3601 }
3602
3603 if ( $this->tableLocksHaveTransactionScope() ) {
3604 $this->startAtomic( $method );
3605 }
3606
3607 return $this->doLockTables( $read, $write, $method );
3608 }
3609
3610 /**
3611 * Helper function for lockTables() that handles the actual table locking
3612 *
3613 * @param array $read Array of tables to lock for read access
3614 * @param array $write Array of tables to lock for write access
3615 * @param string $method Name of caller
3616 * @return true
3617 */
3618 protected function doLockTables( array $read, array $write, $method ) {
3619 return true;
3620 }
3621
3622 final public function unlockTables( $method ) {
3623 if ( $this->tableLocksHaveTransactionScope() ) {
3624 $this->endAtomic( $method );
3625
3626 return true; // locks released on COMMIT/ROLLBACK
3627 }
3628
3629 return $this->doUnlockTables( $method );
3630 }
3631
3632 /**
3633 * Helper function for unlockTables() that handles the actual table unlocking
3634 *
3635 * @param string $method Name of caller
3636 * @return true
3637 */
3638 protected function doUnlockTables( $method ) {
3639 return true;
3640 }
3641
3642 /**
3643 * Delete a table
3644 * @param string $tableName
3645 * @param string $fName
3646 * @return bool|ResultWrapper
3647 * @since 1.18
3648 */
3649 public function dropTable( $tableName, $fName = __METHOD__ ) {
3650 if ( !$this->tableExists( $tableName, $fName ) ) {
3651 return false;
3652 }
3653 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3654
3655 return $this->query( $sql, $fName );
3656 }
3657
3658 public function getInfinity() {
3659 return 'infinity';
3660 }
3661
3662 public function encodeExpiry( $expiry ) {
3663 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3664 ? $this->getInfinity()
3665 : $this->timestamp( $expiry );
3666 }
3667
3668 public function decodeExpiry( $expiry, $format = TS_MW ) {
3669 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
3670 return 'infinity';
3671 }
3672
3673 return ConvertibleTimestamp::convert( $format, $expiry );
3674 }
3675
3676 public function setBigSelects( $value = true ) {
3677 // no-op
3678 }
3679
3680 public function isReadOnly() {
3681 return ( $this->getReadOnlyReason() !== false );
3682 }
3683
3684 /**
3685 * @return string|bool Reason this DB is read-only or false if it is not
3686 */
3687 protected function getReadOnlyReason() {
3688 $reason = $this->getLBInfo( 'readOnlyReason' );
3689
3690 return is_string( $reason ) ? $reason : false;
3691 }
3692
3693 public function setTableAliases( array $aliases ) {
3694 $this->tableAliases = $aliases;
3695 }
3696
3697 /**
3698 * @return bool Whether a DB user is required to access the DB
3699 * @since 1.28
3700 */
3701 protected function requiresDatabaseUser() {
3702 return true;
3703 }
3704
3705 /**
3706 * Get the underlying binding handle, mConn
3707 *
3708 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3709 * This catches broken callers than catch and ignore disconnection exceptions.
3710 * Unlike checking isOpen(), this is safe to call inside of open().
3711 *
3712 * @return resource|object
3713 * @throws DBUnexpectedError
3714 * @since 1.26
3715 */
3716 protected function getBindingHandle() {
3717 if ( !$this->mConn ) {
3718 throw new DBUnexpectedError(
3719 $this,
3720 'DB connection was already closed or the connection dropped.'
3721 );
3722 }
3723
3724 return $this->mConn;
3725 }
3726
3727 /**
3728 * @since 1.19
3729 * @return string
3730 */
3731 public function __toString() {
3732 return (string)$this->mConn;
3733 }
3734
3735 /**
3736 * Make sure that copies do not share the same client binding handle
3737 * @throws DBConnectionError
3738 */
3739 public function __clone() {
3740 $this->connLogger->warning(
3741 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3742 ( new RuntimeException() )->getTraceAsString()
3743 );
3744
3745 if ( $this->isOpen() ) {
3746 // Open a new connection resource without messing with the old one
3747 $this->mOpened = false;
3748 $this->mConn = false;
3749 $this->mTrxEndCallbacks = []; // don't copy
3750 $this->handleSessionLoss(); // no trx or locks anymore
3751 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3752 $this->lastPing = microtime( true );
3753 }
3754 }
3755
3756 /**
3757 * Called by serialize. Throw an exception when DB connection is serialized.
3758 * This causes problems on some database engines because the connection is
3759 * not restored on unserialize.
3760 */
3761 public function __sleep() {
3762 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3763 'the connection is not restored on wakeup.' );
3764 }
3765
3766 /**
3767 * Run a few simple sanity checks and close dangling connections
3768 */
3769 public function __destruct() {
3770 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3771 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3772 }
3773
3774 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3775 if ( $danglingWriters ) {
3776 $fnames = implode( ', ', $danglingWriters );
3777 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3778 }
3779
3780 if ( $this->mConn ) {
3781 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3782 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3783 \MediaWiki\suppressWarnings();
3784 $this->closeConnection();
3785 \MediaWiki\restoreWarnings();
3786 $this->mConn = false;
3787 $this->mOpened = false;
3788 }
3789 }
3790 }
3791
3792 class_alias( Database::class, 'DatabaseBase' ); // b/c for old name
3793 class_alias( Database::class, 'Database' ); // b/c global alias