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