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