Go to the documentation of this file.
229 # ------------------------------------------------------------------------------
231 # ------------------------------------------------------------------------------
322 # ------------------------------------------------------------------------------
324 # ------------------------------------------------------------------------------
325 # These optionally set a variable and return the previous state
380 if ( is_null( $buffer ) ) {
430 return wfSetVar( $this->mTablePrefix, $prefix );
438 public function dbSchema( $schema =
null ) {
439 return wfSetVar( $this->mSchema, $schema );
448 $this->fileHandle = $fh;
461 if ( is_null(
$name ) ) {
464 if ( array_key_exists(
$name, $this->mLBInfo ) ) {
465 return $this->mLBInfo[
$name];
481 if ( is_null(
$value ) ) {
482 $this->mLBInfo =
$name;
606 return $this->mTrxLevel && (
615 public function isOpen() {
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" );
650 global $wgDebugDBTransactions;
651 $this->mFlags &= ~$flag;
652 if ( ( $flag &
DBO_TRX ) && $wgDebugDBTransactions ) {
653 wfDebug(
"Implicit transactions are now disabled.\n" );
669 public function getFlag( $flag ) {
670 return !!( $this->mFlags & $flag );
687 if ( $this->mTablePrefix ) {
688 return "{$this->mDBname}-{$this->mTablePrefix}";
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 # ------------------------------------------------------------------------------
727 $this->mTrxAtomicLevels =
new SplStack;
735 $tablePrefix =
$params[
'tablePrefix'];
739 wfDeprecated( __METHOD__ .
" method called without parameter array.",
"1.23" );
740 $args = func_get_args();
741 $server = isset(
$args[0] ) ?
$args[0] :
false;
744 $dbName = isset(
$args[3] ) ?
$args[3] :
false;
746 $tablePrefix = isset(
$args[5] ) ?
$args[5] :
'get from global';
747 $schema =
'get from global';
748 $foreign = isset(
$args[6] ) ?
$args[6] :
false;
755 if ( $wgDebugDBTransactions ) {
756 wfDebug(
"Implicit transaction open disabled.\n" );
760 if ( $wgDebugDBTransactions ) {
761 wfDebug(
"Implicit transaction open enabled.\n" );
767 if ( $tablePrefix ==
'get from global' ) {
768 $this->mTablePrefix = $wgDBprefix;
770 $this->mTablePrefix = $tablePrefix;
774 if ( $schema ==
'get from global' ) {
775 $this->mSchema = $wgDBmwschema;
777 $this->mSchema = $schema;
780 $this->mForeign = $foreign;
793 throw new MWException(
'Database serialization may cause problems, since ' .
794 'the connection is not restored on wakeup.' );
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'];
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 ) {
852 " no viable database extension found for type '$dbType'" );
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
887 $this->mPHPError =
false;
888 $this->htmlErrors = ini_set(
'html_errors',
'0' );
889 set_error_handler(
array( $this,
'connectionErrorHandler' ) );
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 );
915 $this->mPHPError = $errstr;
925 public function close() {
926 if ( count( $this->mTrxIdleCallbacks ) ) {
927 throw new MWException(
"Transaction idle callbacks still pending." );
929 $this->mOpened =
false;
930 if ( $this->mConn ) {
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' );
941 $this->mConn =
false;
977 abstract protected function doQuery( $sql );
987 return !preg_match(
'/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1012 public function query( $sql,
$fname = __METHOD__, $tempIgnore =
false ) {
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
1024 $userName =
$wgUser->getName();
1025 if ( mb_strlen( $userName ) > 15 ) {
1026 $userName = mb_substr( $userName, 0, 15 ) .
'...';
1028 $userName = str_replace(
'/',
'', $userName );
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 );
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;
1062 $isMaster = !is_null( $this->
getLBInfo(
'master' ) );
1065 # generalizeSQL will probably cut down the query to reasonable
1066 # logging size most of the time. The substr is really just a sanity check.
1069 $totalProf =
'DatabaseBase::query-master';
1072 $totalProf =
'DatabaseBase::query';
1078 if ( $this->
debug() ) {
1082 $sqlx = substr( $commentedSql, 0, 500 );
1083 $sqlx = strtr( $sqlx,
"\t\n",
' ' );
1085 $master = $isMaster ?
'master' :
'slave';
1086 wfDebug(
"Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1091 # Do the query and handle errors
1096 # Try reconnecting if the connection was lost
1098 # Transaction is gone, like it or not
1100 $this->mTrxLevel = 0;
1101 wfDebug(
"Connection lost, reconnecting...\n" );
1103 if ( $this->
ping() ) {
1105 $sqlx = substr( $commentedSql, 0, 500 );
1106 $sqlx = strtr( $sqlx,
"\t\n",
' ' );
1109 if ( $elapsed < 300 ) {
1110 # Not a database error to lose a transaction after a minute or two
1111 wfLogDBError(
"Connection lost and reconnected after {$elapsed}s, query: $sqlx" );
1114 # Should be safe to silently retry
1122 if (
false ===
$ret ) {
1146 # Ignore errors during error handling to avoid infinite recursion
1150 if (
$ignore || $tempIgnore ) {
1151 wfDebug(
"SQL ERROR (ignored): $error\n" );
1154 $sql1line = mb_substr( str_replace(
"\n",
"\\n", $sql ), 0, 5 * 1024 );
1155 wfLogDBError(
"$fname\t{$this->mServer}\t$errno\t$error\t$sql1line" );
1175 protected function prepare( $sql, $func =
'DatabaseBase::prepare' ) {
1180 return array(
'query' => $sql,
'func' => $func );
1199 if ( !is_array(
$args ) ) {
1201 $args = func_get_args();
1202 array_shift(
$args );
1207 return $this->
query( $sql, $prepared[
'func'] );
1219 $this->preparedArgs =&
$args;
1221 return preg_replace_callback(
'/(\\\\[?!&]|[?!&])/',
1222 array( &$this,
'fillPreparedArg' ), $preparedQuery );
1244 list( , $arg ) = each( $this->preparedArgs );
1252 # return $this->addQuotes( file_get_contents( $arg ) );
1255 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1260 'Received invalid match. This should never happen!'
1309 if ( $row !==
false ) {
1310 return reset( $row );
1326 $preLimitTail = $postLimitTail =
'';
1329 $noKeyOptions =
array();
1332 if ( is_numeric( $key ) ) {
1333 $noKeyOptions[$option] =
true;
1347 if ( isset( $noKeyOptions[
'FOR UPDATE'] ) ) {
1348 $postLimitTail .=
' FOR UPDATE';
1351 if ( isset( $noKeyOptions[
'LOCK IN SHARE MODE'] ) ) {
1352 $postLimitTail .=
' LOCK IN SHARE MODE';
1355 if ( isset( $noKeyOptions[
'DISTINCT'] ) || isset( $noKeyOptions[
'DISTINCTROW'] ) ) {
1356 $startOpts .=
'DISTINCT';
1359 # Various MySQL extensions
1360 if ( isset( $noKeyOptions[
'STRAIGHT_JOIN'] ) ) {
1361 $startOpts .=
' /*! STRAIGHT_JOIN */';
1364 if ( isset( $noKeyOptions[
'HIGH_PRIORITY'] ) ) {
1365 $startOpts .=
' HIGH_PRIORITY';
1368 if ( isset( $noKeyOptions[
'SQL_BIG_RESULT'] ) ) {
1369 $startOpts .=
' SQL_BIG_RESULT';
1372 if ( isset( $noKeyOptions[
'SQL_BUFFER_RESULT'] ) ) {
1373 $startOpts .=
' SQL_BUFFER_RESULT';
1376 if ( isset( $noKeyOptions[
'SQL_SMALL_RESULT'] ) ) {
1377 $startOpts .=
' SQL_SMALL_RESULT';
1380 if ( isset( $noKeyOptions[
'SQL_CALC_FOUND_ROWS'] ) ) {
1381 $startOpts .=
' SQL_CALC_FOUND_ROWS';
1384 if ( isset( $noKeyOptions[
'SQL_CACHE'] ) ) {
1385 $startOpts .=
' SQL_CACHE';
1388 if ( isset( $noKeyOptions[
'SQL_NO_CACHE'] ) ) {
1389 $startOpts .=
' SQL_NO_CACHE';
1392 if ( isset(
$options[
'USE INDEX'] ) && is_string(
$options[
'USE INDEX'] ) ) {
1398 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1411 if ( isset(
$options[
'GROUP BY'] ) ) {
1412 $gb = is_array(
$options[
'GROUP BY'] )
1413 ? implode(
',',
$options[
'GROUP BY'] )
1415 $sql .=
' GROUP BY ' . $gb;
1417 if ( isset(
$options[
'HAVING'] ) ) {
1418 $having = is_array(
$options[
'HAVING'] )
1421 $sql .=
' HAVING ' . $having;
1436 if ( isset(
$options[
'ORDER BY'] ) ) {
1437 $ob = is_array(
$options[
'ORDER BY'] )
1438 ? implode(
',',
$options[
'ORDER BY'] )
1441 return ' ORDER BY ' . $ob;
1612 if ( is_array(
$vars ) ) {
1617 $useIndexes = ( isset(
$options[
'USE INDEX'] ) && is_array(
$options[
'USE INDEX'] ) )
1621 if ( is_array( $table ) ) {
1624 } elseif ( $table !=
'' ) {
1625 if ( $table[0] ==
' ' ) {
1626 $from =
' FROM ' . $table;
1635 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1638 if ( !empty( $conds ) ) {
1639 if ( is_array( $conds ) ) {
1642 $sql =
"SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1644 $sql =
"SELECT $startOpts $vars $from $useIndex $preLimitTail";
1647 if ( isset(
$options[
'LIMIT'] ) ) {
1651 $sql =
"$sql $postLimitTail";
1653 if ( isset(
$options[
'EXPLAIN'] ) ) {
1654 $sql =
'EXPLAIN ' . $sql;
1681 if (
$res ===
false ) {
1722 $rows = ( isset( $row[
'rowcount'] ) ) ? $row[
'rowcount'] : 0;
1737 # This does the same as the regexp below would do, but in such a way
1738 # as to avoid crashing php on some large strings.
1739 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1741 $sql = str_replace(
"\\\\",
'', $sql );
1742 $sql = str_replace(
"\\'",
'', $sql );
1743 $sql = str_replace(
"\\\"",
'', $sql );
1744 $sql = preg_replace(
"/'.*'/s",
"'X'", $sql );
1745 $sql = preg_replace(
'/".*"/s',
"'X'", $sql );
1747 # All newlines, tabs, etc replaced by single space
1748 $sql = preg_replace(
'/\s+/',
' ', $sql );
1751 $sql = preg_replace(
'/-?\d+(,-?\d+)+/s',
'N,...,N', $sql );
1752 $sql = preg_replace(
'/-?\d+/s',
'N', $sql );
1766 $info = $this->
fieldInfo( $table, $field );
1787 if ( is_null( $info ) ) {
1790 return $info !==
false;
1804 $res = $this->
query(
"SELECT 1 FROM $table LIMIT 1", $fname );
1819 $indexInfo = $this->
indexInfo( $table, $index );
1821 if ( !$indexInfo ) {
1825 return !$indexInfo[0]->Non_unique;
1872 # No rows to insert, easy just return now
1873 if ( !count( $a ) ) {
1884 if ( isset(
$options[
'fileHandle'] ) ) {
1889 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1891 $keys = array_keys( $a[0] );
1894 $keys = array_keys( $a );
1898 " INTO $table (" . implode(
',',
$keys ) .
') VALUES ';
1902 foreach ( $a
as $row ) {
1908 $sql .=
'(' . $this->
makeList( $row ) .
')';
1911 $sql .=
'(' . $this->
makeList( $a ) .
')';
1914 if ( $fh !==
null &&
false === fwrite( $fh, $sql ) ) {
1916 } elseif ( $fh !==
null ) {
1936 if ( in_array(
'LOW_PRIORITY',
$options ) ) {
1940 if ( in_array(
'IGNORE',
$options ) ) {
1956 return implode(
' ', $opts );
1982 if ( $conds !==
array() && $conds !==
'*' ) {
2004 if ( !is_array( $a ) ) {
2005 throw new DBUnexpectedError( $this,
'DatabaseBase::makeList called with incorrect parameters' );
2011 foreach ( $a
as $field =>
$value ) {
2015 } elseif ( $mode ==
LIST_OR ) {
2024 if ( ( $mode ==
LIST_AND || $mode ==
LIST_OR ) && is_numeric( $field ) ) {
2025 $list .=
"($value)";
2026 } elseif ( ( $mode ==
LIST_SET ) && is_numeric( $field ) ) {
2029 if ( count(
$value ) == 0 ) {
2030 throw new MWException( __METHOD__ .
": empty input for field $field" );
2031 } elseif ( count(
$value ) == 1 ) {
2040 } elseif (
$value ===
null ) {
2042 $list .=
"$field IS ";
2044 $list .=
"$field = ";
2049 $list .=
"$field = ";
2071 foreach ( $data
as $base => $sub ) {
2072 if ( count( $sub ) ) {
2074 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2095 public function aggregateValue( $valuedata, $valuename =
'value' ) {
2103 public function bitNot( $field ) {
2112 public function bitAnd( $fieldLeft, $fieldRight ) {
2113 return "($fieldLeft & $fieldRight)";
2121 public function bitOr( $fieldLeft, $fieldRight ) {
2122 return "($fieldLeft | $fieldRight)";
2132 return 'CONCAT(' . implode(
',', $stringList ) .
')';
2152 $delim, $table, $field, $conds =
'', $join_conds =
array()
2154 $fld =
"GROUP_CONCAT($field SEPARATOR " . $this->
addQuotes( $delim ) .
')';
2156 return '(' . $this->
selectSQLText( $table, $fld, $conds,
null,
array(), $join_conds ) .
')';
2169 # Stub. Shouldn't cause serious problems if it's not overridden, but
2170 # if your database engine supports a concept similar to MySQL's
2171 # databases you may as well.
2172 $this->mDBname = $db;
2209 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2210 # Skip the entire process when we have a string quoted on both ends.
2211 # Note that we check the end so that we will still quote any use of
2212 # use of `database`.table. But won't break things if someone wants
2213 # to query a database table with a dot in the name.
2218 # Lets test for any bits of text that should never show up in a table
2219 # name. Basically anything like JOIN or ON which are actually part of
2220 # SQL queries, but may end up inside of the table value to combine
2221 # sql. Such as how the API is doing.
2222 # Note that we use a whitespace test rather than a \b test to avoid
2223 # any remote case where a word like on may be inside of a table name
2224 # surrounded by symbols which may be considered word breaks.
2225 if ( preg_match(
'/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i',
$name ) !== 0 ) {
2229 # Split database and table into proper variables.
2230 # We reverse the explode so that database.table and table both output
2231 # the correct table.
2232 $dbDetails = explode(
'.',
$name, 2 );
2233 if ( count( $dbDetails ) == 3 ) {
2234 list( $database, $schema, $table ) = $dbDetails;
2235 # We don't want any prefix added in this case
2237 } elseif ( count( $dbDetails ) == 2 ) {
2238 list( $database, $table ) = $dbDetails;
2239 # We don't want any prefix added in this case
2240 # In dbs that support it, $database may actually be the schema
2241 # but that doesn't affect any of the functionality here
2245 list( $table ) = $dbDetails;
2246 if ( $wgSharedDB !==
null # We have a shared
database
2247 && $this->mForeign ==
false # We
're not working on a foreign database
2248 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`
table`
'
2249 && in_array( $table, $wgSharedTables ) # A shared table is selected
2251 $database = $wgSharedDB;
2252 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2253 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2256 $schema = $this->mSchema; # Default schema
2257 $prefix = $this->mTablePrefix; # Default prefix
2261 # Quote $table and apply the prefix if not quoted.
2262 # $tableName might be empty if this is called from Database::replaceVars()
2263 $tableName = "{$prefix}{$table}";
2264 if ( $format == 'quoted
' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2265 $tableName = $this->addIdentifierQuotes( $tableName );
2268 # Quote $schema and merge it with the table name if needed
2269 if ( $schema !== null ) {
2270 if ( $format == 'quoted
' && !$this->isQuotedIdentifier( $schema ) ) {
2271 $schema = $this->addIdentifierQuotes( $schema );
2273 $tableName = $schema . '.
' . $tableName;
2276 # Quote $database and merge it with the table name if needed
2277 if ( $database !== null ) {
2278 if ( $format == 'quoted
' && !$this->isQuotedIdentifier( $database ) ) {
2279 $database = $this->addIdentifierQuotes( $database );
2281 $tableName = $database . '.
' . $tableName;
2298 public function tableNames() {
2299 $inArray = func_get_args();
2302 foreach ( $inArray as $name ) {
2303 $retVal[$name] = $this->tableName( $name );
2320 public function tableNamesN() {
2321 $inArray = func_get_args();
2324 foreach ( $inArray as $name ) {
2325 $retVal[] = $this->tableName( $name );
2339 public function tableNameWithAlias( $name, $alias = false ) {
2340 if ( !$alias || $alias == $name ) {
2341 return $this->tableName( $name );
2343 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2353 public function tableNamesWithAlias( $tables ) {
2355 foreach ( $tables as $alias => $table ) {
2356 if ( is_numeric( $alias ) ) {
2359 $retval[] = $this->tableNameWithAlias( $table, $alias );
2373 public function fieldNameWithAlias( $name, $alias = false ) {
2374 if ( !$alias || (string)$alias === (string)$name ) {
2377 return $name . ' AS
' . $alias; //PostgreSQL needs AS
2387 public function fieldNamesWithAlias( $fields ) {
2389 foreach ( $fields as $alias => $field ) {
2390 if ( is_numeric( $alias ) ) {
2393 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2408 protected function tableNamesWithUseIndexOrJOIN(
2409 $tables, $use_index = array(), $join_conds = array()
2413 $use_index = (array)$use_index;
2414 $join_conds = (array)$join_conds;
2416 foreach ( $tables as $alias => $table ) {
2417 if ( !is_string( $alias ) ) {
2418 // No alias? Set it equal to the table name
2421 // Is there a JOIN clause for this table?
2422 if ( isset( $join_conds[$alias] ) ) {
2423 list( $joinType, $conds ) = $join_conds[$alias];
2424 $tableClause = $joinType;
2425 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2426 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2427 $use = $this->useIndexClause( implode( ',
', (array)$use_index[$alias] ) );
2429 $tableClause .= ' ' . $use;
2432 $on = $this->makeList( (array)$conds, LIST_AND );
2434 $tableClause .= ' ON (
' . $on . ')
';
2437 $retJOIN[] = $tableClause;
2438 } elseif ( isset( $use_index[$alias] ) ) {
2439 // Is there an INDEX clause for this table?
2440 $tableClause = $this->tableNameWithAlias( $table, $alias );
2441 $tableClause .= ' ' . $this->useIndexClause(
2442 implode( ',
', (array)$use_index[$alias] )
2445 $ret[] = $tableClause;
2447 $tableClause = $this->tableNameWithAlias( $table, $alias );
2449 $ret[] = $tableClause;
2453 // We can't separate
explicit JOIN clauses with
',', use
' ' for those
2454 $implicitJoins = !empty(
$ret ) ? implode(
',',
$ret ) :
"";
2455 $explicitJoins = !empty( $retJOIN ) ? implode(
' ', $retJOIN ) :
"";
2458 return implode(
' ',
array( $implicitJoins, $explicitJoins ) );
2467 protected function indexName( $index ) {
2470 'ar_usertext_timestamp' =>
'usertext_timestamp',
2471 'un_user_id' =>
'user_id',
2472 'un_user_ip' =>
'user_ip',
2475 if ( isset( $renamed[$index] ) ) {
2476 return $renamed[$index];
2489 if (
$s ===
null ) {
2492 # This will also quote numeric values. This should be harmless,
2493 # and protects against weird problems that occur when they really
2494 # _are_ strings such as article titles and string->number->string
2495 # conversion is not 1:1.
2510 return '"' . str_replace(
'"',
'""',
$s ) .
'"';
2521 return $name[0] ==
'"' && substr(
$name, -1, 1 ) ==
'"';
2529 $s = str_replace(
'\\',
'\\\\',
$s );
2569 return " LIKE '" .
$s .
"' ";
2641 public function replace( $table, $uniqueIndexes, $rows,
$fname = __METHOD__ ) {
2642 $quotedTable = $this->
tableName( $table );
2644 if ( count( $rows ) == 0 ) {
2649 if ( !is_array( reset( $rows ) ) ) {
2650 $rows =
array( $rows );
2653 foreach ( $rows
as $row ) {
2654 # Delete rows which collide
2655 if ( $uniqueIndexes ) {
2656 $sql =
"DELETE FROM $quotedTable WHERE ";
2658 foreach ( $uniqueIndexes
as $index ) {
2665 if ( is_array( $index ) ) {
2667 foreach ( $index
as $col ) {
2673 $sql .= $col .
'=' . $this->
addQuotes( $row[$col] );
2676 $sql .= $index .
'=' . $this->
addQuotes( $row[$index] );
2683 # Now insert the row
2702 if ( !is_array( reset( $rows ) ) ) {
2703 $rows =
array( $rows );
2706 $sql =
"REPLACE INTO $table (" . implode(
',', array_keys( $rows[0] ) ) .
') VALUES ';
2709 foreach ( $rows
as $row ) {
2716 $sql .=
'(' . $this->
makeList( $row ) .
')';
2759 if ( !count( $rows ) ) {
2763 if ( !is_array( reset( $rows ) ) ) {
2764 $rows =
array( $rows );
2767 if ( count( $uniqueIndexes ) ) {
2769 foreach ( $rows
as $row ) {
2770 foreach ( $uniqueIndexes
as $index ) {
2771 $index = is_array( $index ) ? $index :
array( $index );
2773 foreach ( $index
as $column ) {
2774 $rowKey[$column] = $row[$column];
2786 $this->
begin( $fname );
2789 # Update any existing conflicting row(s)
2790 if ( $where !==
false ) {
2795 # Now insert any non-conflicting row(s)
2797 }
catch ( Exception
$e ) {
2830 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2835 'DatabaseBase::deleteJoin() called with empty $conds' );
2838 $delTable = $this->
tableName( $delTable );
2839 $joinTable = $this->
tableName( $joinTable );
2840 $sql =
"DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2841 if ( $conds !=
'*' ) {
2858 $sql =
"SHOW COLUMNS FROM $table LIKE \"$field\";";
2859 $res = $this->
query( $sql,
'DatabaseBase::textFieldSize' );
2864 if ( preg_match(
'/\((.*)\)/', $row->Type, $m ) ) {
2895 public function delete( $table, $conds,
$fname = __METHOD__ ) {
2897 throw new DBUnexpectedError( $this,
'DatabaseBase::delete() called with no conditions' );
2901 $sql =
"DELETE FROM $table";
2903 if ( $conds !=
'*' ) {
2904 if ( is_array( $conds ) ) {
2907 $sql .=
' WHERE ' . $conds;
2939 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2941 $insertOptions =
array(), $selectOptions =
array()
2943 $destTable = $this->
tableName( $destTable );
2945 if ( !is_array( $insertOptions ) ) {
2946 $insertOptions =
array( $insertOptions );
2951 if ( !is_array( $selectOptions ) ) {
2952 $selectOptions =
array( $selectOptions );
2957 if ( is_array( $srcTable ) ) {
2958 $srcTable = implode(
',', array_map(
array( &$this,
'tableName' ), $srcTable ) );
2960 $srcTable = $this->
tableName( $srcTable );
2963 $sql =
"INSERT $insertOptions INTO $destTable (" . implode(
',', array_keys( $varMap ) ) .
')' .
2964 " SELECT $startOpts " . implode(
',', $varMap ) .
2965 " FROM $srcTable $useIndex ";
2967 if ( $conds !=
'*' ) {
2968 if ( is_array( $conds ) ) {
2971 $sql .=
" WHERE $conds";
2974 $sql .=
" $tailOpts";
2999 if ( !is_numeric(
$limit ) ) {
3000 throw new DBUnexpectedError( $this,
"Invalid non-numeric limit passed to limitResult()\n" );
3003 return "$sql LIMIT "
3004 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," :
"" )
3026 $glue = $all ?
') UNION ALL (' :
') UNION (';
3028 return '(' . implode( $glue, $sqls ) .
')';
3040 public function conditional( $cond, $trueVal, $falseVal ) {
3041 if ( is_array( $cond ) ) {
3045 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3058 public function strreplace( $orig, $old, $new ) {
3059 return "REPLACE({$orig}, {$old}, {$new})";
3132 $this->
begin( __METHOD__ );
3133 $args = func_get_args();
3134 $function = array_shift(
$args );
3138 if ( is_array( $function ) ) {
3145 $retVal = call_user_func_array( $function,
$args );
3153 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3162 if ( $tries <= 0 ) {
3168 $this->
commit( __METHOD__ );
3185 # Real waits are implemented in the subclass.
3225 if ( !$this->mTrxLevel ) {
3242 if ( $this->mTrxLevel ) {
3255 $autoTrx = $this->
getFlag( DBO_TRX );
3260 $this->mTrxIdleCallbacks =
array();
3261 foreach ( $callbacks
as $callback ) {
3263 list( $phpCallback ) = $callback;
3265 call_user_func( $phpCallback );
3267 }
catch ( Exception
$e ) {
3270 }
while ( count( $this->mTrxIdleCallbacks ) );
3272 if (
$e instanceof Exception ) {
3286 $this->mTrxPreCommitCallbacks =
array();
3287 foreach ( $callbacks
as $callback ) {
3289 list( $phpCallback ) = $callback;
3290 call_user_func( $phpCallback );
3291 }
catch ( Exception
$e ) {
3294 }
while ( count( $this->mTrxPreCommitCallbacks ) );
3296 if (
$e instanceof Exception ) {
3326 if ( !$this->mTrxLevel ) {
3327 $this->
begin( $fname );
3328 $this->mTrxAutomatic =
true;
3329 $this->mTrxAutomaticAtomic =
true;
3332 $this->mTrxAtomicLevels->push(
$fname );
3347 if ( !$this->mTrxLevel ) {
3350 if ( $this->mTrxAtomicLevels->isEmpty() ||
3351 $this->mTrxAtomicLevels->pop() !==
$fname
3357 $this->
commit( $fname,
'flush' );
3376 final public function begin(
$fname = __METHOD__ ) {
3377 global $wgDebugDBTransactions;
3379 if ( $this->mTrxLevel ) {
3380 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3384 "Attempted to start explicit transaction when atomic levels are still open."
3386 } elseif ( !$this->mTrxAutomatic ) {
3389 $msg =
"$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3390 " performing implicit commit!";
3396 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3397 wfDebug(
"$fname: Automatic transaction with writes in progress" .
3398 " (from {$this->mTrxFname}), performing implicit commit!\n"
3405 if ( $this->mTrxDoneWrites ) {
3412 $this->mTrxFname =
$fname;
3413 $this->mTrxDoneWrites =
false;
3414 $this->mTrxAutomatic =
false;
3415 $this->mTrxAutomaticAtomic =
false;
3416 $this->mTrxAtomicLevels =
new SplStack;
3417 $this->mTrxIdleCallbacks =
array();
3418 $this->mTrxPreCommitCallbacks =
array();
3428 $this->
query(
'BEGIN', $fname );
3429 $this->mTrxLevel = 1;
3446 final public function commit(
$fname = __METHOD__, $flush =
'' ) {
3447 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3451 "Attempted to commit transaction while atomic sections are still open"
3455 if ( $flush !==
'flush' ) {
3456 if ( !$this->mTrxLevel ) {
3457 wfWarn(
"$fname: No transaction to commit, something got out of sync!" );
3458 } elseif ( $this->mTrxAutomatic ) {
3459 wfWarn(
"$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3462 if ( !$this->mTrxLevel ) {
3464 } elseif ( !$this->mTrxAutomatic ) {
3465 wfWarn(
"$fname: Flushing an explicit transaction, getting out of sync!" );
3471 if ( $this->mTrxDoneWrites ) {
3483 protected function doCommit( $fname ) {
3484 if ( $this->mTrxLevel ) {
3485 $this->
query(
'COMMIT', $fname );
3486 $this->mTrxLevel = 0;
3503 final public function rollback(
$fname = __METHOD__, $flush =
'' ) {
3504 if ( $flush !==
'flush' ) {
3505 if ( !$this->mTrxLevel ) {
3506 wfWarn(
"$fname: No transaction to rollback, something got out of sync!" );
3507 } elseif ( $this->mTrxAutomatic ) {
3508 wfWarn(
"$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3511 if ( !$this->mTrxLevel ) {
3513 } elseif ( !$this->mTrxAutomatic ) {
3514 wfWarn(
"$fname: Flushing an explicit transaction, getting out of sync!" );
3519 $this->mTrxIdleCallbacks =
array();
3520 $this->mTrxPreCommitCallbacks =
array();
3521 $this->mTrxAtomicLevels =
new SplStack;
3522 if ( $this->mTrxDoneWrites ) {
3534 if ( $this->mTrxLevel ) {
3535 $this->
query(
'ROLLBACK', $fname,
true );
3536 $this->mTrxLevel = 0;
3559 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3570 throw new MWException(
'DatabaseBase::listTables is not implemented in descendant class' );
3578 $this->allViews =
null;
3593 throw new MWException(
'DatabaseBase::listViews is not implemented in descendant class' );
3604 throw new MWException(
'DatabaseBase::isView is not implemented in descendant class' );
3636 if ( is_null( $ts ) ) {
3662 } elseif (
$result ===
true ) {
3675 public function ping() {
3676 # Stub. Not essential to override.
3689 public function getLag() {
3757 $filename, $lineCallback =
false, $resultCallback =
false,
$fname =
false, $inputCallback =
false
3760 $fp = fopen( $filename,
'r' );
3763 if (
false === $fp ) {
3764 throw new MWException(
"Could not open \"{$filename}\".\n" );
3768 $fname = __METHOD__ .
"( $filename )";
3795 if ( file_exists(
"$IP/maintenance/$dbType/archives/$patch" ) ) {
3796 return "$IP/maintenance/$dbType/archives/$patch";
3798 return "$IP/maintenance/archives/$patch";
3810 $this->mSchemaVars =
$vars;
3826 public function sourceStream( $fp, $lineCallback =
false, $resultCallback =
false,
3827 $fname = __METHOD__, $inputCallback =
false
3831 while ( !feof( $fp ) ) {
3832 if ( $lineCallback ) {
3833 call_user_func( $lineCallback );
3836 $line = trim( fgets( $fp ) );
3838 if (
$line ==
'' ) {
3854 if ( $done || feof( $fp ) ) {
3857 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3860 if ( $resultCallback ) {
3861 call_user_func( $resultCallback,
$res, $this );
3864 if (
false ===
$res ) {
3867 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3885 if ( $this->delimiter ) {
3887 $newLine = preg_replace(
'/' . preg_quote( $this->delimiter,
'/' ) .
'$/',
'', $newLine );
3888 if ( $newLine != $prev ) {
3917 $ins = str_replace(
'\'{$
' . $var . '}\
'', $this->
addQuotes( $value ), $ins );
3921 $ins = str_replace(
'/*$' . $var .
'*/', $this->
strencode( $value ), $ins );
3937 $ins = preg_replace_callback(
'!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3938 array( $this,
'tableNameCallback' ), $ins );
3941 $ins = preg_replace_callback(
'!/\*i\*/([a-zA-Z_0-9]*)!',
3942 array( $this,
'indexNameCallback' ), $ins );
3954 if ( $this->mSchemaVars ) {
4001 public function lockIsFree( $lockName, $method ) {
4016 public function lock( $lockName, $method, $timeout = 5 ) {
4030 public function unlock( $lockName, $method ) {
4043 public function lockTables( $read, $write, $method, $lowPriority =
true ) {
4064 public function dropTable( $tableName, $fName = __METHOD__ ) {
4065 if ( !$this->
tableExists( $tableName, $fName ) ) {
4068 $sql =
"DROP TABLE " . $this->
tableName( $tableName );
4073 return $this->
query( $sql, $fName );
4083 return 'SearchEngineDummy';
4104 return ( $expiry ==
'' || $expiry ==
'infinity' || $expiry == $this->
getInfinity() )
4117 return ( $expiry ==
'' || $expiry == $this->
getInfinity() )
4146 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4147 trigger_error(
"Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4149 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4151 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4152 $callers[] = $callbackInfo[1];
4154 $callers = implode(
', ', $callers );
4155 trigger_error(
"DB transaction callbacks still pending (from $callers)." );
writesOrCallbacksPending()
Returns true if there is a transaction open with possible write queries or transaction pre-commit/idl...
tableName( $name, $format='quoted')
Format a table name ready for use in constructing an SQL query.
startAtomic( $fname=__METHOD__)
Begin an atomic section of statements.
replace( $table, $uniqueIndexes, $rows, $fname=__METHOD__)
REPLACE query wrapper.
replaceVars( $ins)
Replace variables in sourced SQL.
lastQuery()
Return the last query that went through DatabaseBase::query()
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. $title:Title object for the current page $request:WebRequest $ignoreRedirect:boolean to skip redirect check $target:Title/string of redirect target $article:Article object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) $article:article(object) being checked 'IsTrustedProxy':Override the result of wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of User::isValidEmailAddr(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetMagic':DEPRECATED, use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetSpecialPageAliases':DEPRECATED, use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LinkBegin':Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
reportConnectionError( $error='Unknown error')
doBegin( $fname)
Issues the BEGIN command to the database server.
functionalIndexes()
Returns true if this database can use functional indexes.
debug( $debug=null)
Boolean, controls output of large amounts of debug information.
static query( $sql, $function, $isMaster)
Begins profiling on a database query.
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
wasReadOnlyError()
Determines if the last failure was due to the database being read-only.
numRows( $res)
Get the number of rows in a result object.
setLBInfo( $name, $value=null)
Set the LB info array, or a member of it.
fetchRow( $res)
Fetch the next row from the given result object, in associative array form.
insertSelect( $destTable, $srcTable, $varMap, $conds, $fname=__METHOD__, $insertOptions=array(), $selectOptions=array())
INSERT SELECT wrapper.
fieldInfo( $table, $field)
mysql_fetch_field() wrapper Returns false if the field doesn't exist
execute( $prepared, $args=null)
Execute a prepared query with the various arguments.
static instance()
Singleton.
onTransactionPreCommitOrIdle( $callback)
Run an anonymous function before the current transaction commits or now if there is none.
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
realTimestamps()
Returns true if this database uses timestamps rather than integers.
useIndexClause( $index)
USE INDEX clause.
makeUpdateOptions( $options)
Make UPDATE options for the DatabaseBase::update function.
buildConcat( $stringList)
Build a concatenation list to feed into a SQL query.
makeList( $a, $mode=LIST_COMMA)
Makes an encoded list of strings from an array.
makeWhereFrom2d( $data, $baseKey, $subKey)
Build a partial where clause from a 2-d array such as used for LinkBatch.
wfSetBit(&$dest, $bit, $state=true)
As for wfSetVar except setting a bit.
lockIsFree( $lockName, $method)
Check to see if a named lock is available.
wasLockTimeout()
Determines if the last failure was due to a lock timeout STUB.
bitAnd( $fieldLeft, $fieldRight)
close()
Closes a database connection.
query( $sql, $fname=__METHOD__, $tempIgnore=false)
Run an SQL query and return the result.
freePrepared( $prepared)
Free a prepared query, generated by prepare().
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
affectedRows()
Get the number of rows affected by the last write query.
isQuotedIdentifier( $name)
Returns if the given identifier looks quoted or not according to the database convention for quoting ...
wfProfileIn( $functionname)
Begin profiling of a function.
indexNameCallback( $matches)
Index name callback.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
wfSuppressWarnings( $end=false)
Reference-counted warning suppression.
getFlag( $flag)
Returns a boolean whether the flag $flag is set for this connection.
buildLike()
LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match conta...
resultObject( $result)
Take the result from a query, and wrap it in a ResultWrapper if necessary.
if(!defined( 'MEDIAWIKI')) $fname
This file is not a valid entry point, perform no further processing unless MEDIAWIKI is defined.
lowPriorityOption()
A string to insert into queries to show that they're low-priority, like MySQL's LOW_PRIORITY.
textFieldSize( $table, $field)
Returns the size of a text field, or -1 for "unlimited".
getServerVersion()
A string describing the current software version, like from mysql_get_server_info().
makeOrderBy( $options)
Returns an optional ORDER BY.
connectionErrorHandler( $errno, $errstr)
setFileHandle( $fh)
Set the filehandle to copy write statements to.
anyString()
Returns a token for buildLike() that denotes a '' to be used in a LIKE query.
replaceSchemaVars( $ins)
Database independent variable replacement.
dropTable( $tableName, $fName=__METHOD__)
Delete a table.
strictIPs()
Returns true if this database is strict about what can be put into an IP field.
unionSupportsOrderAndLimit()
Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries within th...
getSchemaVars()
Get schema variables.
it s the revision text itself In either if gzip is the revision text is gzipped $flags
An object representing a master or slave position in a replicated setup.
limitResult( $sql, $limit, $offset=false)
Construct a LIMIT query with optional offset.
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
encodeBlob( $b)
Some DBMSs have a special format for inserting into blob fields, they don't allow simple quoted strin...
buildGroupConcatField( $delim, $table, $field, $conds='', $join_conds=array())
Build a GROUP_CONCAT or equivalent statement for a query.
implicitOrderby()
Returns true if this database does an implicit order by when the column has an index For example: SEL...
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=array(), $join_conds=array())
Single row SELECT wrapper.
bool $mTrxAutomaticAtomic
Record if the current transaction was started implicitly by DatabaseBase::startAtomic.
tableNamesWithUseIndexOrJOIN( $tables, $use_index=array(), $join_conds=array())
Get the aliased table name clause for a FROM clause which might have a JOIN and/or USE INDEX clause.
doQuery( $sql)
The DBMS-dependent part of query()
tableExists( $table, $fname=__METHOD__)
Query whether a given table exists.
Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE claus...
indexInfo( $table, $index, $fname=__METHOD__)
Get information about an index into an object.
tablePrefix( $prefix=null)
Get/set the table prefix.
setFakeSlaveLag( $lag)
Set lag time in seconds for a fake slave.
unlockTables( $method)
Unlock specific tables.
__destruct()
Run a few simple sanity checks.
setSchemaVars( $vars)
Set variables to be used in sourceFile/sourceStream, in preference to the ones in $GLOBALS.
update( $table, $values, $conds, $fname=__METHOD__, $options=array())
UPDATE wrapper.
selectSQLText( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
The equivalent of DatabaseBase::select() except that the constructed SQL is returned,...
indexName( $index)
Get the name of an index in a given table.
errorCount( $count=null)
Get/set the number of errors logged.
addQuotes( $s)
Adds quotes and backslashes.
endAtomic( $fname=__METHOD__)
Ends an atomic section of SQL statements.
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=array())
A SELECT wrapper which returns a single field from a single result row.
doRollback( $fname)
Issues the ROLLBACK command to the database server.
unlock( $lockName, $method)
Release a lock.
isView( $name)
Differentiates between a TABLE and a VIEW.
fillPrepared( $preparedQuery, $args)
For faking prepared SQL statements on DBs that don't support it directly.
freeResult( $res)
Free a result object returned by query() or select().
getServerInfo()
A string describing the current software version, and possibly other details in a user-friendly way.
resource $mConn
Database connection *.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
select( $table, $vars, $conds='', $fname=__METHOD__, $options=array(), $join_conds=array())
Execute a SELECT query constructed using the various parameters provided.
wfRestoreWarnings()
Restore error level to previous value.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global then executing the whole list after the page is displayed We don t do anything smart like collating updates to the same table or such because the list is almost always going to have just one item on if so it s not worth the trouble Since there is a job queue in the jobs table
getDefaultSchemaVars()
Get schema variables to use if none have been set via setSchemaVars().
global $wgCommandLineMode
cleanupTriggers()
Returns true if this database supports (and uses) triggers (e.g.
tableNameCallback( $matches)
Table name callback.
ignoreErrors( $ignoreErrors=null)
Turns on (false) or off (true) the automatic generation and sending of a "we're sorry,...
static queryTime( $id)
Calculates how long a query took.
setFlag( $flag)
Set a flag for this connection.
wfProfileOut( $functionname='missing')
Stop profiling of a function.
indexUnique( $table, $index)
Determines if a given index is unique.
int $mTrxLevel
Either 1 if a transaction is active or 0 otherwise.
reportQueryError( $error, $errno, $sql, $fname, $tempIgnore=false)
Report a query error.
listTables( $prefix=null, $fname=__METHOD__)
List all tables on the database.
getSchemaPath()
Return a path to the DBMS-specific schema file, otherwise default to tables.sql.
estimateRowCount( $table, $vars=' *', $conds='', $fname=__METHOD__, $options=array())
Estimate rows in dataset.
nativeReplace( $table, $rows, $fname)
REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE statement.
bool $mTrxAutomatic
Record if the current transaction was started implicitly due to DBO_TRX being set.
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
wasErrorReissuable()
Determines if the last query error was something that should be dealt with by pinging the connection ...
clearViewsCache()
Reset the views process cache set by listViews()
const DEADLOCK_TRIES
Number of times to re-try an operation in case of deadlock.
isWriteQuery( $sql)
Determine whether a query writes to the DB.
when a variable name is used in a it is silently declared as a new masking the global
numFields( $res)
Get the number of fields in a result object.
__sleep()
Called by serialize.
static factory( $dbType, $p=array())
Given a DB type, construct the name of the appropriate child class of DatabaseBase.
runOnTransactionPreCommitCallbacks()
Actually any "on transaction pre-commit" callbacks.
getServer()
Get the server hostname or IP address.
selectDB( $db)
Change the current database.
implicitGroupby()
Returns true if this database does an implicit sort when doing GROUP BY.
getSoftwareLink()
Returns a wikitext link to the DB's website, e.g., return "[http://www.mysql.com/ MySQL]"; Should at ...
getServerInfo()
A string describing the current software version, and possibly other details in a user-friendly way.
SplStack $mTrxAtomicLevels
Array of levels of atomicity within transactions.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
strencode( $s)
Wrapper for addslashes()
getType()
Get the type of the DBMS, as it appears in $wgDBtype.
makeGroupByWithHaving( $options)
Returns an optional GROUP BY with an optional HAVING.
insertId()
Get the inserted value of an auto-increment row.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the database
wasDeadlock()
Determines if the last failure was due to a deadlock STUB.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
getProperty( $name)
General read-only accessor.
getSlavePos()
Get the replication position of this slave.
trxLevel()
Gets the current transaction level.
sourceFile( $filename, $lineCallback=false, $resultCallback=false, $fname=false, $inputCallback=false)
Read and execute SQL commands from a file.
fieldNamesWithAlias( $fields)
Gets an array of aliased field names.
const TS_MW
MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
wfDebug( $text, $dest='all')
Sends a line to the debug log if enabled or, optionally, to a comment in output.
deadlockLoop()
Perform a deadlock-prone transaction.
makeInsertOptions( $options)
Helper for DatabaseBase::insert().
prepare( $sql, $func='DatabaseBase::prepare')
Intended to be compatible with the PEAR::DB wrapper functions.
anyChar()
Returns a token for buildLike() that denotes a '_' to be used in a LIKE query.
while(false !==( $line=fgets( $in))) if(! $columns) $ignore
Allows to change the fields on the form that will be generated $name
getInfinity()
Find out when 'infinity' is.
if(!defined( 'MEDIAWIKI')) if(!isset( $wgVersion)) $matches
wfLogDBError( $text)
Log for database errors.
decodeExpiry( $expiry, $format=TS_MW)
Decode an expiry time into a DBMS independent format.
unionQueries( $sqls, $all)
Construct a UNION query This is used for providing overload point for other DB abstractions not compa...
aggregateValue( $valuedata, $valuename='value')
Return aggregated value alias.
dataSeek( $res, $row)
Change the position of the cursor in a result object.
streamStatementEnd(&$sql, &$newLine)
Called by sourceStream() to check if we've reached a statement end.
Database abstraction object.
bitOr( $fieldLeft, $fieldRight)
timestampOrNull( $ts=null)
Convert a timestamp in one of the formats accepted by wfTimestamp() to the format used for inserting ...
masterPosWait(DBMasterPos $pos, $timeout)
Wait for the slave to catch up to a given master position.
makeSelectOptions( $options)
Returns an optional USE INDEX clause to go after the table, and a string to go at the end of the quer...
getDBname()
Get the current DB name.
bool $mTrxDoneWrites
Record if possible write queries were done in the last transaction started.
callable[] $mTrxIdleCallbacks
getMasterPos()
Get the position of this master.
lockTables( $read, $write, $method, $lowPriority=true)
Lock specific tables.
lastError()
Get a description of the last error.
strreplace( $orig, $old, $new)
Returns a comand for str_replace function in SQL query.
duplicateTableStructure( $oldName, $newName, $temporary=false, $fname=__METHOD__)
Creates a new table with structure copied from existing table Note that unlike most database abstract...
bufferResults( $buffer=null)
Turns buffering of SQL result sets on (true) or off (false).
doCommit( $fname)
Issues the COMMIT command to the database server.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Interface for classes that implement or wrap DatabaseBase.
callable[] $mTrxPreCommitCallbacks
getSearchEngine()
Get search engine class.
makeUpdateOptionsArray( $options)
Make UPDATE options array for DatabaseBase::makeUpdateOptions.
commit( $fname=__METHOD__, $flush='')
Commits a transaction previously started using begin().
return false to override stock group addition can be modified try getUserPermissionsErrors userCan checks are continued by internal code can override on output return false to not delete it return false to override the default password checks this Boolean value will be checked to determine if the password was valid return false to implement your own hashing method & $password
rollback( $fname=__METHOD__, $flush='')
Rollback a transaction previously started using begin().
static generalizeSQL( $sql)
Removes most variables from an SQL query and replaces them with X or N for numbers.
lastErrno()
Get the last error number.
addIdentifierQuotes( $s)
Quotes an identifier using backticks or "double quotes" depending on the database type.
searchableIPs()
Returns true if this database can do a native search on IP columns e.g.
lock( $lockName, $method, $timeout=5)
Acquire a named lock.
const DEADLOCK_DELAY_MIN
Minimum time to wait before retry, in microseconds.
string $mTrxFname
Remembers the function name given for starting the most recent transaction via begin().
isOpen()
Is a connection to the database open?
listViews( $prefix=null, $fname=__METHOD__)
Lists all the VIEWs in the database.
begin( $fname=__METHOD__)
Begin a transaction.
doneWrites()
Returns true if the connection may have been used for write queries.
setBigSelects( $value=true)
Allow or deny "big selects" for this session only.
nextSequenceValue( $seqName)
Returns an appropriately quoted sequence value for inserting a new row.
patchPath( $patch)
Get the full path of a patch file.
fetchObject( $res)
Fetch the next row from the given result object, in object form.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
fieldExists( $table, $field, $fname=__METHOD__)
Determines whether a field exists in a table.
closeConnection()
Closes underlying database connection.
cascadingDeletes()
Returns true if this database supports (and uses) cascading deletes.
runOnTransactionIdleCallbacks()
Actually any "on transaction idle" callbacks.
open( $server, $user, $password, $dbName)
Open a connection to the database.
ping()
Ping the server and try to reconnect if it there is no connection.
getLBInfo( $name=null)
Get properties passed down from the server info array of the load balancer.
__construct( $params=null)
Constructor.
wfWarn( $msg, $callerOffset=1, $level=E_USER_NOTICE)
Send a warning either to the debug log or in a PHP error depending on $wgDevelopmentWarnings.
upsert( $table, array $rows, array $uniqueIndexes, array $set, $fname=__METHOD__)
INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
const DEADLOCK_DELAY_MAX
Maximum time to wait before retry.
static configuration should be added through ResourceLoaderGetConfigVars instead & $vars
usually copyright or history_copyright This message must be in HTML not wikitext $subpages will be ignored and the rest of subPageSubtitle() will run. 'SkinTemplateBuildNavUrlsNav_urlsAfterPermalink' whether MediaWiki currently thinks this is a CSS JS page Hooks may change this value to override the return value of Title::isCssOrJsPage(). 'TitleIsAlwaysKnown' whether MediaWiki currently thinks this page is known isMovable() always returns false. $title whether MediaWiki currently thinks this page is movable Hooks may change this value to override the return value of Title::isMovable(). 'TitleIsWikitextPage' whether MediaWiki currently thinks this is a wikitext page Hooks may change this value to override the return value of Title::isWikitextPage() 'TitleMove' use UploadVerification and UploadVerifyFile instead where the first element is the message key and the remaining elements are used as parameters to the message based on mime etc Preferred in most cases over UploadVerification object with all info about the upload string as detected by MediaWiki Handlers will typically only apply for specific mime types object & $error
maxListLen()
Return the maximum number of items allowed in a list, or 0 for unlimited.
dbSchema( $schema=null)
Get/set the db schema.
deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname=__METHOD__)
DELETE where the condition is a join.
sourceStream( $fp, $lineCallback=false, $resultCallback=false, $fname=__METHOD__, $inputCallback=false)
Read and execute commands from an open file handle.
encodeExpiry( $expiry)
Encode an expiry time into the DBMS dependent format.
setSessionOptions(array $options)
Override database's default behavior.
clearFlag( $flag)
Clear a flag for this connection.
fieldName( $res, $n)
Get a field name in a result object.
wfGetCaller( $level=2)
Get the name of the function which called this function wfGetCaller( 1 ) is the function with the wfG...
indexExists( $table, $index, $fname=__METHOD__)
Determines whether an index exists Usually throws a DBQueryError on failure If errors are explicitly ...
setFakeMaster( $enabled=true)
Make this connection a fake master.
getServerUptime()
Determines how long the server has been up STUB.
onTransactionIdle( $callback)
Run an anonymous function as soon as there is no transaction pending.
conditional( $cond, $trueVal, $falseVal)
Returns an SQL expression for a simple conditional.
decodeBlob( $b)
Some DBMSs return a special placeholder object representing blob fields in result objects.
Result wrapper for grabbing data queried by someone else.
fillPreparedArg( $matches)
preg_callback func for fillPrepared() The arguments should be in $this->preparedArgs and must not be ...
insert( $table, $a, $fname=__METHOD__, $options=array())
INSERT wrapper, inserts an array into a table.