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