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