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