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