dd89c443c75d6428af5569a07e0293e4ee4bc18b
4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
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.
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.
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
29 * Base interface for all DBMS-specific code. At a bare minimum, all of the
30 * following must be implemented to support MediaWiki
35 interface DatabaseType
{
37 * Get the type of the DBMS, as it appears in $wgDBtype.
44 * Open a connection to the database. Usually aborts on failure
46 * @param string $server Database server host
47 * @param string $user Database user name
48 * @param string $password Database user password
49 * @param string $dbName Database name
51 * @throws DBConnectionError
53 function open( $server, $user, $password, $dbName );
56 * Fetch the next row from the given result object, in object form.
57 * Fields can be retrieved with $row->fieldname, with fields acting like
59 * If no more rows are available, false is returned.
61 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
62 * @return stdClass|bool
63 * @throws DBUnexpectedError Thrown if the database returns an error
65 function fetchObject( $res );
68 * Fetch the next row from the given result object, in associative array
69 * form. Fields are retrieved with $row['fieldname'].
70 * If no more rows are available, false is returned.
72 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
74 * @throws DBUnexpectedError Thrown if the database returns an error
76 function fetchRow( $res );
79 * Get the number of rows in a result object
81 * @param mixed $res A SQL result
84 function numRows( $res );
87 * Get the number of fields in a result object
88 * @see http://www.php.net/mysql_num_fields
90 * @param mixed $res A SQL result
93 function numFields( $res );
96 * Get a field name in a result object
97 * @see http://www.php.net/mysql_field_name
99 * @param mixed $res A SQL result
103 function fieldName( $res, $n );
106 * Get the inserted value of an auto-increment row
108 * The value inserted should be fetched from nextSequenceValue()
111 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
112 * $dbw->insert( 'page', array( 'page_id' => $id ) );
113 * $id = $dbw->insertId();
120 * Change the position of the cursor in a result object
121 * @see http://www.php.net/mysql_data_seek
123 * @param mixed $res A SQL result
126 function dataSeek( $res, $row );
129 * Get the last error number
130 * @see http://www.php.net/mysql_errno
134 function lastErrno();
137 * Get a description of the last error
138 * @see http://www.php.net/mysql_error
142 function lastError();
145 * mysql_fetch_field() wrapper
146 * Returns false if the field doesn't exist
148 * @param string $table Table name
149 * @param string $field Field name
153 function fieldInfo( $table, $field );
156 * Get information about an index into an object
157 * @param string $table Table name
158 * @param string $index Index name
159 * @param string $fname Calling function name
160 * @return mixed Database-specific index description class or false if the index does not exist
162 function indexInfo( $table, $index, $fname = __METHOD__
);
165 * Get the number of rows affected by the last write query
166 * @see http://www.php.net/mysql_affected_rows
170 function affectedRows();
173 * Wrapper for addslashes()
175 * @param string $s String to be slashed.
176 * @return string Slashed string.
178 function strencode( $s );
181 * Returns a wikitext link to the DB's website, e.g.,
182 * return "[http://www.mysql.com/ MySQL]";
183 * Should at least contain plain text, if for some reason
184 * your database has no website.
186 * @return string Wikitext of a link to the server software's web site
188 function getSoftwareLink();
191 * A string describing the current software version, like from
192 * mysql_get_server_info().
194 * @return string Version information from the database server.
196 function getServerVersion();
199 * A string describing the current software version, and possibly
200 * other details in a user-friendly way. Will be listed on Special:Version, etc.
201 * Use getServerVersion() to get machine-friendly information.
203 * @return string Version information from the database server
205 function getServerInfo();
209 * Interface for classes that implement or wrap DatabaseBase
212 interface IDatabase
{
216 * Database abstraction object
219 abstract class DatabaseBase
implements IDatabase
, DatabaseType
{
220 /** Number of times to re-try an operation in case of deadlock */
221 const DEADLOCK_TRIES
= 4;
223 /** Minimum time to wait before retry, in microseconds */
224 const DEADLOCK_DELAY_MIN
= 500000;
226 /** Maximum time to wait before retry */
227 const DEADLOCK_DELAY_MAX
= 1500000;
229 # ------------------------------------------------------------------------------
231 # ------------------------------------------------------------------------------
233 protected $mLastQuery = '';
234 protected $mDoneWrites = false;
235 protected $mPHPError = false;
237 protected $mServer, $mUser, $mPassword, $mDBname;
239 /** @var resource Database connection */
240 protected $mConn = null;
241 protected $mOpened = false;
243 /** @var callable[] */
244 protected $mTrxIdleCallbacks = array();
245 /** @var callable[] */
246 protected $mTrxPreCommitCallbacks = array();
248 protected $mTablePrefix;
252 protected $mErrorCount = 0;
253 protected $mLBInfo = array();
254 protected $mDefaultBigSelects = null;
255 protected $mSchemaVars = false;
257 protected $preparedArgs;
259 protected $htmlErrors;
261 protected $delimiter = ';';
264 * Either 1 if a transaction is active or 0 otherwise.
265 * The other Trx fields may not be meaningfull if this is 0.
269 protected $mTrxLevel = 0;
272 * Remembers the function name given for starting the most recent transaction via begin().
273 * Used to provide additional context for error reporting.
276 * @see DatabaseBase::mTrxLevel
278 private $mTrxFname = null;
281 * Record if possible write queries were done in the last transaction started
284 * @see DatabaseBase::mTrxLevel
286 private $mTrxDoneWrites = false;
289 * Record if the current transaction was started implicitly due to DBO_TRX being set.
292 * @see DatabaseBase::mTrxLevel
294 private $mTrxAutomatic = false;
297 * Array of levels of atomicity within transactions
301 private $mTrxAtomicLevels;
304 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
308 private $mTrxAutomaticAtomic = false;
312 * @var resource File handle for upgrade
314 protected $fileHandle = null;
318 * @var string[] Process cache of VIEWs names in the database
320 protected $allViews = null;
322 # ------------------------------------------------------------------------------
324 # ------------------------------------------------------------------------------
325 # These optionally set a variable and return the previous state
328 * A string describing the current software version, and possibly
329 * other details in a user-friendly way. Will be listed on Special:Version, etc.
330 * Use getServerVersion() to get machine-friendly information.
332 * @return string Version information from the database server
334 public function getServerInfo() {
335 return $this->getServerVersion();
339 * @return string Command delimiter used by this database engine
341 public function getDelimiter() {
342 return $this->delimiter
;
346 * Boolean, controls output of large amounts of debug information.
347 * @param bool|null $debug
348 * - true to enable debugging
349 * - false to disable debugging
350 * - omitted or null to do nothing
352 * @return bool|null Previous value of the flag
354 public function debug( $debug = null ) {
355 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
359 * Turns buffering of SQL result sets on (true) or off (false). Default is
362 * Unbuffered queries are very troublesome in MySQL:
364 * - If another query is executed while the first query is being read
365 * out, the first query is killed. This means you can't call normal
366 * MediaWiki functions while you are reading an unbuffered query result
367 * from a normal wfGetDB() connection.
369 * - Unbuffered queries cause the MySQL server to use large amounts of
370 * memory and to hold broad locks which block other queries.
372 * If you want to limit client-side memory, it's almost always better to
373 * split up queries into batches using a LIMIT clause than to switch off
376 * @param null|bool $buffer
377 * @return null|bool The previous value of the flag
379 public function bufferResults( $buffer = null ) {
380 if ( is_null( $buffer ) ) {
381 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
383 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
388 * Turns on (false) or off (true) the automatic generation and sending
389 * of a "we're sorry, but there has been a database error" page on
390 * database errors. Default is on (false). When turned off, the
391 * code should use lastErrno() and lastError() to handle the
392 * situation as appropriate.
394 * Do not use this function outside of the Database classes.
396 * @param null|bool $ignoreErrors
397 * @return bool The previous value of the flag.
399 public function ignoreErrors( $ignoreErrors = null ) {
400 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
404 * Gets the current transaction level.
406 * Historically, transactions were allowed to be "nested". This is no
407 * longer supported, so this function really only returns a boolean.
409 * @return int The previous value
411 public function trxLevel() {
412 return $this->mTrxLevel
;
416 * Get/set the number of errors logged. Only useful when errors are ignored
417 * @param int $count The count to set, or omitted to leave it unchanged.
418 * @return int The error count
420 public function errorCount( $count = null ) {
421 return wfSetVar( $this->mErrorCount
, $count );
425 * Get/set the table prefix.
426 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
427 * @return string The previous table prefix.
429 public function tablePrefix( $prefix = null ) {
430 return wfSetVar( $this->mTablePrefix
, $prefix );
434 * Get/set the db schema.
435 * @param string $schema The database schema to set, or omitted to leave it unchanged.
436 * @return string The previous db schema.
438 public function dbSchema( $schema = null ) {
439 return wfSetVar( $this->mSchema
, $schema );
443 * Set the filehandle to copy write statements to.
445 * @param resource $fh File handle
447 public function setFileHandle( $fh ) {
448 $this->fileHandle
= $fh;
452 * Get properties passed down from the server info array of the load
455 * @param string $name The entry of the info array to get, or null to get the
458 * @return array|mixed|null
460 public function getLBInfo( $name = null ) {
461 if ( is_null( $name ) ) {
462 return $this->mLBInfo
;
464 if ( array_key_exists( $name, $this->mLBInfo
) ) {
465 return $this->mLBInfo
[$name];
473 * Set the LB info array, or a member of it. If called with one parameter,
474 * the LB info array is set to that parameter. If it is called with two
475 * parameters, the member with the given name is set to the given value.
477 * @param string $name
478 * @param array $value
480 public function setLBInfo( $name, $value = null ) {
481 if ( is_null( $value ) ) {
482 $this->mLBInfo
= $name;
484 $this->mLBInfo
[$name] = $value;
489 * Set lag time in seconds for a fake slave
491 * @param mixed $lag Valid values for this parameter are determined by the
492 * subclass, but should be a PHP scalar or array that would be sensible
493 * as part of $wgLBFactoryConf.
495 public function setFakeSlaveLag( $lag ) {
499 * Make this connection a fake master
501 * @param bool $enabled
503 public function setFakeMaster( $enabled = true ) {
507 * Returns true if this database supports (and uses) cascading deletes
511 public function cascadingDeletes() {
516 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
520 public function cleanupTriggers() {
525 * Returns true if this database is strict about what can be put into an IP field.
526 * Specifically, it uses a NULL value instead of an empty string.
530 public function strictIPs() {
535 * Returns true if this database uses timestamps rather than integers
539 public function realTimestamps() {
544 * Returns true if this database does an implicit sort when doing GROUP BY
548 public function implicitGroupby() {
553 * Returns true if this database does an implicit order by when the column has an index
554 * For example: SELECT page_title FROM page LIMIT 1
558 public function implicitOrderby() {
563 * Returns true if this database can do a native search on IP columns
564 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
568 public function searchableIPs() {
573 * Returns true if this database can use functional indexes
577 public function functionalIndexes() {
582 * Return the last query that went through DatabaseBase::query()
585 public function lastQuery() {
586 return $this->mLastQuery
;
590 * Returns true if the connection may have been used for write queries.
591 * Should return true if unsure.
595 public function doneWrites() {
596 return $this->mDoneWrites
;
600 * Returns true if there is a transaction open with possible write
601 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
605 public function writesOrCallbacksPending() {
606 return $this->mTrxLevel
&& (
607 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
612 * Is a connection to the database open?
615 public function isOpen() {
616 return $this->mOpened
;
620 * Set a flag for this connection
622 * @param int $flag DBO_* constants from Defines.php:
623 * - DBO_DEBUG: output some debug info (same as debug())
624 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
625 * - DBO_TRX: automatically start transactions
626 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
627 * and removes it in command line mode
628 * - DBO_PERSISTENT: use persistant database connection
630 public function setFlag( $flag ) {
631 global $wgDebugDBTransactions;
632 $this->mFlags |
= $flag;
633 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
634 wfDebug( "Implicit transactions are now enabled.\n" );
639 * Clear a flag for this connection
641 * @param int $flag DBO_* constants from Defines.php:
642 * - DBO_DEBUG: output some debug info (same as debug())
643 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
644 * - DBO_TRX: automatically start transactions
645 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
646 * and removes it in command line mode
647 * - DBO_PERSISTENT: use persistant database connection
649 public function clearFlag( $flag ) {
650 global $wgDebugDBTransactions;
651 $this->mFlags
&= ~
$flag;
652 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
653 wfDebug( "Implicit transactions are now disabled.\n" );
658 * Returns a boolean whether the flag $flag is set for this connection
660 * @param int $flag DBO_* constants from Defines.php:
661 * - DBO_DEBUG: output some debug info (same as debug())
662 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
663 * - DBO_TRX: automatically start transactions
664 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
665 * and removes it in command line mode
666 * - DBO_PERSISTENT: use persistant database connection
669 public function getFlag( $flag ) {
670 return !!( $this->mFlags
& $flag );
674 * General read-only accessor
676 * @param string $name
679 public function getProperty( $name ) {
686 public function getWikiID() {
687 if ( $this->mTablePrefix
) {
688 return "{$this->mDBname}-{$this->mTablePrefix}";
690 return $this->mDBname
;
695 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
699 public function getSchemaPath() {
701 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
702 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
704 return "$IP/maintenance/tables.sql";
708 # ------------------------------------------------------------------------------
710 # ------------------------------------------------------------------------------
715 * FIXME: It is possible to construct a Database object with no associated
716 * connection object, by specifying no parameters to __construct(). This
717 * feature is deprecated and should be removed.
719 * DatabaseBase subclasses should not be constructed directly in external
720 * code. DatabaseBase::factory() should be used instead.
722 * @param array $params Parameters passed from DatabaseBase::factory()
724 function __construct( $params = null ) {
725 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
727 $this->mTrxAtomicLevels
= new SplStack
;
729 if ( is_array( $params ) ) { // MW 1.22
730 $server = $params['host'];
731 $user = $params['user'];
732 $password = $params['password'];
733 $dbName = $params['dbname'];
734 $flags = $params['flags'];
735 $tablePrefix = $params['tablePrefix'];
736 $schema = $params['schema'];
737 $foreign = $params['foreign'];
738 } else { // legacy calling pattern
739 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.23" );
740 $args = func_get_args();
741 $server = isset( $args[0] ) ?
$args[0] : false;
742 $user = isset( $args[1] ) ?
$args[1] : false;
743 $password = isset( $args[2] ) ?
$args[2] : false;
744 $dbName = isset( $args[3] ) ?
$args[3] : false;
745 $flags = isset( $args[4] ) ?
$args[4] : 0;
746 $tablePrefix = isset( $args[5] ) ?
$args[5] : 'get from global';
747 $schema = 'get from global';
748 $foreign = isset( $args[6] ) ?
$args[6] : false;
751 $this->mFlags
= $flags;
752 if ( $this->mFlags
& DBO_DEFAULT
) {
753 if ( $wgCommandLineMode ) {
754 $this->mFlags
&= ~DBO_TRX
;
755 if ( $wgDebugDBTransactions ) {
756 wfDebug( "Implicit transaction open disabled.\n" );
759 $this->mFlags |
= DBO_TRX
;
760 if ( $wgDebugDBTransactions ) {
761 wfDebug( "Implicit transaction open enabled.\n" );
766 /** Get the default table prefix*/
767 if ( $tablePrefix == 'get from global' ) {
768 $this->mTablePrefix
= $wgDBprefix;
770 $this->mTablePrefix
= $tablePrefix;
773 /** Get the database schema*/
774 if ( $schema == 'get from global' ) {
775 $this->mSchema
= $wgDBmwschema;
777 $this->mSchema
= $schema;
780 $this->mForeign
= $foreign;
783 $this->open( $server, $user, $password, $dbName );
788 * Called by serialize. Throw an exception when DB connection is serialized.
789 * This causes problems on some database engines because the connection is
790 * not restored on unserialize.
792 public function __sleep() {
793 throw new MWException( 'Database serialization may cause problems, since ' .
794 'the connection is not restored on wakeup.' );
798 * Given a DB type, construct the name of the appropriate child class of
799 * DatabaseBase. This is designed to replace all of the manual stuff like:
800 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
801 * as well as validate against the canonical list of DB types we have
803 * This factory function is mostly useful for when you need to connect to a
804 * database other than the MediaWiki default (such as for external auth,
805 * an extension, et cetera). Do not use this to connect to the MediaWiki
806 * database. Example uses in core:
807 * @see LoadBalancer::reallyOpenConnection()
808 * @see ForeignDBRepo::getMasterDB()
809 * @see WebInstaller_DBConnect::execute()
813 * @param string $dbType A possible DB type
814 * @param array $p An array of options to pass to the constructor.
815 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
816 * @throws MWException If the database driver or extension cannot be found
817 * @return DatabaseBase|null DatabaseBase subclass or null
819 final public static function factory( $dbType, $p = array() ) {
820 $canonicalDBTypes = array(
821 'mysql' => array( 'mysqli', 'mysql' ),
822 'postgres' => array(),
829 $dbType = strtolower( $dbType );
830 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
831 $possibleDrivers = $canonicalDBTypes[$dbType];
832 if ( !empty( $p['driver'] ) ) {
833 if ( in_array( $p['driver'], $possibleDrivers ) ) {
834 $driver = $p['driver'];
836 throw new MWException( __METHOD__
.
837 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
840 foreach ( $possibleDrivers as $posDriver ) {
841 if ( extension_loaded( $posDriver ) ) {
842 $driver = $posDriver;
850 if ( $driver === false ) {
851 throw new MWException( __METHOD__
.
852 " no viable database extension found for type '$dbType'" );
855 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
856 // and everything else doesn't use a schema (e.g. null)
857 // Although postgres and oracle support schemas, we don't use them (yet)
858 // to maintain backwards compatibility
859 $defaultSchemas = array(
864 'mssql' => 'get from global',
867 $class = 'Database' . ucfirst( $driver );
868 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
870 'host' => isset( $p['host'] ) ?
$p['host'] : false,
871 'user' => isset( $p['user'] ) ?
$p['user'] : false,
872 'password' => isset( $p['password'] ) ?
$p['password'] : false,
873 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
874 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
875 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
876 'schema' => isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType],
877 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
880 return new $class( $params );
886 protected function installErrorHandler() {
887 $this->mPHPError
= false;
888 $this->htmlErrors
= ini_set( 'html_errors', '0' );
889 set_error_handler( array( $this, 'connectionErrorHandler' ) );
893 * @return bool|string
895 protected function restoreErrorHandler() {
896 restore_error_handler();
897 if ( $this->htmlErrors
!== false ) {
898 ini_set( 'html_errors', $this->htmlErrors
);
900 if ( $this->mPHPError
) {
901 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
902 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
912 * @param string $errstr
914 public function connectionErrorHandler( $errno, $errstr ) {
915 $this->mPHPError
= $errstr;
919 * Closes a database connection.
920 * if it is open : commits any open transactions
922 * @throws MWException
923 * @return bool Operation success. true if already closed.
925 public function close() {
926 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
927 throw new MWException( "Transaction idle callbacks still pending." );
929 $this->mOpened
= false;
930 if ( $this->mConn
) {
931 if ( $this->trxLevel() ) {
932 if ( !$this->mTrxAutomatic
) {
933 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
934 " performing implicit commit before closing connection!" );
937 $this->commit( __METHOD__
, 'flush' );
940 $ret = $this->closeConnection();
941 $this->mConn
= false;
950 * Closes underlying database connection
952 * @return bool Whether connection was closed successfully
954 abstract protected function closeConnection();
957 * @param string $error Fallback error message, used if none is given by DB
958 * @throws DBConnectionError
960 function reportConnectionError( $error = 'Unknown error' ) {
961 $myError = $this->lastError();
967 throw new DBConnectionError( $this, $error );
971 * The DBMS-dependent part of query()
973 * @param string $sql SQL query.
974 * @return ResultWrapper|bool Result object to feed to fetchObject,
975 * fetchRow, ...; or false on failure
977 abstract protected function doQuery( $sql );
980 * Determine whether a query writes to the DB.
981 * Should return true if unsure.
986 public function isWriteQuery( $sql ) {
987 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
991 * Run an SQL query and return the result. Normally throws a DBQueryError
992 * on failure. If errors are ignored, returns false instead.
994 * In new code, the query wrappers select(), insert(), update(), delete(),
995 * etc. should be used where possible, since they give much better DBMS
996 * independence and automatically quote or validate user input in a variety
997 * of contexts. This function is generally only useful for queries which are
998 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1001 * However, the query wrappers themselves should call this function.
1003 * @param string $sql SQL query
1004 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1005 * comment (you can use __METHOD__ or add some extra info)
1006 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1007 * maybe best to catch the exception instead?
1008 * @throws MWException
1009 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1010 * for a successful read query, or false on failure if $tempIgnore set
1012 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1013 global $wgUser, $wgDebugDBTransactions;
1015 $this->mLastQuery
= $sql;
1016 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1017 # Set a flag indicating that writes have been done
1018 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
1019 $this->mDoneWrites
= true;
1022 # Add a comment for easy SHOW PROCESSLIST interpretation
1023 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1024 $userName = $wgUser->getName();
1025 if ( mb_strlen( $userName ) > 15 ) {
1026 $userName = mb_substr( $userName, 0, 15 ) . '...';
1028 $userName = str_replace( '/', '', $userName );
1033 // Add trace comment to the begin of the sql string, right after the operator.
1034 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1035 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1037 # If DBO_TRX is set, start a transaction
1038 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
1039 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
1041 # Avoid establishing transactions for SHOW and SET statements too -
1042 # that would delay transaction initializations to once connection
1043 # is really used by application
1044 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
1045 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
1046 if ( $wgDebugDBTransactions ) {
1047 wfDebug( "Implicit transaction start.\n" );
1049 $this->begin( __METHOD__
. " ($fname)" );
1050 $this->mTrxAutomatic
= true;
1054 # Keep track of whether the transaction has write queries pending
1055 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1056 $this->mTrxDoneWrites
= true;
1057 $id = spl_object_hash( $this );
1058 Profiler
::instance()->transactionWritingIn( $this->mServer
, $this->mDBname
, $id );
1063 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1065 if ( !Profiler
::instance()->isStub() ) {
1066 # generalizeSQL will probably cut down the query to reasonable
1067 # logging size most of the time. The substr is really just a sanity check.
1069 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1070 $totalProf = 'DatabaseBase::query-master';
1072 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1073 $totalProf = 'DatabaseBase::query';
1075 wfProfileIn( $totalProf );
1076 wfProfileIn( $queryProf );
1079 if ( $this->debug() ) {
1083 $sqlx = substr( $commentedSql, 0, 500 );
1084 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1086 $master = $isMaster ?
'master' : 'slave';
1087 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1090 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1092 # Avoid fatals if close() was called
1093 if ( !$this->isOpen() ) {
1094 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1097 # Do the query and handle errors
1098 $ret = $this->doQuery( $commentedSql );
1100 MWDebug
::queryTime( $queryId );
1102 # Try reconnecting if the connection was lost
1103 if ( false === $ret && $this->wasErrorReissuable() ) {
1104 # Transaction is gone, like it or not
1105 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1106 $this->mTrxLevel
= 0;
1107 $this->mTrxIdleCallbacks
= array(); // bug 65263
1108 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1109 wfDebug( "Connection lost, reconnecting...\n" );
1111 if ( $this->ping() ) {
1112 global $wgRequestTime;
1113 wfDebug( "Reconnected\n" );
1114 $sqlx = substr( $commentedSql, 0, 500 );
1115 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1116 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1117 if ( $elapsed < 300 ) {
1118 # Not a database error to lose a transaction after a minute or two
1119 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx" );
1122 # Leave $ret as false and let an error be reported.
1123 # Callers may catch the exception and continue to use the DB.
1125 # Should be safe to silently retry (no trx and thus no callbacks)
1126 $ret = $this->doQuery( $commentedSql );
1129 wfDebug( "Failed\n" );
1133 if ( false === $ret ) {
1134 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1137 if ( !Profiler
::instance()->isStub() ) {
1138 wfProfileOut( $queryProf );
1139 wfProfileOut( $totalProf );
1142 return $this->resultObject( $ret );
1146 * Report a query error. Log the error, and if neither the object ignore
1147 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1149 * @param string $error
1151 * @param string $sql
1152 * @param string $fname
1153 * @param bool $tempIgnore
1154 * @throws DBQueryError
1156 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1157 # Ignore errors during error handling to avoid infinite recursion
1158 $ignore = $this->ignoreErrors( true );
1159 ++
$this->mErrorCount
;
1161 if ( $ignore ||
$tempIgnore ) {
1162 wfDebug( "SQL ERROR (ignored): $error\n" );
1163 $this->ignoreErrors( $ignore );
1165 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1166 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line" );
1167 wfDebug( "SQL ERROR: " . $error . "\n" );
1168 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1173 * Intended to be compatible with the PEAR::DB wrapper functions.
1174 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1176 * ? = scalar value, quoted as necessary
1177 * ! = raw SQL bit (a function for instance)
1178 * & = filename; reads the file and inserts as a blob
1179 * (we don't use this though...)
1181 * @param string $sql
1182 * @param string $func
1186 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1187 /* MySQL doesn't support prepared statements (yet), so just
1188 * pack up the query for reference. We'll manually replace
1191 return array( 'query' => $sql, 'func' => $func );
1195 * Free a prepared query, generated by prepare().
1196 * @param string $prepared
1198 protected function freePrepared( $prepared ) {
1199 /* No-op by default */
1203 * Execute a prepared query with the various arguments
1204 * @param string $prepared The prepared sql
1205 * @param mixed $args Either an array here, or put scalars as varargs
1207 * @return ResultWrapper
1209 public function execute( $prepared, $args = null ) {
1210 if ( !is_array( $args ) ) {
1212 $args = func_get_args();
1213 array_shift( $args );
1216 $sql = $this->fillPrepared( $prepared['query'], $args );
1218 return $this->query( $sql, $prepared['func'] );
1222 * For faking prepared SQL statements on DBs that don't support it directly.
1224 * @param string $preparedQuery A 'preparable' SQL statement
1225 * @param array $args Array of Arguments to fill it with
1226 * @return string Executable SQL
1228 public function fillPrepared( $preparedQuery, $args ) {
1230 $this->preparedArgs
=& $args;
1232 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1233 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1237 * preg_callback func for fillPrepared()
1238 * The arguments should be in $this->preparedArgs and must not be touched
1239 * while we're doing this.
1241 * @param array $matches
1242 * @throws DBUnexpectedError
1245 protected function fillPreparedArg( $matches ) {
1246 switch ( $matches[1] ) {
1255 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1257 switch ( $matches[1] ) {
1259 return $this->addQuotes( $arg );
1263 # return $this->addQuotes( file_get_contents( $arg ) );
1264 throw new DBUnexpectedError(
1266 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1269 throw new DBUnexpectedError(
1271 'Received invalid match. This should never happen!'
1277 * Free a result object returned by query() or select(). It's usually not
1278 * necessary to call this, just use unset() or let the variable holding
1279 * the result object go out of scope.
1281 * @param mixed $res A SQL result
1283 public function freeResult( $res ) {
1287 * A SELECT wrapper which returns a single field from a single result row.
1289 * Usually throws a DBQueryError on failure. If errors are explicitly
1290 * ignored, returns false on failure.
1292 * If no result rows are returned from the query, false is returned.
1294 * @param string|array $table Table name. See DatabaseBase::select() for details.
1295 * @param string $var The field name to select. This must be a valid SQL
1296 * fragment: do not use unvalidated user input.
1297 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1298 * @param string $fname The function name of the caller.
1299 * @param string|array $options The query options. See DatabaseBase::select() for details.
1301 * @return bool|mixed The value from the field, or false on failure.
1303 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1306 if ( !is_array( $options ) ) {
1307 $options = array( $options );
1310 $options['LIMIT'] = 1;
1312 $res = $this->select( $table, $var, $cond, $fname, $options );
1314 if ( $res === false ||
!$this->numRows( $res ) ) {
1318 $row = $this->fetchRow( $res );
1320 if ( $row !== false ) {
1321 return reset( $row );
1328 * Returns an optional USE INDEX clause to go after the table, and a
1329 * string to go at the end of the query.
1331 * @param array $options Associative array of options to be turned into
1332 * an SQL query, valid keys are listed in the function.
1334 * @see DatabaseBase::select()
1336 public function makeSelectOptions( $options ) {
1337 $preLimitTail = $postLimitTail = '';
1340 $noKeyOptions = array();
1342 foreach ( $options as $key => $option ) {
1343 if ( is_numeric( $key ) ) {
1344 $noKeyOptions[$option] = true;
1348 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1350 $preLimitTail .= $this->makeOrderBy( $options );
1352 // if (isset($options['LIMIT'])) {
1353 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1354 // isset($options['OFFSET']) ? $options['OFFSET']
1358 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1359 $postLimitTail .= ' FOR UPDATE';
1362 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1363 $postLimitTail .= ' LOCK IN SHARE MODE';
1366 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1367 $startOpts .= 'DISTINCT';
1370 # Various MySQL extensions
1371 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1372 $startOpts .= ' /*! STRAIGHT_JOIN */';
1375 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1376 $startOpts .= ' HIGH_PRIORITY';
1379 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1380 $startOpts .= ' SQL_BIG_RESULT';
1383 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1384 $startOpts .= ' SQL_BUFFER_RESULT';
1387 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1388 $startOpts .= ' SQL_SMALL_RESULT';
1391 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1392 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1395 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1396 $startOpts .= ' SQL_CACHE';
1399 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1400 $startOpts .= ' SQL_NO_CACHE';
1403 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1404 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1409 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1413 * Returns an optional GROUP BY with an optional HAVING
1415 * @param array $options Associative array of options
1417 * @see DatabaseBase::select()
1420 public function makeGroupByWithHaving( $options ) {
1422 if ( isset( $options['GROUP BY'] ) ) {
1423 $gb = is_array( $options['GROUP BY'] )
1424 ?
implode( ',', $options['GROUP BY'] )
1425 : $options['GROUP BY'];
1426 $sql .= ' GROUP BY ' . $gb;
1428 if ( isset( $options['HAVING'] ) ) {
1429 $having = is_array( $options['HAVING'] )
1430 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1431 : $options['HAVING'];
1432 $sql .= ' HAVING ' . $having;
1439 * Returns an optional ORDER BY
1441 * @param array $options Associative array of options
1443 * @see DatabaseBase::select()
1446 public function makeOrderBy( $options ) {
1447 if ( isset( $options['ORDER BY'] ) ) {
1448 $ob = is_array( $options['ORDER BY'] )
1449 ?
implode( ',', $options['ORDER BY'] )
1450 : $options['ORDER BY'];
1452 return ' ORDER BY ' . $ob;
1459 * Execute a SELECT query constructed using the various parameters provided.
1460 * See below for full details of the parameters.
1462 * @param string|array $table Table name
1463 * @param string|array $vars Field names
1464 * @param string|array $conds Conditions
1465 * @param string $fname Caller function name
1466 * @param array $options Query options
1467 * @param array $join_conds Join conditions
1469 * @param string|array $table
1471 * May be either an array of table names, or a single string holding a table
1472 * name. If an array is given, table aliases can be specified, for example:
1474 * array( 'a' => 'user' )
1476 * This includes the user table in the query, with the alias "a" available
1477 * for use in field names (e.g. a.user_name).
1479 * All of the table names given here are automatically run through
1480 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1481 * added, and various other table name mappings to be performed.
1484 * @param string|array $vars
1486 * May be either a field name or an array of field names. The field names
1487 * can be complete fragments of SQL, for direct inclusion into the SELECT
1488 * query. If an array is given, field aliases can be specified, for example:
1490 * array( 'maxrev' => 'MAX(rev_id)' )
1492 * This includes an expression with the alias "maxrev" in the query.
1494 * If an expression is given, care must be taken to ensure that it is
1498 * @param string|array $conds
1500 * May be either a string containing a single condition, or an array of
1501 * conditions. If an array is given, the conditions constructed from each
1502 * element are combined with AND.
1504 * Array elements may take one of two forms:
1506 * - Elements with a numeric key are interpreted as raw SQL fragments.
1507 * - Elements with a string key are interpreted as equality conditions,
1508 * where the key is the field name.
1509 * - If the value of such an array element is a scalar (such as a
1510 * string), it will be treated as data and thus quoted appropriately.
1511 * If it is null, an IS NULL clause will be added.
1512 * - If the value is an array, an IN(...) clause will be constructed,
1513 * such that the field name may match any of the elements in the
1514 * array. The elements of the array will be quoted.
1516 * Note that expressions are often DBMS-dependent in their syntax.
1517 * DBMS-independent wrappers are provided for constructing several types of
1518 * expression commonly used in condition queries. See:
1519 * - DatabaseBase::buildLike()
1520 * - DatabaseBase::conditional()
1523 * @param string|array $options
1525 * Optional: Array of query options. Boolean options are specified by
1526 * including them in the array as a string value with a numeric key, for
1529 * array( 'FOR UPDATE' )
1531 * The supported options are:
1533 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1534 * with LIMIT can theoretically be used for paging through a result set,
1535 * but this is discouraged in MediaWiki for performance reasons.
1537 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1538 * and then the first rows are taken until the limit is reached. LIMIT
1539 * is applied to a result set after OFFSET.
1541 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1542 * changed until the next COMMIT.
1544 * - DISTINCT: Boolean: return only unique result rows.
1546 * - GROUP BY: May be either an SQL fragment string naming a field or
1547 * expression to group by, or an array of such SQL fragments.
1549 * - HAVING: May be either an string containing a HAVING clause or an array of
1550 * conditions building the HAVING clause. If an array is given, the conditions
1551 * constructed from each element are combined with AND.
1553 * - ORDER BY: May be either an SQL fragment giving a field name or
1554 * expression to order by, or an array of such SQL fragments.
1556 * - USE INDEX: This may be either a string giving the index name to use
1557 * for the query, or an array. If it is an associative array, each key
1558 * gives the table name (or alias), each value gives the index name to
1559 * use for that table. All strings are SQL fragments and so should be
1560 * validated by the caller.
1562 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1563 * instead of SELECT.
1565 * And also the following boolean MySQL extensions, see the MySQL manual
1566 * for documentation:
1568 * - LOCK IN SHARE MODE
1572 * - SQL_BUFFER_RESULT
1573 * - SQL_SMALL_RESULT
1574 * - SQL_CALC_FOUND_ROWS
1579 * @param string|array $join_conds
1581 * Optional associative array of table-specific join conditions. In the
1582 * most common case, this is unnecessary, since the join condition can be
1583 * in $conds. However, it is useful for doing a LEFT JOIN.
1585 * The key of the array contains the table name or alias. The value is an
1586 * array with two elements, numbered 0 and 1. The first gives the type of
1587 * join, the second is an SQL fragment giving the join condition for that
1588 * table. For example:
1590 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1592 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1593 * with no rows in it will be returned. If there was a query error, a
1594 * DBQueryError exception will be thrown, except if the "ignore errors"
1595 * option was set, in which case false will be returned.
1597 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1598 $options = array(), $join_conds = array() ) {
1599 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1601 return $this->query( $sql, $fname );
1605 * The equivalent of DatabaseBase::select() except that the constructed SQL
1606 * is returned, instead of being immediately executed. This can be useful for
1607 * doing UNION queries, where the SQL text of each query is needed. In general,
1608 * however, callers outside of Database classes should just use select().
1610 * @param string|array $table Table name
1611 * @param string|array $vars Field names
1612 * @param string|array $conds Conditions
1613 * @param string $fname Caller function name
1614 * @param string|array $options Query options
1615 * @param string|array $join_conds Join conditions
1617 * @return string SQL query string.
1618 * @see DatabaseBase::select()
1620 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1621 $options = array(), $join_conds = array()
1623 if ( is_array( $vars ) ) {
1624 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1627 $options = (array)$options;
1628 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1629 ?
$options['USE INDEX']
1632 if ( is_array( $table ) ) {
1634 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1635 } elseif ( $table != '' ) {
1636 if ( $table[0] == ' ' ) {
1637 $from = ' FROM ' . $table;
1640 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1646 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1647 $this->makeSelectOptions( $options );
1649 if ( !empty( $conds ) ) {
1650 if ( is_array( $conds ) ) {
1651 $conds = $this->makeList( $conds, LIST_AND
);
1653 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1655 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1658 if ( isset( $options['LIMIT'] ) ) {
1659 $sql = $this->limitResult( $sql, $options['LIMIT'],
1660 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1662 $sql = "$sql $postLimitTail";
1664 if ( isset( $options['EXPLAIN'] ) ) {
1665 $sql = 'EXPLAIN ' . $sql;
1672 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1673 * that a single row object is returned. If the query returns no rows,
1674 * false is returned.
1676 * @param string|array $table Table name
1677 * @param string|array $vars Field names
1678 * @param array $conds Conditions
1679 * @param string $fname Caller function name
1680 * @param string|array $options Query options
1681 * @param array|string $join_conds Join conditions
1683 * @return stdClass|bool
1685 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1686 $options = array(), $join_conds = array()
1688 $options = (array)$options;
1689 $options['LIMIT'] = 1;
1690 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1692 if ( $res === false ) {
1696 if ( !$this->numRows( $res ) ) {
1700 $obj = $this->fetchObject( $res );
1706 * Estimate rows in dataset.
1708 * MySQL allows you to estimate the number of rows that would be returned
1709 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1710 * index cardinality statistics, and is notoriously inaccurate, especially
1711 * when large numbers of rows have recently been added or deleted.
1713 * For DBMSs that don't support fast result size estimation, this function
1714 * will actually perform the SELECT COUNT(*).
1716 * Takes the same arguments as DatabaseBase::select().
1718 * @param string $table Table name
1719 * @param string $vars Unused
1720 * @param array|string $conds Filters on the table
1721 * @param string $fname Function name for profiling
1722 * @param array $options Options for select
1723 * @return int Row count
1725 public function estimateRowCount( $table, $vars = '*', $conds = '',
1726 $fname = __METHOD__
, $options = array()
1729 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1732 $row = $this->fetchRow( $res );
1733 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1740 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1741 * It's only slightly flawed. Don't use for anything important.
1743 * @param string $sql A SQL Query
1747 static function generalizeSQL( $sql ) {
1748 # This does the same as the regexp below would do, but in such a way
1749 # as to avoid crashing php on some large strings.
1750 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1752 $sql = str_replace( "\\\\", '', $sql );
1753 $sql = str_replace( "\\'", '', $sql );
1754 $sql = str_replace( "\\\"", '', $sql );
1755 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1756 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1758 # All newlines, tabs, etc replaced by single space
1759 $sql = preg_replace( '/\s+/', ' ', $sql );
1762 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1763 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1769 * Determines whether a field exists in a table
1771 * @param string $table Table name
1772 * @param string $field Filed to check on that table
1773 * @param string $fname Calling function name (optional)
1774 * @return bool Whether $table has filed $field
1776 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1777 $info = $this->fieldInfo( $table, $field );
1783 * Determines whether an index exists
1784 * Usually throws a DBQueryError on failure
1785 * If errors are explicitly ignored, returns NULL on failure
1787 * @param string $table
1788 * @param string $index
1789 * @param string $fname
1792 public function indexExists( $table, $index, $fname = __METHOD__
) {
1793 if ( !$this->tableExists( $table ) ) {
1797 $info = $this->indexInfo( $table, $index, $fname );
1798 if ( is_null( $info ) ) {
1801 return $info !== false;
1806 * Query whether a given table exists
1808 * @param string $table
1809 * @param string $fname
1812 public function tableExists( $table, $fname = __METHOD__
) {
1813 $table = $this->tableName( $table );
1814 $old = $this->ignoreErrors( true );
1815 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1816 $this->ignoreErrors( $old );
1822 * Determines if a given index is unique
1824 * @param string $table
1825 * @param string $index
1829 public function indexUnique( $table, $index ) {
1830 $indexInfo = $this->indexInfo( $table, $index );
1832 if ( !$indexInfo ) {
1836 return !$indexInfo[0]->Non_unique
;
1840 * Helper for DatabaseBase::insert().
1842 * @param array $options
1845 protected function makeInsertOptions( $options ) {
1846 return implode( ' ', $options );
1850 * INSERT wrapper, inserts an array into a table.
1854 * - A single associative array. The array keys are the field names, and
1855 * the values are the values to insert. The values are treated as data
1856 * and will be quoted appropriately. If NULL is inserted, this will be
1857 * converted to a database NULL.
1858 * - An array with numeric keys, holding a list of associative arrays.
1859 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1860 * each subarray must be identical to each other, and in the same order.
1862 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1865 * $options is an array of options, with boolean options encoded as values
1866 * with numeric keys, in the same style as $options in
1867 * DatabaseBase::select(). Supported options are:
1869 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1870 * any rows which cause duplicate key errors are not inserted. It's
1871 * possible to determine how many rows were successfully inserted using
1872 * DatabaseBase::affectedRows().
1874 * @param string $table Table name. This will be passed through
1875 * DatabaseBase::tableName().
1876 * @param array $a Array of rows to insert
1877 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1878 * @param array $options of options
1882 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1883 # No rows to insert, easy just return now
1884 if ( !count( $a ) ) {
1888 $table = $this->tableName( $table );
1890 if ( !is_array( $options ) ) {
1891 $options = array( $options );
1895 if ( isset( $options['fileHandle'] ) ) {
1896 $fh = $options['fileHandle'];
1898 $options = $this->makeInsertOptions( $options );
1900 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1902 $keys = array_keys( $a[0] );
1905 $keys = array_keys( $a );
1908 $sql = 'INSERT ' . $options .
1909 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1913 foreach ( $a as $row ) {
1919 $sql .= '(' . $this->makeList( $row ) . ')';
1922 $sql .= '(' . $this->makeList( $a ) . ')';
1925 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1927 } elseif ( $fh !== null ) {
1931 return (bool)$this->query( $sql, $fname );
1935 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1937 * @param array $options
1940 protected function makeUpdateOptionsArray( $options ) {
1941 if ( !is_array( $options ) ) {
1942 $options = array( $options );
1947 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1948 $opts[] = $this->lowPriorityOption();
1951 if ( in_array( 'IGNORE', $options ) ) {
1959 * Make UPDATE options for the DatabaseBase::update function
1961 * @param array $options The options passed to DatabaseBase::update
1964 protected function makeUpdateOptions( $options ) {
1965 $opts = $this->makeUpdateOptionsArray( $options );
1967 return implode( ' ', $opts );
1971 * UPDATE wrapper. Takes a condition array and a SET array.
1973 * @param string $table Name of the table to UPDATE. This will be passed through
1974 * DatabaseBase::tableName().
1975 * @param array $values An array of values to SET. For each array element,
1976 * the key gives the field name, and the value gives the data to set
1977 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1978 * @param array $conds An array of conditions (WHERE). See
1979 * DatabaseBase::select() for the details of the format of condition
1980 * arrays. Use '*' to update all rows.
1981 * @param string $fname The function name of the caller (from __METHOD__),
1982 * for logging and profiling.
1983 * @param array $options An array of UPDATE options, can be:
1984 * - IGNORE: Ignore unique key conflicts
1985 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1988 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1989 $table = $this->tableName( $table );
1990 $opts = $this->makeUpdateOptions( $options );
1991 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1993 if ( $conds !== array() && $conds !== '*' ) {
1994 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1997 return $this->query( $sql, $fname );
2001 * Makes an encoded list of strings from an array
2003 * @param array $a Containing the data
2004 * @param int $mode Constant
2005 * - LIST_COMMA: Comma separated, no field names
2006 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2007 * documentation for $conds in DatabaseBase::select().
2008 * - LIST_OR: ORed WHERE clause (without the WHERE)
2009 * - LIST_SET: Comma separated with field names, like a SET clause
2010 * - LIST_NAMES: Comma separated field names
2011 * @throws MWException|DBUnexpectedError
2014 public function makeList( $a, $mode = LIST_COMMA
) {
2015 if ( !is_array( $a ) ) {
2016 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2022 foreach ( $a as $field => $value ) {
2024 if ( $mode == LIST_AND
) {
2026 } elseif ( $mode == LIST_OR
) {
2035 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2036 $list .= "($value)";
2037 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2039 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2040 if ( count( $value ) == 0 ) {
2041 throw new MWException( __METHOD__
. ": empty input for field $field" );
2042 } elseif ( count( $value ) == 1 ) {
2043 // Special-case single values, as IN isn't terribly efficient
2044 // Don't necessarily assume the single key is 0; we don't
2045 // enforce linear numeric ordering on other arrays here.
2046 $value = array_values( $value );
2047 $list .= $field . " = " . $this->addQuotes( $value[0] );
2049 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2051 } elseif ( $value === null ) {
2052 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2053 $list .= "$field IS ";
2054 } elseif ( $mode == LIST_SET
) {
2055 $list .= "$field = ";
2059 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2060 $list .= "$field = ";
2062 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2070 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2071 * The keys on each level may be either integers or strings.
2073 * @param array $data organized as 2-d
2074 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2075 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2076 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2077 * @return string|bool string SQL fragment, or false if no items in array.
2079 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2082 foreach ( $data as $base => $sub ) {
2083 if ( count( $sub ) ) {
2084 $conds[] = $this->makeList(
2085 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2091 return $this->makeList( $conds, LIST_OR
);
2093 // Nothing to search for...
2099 * Return aggregated value alias
2101 * @param array $valuedata
2102 * @param string $valuename
2106 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2111 * @param string $field
2114 public function bitNot( $field ) {
2119 * @param string $fieldLeft
2120 * @param string $fieldRight
2123 public function bitAnd( $fieldLeft, $fieldRight ) {
2124 return "($fieldLeft & $fieldRight)";
2128 * @param string $fieldLeft
2129 * @param string $fieldRight
2132 public function bitOr( $fieldLeft, $fieldRight ) {
2133 return "($fieldLeft | $fieldRight)";
2137 * Build a concatenation list to feed into a SQL query
2138 * @param array $stringList List of raw SQL expressions; caller is
2139 * responsible for any quoting
2142 public function buildConcat( $stringList ) {
2143 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2147 * Build a GROUP_CONCAT or equivalent statement for a query.
2149 * This is useful for combining a field for several rows into a single string.
2150 * NULL values will not appear in the output, duplicated values will appear,
2151 * and the resulting delimiter-separated values have no defined sort order.
2152 * Code using the results may need to use the PHP unique() or sort() methods.
2154 * @param string $delim Glue to bind the results together
2155 * @param string|array $table Table name
2156 * @param string $field Field name
2157 * @param string|array $conds Conditions
2158 * @param string|array $join_conds Join conditions
2159 * @return string SQL text
2162 public function buildGroupConcatField(
2163 $delim, $table, $field, $conds = '', $join_conds = array()
2165 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2167 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2171 * Change the current database
2173 * @todo Explain what exactly will fail if this is not overridden.
2177 * @return bool Success or failure
2179 public function selectDB( $db ) {
2180 # Stub. Shouldn't cause serious problems if it's not overridden, but
2181 # if your database engine supports a concept similar to MySQL's
2182 # databases you may as well.
2183 $this->mDBname
= $db;
2189 * Get the current DB name
2192 public function getDBname() {
2193 return $this->mDBname
;
2197 * Get the server hostname or IP address
2200 public function getServer() {
2201 return $this->mServer
;
2205 * Format a table name ready for use in constructing an SQL query
2207 * This does two important things: it quotes the table names to clean them up,
2208 * and it adds a table prefix if only given a table name with no quotes.
2210 * All functions of this object which require a table name call this function
2211 * themselves. Pass the canonical name to such functions. This is only needed
2212 * when calling query() directly.
2214 * @param string $name Database table name
2215 * @param string $format One of:
2216 * quoted - Automatically pass the table name through addIdentifierQuotes()
2217 * so that it can be used in a query.
2218 * raw - Do not add identifier quotes to the table name
2219 * @return string Full database name
2221 public function tableName( $name, $format = 'quoted' ) {
2222 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2223 # Skip the entire process when we have a string quoted on both ends.
2224 # Note that we check the end so that we will still quote any use of
2225 # use of `database`.table. But won't break things if someone wants
2226 # to query a database table with a dot in the name.
2227 if ( $this->isQuotedIdentifier( $name ) ) {
2231 # Lets test for any bits of text that should never show up in a table
2232 # name. Basically anything like JOIN or ON which are actually part of
2233 # SQL queries, but may end up inside of the table value to combine
2234 # sql. Such as how the API is doing.
2235 # Note that we use a whitespace test rather than a \b test to avoid
2236 # any remote case where a word like on may be inside of a table name
2237 # surrounded by symbols which may be considered word breaks.
2238 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2242 # Split database and table into proper variables.
2243 # We reverse the explode so that database.table and table both output
2244 # the correct table.
2245 $dbDetails = explode( '.', $name, 2 );
2246 if ( count( $dbDetails ) == 3 ) {
2247 list( $database, $schema, $table ) = $dbDetails;
2248 # We don't want any prefix added in this case
2250 } elseif ( count( $dbDetails ) == 2 ) {
2251 list( $database, $table ) = $dbDetails;
2252 # We don't want any prefix added in this case
2253 # In dbs that support it, $database may actually be the schema
2254 # but that doesn't affect any of the functionality here
2258 list( $table ) = $dbDetails;
2259 if ( $wgSharedDB !== null # We have a shared database
2260 && $this->mForeign
== false # We're not working on a foreign database
2261 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2262 && in_array( $table, $wgSharedTables ) # A shared table is selected
2264 $database = $wgSharedDB;
2265 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2266 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2269 $schema = $this->mSchema
; # Default schema
2270 $prefix = $this->mTablePrefix
; # Default prefix
2274 # Quote $table and apply the prefix if not quoted.
2275 # $tableName might be empty if this is called from Database::replaceVars()
2276 $tableName = "{$prefix}{$table}";
2277 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2278 $tableName = $this->addIdentifierQuotes( $tableName );
2281 # Quote $schema and merge it with the table name if needed
2282 if ( $schema !== null ) {
2283 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2284 $schema = $this->addIdentifierQuotes( $schema );
2286 $tableName = $schema . '.' . $tableName;
2289 # Quote $database and merge it with the table name if needed
2290 if ( $database !== null ) {
2291 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2292 $database = $this->addIdentifierQuotes( $database );
2294 $tableName = $database . '.' . $tableName;
2301 * Fetch a number of table names into an array
2302 * This is handy when you need to construct SQL for joins
2305 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2306 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2307 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2311 public function tableNames() {
2312 $inArray = func_get_args();
2315 foreach ( $inArray as $name ) {
2316 $retVal[$name] = $this->tableName( $name );
2323 * Fetch a number of table names into an zero-indexed numerical array
2324 * This is handy when you need to construct SQL for joins
2327 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2328 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2329 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2333 public function tableNamesN() {
2334 $inArray = func_get_args();
2337 foreach ( $inArray as $name ) {
2338 $retVal[] = $this->tableName( $name );
2345 * Get an aliased table name
2346 * e.g. tableName AS newTableName
2348 * @param string $name Table name, see tableName()
2349 * @param string|bool $alias Alias (optional)
2350 * @return string SQL name for aliased table. Will not alias a table to its own name
2352 public function tableNameWithAlias( $name, $alias = false ) {
2353 if ( !$alias ||
$alias == $name ) {
2354 return $this->tableName( $name );
2356 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2361 * Gets an array of aliased table names
2363 * @param array $tables array( [alias] => table )
2364 * @return string[] See tableNameWithAlias()
2366 public function tableNamesWithAlias( $tables ) {
2368 foreach ( $tables as $alias => $table ) {
2369 if ( is_numeric( $alias ) ) {
2372 $retval[] = $this->tableNameWithAlias( $table, $alias );
2379 * Get an aliased field name
2380 * e.g. fieldName AS newFieldName
2382 * @param string $name Field name
2383 * @param string|bool $alias Alias (optional)
2384 * @return string SQL name for aliased field. Will not alias a field to its own name
2386 public function fieldNameWithAlias( $name, $alias = false ) {
2387 if ( !$alias ||
(string)$alias === (string)$name ) {
2390 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2395 * Gets an array of aliased field names
2397 * @param array $fields array( [alias] => field )
2398 * @return string[] See fieldNameWithAlias()
2400 public function fieldNamesWithAlias( $fields ) {
2402 foreach ( $fields as $alias => $field ) {
2403 if ( is_numeric( $alias ) ) {
2406 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2413 * Get the aliased table name clause for a FROM clause
2414 * which might have a JOIN and/or USE INDEX clause
2416 * @param array $tables ( [alias] => table )
2417 * @param array $use_index Same as for select()
2418 * @param array $join_conds Same as for select()
2421 protected function tableNamesWithUseIndexOrJOIN(
2422 $tables, $use_index = array(), $join_conds = array()
2426 $use_index = (array)$use_index;
2427 $join_conds = (array)$join_conds;
2429 foreach ( $tables as $alias => $table ) {
2430 if ( !is_string( $alias ) ) {
2431 // No alias? Set it equal to the table name
2434 // Is there a JOIN clause for this table?
2435 if ( isset( $join_conds[$alias] ) ) {
2436 list( $joinType, $conds ) = $join_conds[$alias];
2437 $tableClause = $joinType;
2438 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2439 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2440 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2442 $tableClause .= ' ' . $use;
2445 $on = $this->makeList( (array)$conds, LIST_AND
);
2447 $tableClause .= ' ON (' . $on . ')';
2450 $retJOIN[] = $tableClause;
2451 } elseif ( isset( $use_index[$alias] ) ) {
2452 // Is there an INDEX clause for this table?
2453 $tableClause = $this->tableNameWithAlias( $table, $alias );
2454 $tableClause .= ' ' . $this->useIndexClause(
2455 implode( ',', (array)$use_index[$alias] )
2458 $ret[] = $tableClause;
2460 $tableClause = $this->tableNameWithAlias( $table, $alias );
2462 $ret[] = $tableClause;
2466 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2467 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2468 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2470 // Compile our final table clause
2471 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2475 * Get the name of an index in a given table
2477 * @param string $index
2480 protected function indexName( $index ) {
2481 // Backwards-compatibility hack
2483 'ar_usertext_timestamp' => 'usertext_timestamp',
2484 'un_user_id' => 'user_id',
2485 'un_user_ip' => 'user_ip',
2488 if ( isset( $renamed[$index] ) ) {
2489 return $renamed[$index];
2496 * Adds quotes and backslashes.
2501 public function addQuotes( $s ) {
2502 if ( $s === null ) {
2505 # This will also quote numeric values. This should be harmless,
2506 # and protects against weird problems that occur when they really
2507 # _are_ strings such as article titles and string->number->string
2508 # conversion is not 1:1.
2509 return "'" . $this->strencode( $s ) . "'";
2514 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2515 * MySQL uses `backticks` while basically everything else uses double quotes.
2516 * Since MySQL is the odd one out here the double quotes are our generic
2517 * and we implement backticks in DatabaseMysql.
2522 public function addIdentifierQuotes( $s ) {
2523 return '"' . str_replace( '"', '""', $s ) . '"';
2527 * Returns if the given identifier looks quoted or not according to
2528 * the database convention for quoting identifiers .
2530 * @param string $name
2533 public function isQuotedIdentifier( $name ) {
2534 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2541 protected function escapeLikeInternal( $s ) {
2542 $s = str_replace( '\\', '\\\\', $s );
2543 $s = $this->strencode( $s );
2544 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2550 * LIKE statement wrapper, receives a variable-length argument list with
2551 * parts of pattern to match containing either string literals that will be
2552 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2553 * the function could be provided with an array of aforementioned
2556 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2557 * a LIKE clause that searches for subpages of 'My page title'.
2559 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2560 * $query .= $dbr->buildLike( $pattern );
2563 * @return string Fully built LIKE statement
2565 public function buildLike() {
2566 $params = func_get_args();
2568 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2569 $params = $params[0];
2574 foreach ( $params as $value ) {
2575 if ( $value instanceof LikeMatch
) {
2576 $s .= $value->toString();
2578 $s .= $this->escapeLikeInternal( $value );
2582 return " LIKE '" . $s . "' ";
2586 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2590 public function anyChar() {
2591 return new LikeMatch( '_' );
2595 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2599 public function anyString() {
2600 return new LikeMatch( '%' );
2604 * Returns an appropriately quoted sequence value for inserting a new row.
2605 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2606 * subclass will return an integer, and save the value for insertId()
2608 * Any implementation of this function should *not* involve reusing
2609 * sequence numbers created for rolled-back transactions.
2610 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2611 * @param string $seqName
2614 public function nextSequenceValue( $seqName ) {
2619 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2620 * is only needed because a) MySQL must be as efficient as possible due to
2621 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2622 * which index to pick. Anyway, other databases might have different
2623 * indexes on a given table. So don't bother overriding this unless you're
2625 * @param string $index
2628 public function useIndexClause( $index ) {
2633 * REPLACE query wrapper.
2635 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2636 * except that when there is a duplicate key error, the old row is deleted
2637 * and the new row is inserted in its place.
2639 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2640 * perform the delete, we need to know what the unique indexes are so that
2641 * we know how to find the conflicting rows.
2643 * It may be more efficient to leave off unique indexes which are unlikely
2644 * to collide. However if you do this, you run the risk of encountering
2645 * errors which wouldn't have occurred in MySQL.
2647 * @param string $table The table to replace the row(s) in.
2648 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2649 * a field name or an array of field names
2650 * @param array $rows Can be either a single row to insert, or multiple rows,
2651 * in the same format as for DatabaseBase::insert()
2652 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2654 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2655 $quotedTable = $this->tableName( $table );
2657 if ( count( $rows ) == 0 ) {
2662 if ( !is_array( reset( $rows ) ) ) {
2663 $rows = array( $rows );
2666 foreach ( $rows as $row ) {
2667 # Delete rows which collide
2668 if ( $uniqueIndexes ) {
2669 $sql = "DELETE FROM $quotedTable WHERE ";
2671 foreach ( $uniqueIndexes as $index ) {
2678 if ( is_array( $index ) ) {
2680 foreach ( $index as $col ) {
2686 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2689 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2693 $this->query( $sql, $fname );
2696 # Now insert the row
2697 $this->insert( $table, $row, $fname );
2702 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2705 * @param string $table Table name
2706 * @param array|string $rows Row(s) to insert
2707 * @param string $fname Caller function name
2709 * @return ResultWrapper
2711 protected function nativeReplace( $table, $rows, $fname ) {
2712 $table = $this->tableName( $table );
2715 if ( !is_array( reset( $rows ) ) ) {
2716 $rows = array( $rows );
2719 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2722 foreach ( $rows as $row ) {
2729 $sql .= '(' . $this->makeList( $row ) . ')';
2732 return $this->query( $sql, $fname );
2736 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2738 * This updates any conflicting rows (according to the unique indexes) using
2739 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2741 * $rows may be either:
2742 * - A single associative array. The array keys are the field names, and
2743 * the values are the values to insert. The values are treated as data
2744 * and will be quoted appropriately. If NULL is inserted, this will be
2745 * converted to a database NULL.
2746 * - An array with numeric keys, holding a list of associative arrays.
2747 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2748 * each subarray must be identical to each other, and in the same order.
2750 * It may be more efficient to leave off unique indexes which are unlikely
2751 * to collide. However if you do this, you run the risk of encountering
2752 * errors which wouldn't have occurred in MySQL.
2754 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2759 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2760 * @param array $rows A single row or list of rows to insert
2761 * @param array $uniqueIndexes List of single field names or field name tuples
2762 * @param array $set An array of values to SET. For each array element, the
2763 * key gives the field name, and the value gives the data to set that
2764 * field to. The data will be quoted by DatabaseBase::addQuotes().
2765 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2769 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2772 if ( !count( $rows ) ) {
2773 return true; // nothing to do
2776 if ( !is_array( reset( $rows ) ) ) {
2777 $rows = array( $rows );
2780 if ( count( $uniqueIndexes ) ) {
2781 $clauses = array(); // list WHERE clauses that each identify a single row
2782 foreach ( $rows as $row ) {
2783 foreach ( $uniqueIndexes as $index ) {
2784 $index = is_array( $index ) ?
$index : array( $index ); // columns
2785 $rowKey = array(); // unique key to this row
2786 foreach ( $index as $column ) {
2787 $rowKey[$column] = $row[$column];
2789 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2792 $where = array( $this->makeList( $clauses, LIST_OR
) );
2797 $useTrx = !$this->mTrxLevel
;
2799 $this->begin( $fname );
2802 # Update any existing conflicting row(s)
2803 if ( $where !== false ) {
2804 $ok = $this->update( $table, $set, $where, $fname );
2808 # Now insert any non-conflicting row(s)
2809 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2810 } catch ( Exception
$e ) {
2812 $this->rollback( $fname );
2817 $this->commit( $fname );
2824 * DELETE where the condition is a join.
2826 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2827 * we use sub-selects
2829 * For safety, an empty $conds will not delete everything. If you want to
2830 * delete all rows where the join condition matches, set $conds='*'.
2832 * DO NOT put the join condition in $conds.
2834 * @param string $delTable The table to delete from.
2835 * @param string $joinTable The other table.
2836 * @param string $delVar The variable to join on, in the first table.
2837 * @param string $joinVar The variable to join on, in the second table.
2838 * @param array $conds Condition array of field names mapped to variables,
2839 * ANDed together in the WHERE clause
2840 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2841 * @throws DBUnexpectedError
2843 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2847 throw new DBUnexpectedError( $this,
2848 'DatabaseBase::deleteJoin() called with empty $conds' );
2851 $delTable = $this->tableName( $delTable );
2852 $joinTable = $this->tableName( $joinTable );
2853 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2854 if ( $conds != '*' ) {
2855 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2859 $this->query( $sql, $fname );
2863 * Returns the size of a text field, or -1 for "unlimited"
2865 * @param string $table
2866 * @param string $field
2869 public function textFieldSize( $table, $field ) {
2870 $table = $this->tableName( $table );
2871 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2872 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2873 $row = $this->fetchObject( $res );
2877 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2887 * A string to insert into queries to show that they're low-priority, like
2888 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2889 * string and nothing bad should happen.
2891 * @return string Returns the text of the low priority option if it is
2892 * supported, or a blank string otherwise
2894 public function lowPriorityOption() {
2899 * DELETE query wrapper.
2901 * @param array $table Table name
2902 * @param string|array $conds of conditions. See $conds in DatabaseBase::select()
2903 * for the format. Use $conds == "*" to delete all rows
2904 * @param string $fname name of the calling function
2905 * @throws DBUnexpectedError
2906 * @return bool|ResultWrapper
2908 public function delete( $table, $conds, $fname = __METHOD__
) {
2910 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2913 $table = $this->tableName( $table );
2914 $sql = "DELETE FROM $table";
2916 if ( $conds != '*' ) {
2917 if ( is_array( $conds ) ) {
2918 $conds = $this->makeList( $conds, LIST_AND
);
2920 $sql .= ' WHERE ' . $conds;
2923 return $this->query( $sql, $fname );
2927 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2928 * into another table.
2930 * @param string $destTable The table name to insert into
2931 * @param string|array $srcTable May be either a table name, or an array of table names
2932 * to include in a join.
2934 * @param array $varMap Must be an associative array of the form
2935 * array( 'dest1' => 'source1', ...). Source items may be literals
2936 * rather than field names, but strings should be quoted with
2937 * DatabaseBase::addQuotes()
2939 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2940 * the details of the format of condition arrays. May be "*" to copy the
2943 * @param string $fname The function name of the caller, from __METHOD__
2945 * @param array $insertOptions Options for the INSERT part of the query, see
2946 * DatabaseBase::insert() for details.
2947 * @param array $selectOptions Options for the SELECT part of the query, see
2948 * DatabaseBase::select() for details.
2950 * @return ResultWrapper
2952 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2953 $fname = __METHOD__
,
2954 $insertOptions = array(), $selectOptions = array()
2956 $destTable = $this->tableName( $destTable );
2958 if ( !is_array( $insertOptions ) ) {
2959 $insertOptions = array( $insertOptions );
2962 $insertOptions = $this->makeInsertOptions( $insertOptions );
2964 if ( !is_array( $selectOptions ) ) {
2965 $selectOptions = array( $selectOptions );
2968 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2970 if ( is_array( $srcTable ) ) {
2971 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2973 $srcTable = $this->tableName( $srcTable );
2976 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2977 " SELECT $startOpts " . implode( ',', $varMap ) .
2978 " FROM $srcTable $useIndex ";
2980 if ( $conds != '*' ) {
2981 if ( is_array( $conds ) ) {
2982 $conds = $this->makeList( $conds, LIST_AND
);
2984 $sql .= " WHERE $conds";
2987 $sql .= " $tailOpts";
2989 return $this->query( $sql, $fname );
2993 * Construct a LIMIT query with optional offset. This is used for query
2994 * pages. The SQL should be adjusted so that only the first $limit rows
2995 * are returned. If $offset is provided as well, then the first $offset
2996 * rows should be discarded, and the next $limit rows should be returned.
2997 * If the result of the query is not ordered, then the rows to be returned
2998 * are theoretically arbitrary.
3000 * $sql is expected to be a SELECT, if that makes a difference.
3002 * The version provided by default works in MySQL and SQLite. It will very
3003 * likely need to be overridden for most other DBMSes.
3005 * @param string $sql SQL query we will append the limit too
3006 * @param int $limit The SQL limit
3007 * @param int|bool $offset The SQL offset (default false)
3008 * @throws DBUnexpectedError
3011 public function limitResult( $sql, $limit, $offset = false ) {
3012 if ( !is_numeric( $limit ) ) {
3013 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3016 return "$sql LIMIT "
3017 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3022 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3023 * within the UNION construct.
3026 public function unionSupportsOrderAndLimit() {
3027 return true; // True for almost every DB supported
3031 * Construct a UNION query
3032 * This is used for providing overload point for other DB abstractions
3033 * not compatible with the MySQL syntax.
3034 * @param array $sqls SQL statements to combine
3035 * @param bool $all Use UNION ALL
3036 * @return string SQL fragment
3038 public function unionQueries( $sqls, $all ) {
3039 $glue = $all ?
') UNION ALL (' : ') UNION (';
3041 return '(' . implode( $glue, $sqls ) . ')';
3045 * Returns an SQL expression for a simple conditional. This doesn't need
3046 * to be overridden unless CASE isn't supported in your DBMS.
3048 * @param string|array $cond SQL expression which will result in a boolean value
3049 * @param string $trueVal SQL expression to return if true
3050 * @param string $falseVal SQL expression to return if false
3051 * @return string SQL fragment
3053 public function conditional( $cond, $trueVal, $falseVal ) {
3054 if ( is_array( $cond ) ) {
3055 $cond = $this->makeList( $cond, LIST_AND
);
3058 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3062 * Returns a comand for str_replace function in SQL query.
3063 * Uses REPLACE() in MySQL
3065 * @param string $orig Column to modify
3066 * @param string $old Column to seek
3067 * @param string $new Column to replace with
3071 public function strreplace( $orig, $old, $new ) {
3072 return "REPLACE({$orig}, {$old}, {$new})";
3076 * Determines how long the server has been up
3081 public function getServerUptime() {
3086 * Determines if the last failure was due to a deadlock
3091 public function wasDeadlock() {
3096 * Determines if the last failure was due to a lock timeout
3101 public function wasLockTimeout() {
3106 * Determines if the last query error was something that should be dealt
3107 * with by pinging the connection and reissuing the query.
3112 public function wasErrorReissuable() {
3117 * Determines if the last failure was due to the database being read-only.
3122 public function wasReadOnlyError() {
3127 * Perform a deadlock-prone transaction.
3129 * This function invokes a callback function to perform a set of write
3130 * queries. If a deadlock occurs during the processing, the transaction
3131 * will be rolled back and the callback function will be called again.
3134 * $dbw->deadlockLoop( callback, ... );
3136 * Extra arguments are passed through to the specified callback function.
3138 * Returns whatever the callback function returned on its successful,
3139 * iteration, or false on error, for example if the retry limit was
3144 public function deadlockLoop() {
3145 $this->begin( __METHOD__
);
3146 $args = func_get_args();
3147 $function = array_shift( $args );
3148 $oldIgnore = $this->ignoreErrors( true );
3149 $tries = self
::DEADLOCK_TRIES
;
3151 if ( is_array( $function ) ) {
3152 $fname = $function[0];
3158 $retVal = call_user_func_array( $function, $args );
3159 $error = $this->lastError();
3160 $errno = $this->lastErrno();
3161 $sql = $this->lastQuery();
3164 if ( $this->wasDeadlock() ) {
3166 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3168 $this->reportQueryError( $error, $errno, $sql, $fname );
3171 } while ( $this->wasDeadlock() && --$tries > 0 );
3173 $this->ignoreErrors( $oldIgnore );
3175 if ( $tries <= 0 ) {
3176 $this->rollback( __METHOD__
);
3177 $this->reportQueryError( $error, $errno, $sql, $fname );
3181 $this->commit( __METHOD__
);
3188 * Wait for the slave to catch up to a given master position.
3190 * @param DBMasterPos $pos
3191 * @param int $timeout The maximum number of seconds to wait for
3193 * @return int Zzero if the slave was past that position already,
3194 * greater than zero if we waited for some period of time, less than
3195 * zero if we timed out.
3197 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3198 # Real waits are implemented in the subclass.
3203 * Get the replication position of this slave
3205 * @return DBMasterPos|bool False if this is not a slave.
3207 public function getSlavePos() {
3213 * Get the position of this master
3215 * @return DBMasterPos|bool False if this is not a master
3217 public function getMasterPos() {
3223 * Run an anonymous function as soon as there is no transaction pending.
3224 * If there is a transaction and it is rolled back, then the callback is cancelled.
3225 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3226 * Callbacks must commit any transactions that they begin.
3228 * This is useful for updates to different systems or when separate transactions are needed.
3229 * For example, one might want to enqueue jobs into a system outside the database, but only
3230 * after the database is updated so that the jobs will see the data when they actually run.
3231 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3233 * @param callable $callback
3236 final public function onTransactionIdle( $callback ) {
3237 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3238 if ( !$this->mTrxLevel
) {
3239 $this->runOnTransactionIdleCallbacks();
3244 * Run an anonymous function before the current transaction commits or now if there is none.
3245 * If there is a transaction and it is rolled back, then the callback is cancelled.
3246 * Callbacks must not start nor commit any transactions.
3248 * This is useful for updates that easily cause deadlocks if locks are held too long
3249 * but where atomicity is strongly desired for these updates and some related updates.
3251 * @param callable $callback
3254 final public function onTransactionPreCommitOrIdle( $callback ) {
3255 if ( $this->mTrxLevel
) {
3256 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3258 $this->onTransactionIdle( $callback ); // this will trigger immediately
3263 * Actually any "on transaction idle" callbacks.
3267 protected function runOnTransactionIdleCallbacks() {
3268 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3270 $e = null; // last exception
3271 do { // callbacks may add callbacks :)
3272 $callbacks = $this->mTrxIdleCallbacks
;
3273 $this->mTrxIdleCallbacks
= array(); // recursion guard
3274 foreach ( $callbacks as $callback ) {
3276 list( $phpCallback ) = $callback;
3277 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3278 call_user_func( $phpCallback );
3279 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3280 } catch ( Exception
$e ) {
3283 } while ( count( $this->mTrxIdleCallbacks
) );
3285 if ( $e instanceof Exception
) {
3286 throw $e; // re-throw any last exception
3291 * Actually any "on transaction pre-commit" callbacks.
3295 protected function runOnTransactionPreCommitCallbacks() {
3296 $e = null; // last exception
3297 do { // callbacks may add callbacks :)
3298 $callbacks = $this->mTrxPreCommitCallbacks
;
3299 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3300 foreach ( $callbacks as $callback ) {
3302 list( $phpCallback ) = $callback;
3303 call_user_func( $phpCallback );
3304 } catch ( Exception
$e ) {
3307 } while ( count( $this->mTrxPreCommitCallbacks
) );
3309 if ( $e instanceof Exception
) {
3310 throw $e; // re-throw any last exception
3315 * Begin an atomic section of statements
3317 * If a transaction has been started already, just keep track of the given
3318 * section name to make sure the transaction is not committed pre-maturely.
3319 * This function can be used in layers (with sub-sections), so use a stack
3320 * to keep track of the different atomic sections. If there is no transaction,
3321 * start one implicitly.
3323 * The goal of this function is to create an atomic section of SQL queries
3324 * without having to start a new transaction if it already exists.
3326 * Atomic sections are more strict than transactions. With transactions,
3327 * attempting to begin a new transaction when one is already running results
3328 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3329 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3330 * and any database transactions cannot be began or committed until all atomic
3331 * levels are closed. There is no such thing as implicitly opening or closing
3332 * an atomic section.
3335 * @param string $fname
3338 final public function startAtomic( $fname = __METHOD__
) {
3339 if ( !$this->mTrxLevel
) {
3340 $this->begin( $fname );
3341 $this->mTrxAutomatic
= true;
3342 $this->mTrxAutomaticAtomic
= true;
3345 $this->mTrxAtomicLevels
->push( $fname );
3349 * Ends an atomic section of SQL statements
3351 * Ends the next section of atomic SQL statements and commits the transaction
3355 * @see DatabaseBase::startAtomic
3356 * @param string $fname
3359 final public function endAtomic( $fname = __METHOD__
) {
3360 if ( !$this->mTrxLevel
) {
3361 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3363 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3364 $this->mTrxAtomicLevels
->pop() !== $fname
3366 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3369 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3370 $this->commit( $fname, 'flush' );
3375 * Begin a transaction. If a transaction is already in progress,
3376 * that transaction will be committed before the new transaction is started.
3378 * Note that when the DBO_TRX flag is set (which is usually the case for web
3379 * requests, but not for maintenance scripts), any previous database query
3380 * will have started a transaction automatically.
3382 * Nesting of transactions is not supported. Attempts to nest transactions
3383 * will cause a warning, unless the current transaction was started
3384 * automatically because of the DBO_TRX flag.
3386 * @param string $fname
3389 final public function begin( $fname = __METHOD__
) {
3390 global $wgDebugDBTransactions;
3392 if ( $this->mTrxLevel
) { // implicit commit
3393 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3394 // If the current transaction was an automatic atomic one, then we definitely have
3395 // a problem. Same if there is any unclosed atomic level.
3396 throw new DBUnexpectedError( $this,
3397 "Attempted to start explicit transaction when atomic levels are still open."
3399 } elseif ( !$this->mTrxAutomatic
) {
3400 // We want to warn about inadvertently nested begin/commit pairs, but not about
3401 // auto-committing implicit transactions that were started by query() via DBO_TRX
3402 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3403 " performing implicit commit!";
3405 wfLogDBError( $msg );
3407 // if the transaction was automatic and has done write operations,
3408 // log it if $wgDebugDBTransactions is enabled.
3409 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3410 wfDebug( "$fname: Automatic transaction with writes in progress" .
3411 " (from {$this->mTrxFname}), performing implicit commit!\n"
3416 $this->runOnTransactionPreCommitCallbacks();
3417 $this->doCommit( $fname );
3418 if ( $this->mTrxDoneWrites
) {
3419 $id = spl_object_hash( $this );
3420 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
, $id );
3422 $this->runOnTransactionIdleCallbacks();
3425 $this->doBegin( $fname );
3426 $this->mTrxFname
= $fname;
3427 $this->mTrxDoneWrites
= false;
3428 $this->mTrxAutomatic
= false;
3429 $this->mTrxAutomaticAtomic
= false;
3430 $this->mTrxAtomicLevels
= new SplStack
;
3431 $this->mTrxIdleCallbacks
= array();
3432 $this->mTrxPreCommitCallbacks
= array();
3436 * Issues the BEGIN command to the database server.
3438 * @see DatabaseBase::begin()
3439 * @param string $fname
3441 protected function doBegin( $fname ) {
3442 $this->query( 'BEGIN', $fname );
3443 $this->mTrxLevel
= 1;
3447 * Commits a transaction previously started using begin().
3448 * If no transaction is in progress, a warning is issued.
3450 * Nesting of transactions is not supported.
3452 * @param string $fname
3453 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3454 * explicitly committing implicit transactions, or calling commit when no
3455 * transaction is in progress. This will silently break any ongoing
3456 * explicit transaction. Only set the flush flag if you are sure that it
3457 * is safe to ignore these warnings in your context.
3458 * @throws DBUnexpectedError
3460 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3461 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3462 // There are still atomic sections open. This cannot be ignored
3463 throw new DBUnexpectedError(
3465 "Attempted to commit transaction while atomic sections are still open"
3469 if ( $flush !== 'flush' ) {
3470 if ( !$this->mTrxLevel
) {
3471 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3472 } elseif ( $this->mTrxAutomatic
) {
3473 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3476 if ( !$this->mTrxLevel
) {
3477 return; // nothing to do
3478 } elseif ( !$this->mTrxAutomatic
) {
3479 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3483 $this->runOnTransactionPreCommitCallbacks();
3484 $this->doCommit( $fname );
3485 if ( $this->mTrxDoneWrites
) {
3486 $id = spl_object_hash( $this );
3487 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
, $id );
3489 $this->runOnTransactionIdleCallbacks();
3493 * Issues the COMMIT command to the database server.
3495 * @see DatabaseBase::commit()
3496 * @param string $fname
3498 protected function doCommit( $fname ) {
3499 if ( $this->mTrxLevel
) {
3500 $this->query( 'COMMIT', $fname );
3501 $this->mTrxLevel
= 0;
3506 * Rollback a transaction previously started using begin().
3507 * If no transaction is in progress, a warning is issued.
3509 * No-op on non-transactional databases.
3511 * @param string $fname
3512 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3513 * calling rollback when no transaction is in progress. This will silently
3514 * break any ongoing explicit transaction. Only set the flush flag if you
3515 * are sure that it is safe to ignore these warnings in your context.
3516 * @since 1.23 Added $flush parameter
3518 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3519 if ( $flush !== 'flush' ) {
3520 if ( !$this->mTrxLevel
) {
3521 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3522 } elseif ( $this->mTrxAutomatic
) {
3523 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3526 if ( !$this->mTrxLevel
) {
3527 return; // nothing to do
3528 } elseif ( !$this->mTrxAutomatic
) {
3529 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3533 $this->doRollback( $fname );
3534 $this->mTrxIdleCallbacks
= array(); // cancel
3535 $this->mTrxPreCommitCallbacks
= array(); // cancel
3536 $this->mTrxAtomicLevels
= new SplStack
;
3537 if ( $this->mTrxDoneWrites
) {
3538 $id = spl_object_hash( $this );
3539 Profiler
::instance()->transactionWritingOut( $this->mServer
, $this->mDBname
, $id );
3544 * Issues the ROLLBACK command to the database server.
3546 * @see DatabaseBase::rollback()
3547 * @param string $fname
3549 protected function doRollback( $fname ) {
3550 if ( $this->mTrxLevel
) {
3551 $this->query( 'ROLLBACK', $fname, true );
3552 $this->mTrxLevel
= 0;
3557 * Creates a new table with structure copied from existing table
3558 * Note that unlike most database abstraction functions, this function does not
3559 * automatically append database prefix, because it works at a lower
3560 * abstraction level.
3561 * The table names passed to this function shall not be quoted (this
3562 * function calls addIdentifierQuotes when needed).
3564 * @param string $oldName Name of table whose structure should be copied
3565 * @param string $newName Name of table to be created
3566 * @param bool $temporary Whether the new table should be temporary
3567 * @param string $fname Calling function name
3568 * @throws MWException
3569 * @return bool True if operation was successful
3571 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3574 throw new MWException(
3575 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3579 * List all tables on the database
3581 * @param string $prefix Only show tables with this prefix, e.g. mw_
3582 * @param string $fname Calling function name
3583 * @throws MWException
3585 function listTables( $prefix = null, $fname = __METHOD__
) {
3586 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3590 * Reset the views process cache set by listViews()
3593 final public function clearViewsCache() {
3594 $this->allViews
= null;
3598 * Lists all the VIEWs in the database
3600 * For caching purposes the list of all views should be stored in
3601 * $this->allViews. The process cache can be cleared with clearViewsCache()
3603 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3604 * @param string $fname Name of calling function
3605 * @throws MWException
3608 public function listViews( $prefix = null, $fname = __METHOD__
) {
3609 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3613 * Differentiates between a TABLE and a VIEW
3615 * @param string $name Name of the database-structure to test.
3616 * @throws MWException
3619 public function isView( $name ) {
3620 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3624 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3625 * to the format used for inserting into timestamp fields in this DBMS.
3627 * The result is unquoted, and needs to be passed through addQuotes()
3628 * before it can be included in raw SQL.
3630 * @param string|int $ts
3634 public function timestamp( $ts = 0 ) {
3635 return wfTimestamp( TS_MW
, $ts );
3639 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3640 * to the format used for inserting into timestamp fields in this DBMS. If
3641 * NULL is input, it is passed through, allowing NULL values to be inserted
3642 * into timestamp fields.
3644 * The result is unquoted, and needs to be passed through addQuotes()
3645 * before it can be included in raw SQL.
3647 * @param string|int $ts
3651 public function timestampOrNull( $ts = null ) {
3652 if ( is_null( $ts ) ) {
3655 return $this->timestamp( $ts );
3660 * Take the result from a query, and wrap it in a ResultWrapper if
3661 * necessary. Boolean values are passed through as is, to indicate success
3662 * of write queries or failure.
3664 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3665 * resource, and it was necessary to call this function to convert it to
3666 * a wrapper. Nowadays, raw database objects are never exposed to external
3667 * callers, so this is unnecessary in external code. For compatibility with
3668 * old code, ResultWrapper objects are passed through unaltered.
3670 * @param bool|ResultWrapper|resource $result
3671 * @return bool|ResultWrapper
3673 public function resultObject( $result ) {
3674 if ( empty( $result ) ) {
3676 } elseif ( $result instanceof ResultWrapper
) {
3678 } elseif ( $result === true ) {
3679 // Successful write query
3682 return new ResultWrapper( $this, $result );
3687 * Ping the server and try to reconnect if it there is no connection
3689 * @return bool Success or failure
3691 public function ping() {
3692 # Stub. Not essential to override.
3697 * Get slave lag. Currently supported only by MySQL.
3699 * Note that this function will generate a fatal error on many
3700 * installations. Most callers should use LoadBalancer::safeGetLag()
3703 * @return int Database replication lag in seconds
3705 public function getLag() {
3710 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3714 function maxListLen() {
3719 * Some DBMSs have a special format for inserting into blob fields, they
3720 * don't allow simple quoted strings to be inserted. To insert into such
3721 * a field, pass the data through this function before passing it to
3722 * DatabaseBase::insert().
3727 public function encodeBlob( $b ) {
3732 * Some DBMSs return a special placeholder object representing blob fields
3733 * in result objects. Pass the object through this function to return the
3739 public function decodeBlob( $b ) {
3744 * Override database's default behavior. $options include:
3745 * 'connTimeout' : Set the connection timeout value in seconds.
3746 * May be useful for very long batch queries such as
3747 * full-wiki dumps, where a single query reads out over
3750 * @param array $options
3753 public function setSessionOptions( array $options ) {
3757 * Read and execute SQL commands from a file.
3759 * Returns true on success, error string or exception on failure (depending
3760 * on object's error ignore settings).
3762 * @param string $filename File name to open
3763 * @param bool|callable $lineCallback Optional function called before reading each line
3764 * @param bool|callable $resultCallback Optional function called for each MySQL result
3765 * @param bool|string $fname Calling function name or false if name should be
3766 * generated dynamically using $filename
3767 * @param bool|callable $inputCallback Optional function called for each
3768 * complete line sent
3769 * @throws Exception|MWException
3770 * @return bool|string
3772 public function sourceFile(
3773 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3775 wfSuppressWarnings();
3776 $fp = fopen( $filename, 'r' );
3777 wfRestoreWarnings();
3779 if ( false === $fp ) {
3780 throw new MWException( "Could not open \"{$filename}\".\n" );
3784 $fname = __METHOD__
. "( $filename )";
3788 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3789 } catch ( MWException
$e ) {
3800 * Get the full path of a patch file. Originally based on archive()
3801 * from updaters.inc. Keep in mind this always returns a patch, as
3802 * it fails back to MySQL if no DB-specific patch can be found
3804 * @param string $patch The name of the patch, like patch-something.sql
3805 * @return string Full path to patch file
3807 public function patchPath( $patch ) {
3810 $dbType = $this->getType();
3811 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3812 return "$IP/maintenance/$dbType/archives/$patch";
3814 return "$IP/maintenance/archives/$patch";
3819 * Set variables to be used in sourceFile/sourceStream, in preference to the
3820 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3821 * all. If it's set to false, $GLOBALS will be used.
3823 * @param bool|array $vars Mapping variable name to value.
3825 public function setSchemaVars( $vars ) {
3826 $this->mSchemaVars
= $vars;
3830 * Read and execute commands from an open file handle.
3832 * Returns true on success, error string or exception on failure (depending
3833 * on object's error ignore settings).
3835 * @param resource $fp File handle
3836 * @param bool|callable $lineCallback Optional function called before reading each query
3837 * @param bool|callable $resultCallback Optional function called for each MySQL result
3838 * @param string $fname Calling function name
3839 * @param bool|callable $inputCallback Optional function called for each complete query sent
3840 * @return bool|string
3842 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3843 $fname = __METHOD__
, $inputCallback = false
3847 while ( !feof( $fp ) ) {
3848 if ( $lineCallback ) {
3849 call_user_func( $lineCallback );
3852 $line = trim( fgets( $fp ) );
3854 if ( $line == '' ) {
3858 if ( '-' == $line[0] && '-' == $line[1] ) {
3866 $done = $this->streamStatementEnd( $cmd, $line );
3870 if ( $done ||
feof( $fp ) ) {
3871 $cmd = $this->replaceVars( $cmd );
3873 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3874 $res = $this->query( $cmd, $fname );
3876 if ( $resultCallback ) {
3877 call_user_func( $resultCallback, $res, $this );
3880 if ( false === $res ) {
3881 $err = $this->lastError();
3883 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3894 * Called by sourceStream() to check if we've reached a statement end
3896 * @param string $sql SQL assembled so far
3897 * @param string $newLine New line about to be added to $sql
3898 * @return bool Whether $newLine contains end of the statement
3900 public function streamStatementEnd( &$sql, &$newLine ) {
3901 if ( $this->delimiter
) {
3903 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3904 if ( $newLine != $prev ) {
3913 * Database independent variable replacement. Replaces a set of variables
3914 * in an SQL statement with their contents as given by $this->getSchemaVars().
3916 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3918 * - '{$var}' should be used for text and is passed through the database's
3920 * - `{$var}` should be used for identifiers (eg: table and database names),
3921 * it is passed through the database's addIdentifierQuotes method which
3922 * can be overridden if the database uses something other than backticks.
3923 * - / *$var* / is just encoded, besides traditional table prefix and
3924 * table options its use should be avoided.
3926 * @param string $ins SQL statement to replace variables in
3927 * @return string The new SQL statement with variables replaced
3929 protected function replaceSchemaVars( $ins ) {
3930 $vars = $this->getSchemaVars();
3931 foreach ( $vars as $var => $value ) {
3933 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3935 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3937 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3944 * Replace variables in sourced SQL
3946 * @param string $ins
3949 protected function replaceVars( $ins ) {
3950 $ins = $this->replaceSchemaVars( $ins );
3953 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3954 array( $this, 'tableNameCallback' ), $ins );
3957 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3958 array( $this, 'indexNameCallback' ), $ins );
3964 * Get schema variables. If none have been set via setSchemaVars(), then
3965 * use some defaults from the current object.
3969 protected function getSchemaVars() {
3970 if ( $this->mSchemaVars
) {
3971 return $this->mSchemaVars
;
3973 return $this->getDefaultSchemaVars();
3978 * Get schema variables to use if none have been set via setSchemaVars().
3980 * Override this in derived classes to provide variables for tables.sql
3981 * and SQL patch files.
3985 protected function getDefaultSchemaVars() {
3990 * Table name callback
3992 * @param array $matches
3995 protected function tableNameCallback( $matches ) {
3996 return $this->tableName( $matches[1] );
4000 * Index name callback
4002 * @param array $matches
4005 protected function indexNameCallback( $matches ) {
4006 return $this->indexName( $matches[1] );
4010 * Check to see if a named lock is available. This is non-blocking.
4012 * @param string $lockName Name of lock to poll
4013 * @param string $method Name of method calling us
4017 public function lockIsFree( $lockName, $method ) {
4022 * Acquire a named lock
4024 * Abstracted from Filestore::lock() so child classes can implement for
4027 * @param string $lockName Name of lock to aquire
4028 * @param string $method Name of method calling us
4029 * @param int $timeout
4032 public function lock( $lockName, $method, $timeout = 5 ) {
4039 * @param string $lockName Name of lock to release
4040 * @param string $method Name of method calling us
4042 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4043 * by this thread (in which case the lock is not released), and NULL if the named
4044 * lock did not exist
4046 public function unlock( $lockName, $method ) {
4051 * Lock specific tables
4053 * @param array $read Array of tables to lock for read access
4054 * @param array $write Array of tables to lock for write access
4055 * @param string $method Name of caller
4056 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4059 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4064 * Unlock specific tables
4066 * @param string $method The caller
4069 public function unlockTables( $method ) {
4075 * @param string $tableName
4076 * @param string $fName
4077 * @return bool|ResultWrapper
4080 public function dropTable( $tableName, $fName = __METHOD__
) {
4081 if ( !$this->tableExists( $tableName, $fName ) ) {
4084 $sql = "DROP TABLE " . $this->tableName( $tableName );
4085 if ( $this->cascadingDeletes() ) {
4089 return $this->query( $sql, $fName );
4093 * Get search engine class. All subclasses of this need to implement this
4094 * if they wish to use searching.
4098 public function getSearchEngine() {
4099 return 'SearchEngineDummy';
4103 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4104 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4105 * because "i" sorts after all numbers.
4109 public function getInfinity() {
4114 * Encode an expiry time into the DBMS dependent format
4116 * @param string $expiry timestamp for expiry, or the 'infinity' string
4119 public function encodeExpiry( $expiry ) {
4120 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4121 ?
$this->getInfinity()
4122 : $this->timestamp( $expiry );
4126 * Decode an expiry time into a DBMS independent format
4128 * @param string $expiry DB timestamp field value for expiry
4129 * @param int $format TS_* constant, defaults to TS_MW
4132 public function decodeExpiry( $expiry, $format = TS_MW
) {
4133 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4135 : wfTimestamp( $format, $expiry );
4139 * Allow or deny "big selects" for this session only. This is done by setting
4140 * the sql_big_selects session variable.
4142 * This is a MySQL-specific feature.
4144 * @param bool|string $value True for allow, false for deny, or "default" to
4145 * restore the initial value
4147 public function setBigSelects( $value = true ) {
4154 public function __toString() {
4155 return (string)$this->mConn
;
4159 * Run a few simple sanity checks
4161 public function __destruct() {
4162 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4163 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4165 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4167 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4168 $callers[] = $callbackInfo[1];
4170 $callers = implode( ', ', $callers );
4171 trigger_error( "DB transaction callbacks still pending (from $callers)." );