Protect WAN cache sets() against uncommitted data
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2
3 /**
4 * @defgroup Database Database
5 *
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @ingroup Database
26 */
27
28 /**
29 * Database abstraction object
30 * @ingroup Database
31 */
32 abstract class DatabaseBase implements IDatabase {
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES = 4;
35
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX = 1500000;
41
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
45
46 protected $mServer, $mUser, $mPassword, $mDBname;
47
48 /** @var BagOStuff APC cache */
49 protected $srvCache;
50
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
54
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
59
60 protected $mTablePrefix;
61 protected $mSchema;
62 protected $mFlags;
63 protected $mForeign;
64 protected $mLBInfo = array();
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
67 /** @var array */
68 protected $mSessionVars = array();
69
70 protected $preparedArgs;
71
72 protected $htmlErrors;
73
74 protected $delimiter = ';';
75
76 /**
77 * Either 1 if a transaction is active or 0 otherwise.
78 * The other Trx fields may not be meaningfull if this is 0.
79 *
80 * @var int
81 */
82 protected $mTrxLevel = 0;
83
84 /**
85 * Either a short hexidecimal string if a transaction is active or ""
86 *
87 * @var string
88 * @see DatabaseBase::mTrxLevel
89 */
90 protected $mTrxShortId = '';
91
92 /**
93 * The UNIX time that the transaction started. Callers can assume that if
94 * snapshot isolation is used, then the data is *at least* up to date to that
95 * point (possibly more up-to-date since the first SELECT defines the snapshot).
96 *
97 * @var float|null
98 * @see DatabaseBase::mTrxLevel
99 */
100 private $mTrxTimestamp = null;
101
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
104
105 /**
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
108 *
109 * @var string
110 * @see DatabaseBase::mTrxLevel
111 */
112 private $mTrxFname = null;
113
114 /**
115 * Record if possible write queries were done in the last transaction started
116 *
117 * @var bool
118 * @see DatabaseBase::mTrxLevel
119 */
120 private $mTrxDoneWrites = false;
121
122 /**
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
124 *
125 * @var bool
126 * @see DatabaseBase::mTrxLevel
127 */
128 private $mTrxAutomatic = false;
129
130 /**
131 * Array of levels of atomicity within transactions
132 *
133 * @var array
134 */
135 private $mTrxAtomicLevels = array();
136
137 /**
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
139 *
140 * @var bool
141 */
142 private $mTrxAutomaticAtomic = false;
143
144 /**
145 * Track the seconds spent in write queries for the current transaction
146 *
147 * @var float
148 */
149 private $mTrxWriteDuration = 0.0;
150
151 /**
152 * @since 1.21
153 * @var resource File handle for upgrade
154 */
155 protected $fileHandle = null;
156
157 /**
158 * @since 1.22
159 * @var string[] Process cache of VIEWs names in the database
160 */
161 protected $allViews = null;
162
163 /** @var TransactionProfiler */
164 protected $trxProfiler;
165
166 /**
167 * A string describing the current software version, and possibly
168 * other details in a user-friendly way. Will be listed on Special:Version, etc.
169 * Use getServerVersion() to get machine-friendly information.
170 *
171 * @return string Version information from the database server
172 */
173 public function getServerInfo() {
174 return $this->getServerVersion();
175 }
176
177 /**
178 * @return string Command delimiter used by this database engine
179 */
180 public function getDelimiter() {
181 return $this->delimiter;
182 }
183
184 /**
185 * Boolean, controls output of large amounts of debug information.
186 * @param bool|null $debug
187 * - true to enable debugging
188 * - false to disable debugging
189 * - omitted or null to do nothing
190 *
191 * @return bool|null Previous value of the flag
192 */
193 public function debug( $debug = null ) {
194 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
195 }
196
197 /**
198 * Turns buffering of SQL result sets on (true) or off (false). Default is
199 * "on".
200 *
201 * Unbuffered queries are very troublesome in MySQL:
202 *
203 * - If another query is executed while the first query is being read
204 * out, the first query is killed. This means you can't call normal
205 * MediaWiki functions while you are reading an unbuffered query result
206 * from a normal wfGetDB() connection.
207 *
208 * - Unbuffered queries cause the MySQL server to use large amounts of
209 * memory and to hold broad locks which block other queries.
210 *
211 * If you want to limit client-side memory, it's almost always better to
212 * split up queries into batches using a LIMIT clause than to switch off
213 * buffering.
214 *
215 * @param null|bool $buffer
216 * @return null|bool The previous value of the flag
217 */
218 public function bufferResults( $buffer = null ) {
219 if ( is_null( $buffer ) ) {
220 return !(bool)( $this->mFlags & DBO_NOBUFFER );
221 } else {
222 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
223 }
224 }
225
226 /**
227 * Turns on (false) or off (true) the automatic generation and sending
228 * of a "we're sorry, but there has been a database error" page on
229 * database errors. Default is on (false). When turned off, the
230 * code should use lastErrno() and lastError() to handle the
231 * situation as appropriate.
232 *
233 * Do not use this function outside of the Database classes.
234 *
235 * @param null|bool $ignoreErrors
236 * @return bool The previous value of the flag.
237 */
238 protected function ignoreErrors( $ignoreErrors = null ) {
239 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
240 }
241
242 /**
243 * Gets the current transaction level.
244 *
245 * Historically, transactions were allowed to be "nested". This is no
246 * longer supported, so this function really only returns a boolean.
247 *
248 * @return int The previous value
249 */
250 public function trxLevel() {
251 return $this->mTrxLevel;
252 }
253
254 /**
255 * Get the UNIX timestamp of the time that the transaction was established
256 *
257 * This can be used to reason about the staleness of SELECT data
258 * in REPEATABLE-READ transaction isolation level.
259 *
260 * @return float|null Returns null if there is not active transaction
261 * @since 1.25
262 */
263 public function trxTimestamp() {
264 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
265 }
266
267 /**
268 * Get/set the table prefix.
269 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
270 * @return string The previous table prefix.
271 */
272 public function tablePrefix( $prefix = null ) {
273 return wfSetVar( $this->mTablePrefix, $prefix );
274 }
275
276 /**
277 * Get/set the db schema.
278 * @param string $schema The database schema to set, or omitted to leave it unchanged.
279 * @return string The previous db schema.
280 */
281 public function dbSchema( $schema = null ) {
282 return wfSetVar( $this->mSchema, $schema );
283 }
284
285 /**
286 * Set the filehandle to copy write statements to.
287 *
288 * @param resource $fh File handle
289 */
290 public function setFileHandle( $fh ) {
291 $this->fileHandle = $fh;
292 }
293
294 /**
295 * Get properties passed down from the server info array of the load
296 * balancer.
297 *
298 * @param string $name The entry of the info array to get, or null to get the
299 * whole array
300 *
301 * @return array|mixed|null
302 */
303 public function getLBInfo( $name = null ) {
304 if ( is_null( $name ) ) {
305 return $this->mLBInfo;
306 } else {
307 if ( array_key_exists( $name, $this->mLBInfo ) ) {
308 return $this->mLBInfo[$name];
309 } else {
310 return null;
311 }
312 }
313 }
314
315 /**
316 * Set the LB info array, or a member of it. If called with one parameter,
317 * the LB info array is set to that parameter. If it is called with two
318 * parameters, the member with the given name is set to the given value.
319 *
320 * @param string $name
321 * @param array $value
322 */
323 public function setLBInfo( $name, $value = null ) {
324 if ( is_null( $value ) ) {
325 $this->mLBInfo = $name;
326 } else {
327 $this->mLBInfo[$name] = $value;
328 }
329 }
330
331 /**
332 * @return TransactionProfiler
333 */
334 protected function getTransactionProfiler() {
335 return $this->trxProfiler
336 ? $this->trxProfiler
337 : Profiler::instance()->getTransactionProfiler();
338 }
339
340 /**
341 * Returns true if this database supports (and uses) cascading deletes
342 *
343 * @return bool
344 */
345 public function cascadingDeletes() {
346 return false;
347 }
348
349 /**
350 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
351 *
352 * @return bool
353 */
354 public function cleanupTriggers() {
355 return false;
356 }
357
358 /**
359 * Returns true if this database is strict about what can be put into an IP field.
360 * Specifically, it uses a NULL value instead of an empty string.
361 *
362 * @return bool
363 */
364 public function strictIPs() {
365 return false;
366 }
367
368 /**
369 * Returns true if this database uses timestamps rather than integers
370 *
371 * @return bool
372 */
373 public function realTimestamps() {
374 return false;
375 }
376
377 /**
378 * Returns true if this database does an implicit sort when doing GROUP BY
379 *
380 * @return bool
381 */
382 public function implicitGroupby() {
383 return true;
384 }
385
386 /**
387 * Returns true if this database does an implicit order by when the column has an index
388 * For example: SELECT page_title FROM page LIMIT 1
389 *
390 * @return bool
391 */
392 public function implicitOrderby() {
393 return true;
394 }
395
396 /**
397 * Returns true if this database can do a native search on IP columns
398 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
399 *
400 * @return bool
401 */
402 public function searchableIPs() {
403 return false;
404 }
405
406 /**
407 * Returns true if this database can use functional indexes
408 *
409 * @return bool
410 */
411 public function functionalIndexes() {
412 return false;
413 }
414
415 /**
416 * Return the last query that went through DatabaseBase::query()
417 * @return string
418 */
419 public function lastQuery() {
420 return $this->mLastQuery;
421 }
422
423 /**
424 * Returns true if the connection may have been used for write queries.
425 * Should return true if unsure.
426 *
427 * @return bool
428 */
429 public function doneWrites() {
430 return (bool)$this->mDoneWrites;
431 }
432
433 /**
434 * Returns the last time the connection may have been used for write queries.
435 * Should return a timestamp if unsure.
436 *
437 * @return int|float UNIX timestamp or false
438 * @since 1.24
439 */
440 public function lastDoneWrites() {
441 return $this->mDoneWrites ?: false;
442 }
443
444 /**
445 * @return bool Whether there is a transaction open with possible write queries
446 * @since 1.27
447 */
448 public function writesPending() {
449 return $this->mTrxLevel && $this->mTrxDoneWrites;
450 }
451
452 /**
453 * Returns true if there is a transaction open with possible write
454 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
455 *
456 * @return bool
457 */
458 public function writesOrCallbacksPending() {
459 return $this->mTrxLevel && (
460 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
461 );
462 }
463
464 /**
465 * Get the time spend running write queries for this
466 *
467 * High times could be due to scanning, updates, locking, and such
468 *
469 * @return float|bool Returns false if not transaction is active
470 * @since 1.26
471 */
472 public function pendingWriteQueryDuration() {
473 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
474 }
475
476 /**
477 * Is a connection to the database open?
478 * @return bool
479 */
480 public function isOpen() {
481 return $this->mOpened;
482 }
483
484 /**
485 * Set a flag for this connection
486 *
487 * @param int $flag DBO_* constants from Defines.php:
488 * - DBO_DEBUG: output some debug info (same as debug())
489 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
490 * - DBO_TRX: automatically start transactions
491 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
492 * and removes it in command line mode
493 * - DBO_PERSISTENT: use persistant database connection
494 */
495 public function setFlag( $flag ) {
496 $this->mFlags |= $flag;
497 }
498
499 /**
500 * Clear a flag for this connection
501 *
502 * @param int $flag DBO_* constants from Defines.php:
503 * - DBO_DEBUG: output some debug info (same as debug())
504 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
505 * - DBO_TRX: automatically start transactions
506 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
507 * and removes it in command line mode
508 * - DBO_PERSISTENT: use persistant database connection
509 */
510 public function clearFlag( $flag ) {
511 $this->mFlags &= ~$flag;
512 }
513
514 /**
515 * Returns a boolean whether the flag $flag is set for this connection
516 *
517 * @param int $flag DBO_* constants from Defines.php:
518 * - DBO_DEBUG: output some debug info (same as debug())
519 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
520 * - DBO_TRX: automatically start transactions
521 * - DBO_PERSISTENT: use persistant database connection
522 * @return bool
523 */
524 public function getFlag( $flag ) {
525 return !!( $this->mFlags & $flag );
526 }
527
528 /**
529 * General read-only accessor
530 *
531 * @param string $name
532 * @return string
533 */
534 public function getProperty( $name ) {
535 return $this->$name;
536 }
537
538 /**
539 * @return string
540 */
541 public function getWikiID() {
542 if ( $this->mTablePrefix ) {
543 return "{$this->mDBname}-{$this->mTablePrefix}";
544 } else {
545 return $this->mDBname;
546 }
547 }
548
549 /**
550 * Return a path to the DBMS-specific SQL file if it exists,
551 * otherwise default SQL file
552 *
553 * @param string $filename
554 * @return string
555 */
556 private function getSqlFilePath( $filename ) {
557 global $IP;
558 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
559 if ( file_exists( $dbmsSpecificFilePath ) ) {
560 return $dbmsSpecificFilePath;
561 } else {
562 return "$IP/maintenance/$filename";
563 }
564 }
565
566 /**
567 * Return a path to the DBMS-specific schema file,
568 * otherwise default to tables.sql
569 *
570 * @return string
571 */
572 public function getSchemaPath() {
573 return $this->getSqlFilePath( 'tables.sql' );
574 }
575
576 /**
577 * Return a path to the DBMS-specific update key file,
578 * otherwise default to update-keys.sql
579 *
580 * @return string
581 */
582 public function getUpdateKeysPath() {
583 return $this->getSqlFilePath( 'update-keys.sql' );
584 }
585
586 /**
587 * Get information about an index into an object
588 * @param string $table Table name
589 * @param string $index Index name
590 * @param string $fname Calling function name
591 * @return mixed Database-specific index description class or false if the index does not exist
592 */
593 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
594
595 /**
596 * Wrapper for addslashes()
597 *
598 * @param string $s String to be slashed.
599 * @return string Slashed string.
600 */
601 abstract function strencode( $s );
602
603 /**
604 * Constructor.
605 *
606 * FIXME: It is possible to construct a Database object with no associated
607 * connection object, by specifying no parameters to __construct(). This
608 * feature is deprecated and should be removed.
609 *
610 * DatabaseBase subclasses should not be constructed directly in external
611 * code. DatabaseBase::factory() should be used instead.
612 *
613 * @param array $params Parameters passed from DatabaseBase::factory()
614 */
615 function __construct( array $params ) {
616 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
617
618 $this->mTrxAtomicLevels = new SplStack;
619 $this->srvCache = ObjectCache::newAccelerator( 'hash' );
620
621 $server = $params['host'];
622 $user = $params['user'];
623 $password = $params['password'];
624 $dbName = $params['dbname'];
625 $flags = $params['flags'];
626 $tablePrefix = $params['tablePrefix'];
627 $schema = $params['schema'];
628 $foreign = $params['foreign'];
629
630 $this->mFlags = $flags;
631 if ( $this->mFlags & DBO_DEFAULT ) {
632 if ( $wgCommandLineMode ) {
633 $this->mFlags &= ~DBO_TRX;
634 } else {
635 $this->mFlags |= DBO_TRX;
636 }
637 }
638
639 $this->mSessionVars = $params['variables'];
640
641 /** Get the default table prefix*/
642 if ( $tablePrefix === 'get from global' ) {
643 $this->mTablePrefix = $wgDBprefix;
644 } else {
645 $this->mTablePrefix = $tablePrefix;
646 }
647
648 /** Get the database schema*/
649 if ( $schema === 'get from global' ) {
650 $this->mSchema = $wgDBmwschema;
651 } else {
652 $this->mSchema = $schema;
653 }
654
655 $this->mForeign = $foreign;
656
657 if ( isset( $params['trxProfiler'] ) ) {
658 $this->trxProfiler = $params['trxProfiler']; // override
659 }
660
661 if ( $user ) {
662 $this->open( $server, $user, $password, $dbName );
663 }
664 }
665
666 /**
667 * Called by serialize. Throw an exception when DB connection is serialized.
668 * This causes problems on some database engines because the connection is
669 * not restored on unserialize.
670 */
671 public function __sleep() {
672 throw new MWException( 'Database serialization may cause problems, since ' .
673 'the connection is not restored on wakeup.' );
674 }
675
676 /**
677 * Given a DB type, construct the name of the appropriate child class of
678 * DatabaseBase. This is designed to replace all of the manual stuff like:
679 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
680 * as well as validate against the canonical list of DB types we have
681 *
682 * This factory function is mostly useful for when you need to connect to a
683 * database other than the MediaWiki default (such as for external auth,
684 * an extension, et cetera). Do not use this to connect to the MediaWiki
685 * database. Example uses in core:
686 * @see LoadBalancer::reallyOpenConnection()
687 * @see ForeignDBRepo::getMasterDB()
688 * @see WebInstallerDBConnect::execute()
689 *
690 * @since 1.18
691 *
692 * @param string $dbType A possible DB type
693 * @param array $p An array of options to pass to the constructor.
694 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
695 * @throws MWException If the database driver or extension cannot be found
696 * @return DatabaseBase|null DatabaseBase subclass or null
697 */
698 final public static function factory( $dbType, $p = array() ) {
699 $canonicalDBTypes = array(
700 'mysql' => array( 'mysqli', 'mysql' ),
701 'postgres' => array(),
702 'sqlite' => array(),
703 'oracle' => array(),
704 'mssql' => array(),
705 );
706
707 $driver = false;
708 $dbType = strtolower( $dbType );
709 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
710 $possibleDrivers = $canonicalDBTypes[$dbType];
711 if ( !empty( $p['driver'] ) ) {
712 if ( in_array( $p['driver'], $possibleDrivers ) ) {
713 $driver = $p['driver'];
714 } else {
715 throw new MWException( __METHOD__ .
716 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
717 }
718 } else {
719 foreach ( $possibleDrivers as $posDriver ) {
720 if ( extension_loaded( $posDriver ) ) {
721 $driver = $posDriver;
722 break;
723 }
724 }
725 }
726 } else {
727 $driver = $dbType;
728 }
729 if ( $driver === false ) {
730 throw new MWException( __METHOD__ .
731 " no viable database extension found for type '$dbType'" );
732 }
733
734 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
735 // and everything else doesn't use a schema (e.g. null)
736 // Although postgres and oracle support schemas, we don't use them (yet)
737 // to maintain backwards compatibility
738 $defaultSchemas = array(
739 'mssql' => 'get from global',
740 );
741
742 $class = 'Database' . ucfirst( $driver );
743 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
744 // Resolve some defaults for b/c
745 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
746 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
747 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
748 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
749 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
750 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
751 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
752 if ( !isset( $p['schema'] ) ) {
753 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
754 }
755 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
756
757 return new $class( $p );
758 } else {
759 return null;
760 }
761 }
762
763 protected function installErrorHandler() {
764 $this->mPHPError = false;
765 $this->htmlErrors = ini_set( 'html_errors', '0' );
766 set_error_handler( array( $this, 'connectionErrorHandler' ) );
767 }
768
769 /**
770 * @return bool|string
771 */
772 protected function restoreErrorHandler() {
773 restore_error_handler();
774 if ( $this->htmlErrors !== false ) {
775 ini_set( 'html_errors', $this->htmlErrors );
776 }
777 if ( $this->mPHPError ) {
778 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
779 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
780
781 return $error;
782 } else {
783 return false;
784 }
785 }
786
787 /**
788 * @param int $errno
789 * @param string $errstr
790 */
791 public function connectionErrorHandler( $errno, $errstr ) {
792 $this->mPHPError = $errstr;
793 }
794
795 /**
796 * Create a log context to pass to wfLogDBError or other logging functions.
797 *
798 * @param array $extras Additional data to add to context
799 * @return array
800 */
801 protected function getLogContext( array $extras = array() ) {
802 return array_merge(
803 array(
804 'db_server' => $this->mServer,
805 'db_name' => $this->mDBname,
806 'db_user' => $this->mUser,
807 ),
808 $extras
809 );
810 }
811
812 /**
813 * Closes a database connection.
814 * if it is open : commits any open transactions
815 *
816 * @throws MWException
817 * @return bool Operation success. true if already closed.
818 */
819 public function close() {
820 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
821 throw new MWException( "Transaction idle callbacks still pending." );
822 }
823 if ( $this->mConn ) {
824 if ( $this->trxLevel() ) {
825 if ( !$this->mTrxAutomatic ) {
826 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
827 " performing implicit commit before closing connection!" );
828 }
829
830 $this->commit( __METHOD__, 'flush' );
831 }
832
833 $closed = $this->closeConnection();
834 $this->mConn = false;
835 } else {
836 $closed = true;
837 }
838 $this->mOpened = false;
839
840 return $closed;
841 }
842
843 /**
844 * Make sure isOpen() returns true as a sanity check
845 *
846 * @throws DBUnexpectedError
847 */
848 protected function assertOpen() {
849 if ( !$this->isOpen() ) {
850 throw new DBUnexpectedError( $this, "DB connection was already closed." );
851 }
852 }
853
854 /**
855 * Closes underlying database connection
856 * @since 1.20
857 * @return bool Whether connection was closed successfully
858 */
859 abstract protected function closeConnection();
860
861 /**
862 * @param string $error Fallback error message, used if none is given by DB
863 * @throws DBConnectionError
864 */
865 function reportConnectionError( $error = 'Unknown error' ) {
866 $myError = $this->lastError();
867 if ( $myError ) {
868 $error = $myError;
869 }
870
871 # New method
872 throw new DBConnectionError( $this, $error );
873 }
874
875 /**
876 * The DBMS-dependent part of query()
877 *
878 * @param string $sql SQL query.
879 * @return ResultWrapper|bool Result object to feed to fetchObject,
880 * fetchRow, ...; or false on failure
881 */
882 abstract protected function doQuery( $sql );
883
884 /**
885 * Determine whether a query writes to the DB.
886 * Should return true if unsure.
887 *
888 * @param string $sql
889 * @return bool
890 */
891 protected function isWriteQuery( $sql ) {
892 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
893 }
894
895 /**
896 * Determine whether a SQL statement is sensitive to isolation level.
897 * A SQL statement is considered transactable if its result could vary
898 * depending on the transaction isolation level. Operational commands
899 * such as 'SET' and 'SHOW' are not considered to be transactable.
900 *
901 * @param string $sql
902 * @return bool
903 */
904 protected function isTransactableQuery( $sql ) {
905 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
906 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
907 }
908
909 /**
910 * Run an SQL query and return the result. Normally throws a DBQueryError
911 * on failure. If errors are ignored, returns false instead.
912 *
913 * In new code, the query wrappers select(), insert(), update(), delete(),
914 * etc. should be used where possible, since they give much better DBMS
915 * independence and automatically quote or validate user input in a variety
916 * of contexts. This function is generally only useful for queries which are
917 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
918 * as CREATE TABLE.
919 *
920 * However, the query wrappers themselves should call this function.
921 *
922 * @param string $sql SQL query
923 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
924 * comment (you can use __METHOD__ or add some extra info)
925 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
926 * maybe best to catch the exception instead?
927 * @throws MWException
928 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
929 * for a successful read query, or false on failure if $tempIgnore set
930 */
931 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
932 global $wgUser;
933
934 $this->mLastQuery = $sql;
935
936 $isWriteQuery = $this->isWriteQuery( $sql );
937 if ( $isWriteQuery ) {
938 $reason = $this->getReadOnlyReason();
939 if ( $reason !== false ) {
940 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
941 }
942 # Set a flag indicating that writes have been done
943 $this->mDoneWrites = microtime( true );
944 }
945
946 # Add a comment for easy SHOW PROCESSLIST interpretation
947 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
948 $userName = $wgUser->getName();
949 if ( mb_strlen( $userName ) > 15 ) {
950 $userName = mb_substr( $userName, 0, 15 ) . '...';
951 }
952 $userName = str_replace( '/', '', $userName );
953 } else {
954 $userName = '';
955 }
956
957 // Add trace comment to the begin of the sql string, right after the operator.
958 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
959 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
960
961 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
962 $this->begin( __METHOD__ . " ($fname)" );
963 $this->mTrxAutomatic = true;
964 }
965
966 # Keep track of whether the transaction has write queries pending
967 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
968 $this->mTrxDoneWrites = true;
969 $this->getTransactionProfiler()->transactionWritingIn(
970 $this->mServer, $this->mDBname, $this->mTrxShortId );
971 }
972
973 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
974 # generalizeSQL will probably cut down the query to reasonable
975 # logging size most of the time. The substr is really just a sanity check.
976 if ( $isMaster ) {
977 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
978 $totalProf = 'DatabaseBase::query-master';
979 } else {
980 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
981 $totalProf = 'DatabaseBase::query';
982 }
983 # Include query transaction state
984 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
985
986 $profiler = Profiler::instance();
987 if ( !$profiler instanceof ProfilerStub ) {
988 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
989 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
990 }
991
992 if ( $this->debug() ) {
993 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname, $sql ) );
994 }
995
996 $queryId = MWDebug::query( $sql, $fname, $isMaster );
997
998 # Avoid fatals if close() was called
999 $this->assertOpen();
1000
1001 # Do the query and handle errors
1002 $startTime = microtime( true );
1003 $ret = $this->doQuery( $commentedSql );
1004 $queryRuntime = microtime( true ) - $startTime;
1005 # Log the query time and feed it into the DB trx profiler
1006 $this->getTransactionProfiler()->recordQueryCompletion(
1007 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1008
1009 MWDebug::queryTime( $queryId );
1010
1011 # Try reconnecting if the connection was lost
1012 if ( false === $ret && $this->wasErrorReissuable() ) {
1013 # Transaction is gone, like it or not
1014 $hadTrx = $this->mTrxLevel; // possible lost transaction
1015 $this->mTrxLevel = 0;
1016 $this->mTrxIdleCallbacks = array(); // bug 65263
1017 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1018 wfDebug( "Connection lost, reconnecting...\n" );
1019 # Stash the last error values since ping() might clear them
1020 $lastError = $this->lastError();
1021 $lastErrno = $this->lastErrno();
1022 if ( $this->ping() ) {
1023 wfDebug( "Reconnected\n" );
1024 $server = $this->getServer();
1025 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1026 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1027
1028 if ( $hadTrx ) {
1029 # Leave $ret as false and let an error be reported.
1030 # Callers may catch the exception and continue to use the DB.
1031 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1032 } else {
1033 # Should be safe to silently retry (no trx and thus no callbacks)
1034 $startTime = microtime( true );
1035 $ret = $this->doQuery( $commentedSql );
1036 $queryRuntime = microtime( true ) - $startTime;
1037 # Log the query time and feed it into the DB trx profiler
1038 $this->getTransactionProfiler()->recordQueryCompletion(
1039 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1040 }
1041 } else {
1042 wfDebug( "Failed\n" );
1043 }
1044 }
1045
1046 if ( false === $ret ) {
1047 $this->reportQueryError(
1048 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1049 }
1050
1051 $res = $this->resultObject( $ret );
1052
1053 // Destroy profile sections in the opposite order to their creation
1054 ScopedCallback::consume( $queryProfSection );
1055 ScopedCallback::consume( $totalProfSection );
1056
1057 if ( $isWriteQuery && $this->mTrxLevel ) {
1058 $this->mTrxWriteDuration += $queryRuntime;
1059 }
1060
1061 return $res;
1062 }
1063
1064 /**
1065 * Report a query error. Log the error, and if neither the object ignore
1066 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1067 *
1068 * @param string $error
1069 * @param int $errno
1070 * @param string $sql
1071 * @param string $fname
1072 * @param bool $tempIgnore
1073 * @throws DBQueryError
1074 */
1075 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1076 if ( $this->ignoreErrors() || $tempIgnore ) {
1077 wfDebug( "SQL ERROR (ignored): $error\n" );
1078 } else {
1079 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1080 wfLogDBError(
1081 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1082 $this->getLogContext( array(
1083 'method' => __METHOD__,
1084 'errno' => $errno,
1085 'error' => $error,
1086 'sql1line' => $sql1line,
1087 'fname' => $fname,
1088 ) )
1089 );
1090 wfDebug( "SQL ERROR: " . $error . "\n" );
1091 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1092 }
1093 }
1094
1095 /**
1096 * Intended to be compatible with the PEAR::DB wrapper functions.
1097 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1098 *
1099 * ? = scalar value, quoted as necessary
1100 * ! = raw SQL bit (a function for instance)
1101 * & = filename; reads the file and inserts as a blob
1102 * (we don't use this though...)
1103 *
1104 * @param string $sql
1105 * @param string $func
1106 *
1107 * @return array
1108 */
1109 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1110 /* MySQL doesn't support prepared statements (yet), so just
1111 * pack up the query for reference. We'll manually replace
1112 * the bits later.
1113 */
1114 return array( 'query' => $sql, 'func' => $func );
1115 }
1116
1117 /**
1118 * Free a prepared query, generated by prepare().
1119 * @param string $prepared
1120 */
1121 protected function freePrepared( $prepared ) {
1122 /* No-op by default */
1123 }
1124
1125 /**
1126 * Execute a prepared query with the various arguments
1127 * @param string $prepared The prepared sql
1128 * @param mixed $args Either an array here, or put scalars as varargs
1129 *
1130 * @return ResultWrapper
1131 */
1132 public function execute( $prepared, $args = null ) {
1133 if ( !is_array( $args ) ) {
1134 # Pull the var args
1135 $args = func_get_args();
1136 array_shift( $args );
1137 }
1138
1139 $sql = $this->fillPrepared( $prepared['query'], $args );
1140
1141 return $this->query( $sql, $prepared['func'] );
1142 }
1143
1144 /**
1145 * For faking prepared SQL statements on DBs that don't support it directly.
1146 *
1147 * @param string $preparedQuery A 'preparable' SQL statement
1148 * @param array $args Array of Arguments to fill it with
1149 * @return string Executable SQL
1150 */
1151 public function fillPrepared( $preparedQuery, $args ) {
1152 reset( $args );
1153 $this->preparedArgs =& $args;
1154
1155 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1156 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1157 }
1158
1159 /**
1160 * preg_callback func for fillPrepared()
1161 * The arguments should be in $this->preparedArgs and must not be touched
1162 * while we're doing this.
1163 *
1164 * @param array $matches
1165 * @throws DBUnexpectedError
1166 * @return string
1167 */
1168 protected function fillPreparedArg( $matches ) {
1169 switch ( $matches[1] ) {
1170 case '\\?':
1171 return '?';
1172 case '\\!':
1173 return '!';
1174 case '\\&':
1175 return '&';
1176 }
1177
1178 list( /* $n */, $arg ) = each( $this->preparedArgs );
1179
1180 switch ( $matches[1] ) {
1181 case '?':
1182 return $this->addQuotes( $arg );
1183 case '!':
1184 return $arg;
1185 case '&':
1186 # return $this->addQuotes( file_get_contents( $arg ) );
1187 throw new DBUnexpectedError(
1188 $this,
1189 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1190 );
1191 default:
1192 throw new DBUnexpectedError(
1193 $this,
1194 'Received invalid match. This should never happen!'
1195 );
1196 }
1197 }
1198
1199 /**
1200 * Free a result object returned by query() or select(). It's usually not
1201 * necessary to call this, just use unset() or let the variable holding
1202 * the result object go out of scope.
1203 *
1204 * @param mixed $res A SQL result
1205 */
1206 public function freeResult( $res ) {
1207 }
1208
1209 /**
1210 * A SELECT wrapper which returns a single field from a single result row.
1211 *
1212 * Usually throws a DBQueryError on failure. If errors are explicitly
1213 * ignored, returns false on failure.
1214 *
1215 * If no result rows are returned from the query, false is returned.
1216 *
1217 * @param string|array $table Table name. See DatabaseBase::select() for details.
1218 * @param string $var The field name to select. This must be a valid SQL
1219 * fragment: do not use unvalidated user input.
1220 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1221 * @param string $fname The function name of the caller.
1222 * @param string|array $options The query options. See DatabaseBase::select() for details.
1223 *
1224 * @return bool|mixed The value from the field, or false on failure.
1225 * @throws DBUnexpectedError
1226 */
1227 public function selectField(
1228 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1229 ) {
1230 if ( $var === '*' ) { // sanity
1231 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1232 }
1233
1234 if ( !is_array( $options ) ) {
1235 $options = array( $options );
1236 }
1237
1238 $options['LIMIT'] = 1;
1239
1240 $res = $this->select( $table, $var, $cond, $fname, $options );
1241 if ( $res === false || !$this->numRows( $res ) ) {
1242 return false;
1243 }
1244
1245 $row = $this->fetchRow( $res );
1246
1247 if ( $row !== false ) {
1248 return reset( $row );
1249 } else {
1250 return false;
1251 }
1252 }
1253
1254 /**
1255 * A SELECT wrapper which returns a list of single field values from result rows.
1256 *
1257 * Usually throws a DBQueryError on failure. If errors are explicitly
1258 * ignored, returns false on failure.
1259 *
1260 * If no result rows are returned from the query, false is returned.
1261 *
1262 * @param string|array $table Table name. See DatabaseBase::select() for details.
1263 * @param string $var The field name to select. This must be a valid SQL
1264 * fragment: do not use unvalidated user input.
1265 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1266 * @param string $fname The function name of the caller.
1267 * @param string|array $options The query options. See DatabaseBase::select() for details.
1268 *
1269 * @return bool|array The values from the field, or false on failure
1270 * @throws DBUnexpectedError
1271 * @since 1.25
1272 */
1273 public function selectFieldValues(
1274 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1275 ) {
1276 if ( $var === '*' ) { // sanity
1277 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1278 }
1279
1280 if ( !is_array( $options ) ) {
1281 $options = array( $options );
1282 }
1283
1284 $res = $this->select( $table, $var, $cond, $fname, $options );
1285 if ( $res === false ) {
1286 return false;
1287 }
1288
1289 $values = array();
1290 foreach ( $res as $row ) {
1291 $values[] = $row->$var;
1292 }
1293
1294 return $values;
1295 }
1296
1297 /**
1298 * Returns an optional USE INDEX clause to go after the table, and a
1299 * string to go at the end of the query.
1300 *
1301 * @param array $options Associative array of options to be turned into
1302 * an SQL query, valid keys are listed in the function.
1303 * @return array
1304 * @see DatabaseBase::select()
1305 */
1306 public function makeSelectOptions( $options ) {
1307 $preLimitTail = $postLimitTail = '';
1308 $startOpts = '';
1309
1310 $noKeyOptions = array();
1311
1312 foreach ( $options as $key => $option ) {
1313 if ( is_numeric( $key ) ) {
1314 $noKeyOptions[$option] = true;
1315 }
1316 }
1317
1318 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1319
1320 $preLimitTail .= $this->makeOrderBy( $options );
1321
1322 // if (isset($options['LIMIT'])) {
1323 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1324 // isset($options['OFFSET']) ? $options['OFFSET']
1325 // : false);
1326 // }
1327
1328 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1329 $postLimitTail .= ' FOR UPDATE';
1330 }
1331
1332 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1333 $postLimitTail .= ' LOCK IN SHARE MODE';
1334 }
1335
1336 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1337 $startOpts .= 'DISTINCT';
1338 }
1339
1340 # Various MySQL extensions
1341 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1342 $startOpts .= ' /*! STRAIGHT_JOIN */';
1343 }
1344
1345 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1346 $startOpts .= ' HIGH_PRIORITY';
1347 }
1348
1349 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1350 $startOpts .= ' SQL_BIG_RESULT';
1351 }
1352
1353 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1354 $startOpts .= ' SQL_BUFFER_RESULT';
1355 }
1356
1357 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1358 $startOpts .= ' SQL_SMALL_RESULT';
1359 }
1360
1361 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1362 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1363 }
1364
1365 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1366 $startOpts .= ' SQL_CACHE';
1367 }
1368
1369 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1370 $startOpts .= ' SQL_NO_CACHE';
1371 }
1372
1373 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1374 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1375 } else {
1376 $useIndex = '';
1377 }
1378
1379 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1380 }
1381
1382 /**
1383 * Returns an optional GROUP BY with an optional HAVING
1384 *
1385 * @param array $options Associative array of options
1386 * @return string
1387 * @see DatabaseBase::select()
1388 * @since 1.21
1389 */
1390 public function makeGroupByWithHaving( $options ) {
1391 $sql = '';
1392 if ( isset( $options['GROUP BY'] ) ) {
1393 $gb = is_array( $options['GROUP BY'] )
1394 ? implode( ',', $options['GROUP BY'] )
1395 : $options['GROUP BY'];
1396 $sql .= ' GROUP BY ' . $gb;
1397 }
1398 if ( isset( $options['HAVING'] ) ) {
1399 $having = is_array( $options['HAVING'] )
1400 ? $this->makeList( $options['HAVING'], LIST_AND )
1401 : $options['HAVING'];
1402 $sql .= ' HAVING ' . $having;
1403 }
1404
1405 return $sql;
1406 }
1407
1408 /**
1409 * Returns an optional ORDER BY
1410 *
1411 * @param array $options Associative array of options
1412 * @return string
1413 * @see DatabaseBase::select()
1414 * @since 1.21
1415 */
1416 public function makeOrderBy( $options ) {
1417 if ( isset( $options['ORDER BY'] ) ) {
1418 $ob = is_array( $options['ORDER BY'] )
1419 ? implode( ',', $options['ORDER BY'] )
1420 : $options['ORDER BY'];
1421
1422 return ' ORDER BY ' . $ob;
1423 }
1424
1425 return '';
1426 }
1427
1428 /**
1429 * Execute a SELECT query constructed using the various parameters provided.
1430 * See below for full details of the parameters.
1431 *
1432 * @param string|array $table Table name
1433 * @param string|array $vars Field names
1434 * @param string|array $conds Conditions
1435 * @param string $fname Caller function name
1436 * @param array $options Query options
1437 * @param array $join_conds Join conditions
1438 *
1439 *
1440 * @param string|array $table
1441 *
1442 * May be either an array of table names, or a single string holding a table
1443 * name. If an array is given, table aliases can be specified, for example:
1444 *
1445 * array( 'a' => 'user' )
1446 *
1447 * This includes the user table in the query, with the alias "a" available
1448 * for use in field names (e.g. a.user_name).
1449 *
1450 * All of the table names given here are automatically run through
1451 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1452 * added, and various other table name mappings to be performed.
1453 *
1454 *
1455 * @param string|array $vars
1456 *
1457 * May be either a field name or an array of field names. The field names
1458 * can be complete fragments of SQL, for direct inclusion into the SELECT
1459 * query. If an array is given, field aliases can be specified, for example:
1460 *
1461 * array( 'maxrev' => 'MAX(rev_id)' )
1462 *
1463 * This includes an expression with the alias "maxrev" in the query.
1464 *
1465 * If an expression is given, care must be taken to ensure that it is
1466 * DBMS-independent.
1467 *
1468 *
1469 * @param string|array $conds
1470 *
1471 * May be either a string containing a single condition, or an array of
1472 * conditions. If an array is given, the conditions constructed from each
1473 * element are combined with AND.
1474 *
1475 * Array elements may take one of two forms:
1476 *
1477 * - Elements with a numeric key are interpreted as raw SQL fragments.
1478 * - Elements with a string key are interpreted as equality conditions,
1479 * where the key is the field name.
1480 * - If the value of such an array element is a scalar (such as a
1481 * string), it will be treated as data and thus quoted appropriately.
1482 * If it is null, an IS NULL clause will be added.
1483 * - If the value is an array, an IN (...) clause will be constructed
1484 * from its non-null elements, and an IS NULL clause will be added
1485 * if null is present, such that the field may match any of the
1486 * elements in the array. The non-null elements will be quoted.
1487 *
1488 * Note that expressions are often DBMS-dependent in their syntax.
1489 * DBMS-independent wrappers are provided for constructing several types of
1490 * expression commonly used in condition queries. See:
1491 * - DatabaseBase::buildLike()
1492 * - DatabaseBase::conditional()
1493 *
1494 *
1495 * @param string|array $options
1496 *
1497 * Optional: Array of query options. Boolean options are specified by
1498 * including them in the array as a string value with a numeric key, for
1499 * example:
1500 *
1501 * array( 'FOR UPDATE' )
1502 *
1503 * The supported options are:
1504 *
1505 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1506 * with LIMIT can theoretically be used for paging through a result set,
1507 * but this is discouraged in MediaWiki for performance reasons.
1508 *
1509 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1510 * and then the first rows are taken until the limit is reached. LIMIT
1511 * is applied to a result set after OFFSET.
1512 *
1513 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1514 * changed until the next COMMIT.
1515 *
1516 * - DISTINCT: Boolean: return only unique result rows.
1517 *
1518 * - GROUP BY: May be either an SQL fragment string naming a field or
1519 * expression to group by, or an array of such SQL fragments.
1520 *
1521 * - HAVING: May be either an string containing a HAVING clause or an array of
1522 * conditions building the HAVING clause. If an array is given, the conditions
1523 * constructed from each element are combined with AND.
1524 *
1525 * - ORDER BY: May be either an SQL fragment giving a field name or
1526 * expression to order by, or an array of such SQL fragments.
1527 *
1528 * - USE INDEX: This may be either a string giving the index name to use
1529 * for the query, or an array. If it is an associative array, each key
1530 * gives the table name (or alias), each value gives the index name to
1531 * use for that table. All strings are SQL fragments and so should be
1532 * validated by the caller.
1533 *
1534 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1535 * instead of SELECT.
1536 *
1537 * And also the following boolean MySQL extensions, see the MySQL manual
1538 * for documentation:
1539 *
1540 * - LOCK IN SHARE MODE
1541 * - STRAIGHT_JOIN
1542 * - HIGH_PRIORITY
1543 * - SQL_BIG_RESULT
1544 * - SQL_BUFFER_RESULT
1545 * - SQL_SMALL_RESULT
1546 * - SQL_CALC_FOUND_ROWS
1547 * - SQL_CACHE
1548 * - SQL_NO_CACHE
1549 *
1550 *
1551 * @param string|array $join_conds
1552 *
1553 * Optional associative array of table-specific join conditions. In the
1554 * most common case, this is unnecessary, since the join condition can be
1555 * in $conds. However, it is useful for doing a LEFT JOIN.
1556 *
1557 * The key of the array contains the table name or alias. The value is an
1558 * array with two elements, numbered 0 and 1. The first gives the type of
1559 * join, the second is an SQL fragment giving the join condition for that
1560 * table. For example:
1561 *
1562 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1563 *
1564 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1565 * with no rows in it will be returned. If there was a query error, a
1566 * DBQueryError exception will be thrown, except if the "ignore errors"
1567 * option was set, in which case false will be returned.
1568 */
1569 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1570 $options = array(), $join_conds = array() ) {
1571 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1572
1573 return $this->query( $sql, $fname );
1574 }
1575
1576 /**
1577 * The equivalent of DatabaseBase::select() except that the constructed SQL
1578 * is returned, instead of being immediately executed. This can be useful for
1579 * doing UNION queries, where the SQL text of each query is needed. In general,
1580 * however, callers outside of Database classes should just use select().
1581 *
1582 * @param string|array $table Table name
1583 * @param string|array $vars Field names
1584 * @param string|array $conds Conditions
1585 * @param string $fname Caller function name
1586 * @param string|array $options Query options
1587 * @param string|array $join_conds Join conditions
1588 *
1589 * @return string SQL query string.
1590 * @see DatabaseBase::select()
1591 */
1592 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1593 $options = array(), $join_conds = array()
1594 ) {
1595 if ( is_array( $vars ) ) {
1596 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1597 }
1598
1599 $options = (array)$options;
1600 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1601 ? $options['USE INDEX']
1602 : array();
1603
1604 if ( is_array( $table ) ) {
1605 $from = ' FROM ' .
1606 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1607 } elseif ( $table != '' ) {
1608 if ( $table[0] == ' ' ) {
1609 $from = ' FROM ' . $table;
1610 } else {
1611 $from = ' FROM ' .
1612 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1613 }
1614 } else {
1615 $from = '';
1616 }
1617
1618 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1619 $this->makeSelectOptions( $options );
1620
1621 if ( !empty( $conds ) ) {
1622 if ( is_array( $conds ) ) {
1623 $conds = $this->makeList( $conds, LIST_AND );
1624 }
1625 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1626 } else {
1627 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1628 }
1629
1630 if ( isset( $options['LIMIT'] ) ) {
1631 $sql = $this->limitResult( $sql, $options['LIMIT'],
1632 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1633 }
1634 $sql = "$sql $postLimitTail";
1635
1636 if ( isset( $options['EXPLAIN'] ) ) {
1637 $sql = 'EXPLAIN ' . $sql;
1638 }
1639
1640 return $sql;
1641 }
1642
1643 /**
1644 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1645 * that a single row object is returned. If the query returns no rows,
1646 * false is returned.
1647 *
1648 * @param string|array $table Table name
1649 * @param string|array $vars Field names
1650 * @param array $conds Conditions
1651 * @param string $fname Caller function name
1652 * @param string|array $options Query options
1653 * @param array|string $join_conds Join conditions
1654 *
1655 * @return stdClass|bool
1656 */
1657 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1658 $options = array(), $join_conds = array()
1659 ) {
1660 $options = (array)$options;
1661 $options['LIMIT'] = 1;
1662 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1663
1664 if ( $res === false ) {
1665 return false;
1666 }
1667
1668 if ( !$this->numRows( $res ) ) {
1669 return false;
1670 }
1671
1672 $obj = $this->fetchObject( $res );
1673
1674 return $obj;
1675 }
1676
1677 /**
1678 * Estimate the number of rows in dataset
1679 *
1680 * MySQL allows you to estimate the number of rows that would be returned
1681 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1682 * index cardinality statistics, and is notoriously inaccurate, especially
1683 * when large numbers of rows have recently been added or deleted.
1684 *
1685 * For DBMSs that don't support fast result size estimation, this function
1686 * will actually perform the SELECT COUNT(*).
1687 *
1688 * Takes the same arguments as DatabaseBase::select().
1689 *
1690 * @param string $table Table name
1691 * @param string $vars Unused
1692 * @param array|string $conds Filters on the table
1693 * @param string $fname Function name for profiling
1694 * @param array $options Options for select
1695 * @return int Row count
1696 */
1697 public function estimateRowCount(
1698 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1699 ) {
1700 $rows = 0;
1701 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1702
1703 if ( $res ) {
1704 $row = $this->fetchRow( $res );
1705 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1706 }
1707
1708 return $rows;
1709 }
1710
1711 /**
1712 * Get the number of rows in dataset
1713 *
1714 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1715 *
1716 * Takes the same arguments as DatabaseBase::select().
1717 *
1718 * @since 1.27 Added $join_conds parameter
1719 *
1720 * @param array|string $tables Table names
1721 * @param string $vars Unused
1722 * @param array|string $conds Filters on the table
1723 * @param string $fname Function name for profiling
1724 * @param array $options Options for select
1725 * @param array $join_conds Join conditions (since 1.27)
1726 * @return int Row count
1727 */
1728 public function selectRowCount(
1729 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1730 ) {
1731 $rows = 0;
1732 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1733 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1734
1735 if ( $res ) {
1736 $row = $this->fetchRow( $res );
1737 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1738 }
1739
1740 return $rows;
1741 }
1742
1743 /**
1744 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1745 * It's only slightly flawed. Don't use for anything important.
1746 *
1747 * @param string $sql A SQL Query
1748 *
1749 * @return string
1750 */
1751 protected static function generalizeSQL( $sql ) {
1752 # This does the same as the regexp below would do, but in such a way
1753 # as to avoid crashing php on some large strings.
1754 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1755
1756 $sql = str_replace( "\\\\", '', $sql );
1757 $sql = str_replace( "\\'", '', $sql );
1758 $sql = str_replace( "\\\"", '', $sql );
1759 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1760 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1761
1762 # All newlines, tabs, etc replaced by single space
1763 $sql = preg_replace( '/\s+/', ' ', $sql );
1764
1765 # All numbers => N,
1766 # except the ones surrounded by characters, e.g. l10n
1767 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1768 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1769
1770 return $sql;
1771 }
1772
1773 /**
1774 * Determines whether a field exists in a table
1775 *
1776 * @param string $table Table name
1777 * @param string $field Filed to check on that table
1778 * @param string $fname Calling function name (optional)
1779 * @return bool Whether $table has filed $field
1780 */
1781 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1782 $info = $this->fieldInfo( $table, $field );
1783
1784 return (bool)$info;
1785 }
1786
1787 /**
1788 * Determines whether an index exists
1789 * Usually throws a DBQueryError on failure
1790 * If errors are explicitly ignored, returns NULL on failure
1791 *
1792 * @param string $table
1793 * @param string $index
1794 * @param string $fname
1795 * @return bool|null
1796 */
1797 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1798 if ( !$this->tableExists( $table ) ) {
1799 return null;
1800 }
1801
1802 $info = $this->indexInfo( $table, $index, $fname );
1803 if ( is_null( $info ) ) {
1804 return null;
1805 } else {
1806 return $info !== false;
1807 }
1808 }
1809
1810 /**
1811 * Query whether a given table exists
1812 *
1813 * @param string $table
1814 * @param string $fname
1815 * @return bool
1816 */
1817 public function tableExists( $table, $fname = __METHOD__ ) {
1818 $table = $this->tableName( $table );
1819 $old = $this->ignoreErrors( true );
1820 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1821 $this->ignoreErrors( $old );
1822
1823 return (bool)$res;
1824 }
1825
1826 /**
1827 * Determines if a given index is unique
1828 *
1829 * @param string $table
1830 * @param string $index
1831 *
1832 * @return bool
1833 */
1834 public function indexUnique( $table, $index ) {
1835 $indexInfo = $this->indexInfo( $table, $index );
1836
1837 if ( !$indexInfo ) {
1838 return null;
1839 }
1840
1841 return !$indexInfo[0]->Non_unique;
1842 }
1843
1844 /**
1845 * Helper for DatabaseBase::insert().
1846 *
1847 * @param array $options
1848 * @return string
1849 */
1850 protected function makeInsertOptions( $options ) {
1851 return implode( ' ', $options );
1852 }
1853
1854 /**
1855 * INSERT wrapper, inserts an array into a table.
1856 *
1857 * $a may be either:
1858 *
1859 * - A single associative array. The array keys are the field names, and
1860 * the values are the values to insert. The values are treated as data
1861 * and will be quoted appropriately. If NULL is inserted, this will be
1862 * converted to a database NULL.
1863 * - An array with numeric keys, holding a list of associative arrays.
1864 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1865 * each subarray must be identical to each other, and in the same order.
1866 *
1867 * $options is an array of options, with boolean options encoded as values
1868 * with numeric keys, in the same style as $options in
1869 * DatabaseBase::select(). Supported options are:
1870 *
1871 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1872 * any rows which cause duplicate key errors are not inserted. It's
1873 * possible to determine how many rows were successfully inserted using
1874 * DatabaseBase::affectedRows().
1875 *
1876 * @param string $table Table name. This will be passed through
1877 * DatabaseBase::tableName().
1878 * @param array $a Array of rows to insert
1879 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1880 * @param array $options Array of options
1881 *
1882 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1883 * returns success.
1884 *
1885 * @return bool
1886 */
1887 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1888 # No rows to insert, easy just return now
1889 if ( !count( $a ) ) {
1890 return true;
1891 }
1892
1893 $table = $this->tableName( $table );
1894
1895 if ( !is_array( $options ) ) {
1896 $options = array( $options );
1897 }
1898
1899 $fh = null;
1900 if ( isset( $options['fileHandle'] ) ) {
1901 $fh = $options['fileHandle'];
1902 }
1903 $options = $this->makeInsertOptions( $options );
1904
1905 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1906 $multi = true;
1907 $keys = array_keys( $a[0] );
1908 } else {
1909 $multi = false;
1910 $keys = array_keys( $a );
1911 }
1912
1913 $sql = 'INSERT ' . $options .
1914 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1915
1916 if ( $multi ) {
1917 $first = true;
1918 foreach ( $a as $row ) {
1919 if ( $first ) {
1920 $first = false;
1921 } else {
1922 $sql .= ',';
1923 }
1924 $sql .= '(' . $this->makeList( $row ) . ')';
1925 }
1926 } else {
1927 $sql .= '(' . $this->makeList( $a ) . ')';
1928 }
1929
1930 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1931 return false;
1932 } elseif ( $fh !== null ) {
1933 return true;
1934 }
1935
1936 return (bool)$this->query( $sql, $fname );
1937 }
1938
1939 /**
1940 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1941 *
1942 * @param array $options
1943 * @return array
1944 */
1945 protected function makeUpdateOptionsArray( $options ) {
1946 if ( !is_array( $options ) ) {
1947 $options = array( $options );
1948 }
1949
1950 $opts = array();
1951
1952 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1953 $opts[] = $this->lowPriorityOption();
1954 }
1955
1956 if ( in_array( 'IGNORE', $options ) ) {
1957 $opts[] = 'IGNORE';
1958 }
1959
1960 return $opts;
1961 }
1962
1963 /**
1964 * Make UPDATE options for the DatabaseBase::update function
1965 *
1966 * @param array $options The options passed to DatabaseBase::update
1967 * @return string
1968 */
1969 protected function makeUpdateOptions( $options ) {
1970 $opts = $this->makeUpdateOptionsArray( $options );
1971
1972 return implode( ' ', $opts );
1973 }
1974
1975 /**
1976 * UPDATE wrapper. Takes a condition array and a SET array.
1977 *
1978 * @param string $table Name of the table to UPDATE. This will be passed through
1979 * DatabaseBase::tableName().
1980 * @param array $values An array of values to SET. For each array element,
1981 * the key gives the field name, and the value gives the data to set
1982 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1983 * @param array $conds An array of conditions (WHERE). See
1984 * DatabaseBase::select() for the details of the format of condition
1985 * arrays. Use '*' to update all rows.
1986 * @param string $fname The function name of the caller (from __METHOD__),
1987 * for logging and profiling.
1988 * @param array $options An array of UPDATE options, can be:
1989 * - IGNORE: Ignore unique key conflicts
1990 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1991 * @return bool
1992 */
1993 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1994 $table = $this->tableName( $table );
1995 $opts = $this->makeUpdateOptions( $options );
1996 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1997
1998 if ( $conds !== array() && $conds !== '*' ) {
1999 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
2000 }
2001
2002 return $this->query( $sql, $fname );
2003 }
2004
2005 /**
2006 * Makes an encoded list of strings from an array
2007 *
2008 * @param array $a Containing the data
2009 * @param int $mode Constant
2010 * - LIST_COMMA: Comma separated, no field names
2011 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2012 * documentation for $conds in DatabaseBase::select().
2013 * - LIST_OR: ORed WHERE clause (without the WHERE)
2014 * - LIST_SET: Comma separated with field names, like a SET clause
2015 * - LIST_NAMES: Comma separated field names
2016 * @throws MWException|DBUnexpectedError
2017 * @return string
2018 */
2019 public function makeList( $a, $mode = LIST_COMMA ) {
2020 if ( !is_array( $a ) ) {
2021 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2022 }
2023
2024 $first = true;
2025 $list = '';
2026
2027 foreach ( $a as $field => $value ) {
2028 if ( !$first ) {
2029 if ( $mode == LIST_AND ) {
2030 $list .= ' AND ';
2031 } elseif ( $mode == LIST_OR ) {
2032 $list .= ' OR ';
2033 } else {
2034 $list .= ',';
2035 }
2036 } else {
2037 $first = false;
2038 }
2039
2040 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2041 $list .= "($value)";
2042 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2043 $list .= "$value";
2044 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2045 // Remove null from array to be handled separately if found
2046 $includeNull = false;
2047 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2048 $includeNull = true;
2049 unset( $value[$nullKey] );
2050 }
2051 if ( count( $value ) == 0 && !$includeNull ) {
2052 throw new MWException( __METHOD__ . ": empty input for field $field" );
2053 } elseif ( count( $value ) == 0 ) {
2054 // only check if $field is null
2055 $list .= "$field IS NULL";
2056 } else {
2057 // IN clause contains at least one valid element
2058 if ( $includeNull ) {
2059 // Group subconditions to ensure correct precedence
2060 $list .= '(';
2061 }
2062 if ( count( $value ) == 1 ) {
2063 // Special-case single values, as IN isn't terribly efficient
2064 // Don't necessarily assume the single key is 0; we don't
2065 // enforce linear numeric ordering on other arrays here.
2066 $value = array_values( $value );
2067 $list .= $field . " = " . $this->addQuotes( $value[0] );
2068 } else {
2069 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2070 }
2071 // if null present in array, append IS NULL
2072 if ( $includeNull ) {
2073 $list .= " OR $field IS NULL)";
2074 }
2075 }
2076 } elseif ( $value === null ) {
2077 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2078 $list .= "$field IS ";
2079 } elseif ( $mode == LIST_SET ) {
2080 $list .= "$field = ";
2081 }
2082 $list .= 'NULL';
2083 } else {
2084 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2085 $list .= "$field = ";
2086 }
2087 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2088 }
2089 }
2090
2091 return $list;
2092 }
2093
2094 /**
2095 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2096 * The keys on each level may be either integers or strings.
2097 *
2098 * @param array $data Organized as 2-d
2099 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2100 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2101 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2102 * @return string|bool SQL fragment, or false if no items in array
2103 */
2104 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2105 $conds = array();
2106
2107 foreach ( $data as $base => $sub ) {
2108 if ( count( $sub ) ) {
2109 $conds[] = $this->makeList(
2110 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2111 LIST_AND );
2112 }
2113 }
2114
2115 if ( $conds ) {
2116 return $this->makeList( $conds, LIST_OR );
2117 } else {
2118 // Nothing to search for...
2119 return false;
2120 }
2121 }
2122
2123 /**
2124 * Return aggregated value alias
2125 *
2126 * @param array $valuedata
2127 * @param string $valuename
2128 *
2129 * @return string
2130 */
2131 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2132 return $valuename;
2133 }
2134
2135 /**
2136 * @param string $field
2137 * @return string
2138 */
2139 public function bitNot( $field ) {
2140 return "(~$field)";
2141 }
2142
2143 /**
2144 * @param string $fieldLeft
2145 * @param string $fieldRight
2146 * @return string
2147 */
2148 public function bitAnd( $fieldLeft, $fieldRight ) {
2149 return "($fieldLeft & $fieldRight)";
2150 }
2151
2152 /**
2153 * @param string $fieldLeft
2154 * @param string $fieldRight
2155 * @return string
2156 */
2157 public function bitOr( $fieldLeft, $fieldRight ) {
2158 return "($fieldLeft | $fieldRight)";
2159 }
2160
2161 /**
2162 * Build a concatenation list to feed into a SQL query
2163 * @param array $stringList List of raw SQL expressions; caller is
2164 * responsible for any quoting
2165 * @return string
2166 */
2167 public function buildConcat( $stringList ) {
2168 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2169 }
2170
2171 /**
2172 * Build a GROUP_CONCAT or equivalent statement for a query.
2173 *
2174 * This is useful for combining a field for several rows into a single string.
2175 * NULL values will not appear in the output, duplicated values will appear,
2176 * and the resulting delimiter-separated values have no defined sort order.
2177 * Code using the results may need to use the PHP unique() or sort() methods.
2178 *
2179 * @param string $delim Glue to bind the results together
2180 * @param string|array $table Table name
2181 * @param string $field Field name
2182 * @param string|array $conds Conditions
2183 * @param string|array $join_conds Join conditions
2184 * @return string SQL text
2185 * @since 1.23
2186 */
2187 public function buildGroupConcatField(
2188 $delim, $table, $field, $conds = '', $join_conds = array()
2189 ) {
2190 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2191
2192 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2193 }
2194
2195 /**
2196 * Change the current database
2197 *
2198 * @todo Explain what exactly will fail if this is not overridden.
2199 *
2200 * @param string $db
2201 *
2202 * @return bool Success or failure
2203 */
2204 public function selectDB( $db ) {
2205 # Stub. Shouldn't cause serious problems if it's not overridden, but
2206 # if your database engine supports a concept similar to MySQL's
2207 # databases you may as well.
2208 $this->mDBname = $db;
2209
2210 return true;
2211 }
2212
2213 /**
2214 * Get the current DB name
2215 * @return string
2216 */
2217 public function getDBname() {
2218 return $this->mDBname;
2219 }
2220
2221 /**
2222 * Get the server hostname or IP address
2223 * @return string
2224 */
2225 public function getServer() {
2226 return $this->mServer;
2227 }
2228
2229 /**
2230 * Format a table name ready for use in constructing an SQL query
2231 *
2232 * This does two important things: it quotes the table names to clean them up,
2233 * and it adds a table prefix if only given a table name with no quotes.
2234 *
2235 * All functions of this object which require a table name call this function
2236 * themselves. Pass the canonical name to such functions. This is only needed
2237 * when calling query() directly.
2238 *
2239 * @param string $name Database table name
2240 * @param string $format One of:
2241 * quoted - Automatically pass the table name through addIdentifierQuotes()
2242 * so that it can be used in a query.
2243 * raw - Do not add identifier quotes to the table name
2244 * @return string Full database name
2245 */
2246 public function tableName( $name, $format = 'quoted' ) {
2247 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2248 # Skip the entire process when we have a string quoted on both ends.
2249 # Note that we check the end so that we will still quote any use of
2250 # use of `database`.table. But won't break things if someone wants
2251 # to query a database table with a dot in the name.
2252 if ( $this->isQuotedIdentifier( $name ) ) {
2253 return $name;
2254 }
2255
2256 # Lets test for any bits of text that should never show up in a table
2257 # name. Basically anything like JOIN or ON which are actually part of
2258 # SQL queries, but may end up inside of the table value to combine
2259 # sql. Such as how the API is doing.
2260 # Note that we use a whitespace test rather than a \b test to avoid
2261 # any remote case where a word like on may be inside of a table name
2262 # surrounded by symbols which may be considered word breaks.
2263 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2264 return $name;
2265 }
2266
2267 # Split database and table into proper variables.
2268 # We reverse the explode so that database.table and table both output
2269 # the correct table.
2270 $dbDetails = explode( '.', $name, 3 );
2271 if ( count( $dbDetails ) == 3 ) {
2272 list( $database, $schema, $table ) = $dbDetails;
2273 # We don't want any prefix added in this case
2274 $prefix = '';
2275 } elseif ( count( $dbDetails ) == 2 ) {
2276 list( $database, $table ) = $dbDetails;
2277 # We don't want any prefix added in this case
2278 # In dbs that support it, $database may actually be the schema
2279 # but that doesn't affect any of the functionality here
2280 $prefix = '';
2281 $schema = null;
2282 } else {
2283 list( $table ) = $dbDetails;
2284 if ( $wgSharedDB !== null # We have a shared database
2285 && $this->mForeign == false # We're not working on a foreign database
2286 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2287 && in_array( $table, $wgSharedTables ) # A shared table is selected
2288 ) {
2289 $database = $wgSharedDB;
2290 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2291 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2292 } else {
2293 $database = null;
2294 $schema = $this->mSchema; # Default schema
2295 $prefix = $this->mTablePrefix; # Default prefix
2296 }
2297 }
2298
2299 # Quote $table and apply the prefix if not quoted.
2300 # $tableName might be empty if this is called from Database::replaceVars()
2301 $tableName = "{$prefix}{$table}";
2302 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2303 $tableName = $this->addIdentifierQuotes( $tableName );
2304 }
2305
2306 # Quote $schema and merge it with the table name if needed
2307 if ( strlen( $schema ) ) {
2308 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2309 $schema = $this->addIdentifierQuotes( $schema );
2310 }
2311 $tableName = $schema . '.' . $tableName;
2312 }
2313
2314 # Quote $database and merge it with the table name if needed
2315 if ( $database !== null ) {
2316 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2317 $database = $this->addIdentifierQuotes( $database );
2318 }
2319 $tableName = $database . '.' . $tableName;
2320 }
2321
2322 return $tableName;
2323 }
2324
2325 /**
2326 * Fetch a number of table names into an array
2327 * This is handy when you need to construct SQL for joins
2328 *
2329 * Example:
2330 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2331 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2332 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2333 *
2334 * @return array
2335 */
2336 public function tableNames() {
2337 $inArray = func_get_args();
2338 $retVal = array();
2339
2340 foreach ( $inArray as $name ) {
2341 $retVal[$name] = $this->tableName( $name );
2342 }
2343
2344 return $retVal;
2345 }
2346
2347 /**
2348 * Fetch a number of table names into an zero-indexed numerical array
2349 * This is handy when you need to construct SQL for joins
2350 *
2351 * Example:
2352 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2353 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2354 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2355 *
2356 * @return array
2357 */
2358 public function tableNamesN() {
2359 $inArray = func_get_args();
2360 $retVal = array();
2361
2362 foreach ( $inArray as $name ) {
2363 $retVal[] = $this->tableName( $name );
2364 }
2365
2366 return $retVal;
2367 }
2368
2369 /**
2370 * Get an aliased table name
2371 * e.g. tableName AS newTableName
2372 *
2373 * @param string $name Table name, see tableName()
2374 * @param string|bool $alias Alias (optional)
2375 * @return string SQL name for aliased table. Will not alias a table to its own name
2376 */
2377 public function tableNameWithAlias( $name, $alias = false ) {
2378 if ( !$alias || $alias == $name ) {
2379 return $this->tableName( $name );
2380 } else {
2381 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2382 }
2383 }
2384
2385 /**
2386 * Gets an array of aliased table names
2387 *
2388 * @param array $tables Array( [alias] => table )
2389 * @return string[] See tableNameWithAlias()
2390 */
2391 public function tableNamesWithAlias( $tables ) {
2392 $retval = array();
2393 foreach ( $tables as $alias => $table ) {
2394 if ( is_numeric( $alias ) ) {
2395 $alias = $table;
2396 }
2397 $retval[] = $this->tableNameWithAlias( $table, $alias );
2398 }
2399
2400 return $retval;
2401 }
2402
2403 /**
2404 * Get an aliased field name
2405 * e.g. fieldName AS newFieldName
2406 *
2407 * @param string $name Field name
2408 * @param string|bool $alias Alias (optional)
2409 * @return string SQL name for aliased field. Will not alias a field to its own name
2410 */
2411 public function fieldNameWithAlias( $name, $alias = false ) {
2412 if ( !$alias || (string)$alias === (string)$name ) {
2413 return $name;
2414 } else {
2415 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2416 }
2417 }
2418
2419 /**
2420 * Gets an array of aliased field names
2421 *
2422 * @param array $fields Array( [alias] => field )
2423 * @return string[] See fieldNameWithAlias()
2424 */
2425 public function fieldNamesWithAlias( $fields ) {
2426 $retval = array();
2427 foreach ( $fields as $alias => $field ) {
2428 if ( is_numeric( $alias ) ) {
2429 $alias = $field;
2430 }
2431 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2432 }
2433
2434 return $retval;
2435 }
2436
2437 /**
2438 * Get the aliased table name clause for a FROM clause
2439 * which might have a JOIN and/or USE INDEX clause
2440 *
2441 * @param array $tables ( [alias] => table )
2442 * @param array $use_index Same as for select()
2443 * @param array $join_conds Same as for select()
2444 * @return string
2445 */
2446 protected function tableNamesWithUseIndexOrJOIN(
2447 $tables, $use_index = array(), $join_conds = array()
2448 ) {
2449 $ret = array();
2450 $retJOIN = array();
2451 $use_index = (array)$use_index;
2452 $join_conds = (array)$join_conds;
2453
2454 foreach ( $tables as $alias => $table ) {
2455 if ( !is_string( $alias ) ) {
2456 // No alias? Set it equal to the table name
2457 $alias = $table;
2458 }
2459 // Is there a JOIN clause for this table?
2460 if ( isset( $join_conds[$alias] ) ) {
2461 list( $joinType, $conds ) = $join_conds[$alias];
2462 $tableClause = $joinType;
2463 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2464 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2465 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2466 if ( $use != '' ) {
2467 $tableClause .= ' ' . $use;
2468 }
2469 }
2470 $on = $this->makeList( (array)$conds, LIST_AND );
2471 if ( $on != '' ) {
2472 $tableClause .= ' ON (' . $on . ')';
2473 }
2474
2475 $retJOIN[] = $tableClause;
2476 } elseif ( isset( $use_index[$alias] ) ) {
2477 // Is there an INDEX clause for this table?
2478 $tableClause = $this->tableNameWithAlias( $table, $alias );
2479 $tableClause .= ' ' . $this->useIndexClause(
2480 implode( ',', (array)$use_index[$alias] )
2481 );
2482
2483 $ret[] = $tableClause;
2484 } else {
2485 $tableClause = $this->tableNameWithAlias( $table, $alias );
2486
2487 $ret[] = $tableClause;
2488 }
2489 }
2490
2491 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2492 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2493 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2494
2495 // Compile our final table clause
2496 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2497 }
2498
2499 /**
2500 * Get the name of an index in a given table.
2501 *
2502 * @protected Don't use outside of DatabaseBase and childs
2503 * @param string $index
2504 * @return string
2505 */
2506 public function indexName( $index ) {
2507 // @FIXME: Make this protected once we move away from PHP 5.3
2508 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2509
2510 // Backwards-compatibility hack
2511 $renamed = array(
2512 'ar_usertext_timestamp' => 'usertext_timestamp',
2513 'un_user_id' => 'user_id',
2514 'un_user_ip' => 'user_ip',
2515 );
2516
2517 if ( isset( $renamed[$index] ) ) {
2518 return $renamed[$index];
2519 } else {
2520 return $index;
2521 }
2522 }
2523
2524 /**
2525 * Adds quotes and backslashes.
2526 *
2527 * @param string|Blob $s
2528 * @return string
2529 */
2530 public function addQuotes( $s ) {
2531 if ( $s instanceof Blob ) {
2532 $s = $s->fetch();
2533 }
2534 if ( $s === null ) {
2535 return 'NULL';
2536 } else {
2537 # This will also quote numeric values. This should be harmless,
2538 # and protects against weird problems that occur when they really
2539 # _are_ strings such as article titles and string->number->string
2540 # conversion is not 1:1.
2541 return "'" . $this->strencode( $s ) . "'";
2542 }
2543 }
2544
2545 /**
2546 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2547 * MySQL uses `backticks` while basically everything else uses double quotes.
2548 * Since MySQL is the odd one out here the double quotes are our generic
2549 * and we implement backticks in DatabaseMysql.
2550 *
2551 * @param string $s
2552 * @return string
2553 */
2554 public function addIdentifierQuotes( $s ) {
2555 return '"' . str_replace( '"', '""', $s ) . '"';
2556 }
2557
2558 /**
2559 * Returns if the given identifier looks quoted or not according to
2560 * the database convention for quoting identifiers .
2561 *
2562 * @param string $name
2563 * @return bool
2564 */
2565 public function isQuotedIdentifier( $name ) {
2566 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2567 }
2568
2569 /**
2570 * @param string $s
2571 * @return string
2572 */
2573 protected function escapeLikeInternal( $s ) {
2574 return addcslashes( $s, '\%_' );
2575 }
2576
2577 /**
2578 * LIKE statement wrapper, receives a variable-length argument list with
2579 * parts of pattern to match containing either string literals that will be
2580 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2581 * the function could be provided with an array of aforementioned
2582 * parameters.
2583 *
2584 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2585 * a LIKE clause that searches for subpages of 'My page title'.
2586 * Alternatively:
2587 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2588 * $query .= $dbr->buildLike( $pattern );
2589 *
2590 * @since 1.16
2591 * @return string Fully built LIKE statement
2592 */
2593 public function buildLike() {
2594 $params = func_get_args();
2595
2596 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2597 $params = $params[0];
2598 }
2599
2600 $s = '';
2601
2602 foreach ( $params as $value ) {
2603 if ( $value instanceof LikeMatch ) {
2604 $s .= $value->toString();
2605 } else {
2606 $s .= $this->escapeLikeInternal( $value );
2607 }
2608 }
2609
2610 return " LIKE {$this->addQuotes( $s )} ";
2611 }
2612
2613 /**
2614 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2615 *
2616 * @return LikeMatch
2617 */
2618 public function anyChar() {
2619 return new LikeMatch( '_' );
2620 }
2621
2622 /**
2623 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2624 *
2625 * @return LikeMatch
2626 */
2627 public function anyString() {
2628 return new LikeMatch( '%' );
2629 }
2630
2631 /**
2632 * Returns an appropriately quoted sequence value for inserting a new row.
2633 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2634 * subclass will return an integer, and save the value for insertId()
2635 *
2636 * Any implementation of this function should *not* involve reusing
2637 * sequence numbers created for rolled-back transactions.
2638 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2639 * @param string $seqName
2640 * @return null|int
2641 */
2642 public function nextSequenceValue( $seqName ) {
2643 return null;
2644 }
2645
2646 /**
2647 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2648 * is only needed because a) MySQL must be as efficient as possible due to
2649 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2650 * which index to pick. Anyway, other databases might have different
2651 * indexes on a given table. So don't bother overriding this unless you're
2652 * MySQL.
2653 * @param string $index
2654 * @return string
2655 */
2656 public function useIndexClause( $index ) {
2657 return '';
2658 }
2659
2660 /**
2661 * REPLACE query wrapper.
2662 *
2663 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2664 * except that when there is a duplicate key error, the old row is deleted
2665 * and the new row is inserted in its place.
2666 *
2667 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2668 * perform the delete, we need to know what the unique indexes are so that
2669 * we know how to find the conflicting rows.
2670 *
2671 * It may be more efficient to leave off unique indexes which are unlikely
2672 * to collide. However if you do this, you run the risk of encountering
2673 * errors which wouldn't have occurred in MySQL.
2674 *
2675 * @param string $table The table to replace the row(s) in.
2676 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2677 * a field name or an array of field names
2678 * @param array $rows Can be either a single row to insert, or multiple rows,
2679 * in the same format as for DatabaseBase::insert()
2680 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2681 */
2682 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2683 $quotedTable = $this->tableName( $table );
2684
2685 if ( count( $rows ) == 0 ) {
2686 return;
2687 }
2688
2689 # Single row case
2690 if ( !is_array( reset( $rows ) ) ) {
2691 $rows = array( $rows );
2692 }
2693
2694 // @FXIME: this is not atomic, but a trx would break affectedRows()
2695 foreach ( $rows as $row ) {
2696 # Delete rows which collide
2697 if ( $uniqueIndexes ) {
2698 $sql = "DELETE FROM $quotedTable WHERE ";
2699 $first = true;
2700 foreach ( $uniqueIndexes as $index ) {
2701 if ( $first ) {
2702 $first = false;
2703 $sql .= '( ';
2704 } else {
2705 $sql .= ' ) OR ( ';
2706 }
2707 if ( is_array( $index ) ) {
2708 $first2 = true;
2709 foreach ( $index as $col ) {
2710 if ( $first2 ) {
2711 $first2 = false;
2712 } else {
2713 $sql .= ' AND ';
2714 }
2715 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2716 }
2717 } else {
2718 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2719 }
2720 }
2721 $sql .= ' )';
2722 $this->query( $sql, $fname );
2723 }
2724
2725 # Now insert the row
2726 $this->insert( $table, $row, $fname );
2727 }
2728 }
2729
2730 /**
2731 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2732 * statement.
2733 *
2734 * @param string $table Table name
2735 * @param array|string $rows Row(s) to insert
2736 * @param string $fname Caller function name
2737 *
2738 * @return ResultWrapper
2739 */
2740 protected function nativeReplace( $table, $rows, $fname ) {
2741 $table = $this->tableName( $table );
2742
2743 # Single row case
2744 if ( !is_array( reset( $rows ) ) ) {
2745 $rows = array( $rows );
2746 }
2747
2748 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2749 $first = true;
2750
2751 foreach ( $rows as $row ) {
2752 if ( $first ) {
2753 $first = false;
2754 } else {
2755 $sql .= ',';
2756 }
2757
2758 $sql .= '(' . $this->makeList( $row ) . ')';
2759 }
2760
2761 return $this->query( $sql, $fname );
2762 }
2763
2764 /**
2765 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2766 *
2767 * This updates any conflicting rows (according to the unique indexes) using
2768 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2769 *
2770 * $rows may be either:
2771 * - A single associative array. The array keys are the field names, and
2772 * the values are the values to insert. The values are treated as data
2773 * and will be quoted appropriately. If NULL is inserted, this will be
2774 * converted to a database NULL.
2775 * - An array with numeric keys, holding a list of associative arrays.
2776 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2777 * each subarray must be identical to each other, and in the same order.
2778 *
2779 * It may be more efficient to leave off unique indexes which are unlikely
2780 * to collide. However if you do this, you run the risk of encountering
2781 * errors which wouldn't have occurred in MySQL.
2782 *
2783 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2784 * returns success.
2785 *
2786 * @since 1.22
2787 *
2788 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2789 * @param array $rows A single row or list of rows to insert
2790 * @param array $uniqueIndexes List of single field names or field name tuples
2791 * @param array $set An array of values to SET. For each array element, the
2792 * key gives the field name, and the value gives the data to set that
2793 * field to. The data will be quoted by DatabaseBase::addQuotes().
2794 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2795 * @throws Exception
2796 * @return bool
2797 */
2798 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2799 $fname = __METHOD__
2800 ) {
2801 if ( !count( $rows ) ) {
2802 return true; // nothing to do
2803 }
2804
2805 if ( !is_array( reset( $rows ) ) ) {
2806 $rows = array( $rows );
2807 }
2808
2809 if ( count( $uniqueIndexes ) ) {
2810 $clauses = array(); // list WHERE clauses that each identify a single row
2811 foreach ( $rows as $row ) {
2812 foreach ( $uniqueIndexes as $index ) {
2813 $index = is_array( $index ) ? $index : array( $index ); // columns
2814 $rowKey = array(); // unique key to this row
2815 foreach ( $index as $column ) {
2816 $rowKey[$column] = $row[$column];
2817 }
2818 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2819 }
2820 }
2821 $where = array( $this->makeList( $clauses, LIST_OR ) );
2822 } else {
2823 $where = false;
2824 }
2825
2826 $useTrx = !$this->mTrxLevel;
2827 if ( $useTrx ) {
2828 $this->begin( $fname );
2829 }
2830 try {
2831 # Update any existing conflicting row(s)
2832 if ( $where !== false ) {
2833 $ok = $this->update( $table, $set, $where, $fname );
2834 } else {
2835 $ok = true;
2836 }
2837 # Now insert any non-conflicting row(s)
2838 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2839 } catch ( Exception $e ) {
2840 if ( $useTrx ) {
2841 $this->rollback( $fname );
2842 }
2843 throw $e;
2844 }
2845 if ( $useTrx ) {
2846 $this->commit( $fname );
2847 }
2848
2849 return $ok;
2850 }
2851
2852 /**
2853 * DELETE where the condition is a join.
2854 *
2855 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2856 * we use sub-selects
2857 *
2858 * For safety, an empty $conds will not delete everything. If you want to
2859 * delete all rows where the join condition matches, set $conds='*'.
2860 *
2861 * DO NOT put the join condition in $conds.
2862 *
2863 * @param string $delTable The table to delete from.
2864 * @param string $joinTable The other table.
2865 * @param string $delVar The variable to join on, in the first table.
2866 * @param string $joinVar The variable to join on, in the second table.
2867 * @param array $conds Condition array of field names mapped to variables,
2868 * ANDed together in the WHERE clause
2869 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2870 * @throws DBUnexpectedError
2871 */
2872 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2873 $fname = __METHOD__
2874 ) {
2875 if ( !$conds ) {
2876 throw new DBUnexpectedError( $this,
2877 'DatabaseBase::deleteJoin() called with empty $conds' );
2878 }
2879
2880 $delTable = $this->tableName( $delTable );
2881 $joinTable = $this->tableName( $joinTable );
2882 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2883 if ( $conds != '*' ) {
2884 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2885 }
2886 $sql .= ')';
2887
2888 $this->query( $sql, $fname );
2889 }
2890
2891 /**
2892 * Returns the size of a text field, or -1 for "unlimited"
2893 *
2894 * @param string $table
2895 * @param string $field
2896 * @return int
2897 */
2898 public function textFieldSize( $table, $field ) {
2899 $table = $this->tableName( $table );
2900 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2901 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2902 $row = $this->fetchObject( $res );
2903
2904 $m = array();
2905
2906 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2907 $size = $m[1];
2908 } else {
2909 $size = -1;
2910 }
2911
2912 return $size;
2913 }
2914
2915 /**
2916 * A string to insert into queries to show that they're low-priority, like
2917 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2918 * string and nothing bad should happen.
2919 *
2920 * @return string Returns the text of the low priority option if it is
2921 * supported, or a blank string otherwise
2922 */
2923 public function lowPriorityOption() {
2924 return '';
2925 }
2926
2927 /**
2928 * DELETE query wrapper.
2929 *
2930 * @param array $table Table name
2931 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2932 * for the format. Use $conds == "*" to delete all rows
2933 * @param string $fname Name of the calling function
2934 * @throws DBUnexpectedError
2935 * @return bool|ResultWrapper
2936 */
2937 public function delete( $table, $conds, $fname = __METHOD__ ) {
2938 if ( !$conds ) {
2939 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2940 }
2941
2942 $table = $this->tableName( $table );
2943 $sql = "DELETE FROM $table";
2944
2945 if ( $conds != '*' ) {
2946 if ( is_array( $conds ) ) {
2947 $conds = $this->makeList( $conds, LIST_AND );
2948 }
2949 $sql .= ' WHERE ' . $conds;
2950 }
2951
2952 return $this->query( $sql, $fname );
2953 }
2954
2955 /**
2956 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2957 * into another table.
2958 *
2959 * @param string $destTable The table name to insert into
2960 * @param string|array $srcTable May be either a table name, or an array of table names
2961 * to include in a join.
2962 *
2963 * @param array $varMap Must be an associative array of the form
2964 * array( 'dest1' => 'source1', ...). Source items may be literals
2965 * rather than field names, but strings should be quoted with
2966 * DatabaseBase::addQuotes()
2967 *
2968 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2969 * the details of the format of condition arrays. May be "*" to copy the
2970 * whole table.
2971 *
2972 * @param string $fname The function name of the caller, from __METHOD__
2973 *
2974 * @param array $insertOptions Options for the INSERT part of the query, see
2975 * DatabaseBase::insert() for details.
2976 * @param array $selectOptions Options for the SELECT part of the query, see
2977 * DatabaseBase::select() for details.
2978 *
2979 * @return ResultWrapper
2980 */
2981 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2982 $fname = __METHOD__,
2983 $insertOptions = array(), $selectOptions = array()
2984 ) {
2985 $destTable = $this->tableName( $destTable );
2986
2987 if ( !is_array( $insertOptions ) ) {
2988 $insertOptions = array( $insertOptions );
2989 }
2990
2991 $insertOptions = $this->makeInsertOptions( $insertOptions );
2992
2993 if ( !is_array( $selectOptions ) ) {
2994 $selectOptions = array( $selectOptions );
2995 }
2996
2997 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2998
2999 if ( is_array( $srcTable ) ) {
3000 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3001 } else {
3002 $srcTable = $this->tableName( $srcTable );
3003 }
3004
3005 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3006 " SELECT $startOpts " . implode( ',', $varMap ) .
3007 " FROM $srcTable $useIndex ";
3008
3009 if ( $conds != '*' ) {
3010 if ( is_array( $conds ) ) {
3011 $conds = $this->makeList( $conds, LIST_AND );
3012 }
3013 $sql .= " WHERE $conds";
3014 }
3015
3016 $sql .= " $tailOpts";
3017
3018 return $this->query( $sql, $fname );
3019 }
3020
3021 /**
3022 * Construct a LIMIT query with optional offset. This is used for query
3023 * pages. The SQL should be adjusted so that only the first $limit rows
3024 * are returned. If $offset is provided as well, then the first $offset
3025 * rows should be discarded, and the next $limit rows should be returned.
3026 * If the result of the query is not ordered, then the rows to be returned
3027 * are theoretically arbitrary.
3028 *
3029 * $sql is expected to be a SELECT, if that makes a difference.
3030 *
3031 * The version provided by default works in MySQL and SQLite. It will very
3032 * likely need to be overridden for most other DBMSes.
3033 *
3034 * @param string $sql SQL query we will append the limit too
3035 * @param int $limit The SQL limit
3036 * @param int|bool $offset The SQL offset (default false)
3037 * @throws DBUnexpectedError
3038 * @return string
3039 */
3040 public function limitResult( $sql, $limit, $offset = false ) {
3041 if ( !is_numeric( $limit ) ) {
3042 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3043 }
3044
3045 return "$sql LIMIT "
3046 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3047 . "{$limit} ";
3048 }
3049
3050 /**
3051 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3052 * within the UNION construct.
3053 * @return bool
3054 */
3055 public function unionSupportsOrderAndLimit() {
3056 return true; // True for almost every DB supported
3057 }
3058
3059 /**
3060 * Construct a UNION query
3061 * This is used for providing overload point for other DB abstractions
3062 * not compatible with the MySQL syntax.
3063 * @param array $sqls SQL statements to combine
3064 * @param bool $all Use UNION ALL
3065 * @return string SQL fragment
3066 */
3067 public function unionQueries( $sqls, $all ) {
3068 $glue = $all ? ') UNION ALL (' : ') UNION (';
3069
3070 return '(' . implode( $glue, $sqls ) . ')';
3071 }
3072
3073 /**
3074 * Returns an SQL expression for a simple conditional. This doesn't need
3075 * to be overridden unless CASE isn't supported in your DBMS.
3076 *
3077 * @param string|array $cond SQL expression which will result in a boolean value
3078 * @param string $trueVal SQL expression to return if true
3079 * @param string $falseVal SQL expression to return if false
3080 * @return string SQL fragment
3081 */
3082 public function conditional( $cond, $trueVal, $falseVal ) {
3083 if ( is_array( $cond ) ) {
3084 $cond = $this->makeList( $cond, LIST_AND );
3085 }
3086
3087 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3088 }
3089
3090 /**
3091 * Returns a comand for str_replace function in SQL query.
3092 * Uses REPLACE() in MySQL
3093 *
3094 * @param string $orig Column to modify
3095 * @param string $old Column to seek
3096 * @param string $new Column to replace with
3097 *
3098 * @return string
3099 */
3100 public function strreplace( $orig, $old, $new ) {
3101 return "REPLACE({$orig}, {$old}, {$new})";
3102 }
3103
3104 /**
3105 * Determines how long the server has been up
3106 * STUB
3107 *
3108 * @return int
3109 */
3110 public function getServerUptime() {
3111 return 0;
3112 }
3113
3114 /**
3115 * Determines if the last failure was due to a deadlock
3116 * STUB
3117 *
3118 * @return bool
3119 */
3120 public function wasDeadlock() {
3121 return false;
3122 }
3123
3124 /**
3125 * Determines if the last failure was due to a lock timeout
3126 * STUB
3127 *
3128 * @return bool
3129 */
3130 public function wasLockTimeout() {
3131 return false;
3132 }
3133
3134 /**
3135 * Determines if the last query error was something that should be dealt
3136 * with by pinging the connection and reissuing the query.
3137 * STUB
3138 *
3139 * @return bool
3140 */
3141 public function wasErrorReissuable() {
3142 return false;
3143 }
3144
3145 /**
3146 * Determines if the last failure was due to the database being read-only.
3147 * STUB
3148 *
3149 * @return bool
3150 */
3151 public function wasReadOnlyError() {
3152 return false;
3153 }
3154
3155 /**
3156 * Determines if the given query error was a connection drop
3157 * STUB
3158 *
3159 * @param integer|string $errno
3160 * @return bool
3161 */
3162 public function wasConnectionError( $errno ) {
3163 return false;
3164 }
3165
3166 /**
3167 * Perform a deadlock-prone transaction.
3168 *
3169 * This function invokes a callback function to perform a set of write
3170 * queries. If a deadlock occurs during the processing, the transaction
3171 * will be rolled back and the callback function will be called again.
3172 *
3173 * Usage:
3174 * $dbw->deadlockLoop( callback, ... );
3175 *
3176 * Extra arguments are passed through to the specified callback function.
3177 *
3178 * Returns whatever the callback function returned on its successful,
3179 * iteration, or false on error, for example if the retry limit was
3180 * reached.
3181 *
3182 * @return mixed
3183 * @throws DBQueryError
3184 */
3185 public function deadlockLoop() {
3186 $args = func_get_args();
3187 $function = array_shift( $args );
3188 $tries = self::DEADLOCK_TRIES;
3189
3190 $this->begin( __METHOD__ );
3191
3192 $retVal = null;
3193 $e = null;
3194 do {
3195 try {
3196 $retVal = call_user_func_array( $function, $args );
3197 break;
3198 } catch ( DBQueryError $e ) {
3199 if ( $this->wasDeadlock() ) {
3200 // Retry after a randomized delay
3201 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3202 } else {
3203 // Throw the error back up
3204 throw $e;
3205 }
3206 }
3207 } while ( --$tries > 0 );
3208
3209 if ( $tries <= 0 ) {
3210 // Too many deadlocks; give up
3211 $this->rollback( __METHOD__ );
3212 throw $e;
3213 } else {
3214 $this->commit( __METHOD__ );
3215
3216 return $retVal;
3217 }
3218 }
3219
3220 /**
3221 * Wait for the slave to catch up to a given master position.
3222 *
3223 * @param DBMasterPos $pos
3224 * @param int $timeout The maximum number of seconds to wait for
3225 * synchronisation
3226 * @return int Zero if the slave was past that position already,
3227 * greater than zero if we waited for some period of time, less than
3228 * zero if we timed out.
3229 */
3230 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3231 # Real waits are implemented in the subclass.
3232 return 0;
3233 }
3234
3235 /**
3236 * Get the replication position of this slave
3237 *
3238 * @return DBMasterPos|bool False if this is not a slave.
3239 */
3240 public function getSlavePos() {
3241 # Stub
3242 return false;
3243 }
3244
3245 /**
3246 * Get the position of this master
3247 *
3248 * @return DBMasterPos|bool False if this is not a master
3249 */
3250 public function getMasterPos() {
3251 # Stub
3252 return false;
3253 }
3254
3255 /**
3256 * Run an anonymous function as soon as there is no transaction pending.
3257 * If there is a transaction and it is rolled back, then the callback is cancelled.
3258 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3259 * Callbacks must commit any transactions that they begin.
3260 *
3261 * This is useful for updates to different systems or when separate transactions are needed.
3262 * For example, one might want to enqueue jobs into a system outside the database, but only
3263 * after the database is updated so that the jobs will see the data when they actually run.
3264 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3265 *
3266 * @param callable $callback
3267 * @since 1.20
3268 */
3269 final public function onTransactionIdle( $callback ) {
3270 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3271 if ( !$this->mTrxLevel ) {
3272 $this->runOnTransactionIdleCallbacks();
3273 }
3274 }
3275
3276 /**
3277 * Run an anonymous function before the current transaction commits or now if there is none.
3278 * If there is a transaction and it is rolled back, then the callback is cancelled.
3279 * Callbacks must not start nor commit any transactions.
3280 *
3281 * This is useful for updates that easily cause deadlocks if locks are held too long
3282 * but where atomicity is strongly desired for these updates and some related updates.
3283 *
3284 * @param callable $callback
3285 * @since 1.22
3286 */
3287 final public function onTransactionPreCommitOrIdle( $callback ) {
3288 if ( $this->mTrxLevel ) {
3289 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3290 } else {
3291 $this->onTransactionIdle( $callback ); // this will trigger immediately
3292 }
3293 }
3294
3295 /**
3296 * Actually any "on transaction idle" callbacks.
3297 *
3298 * @since 1.20
3299 */
3300 protected function runOnTransactionIdleCallbacks() {
3301 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3302
3303 $e = $ePrior = null; // last exception
3304 do { // callbacks may add callbacks :)
3305 $callbacks = $this->mTrxIdleCallbacks;
3306 $this->mTrxIdleCallbacks = array(); // recursion guard
3307 foreach ( $callbacks as $callback ) {
3308 try {
3309 list( $phpCallback ) = $callback;
3310 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3311 call_user_func( $phpCallback );
3312 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3313 } catch ( Exception $e ) {
3314 if ( $ePrior ) {
3315 MWExceptionHandler::logException( $ePrior );
3316 }
3317 $ePrior = $e;
3318 }
3319 }
3320 } while ( count( $this->mTrxIdleCallbacks ) );
3321
3322 if ( $e instanceof Exception ) {
3323 throw $e; // re-throw any last exception
3324 }
3325 }
3326
3327 /**
3328 * Actually any "on transaction pre-commit" callbacks.
3329 *
3330 * @since 1.22
3331 */
3332 protected function runOnTransactionPreCommitCallbacks() {
3333 $e = $ePrior = null; // last exception
3334 do { // callbacks may add callbacks :)
3335 $callbacks = $this->mTrxPreCommitCallbacks;
3336 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3337 foreach ( $callbacks as $callback ) {
3338 try {
3339 list( $phpCallback ) = $callback;
3340 call_user_func( $phpCallback );
3341 } catch ( Exception $e ) {
3342 if ( $ePrior ) {
3343 MWExceptionHandler::logException( $ePrior );
3344 }
3345 $ePrior = $e;
3346 }
3347 }
3348 } while ( count( $this->mTrxPreCommitCallbacks ) );
3349
3350 if ( $e instanceof Exception ) {
3351 throw $e; // re-throw any last exception
3352 }
3353 }
3354
3355 /**
3356 * Begin an atomic section of statements
3357 *
3358 * If a transaction has been started already, just keep track of the given
3359 * section name to make sure the transaction is not committed pre-maturely.
3360 * This function can be used in layers (with sub-sections), so use a stack
3361 * to keep track of the different atomic sections. If there is no transaction,
3362 * start one implicitly.
3363 *
3364 * The goal of this function is to create an atomic section of SQL queries
3365 * without having to start a new transaction if it already exists.
3366 *
3367 * Atomic sections are more strict than transactions. With transactions,
3368 * attempting to begin a new transaction when one is already running results
3369 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3370 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3371 * and any database transactions cannot be began or committed until all atomic
3372 * levels are closed. There is no such thing as implicitly opening or closing
3373 * an atomic section.
3374 *
3375 * @since 1.23
3376 * @param string $fname
3377 * @throws DBError
3378 */
3379 final public function startAtomic( $fname = __METHOD__ ) {
3380 if ( !$this->mTrxLevel ) {
3381 $this->begin( $fname );
3382 $this->mTrxAutomatic = true;
3383 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3384 // in all changes being in one transaction to keep requests transactional.
3385 if ( !$this->getFlag( DBO_TRX ) ) {
3386 $this->mTrxAutomaticAtomic = true;
3387 }
3388 }
3389
3390 $this->mTrxAtomicLevels[] = $fname;
3391 }
3392
3393 /**
3394 * Ends an atomic section of SQL statements
3395 *
3396 * Ends the next section of atomic SQL statements and commits the transaction
3397 * if necessary.
3398 *
3399 * @since 1.23
3400 * @see DatabaseBase::startAtomic
3401 * @param string $fname
3402 * @throws DBError
3403 */
3404 final public function endAtomic( $fname = __METHOD__ ) {
3405 if ( !$this->mTrxLevel ) {
3406 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3407 }
3408 if ( !$this->mTrxAtomicLevels ||
3409 array_pop( $this->mTrxAtomicLevels ) !== $fname
3410 ) {
3411 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3412 }
3413
3414 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
3415 $this->commit( $fname, 'flush' );
3416 }
3417 }
3418
3419 /**
3420 * Begin a transaction. If a transaction is already in progress,
3421 * that transaction will be committed before the new transaction is started.
3422 *
3423 * Note that when the DBO_TRX flag is set (which is usually the case for web
3424 * requests, but not for maintenance scripts), any previous database query
3425 * will have started a transaction automatically.
3426 *
3427 * Nesting of transactions is not supported. Attempts to nest transactions
3428 * will cause a warning, unless the current transaction was started
3429 * automatically because of the DBO_TRX flag.
3430 *
3431 * @param string $fname
3432 * @throws DBError
3433 */
3434 final public function begin( $fname = __METHOD__ ) {
3435 if ( $this->mTrxLevel ) { // implicit commit
3436 if ( $this->mTrxAtomicLevels ) {
3437 // If the current transaction was an automatic atomic one, then we definitely have
3438 // a problem. Same if there is any unclosed atomic level.
3439 $levels = implode( ', ', $this->mTrxAtomicLevels );
3440 throw new DBUnexpectedError(
3441 $this,
3442 "Got explicit BEGIN while atomic sections $levels are still open."
3443 );
3444 } elseif ( !$this->mTrxAutomatic ) {
3445 // We want to warn about inadvertently nested begin/commit pairs, but not about
3446 // auto-committing implicit transactions that were started by query() via DBO_TRX
3447 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3448 " performing implicit commit!";
3449 wfWarn( $msg );
3450 wfLogDBError( $msg,
3451 $this->getLogContext( array(
3452 'method' => __METHOD__,
3453 'fname' => $fname,
3454 ) )
3455 );
3456 } else {
3457 // if the transaction was automatic and has done write operations
3458 if ( $this->mTrxDoneWrites ) {
3459 wfDebug( "$fname: Automatic transaction with writes in progress" .
3460 " (from {$this->mTrxFname}), performing implicit commit!\n"
3461 );
3462 }
3463 }
3464
3465 $this->runOnTransactionPreCommitCallbacks();
3466 $writeTime = $this->pendingWriteQueryDuration();
3467 $this->doCommit( $fname );
3468 if ( $this->mTrxDoneWrites ) {
3469 $this->mDoneWrites = microtime( true );
3470 $this->getTransactionProfiler()->transactionWritingOut(
3471 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3472 }
3473 $this->runOnTransactionIdleCallbacks();
3474 }
3475
3476 # Avoid fatals if close() was called
3477 $this->assertOpen();
3478
3479 $this->doBegin( $fname );
3480 $this->mTrxTimestamp = microtime( true );
3481 $this->mTrxFname = $fname;
3482 $this->mTrxDoneWrites = false;
3483 $this->mTrxAutomatic = false;
3484 $this->mTrxAutomaticAtomic = false;
3485 $this->mTrxAtomicLevels = array();
3486 $this->mTrxIdleCallbacks = array();
3487 $this->mTrxPreCommitCallbacks = array();
3488 $this->mTrxShortId = wfRandomString( 12 );
3489 $this->mTrxWriteDuration = 0.0;
3490 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3491 // Get an estimate of the slave lag before then, treating estimate staleness
3492 // as lag itself just to be safe
3493 $status = $this->getApproximateLagStatus();
3494 $this->mTrxSlaveLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3495 }
3496
3497 /**
3498 * Issues the BEGIN command to the database server.
3499 *
3500 * @see DatabaseBase::begin()
3501 * @param string $fname
3502 */
3503 protected function doBegin( $fname ) {
3504 $this->query( 'BEGIN', $fname );
3505 $this->mTrxLevel = 1;
3506 }
3507
3508 /**
3509 * Commits a transaction previously started using begin().
3510 * If no transaction is in progress, a warning is issued.
3511 *
3512 * Nesting of transactions is not supported.
3513 *
3514 * @param string $fname
3515 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3516 * explicitly committing implicit transactions, or calling commit when no
3517 * transaction is in progress. This will silently break any ongoing
3518 * explicit transaction. Only set the flush flag if you are sure that it
3519 * is safe to ignore these warnings in your context.
3520 * @throws DBUnexpectedError
3521 */
3522 final public function commit( $fname = __METHOD__, $flush = '' ) {
3523 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
3524 // There are still atomic sections open. This cannot be ignored
3525 $levels = implode( ', ', $this->mTrxAtomicLevels );
3526 throw new DBUnexpectedError(
3527 $this,
3528 "Got COMMIT while atomic sections $levels are still open"
3529 );
3530 }
3531
3532 if ( $flush === 'flush' ) {
3533 if ( !$this->mTrxLevel ) {
3534 return; // nothing to do
3535 } elseif ( !$this->mTrxAutomatic ) {
3536 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3537 }
3538 } else {
3539 if ( !$this->mTrxLevel ) {
3540 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3541 return; // nothing to do
3542 } elseif ( $this->mTrxAutomatic ) {
3543 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3544 }
3545 }
3546
3547 # Avoid fatals if close() was called
3548 $this->assertOpen();
3549
3550 $this->runOnTransactionPreCommitCallbacks();
3551 $writeTime = $this->pendingWriteQueryDuration();
3552 $this->doCommit( $fname );
3553 if ( $this->mTrxDoneWrites ) {
3554 $this->mDoneWrites = microtime( true );
3555 $this->getTransactionProfiler()->transactionWritingOut(
3556 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3557 }
3558 $this->runOnTransactionIdleCallbacks();
3559 }
3560
3561 /**
3562 * Issues the COMMIT command to the database server.
3563 *
3564 * @see DatabaseBase::commit()
3565 * @param string $fname
3566 */
3567 protected function doCommit( $fname ) {
3568 if ( $this->mTrxLevel ) {
3569 $this->query( 'COMMIT', $fname );
3570 $this->mTrxLevel = 0;
3571 }
3572 }
3573
3574 /**
3575 * Rollback a transaction previously started using begin().
3576 * If no transaction is in progress, a warning is issued.
3577 *
3578 * No-op on non-transactional databases.
3579 *
3580 * @param string $fname
3581 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3582 * calling rollback when no transaction is in progress. This will silently
3583 * break any ongoing explicit transaction. Only set the flush flag if you
3584 * are sure that it is safe to ignore these warnings in your context.
3585 * @throws DBUnexpectedError
3586 * @since 1.23 Added $flush parameter
3587 */
3588 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3589 if ( $flush !== 'flush' ) {
3590 if ( !$this->mTrxLevel ) {
3591 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3592 return; // nothing to do
3593 } elseif ( $this->mTrxAutomatic ) {
3594 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3595 }
3596 } else {
3597 if ( !$this->mTrxLevel ) {
3598 return; // nothing to do
3599 } elseif ( !$this->mTrxAutomatic ) {
3600 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3601 }
3602 }
3603
3604 # Avoid fatals if close() was called
3605 $this->assertOpen();
3606
3607 $this->doRollback( $fname );
3608 $this->mTrxIdleCallbacks = array(); // cancel
3609 $this->mTrxPreCommitCallbacks = array(); // cancel
3610 $this->mTrxAtomicLevels = array();
3611 if ( $this->mTrxDoneWrites ) {
3612 $this->getTransactionProfiler()->transactionWritingOut(
3613 $this->mServer, $this->mDBname, $this->mTrxShortId );
3614 }
3615 }
3616
3617 /**
3618 * Issues the ROLLBACK command to the database server.
3619 *
3620 * @see DatabaseBase::rollback()
3621 * @param string $fname
3622 */
3623 protected function doRollback( $fname ) {
3624 if ( $this->mTrxLevel ) {
3625 $this->query( 'ROLLBACK', $fname, true );
3626 $this->mTrxLevel = 0;
3627 }
3628 }
3629
3630 /**
3631 * Creates a new table with structure copied from existing table
3632 * Note that unlike most database abstraction functions, this function does not
3633 * automatically append database prefix, because it works at a lower
3634 * abstraction level.
3635 * The table names passed to this function shall not be quoted (this
3636 * function calls addIdentifierQuotes when needed).
3637 *
3638 * @param string $oldName Name of table whose structure should be copied
3639 * @param string $newName Name of table to be created
3640 * @param bool $temporary Whether the new table should be temporary
3641 * @param string $fname Calling function name
3642 * @throws MWException
3643 * @return bool True if operation was successful
3644 */
3645 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3646 $fname = __METHOD__
3647 ) {
3648 throw new MWException(
3649 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3650 }
3651
3652 /**
3653 * List all tables on the database
3654 *
3655 * @param string $prefix Only show tables with this prefix, e.g. mw_
3656 * @param string $fname Calling function name
3657 * @throws MWException
3658 * @return array
3659 */
3660 function listTables( $prefix = null, $fname = __METHOD__ ) {
3661 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3662 }
3663
3664 /**
3665 * Reset the views process cache set by listViews()
3666 * @since 1.22
3667 */
3668 final public function clearViewsCache() {
3669 $this->allViews = null;
3670 }
3671
3672 /**
3673 * Lists all the VIEWs in the database
3674 *
3675 * For caching purposes the list of all views should be stored in
3676 * $this->allViews. The process cache can be cleared with clearViewsCache()
3677 *
3678 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3679 * @param string $fname Name of calling function
3680 * @throws MWException
3681 * @return array
3682 * @since 1.22
3683 */
3684 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3685 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3686 }
3687
3688 /**
3689 * Differentiates between a TABLE and a VIEW
3690 *
3691 * @param string $name Name of the database-structure to test.
3692 * @throws MWException
3693 * @return bool
3694 * @since 1.22
3695 */
3696 public function isView( $name ) {
3697 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3698 }
3699
3700 /**
3701 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3702 * to the format used for inserting into timestamp fields in this DBMS.
3703 *
3704 * The result is unquoted, and needs to be passed through addQuotes()
3705 * before it can be included in raw SQL.
3706 *
3707 * @param string|int $ts
3708 *
3709 * @return string
3710 */
3711 public function timestamp( $ts = 0 ) {
3712 return wfTimestamp( TS_MW, $ts );
3713 }
3714
3715 /**
3716 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3717 * to the format used for inserting into timestamp fields in this DBMS. If
3718 * NULL is input, it is passed through, allowing NULL values to be inserted
3719 * into timestamp fields.
3720 *
3721 * The result is unquoted, and needs to be passed through addQuotes()
3722 * before it can be included in raw SQL.
3723 *
3724 * @param string|int $ts
3725 *
3726 * @return string
3727 */
3728 public function timestampOrNull( $ts = null ) {
3729 if ( is_null( $ts ) ) {
3730 return null;
3731 } else {
3732 return $this->timestamp( $ts );
3733 }
3734 }
3735
3736 /**
3737 * Take the result from a query, and wrap it in a ResultWrapper if
3738 * necessary. Boolean values are passed through as is, to indicate success
3739 * of write queries or failure.
3740 *
3741 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3742 * resource, and it was necessary to call this function to convert it to
3743 * a wrapper. Nowadays, raw database objects are never exposed to external
3744 * callers, so this is unnecessary in external code.
3745 *
3746 * @param bool|ResultWrapper|resource|object $result
3747 * @return bool|ResultWrapper
3748 */
3749 protected function resultObject( $result ) {
3750 if ( !$result ) {
3751 return false;
3752 } elseif ( $result instanceof ResultWrapper ) {
3753 return $result;
3754 } elseif ( $result === true ) {
3755 // Successful write query
3756 return $result;
3757 } else {
3758 return new ResultWrapper( $this, $result );
3759 }
3760 }
3761
3762 /**
3763 * Ping the server and try to reconnect if it there is no connection
3764 *
3765 * @return bool Success or failure
3766 */
3767 public function ping() {
3768 # Stub. Not essential to override.
3769 return true;
3770 }
3771
3772 /**
3773 * Get the slave lag when the current transaction started
3774 * or a general lag estimate if not transaction is active
3775 *
3776 * This is useful when transactions might use snapshot isolation
3777 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3778 * is this lag plus transaction duration. If they don't, it is still
3779 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
3780 * indication of the staleness of subsequent reads.
3781 *
3782 * @return array ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3783 * @since 1.27
3784 */
3785 public function getSessionLagStatus() {
3786 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3787 }
3788
3789 /**
3790 * Get the slave lag when the current transaction started
3791 *
3792 * This is useful when transactions might use snapshot isolation
3793 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3794 * is this lag plus transaction duration. If they don't, it is still
3795 * safe to be pessimistic. This returns null if there is no transaction.
3796 *
3797 * @return array|null ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3798 * @since 1.27
3799 */
3800 public function getTransactionLagStatus() {
3801 return $this->mTrxLevel
3802 ? array( 'lag' => $this->mTrxSlaveLag, 'since' => $this->trxTimestamp() )
3803 : null;
3804 }
3805
3806 /**
3807 * Get a slave lag estimate for this server
3808 *
3809 * @return array ('lag': seconds, 'since': UNIX timestamp of estimate)
3810 * @since 1.27
3811 */
3812 public function getApproximateLagStatus() {
3813 return array(
3814 'lag' => $this->getLBInfo( 'slave' ) ? $this->getLag() : 0,
3815 'since' => microtime( true )
3816 );
3817 }
3818
3819 /**
3820 * Merge the result of getSessionLagStatus() for several DBs
3821 * using the most pessimistic values to estimate the lag of
3822 * any data derived from them in combination
3823 *
3824 * This is information is useful for caching modules
3825 *
3826 * @see WANObjectCache::set()
3827 * @see WANObjectCache::getWithSetCallback()
3828 *
3829 * @param IDatabase $db1
3830 * @param IDatabase ...
3831 * @return array Map of values:
3832 * - lag: highest lag of any of the DBs
3833 * - since: oldest UNIX timestamp of any of the DB lag estimates
3834 * - pending: whether any of the DBs have uncommitted changes
3835 * @since 1.27
3836 */
3837 public static function getCacheSetOptions( IDatabase $db1 ) {
3838 $res = array( 'lag' => 0, 'since' => INF, 'pending' => false );
3839 foreach ( func_get_args() as $db ) {
3840 /** @var IDatabase $db */
3841 $status = $db->getSessionLagStatus();
3842 $res['lag'] = max( $res['lag'], $status['lag'] );
3843 $res['since'] = min( $res['since'], $status['since'] );
3844 $res['pending'] = $res['pending'] ?: $db->writesPending();
3845 }
3846
3847 return $res;
3848 }
3849
3850 /**
3851 * Get slave lag. Currently supported only by MySQL.
3852 *
3853 * Note that this function will generate a fatal error on many
3854 * installations. Most callers should use LoadBalancer::safeGetLag()
3855 * instead.
3856 *
3857 * @return int Database replication lag in seconds
3858 */
3859 public function getLag() {
3860 return 0;
3861 }
3862
3863 /**
3864 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3865 *
3866 * @return int
3867 */
3868 function maxListLen() {
3869 return 0;
3870 }
3871
3872 /**
3873 * Some DBMSs have a special format for inserting into blob fields, they
3874 * don't allow simple quoted strings to be inserted. To insert into such
3875 * a field, pass the data through this function before passing it to
3876 * DatabaseBase::insert().
3877 *
3878 * @param string $b
3879 * @return string
3880 */
3881 public function encodeBlob( $b ) {
3882 return $b;
3883 }
3884
3885 /**
3886 * Some DBMSs return a special placeholder object representing blob fields
3887 * in result objects. Pass the object through this function to return the
3888 * original string.
3889 *
3890 * @param string|Blob $b
3891 * @return string
3892 */
3893 public function decodeBlob( $b ) {
3894 if ( $b instanceof Blob ) {
3895 $b = $b->fetch();
3896 }
3897 return $b;
3898 }
3899
3900 /**
3901 * Override database's default behavior. $options include:
3902 * 'connTimeout' : Set the connection timeout value in seconds.
3903 * May be useful for very long batch queries such as
3904 * full-wiki dumps, where a single query reads out over
3905 * hours or days.
3906 *
3907 * @param array $options
3908 * @return void
3909 */
3910 public function setSessionOptions( array $options ) {
3911 }
3912
3913 /**
3914 * Read and execute SQL commands from a file.
3915 *
3916 * Returns true on success, error string or exception on failure (depending
3917 * on object's error ignore settings).
3918 *
3919 * @param string $filename File name to open
3920 * @param bool|callable $lineCallback Optional function called before reading each line
3921 * @param bool|callable $resultCallback Optional function called for each MySQL result
3922 * @param bool|string $fname Calling function name or false if name should be
3923 * generated dynamically using $filename
3924 * @param bool|callable $inputCallback Optional function called for each
3925 * complete line sent
3926 * @throws Exception|MWException
3927 * @return bool|string
3928 */
3929 public function sourceFile(
3930 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3931 ) {
3932 MediaWiki\suppressWarnings();
3933 $fp = fopen( $filename, 'r' );
3934 MediaWiki\restoreWarnings();
3935
3936 if ( false === $fp ) {
3937 throw new MWException( "Could not open \"{$filename}\".\n" );
3938 }
3939
3940 if ( !$fname ) {
3941 $fname = __METHOD__ . "( $filename )";
3942 }
3943
3944 try {
3945 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3946 } catch ( Exception $e ) {
3947 fclose( $fp );
3948 throw $e;
3949 }
3950
3951 fclose( $fp );
3952
3953 return $error;
3954 }
3955
3956 /**
3957 * Get the full path of a patch file. Originally based on archive()
3958 * from updaters.inc. Keep in mind this always returns a patch, as
3959 * it fails back to MySQL if no DB-specific patch can be found
3960 *
3961 * @param string $patch The name of the patch, like patch-something.sql
3962 * @return string Full path to patch file
3963 */
3964 public function patchPath( $patch ) {
3965 global $IP;
3966
3967 $dbType = $this->getType();
3968 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3969 return "$IP/maintenance/$dbType/archives/$patch";
3970 } else {
3971 return "$IP/maintenance/archives/$patch";
3972 }
3973 }
3974
3975 /**
3976 * Set variables to be used in sourceFile/sourceStream, in preference to the
3977 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3978 * all. If it's set to false, $GLOBALS will be used.
3979 *
3980 * @param bool|array $vars Mapping variable name to value.
3981 */
3982 public function setSchemaVars( $vars ) {
3983 $this->mSchemaVars = $vars;
3984 }
3985
3986 /**
3987 * Read and execute commands from an open file handle.
3988 *
3989 * Returns true on success, error string or exception on failure (depending
3990 * on object's error ignore settings).
3991 *
3992 * @param resource $fp File handle
3993 * @param bool|callable $lineCallback Optional function called before reading each query
3994 * @param bool|callable $resultCallback Optional function called for each MySQL result
3995 * @param string $fname Calling function name
3996 * @param bool|callable $inputCallback Optional function called for each complete query sent
3997 * @return bool|string
3998 */
3999 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4000 $fname = __METHOD__, $inputCallback = false
4001 ) {
4002 $cmd = '';
4003
4004 while ( !feof( $fp ) ) {
4005 if ( $lineCallback ) {
4006 call_user_func( $lineCallback );
4007 }
4008
4009 $line = trim( fgets( $fp ) );
4010
4011 if ( $line == '' ) {
4012 continue;
4013 }
4014
4015 if ( '-' == $line[0] && '-' == $line[1] ) {
4016 continue;
4017 }
4018
4019 if ( $cmd != '' ) {
4020 $cmd .= ' ';
4021 }
4022
4023 $done = $this->streamStatementEnd( $cmd, $line );
4024
4025 $cmd .= "$line\n";
4026
4027 if ( $done || feof( $fp ) ) {
4028 $cmd = $this->replaceVars( $cmd );
4029
4030 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
4031 $res = $this->query( $cmd, $fname );
4032
4033 if ( $resultCallback ) {
4034 call_user_func( $resultCallback, $res, $this );
4035 }
4036
4037 if ( false === $res ) {
4038 $err = $this->lastError();
4039
4040 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4041 }
4042 }
4043 $cmd = '';
4044 }
4045 }
4046
4047 return true;
4048 }
4049
4050 /**
4051 * Called by sourceStream() to check if we've reached a statement end
4052 *
4053 * @param string $sql SQL assembled so far
4054 * @param string $newLine New line about to be added to $sql
4055 * @return bool Whether $newLine contains end of the statement
4056 */
4057 public function streamStatementEnd( &$sql, &$newLine ) {
4058 if ( $this->delimiter ) {
4059 $prev = $newLine;
4060 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4061 if ( $newLine != $prev ) {
4062 return true;
4063 }
4064 }
4065
4066 return false;
4067 }
4068
4069 /**
4070 * Database independent variable replacement. Replaces a set of variables
4071 * in an SQL statement with their contents as given by $this->getSchemaVars().
4072 *
4073 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4074 *
4075 * - '{$var}' should be used for text and is passed through the database's
4076 * addQuotes method.
4077 * - `{$var}` should be used for identifiers (e.g. table and database names).
4078 * It is passed through the database's addIdentifierQuotes method which
4079 * can be overridden if the database uses something other than backticks.
4080 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4081 * database's tableName method.
4082 * - / *i* / passes the name that follows through the database's indexName method.
4083 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4084 * its use should be avoided. In 1.24 and older, string encoding was applied.
4085 *
4086 * @param string $ins SQL statement to replace variables in
4087 * @return string The new SQL statement with variables replaced
4088 */
4089 protected function replaceVars( $ins ) {
4090 $that = $this;
4091 $vars = $this->getSchemaVars();
4092 return preg_replace_callback(
4093 '!
4094 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4095 \'\{\$ (\w+) }\' | # 3. addQuotes
4096 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4097 /\*\$ (\w+) \*/ # 5. leave unencoded
4098 !x',
4099 function ( $m ) use ( $that, $vars ) {
4100 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4101 // check for both nonexistent keys *and* the empty string.
4102 if ( isset( $m[1] ) && $m[1] !== '' ) {
4103 if ( $m[1] === 'i' ) {
4104 return $that->indexName( $m[2] );
4105 } else {
4106 return $that->tableName( $m[2] );
4107 }
4108 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4109 return $that->addQuotes( $vars[$m[3]] );
4110 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4111 return $that->addIdentifierQuotes( $vars[$m[4]] );
4112 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4113 return $vars[$m[5]];
4114 } else {
4115 return $m[0];
4116 }
4117 },
4118 $ins
4119 );
4120 }
4121
4122 /**
4123 * Get schema variables. If none have been set via setSchemaVars(), then
4124 * use some defaults from the current object.
4125 *
4126 * @return array
4127 */
4128 protected function getSchemaVars() {
4129 if ( $this->mSchemaVars ) {
4130 return $this->mSchemaVars;
4131 } else {
4132 return $this->getDefaultSchemaVars();
4133 }
4134 }
4135
4136 /**
4137 * Get schema variables to use if none have been set via setSchemaVars().
4138 *
4139 * Override this in derived classes to provide variables for tables.sql
4140 * and SQL patch files.
4141 *
4142 * @return array
4143 */
4144 protected function getDefaultSchemaVars() {
4145 return array();
4146 }
4147
4148 /**
4149 * Check to see if a named lock is available (non-blocking)
4150 *
4151 * @param string $lockName Name of lock to poll
4152 * @param string $method Name of method calling us
4153 * @return bool
4154 * @since 1.20
4155 */
4156 public function lockIsFree( $lockName, $method ) {
4157 return true;
4158 }
4159
4160 /**
4161 * Acquire a named lock
4162 *
4163 * Named locks are not related to transactions
4164 *
4165 * @param string $lockName Name of lock to aquire
4166 * @param string $method Name of method calling us
4167 * @param int $timeout
4168 * @return bool
4169 */
4170 public function lock( $lockName, $method, $timeout = 5 ) {
4171 return true;
4172 }
4173
4174 /**
4175 * Release a lock
4176 *
4177 * Named locks are not related to transactions
4178 *
4179 * @param string $lockName Name of lock to release
4180 * @param string $method Name of method calling us
4181 *
4182 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4183 * by this thread (in which case the lock is not released), and NULL if the named
4184 * lock did not exist
4185 */
4186 public function unlock( $lockName, $method ) {
4187 return true;
4188 }
4189
4190 /**
4191 * Check to see if a named lock used by lock() use blocking queues
4192 *
4193 * @return bool
4194 * @since 1.26
4195 */
4196 public function namedLocksEnqueue() {
4197 return false;
4198 }
4199
4200 /**
4201 * Lock specific tables
4202 *
4203 * @param array $read Array of tables to lock for read access
4204 * @param array $write Array of tables to lock for write access
4205 * @param string $method Name of caller
4206 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4207 * @return bool
4208 */
4209 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4210 return true;
4211 }
4212
4213 /**
4214 * Unlock specific tables
4215 *
4216 * @param string $method The caller
4217 * @return bool
4218 */
4219 public function unlockTables( $method ) {
4220 return true;
4221 }
4222
4223 /**
4224 * Delete a table
4225 * @param string $tableName
4226 * @param string $fName
4227 * @return bool|ResultWrapper
4228 * @since 1.18
4229 */
4230 public function dropTable( $tableName, $fName = __METHOD__ ) {
4231 if ( !$this->tableExists( $tableName, $fName ) ) {
4232 return false;
4233 }
4234 $sql = "DROP TABLE " . $this->tableName( $tableName );
4235 if ( $this->cascadingDeletes() ) {
4236 $sql .= " CASCADE";
4237 }
4238
4239 return $this->query( $sql, $fName );
4240 }
4241
4242 /**
4243 * Get search engine class. All subclasses of this need to implement this
4244 * if they wish to use searching.
4245 *
4246 * @return string
4247 */
4248 public function getSearchEngine() {
4249 return 'SearchEngineDummy';
4250 }
4251
4252 /**
4253 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4254 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4255 * because "i" sorts after all numbers.
4256 *
4257 * @return string
4258 */
4259 public function getInfinity() {
4260 return 'infinity';
4261 }
4262
4263 /**
4264 * Encode an expiry time into the DBMS dependent format
4265 *
4266 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4267 * @return string
4268 */
4269 public function encodeExpiry( $expiry ) {
4270 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4271 ? $this->getInfinity()
4272 : $this->timestamp( $expiry );
4273 }
4274
4275 /**
4276 * Decode an expiry time into a DBMS independent format
4277 *
4278 * @param string $expiry DB timestamp field value for expiry
4279 * @param int $format TS_* constant, defaults to TS_MW
4280 * @return string
4281 */
4282 public function decodeExpiry( $expiry, $format = TS_MW ) {
4283 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4284 ? 'infinity'
4285 : wfTimestamp( $format, $expiry );
4286 }
4287
4288 /**
4289 * Allow or deny "big selects" for this session only. This is done by setting
4290 * the sql_big_selects session variable.
4291 *
4292 * This is a MySQL-specific feature.
4293 *
4294 * @param bool|string $value True for allow, false for deny, or "default" to
4295 * restore the initial value
4296 */
4297 public function setBigSelects( $value = true ) {
4298 // no-op
4299 }
4300
4301 public function isReadOnly() {
4302 return ( $this->getReadOnlyReason() !== false );
4303 }
4304
4305 /**
4306 * @return string|bool Reason this DB is read-only or false if it is not
4307 */
4308 protected function getReadOnlyReason() {
4309 $reason = $this->getLBInfo( 'readOnlyReason' );
4310
4311 return is_string( $reason ) ? $reason : false;
4312 }
4313
4314 /**
4315 * @since 1.19
4316 * @return string
4317 */
4318 public function __toString() {
4319 return (string)$this->mConn;
4320 }
4321
4322 /**
4323 * Run a few simple sanity checks
4324 */
4325 public function __destruct() {
4326 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4327 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4328 }
4329 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4330 $callers = array();
4331 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4332 $callers[] = $callbackInfo[1];
4333 }
4334 $callers = implode( ', ', $callers );
4335 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4336 }
4337 }
4338 }
4339
4340 /**
4341 * @since 1.27
4342 */
4343 abstract class Database extends DatabaseBase {
4344 // B/C until nothing type hints for DatabaseBase
4345 // @TODO: finish renaming DatabaseBase => Database
4346 }