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