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