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