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