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