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