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