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