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