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