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