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