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