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