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