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