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