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