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