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