$info = $lb->parentInfo();
if ( !$db || !$db->doneWrites() ) {
wfDebug( __METHOD__ . ": LB {$info['id']}, no writes done\n" );
+
return;
}
$pos = $db->getMasterPos();
*/
class CloneDatabase {
-
/**
* Table prefix for cloning
* @var String
* @param $dropCurrentTables bool
*/
public function __construct( DatabaseBase $db, array $tablesToClone,
- $newTablePrefix, $oldTablePrefix = '', $dropCurrentTables = true )
- {
+ $newTablePrefix, $oldTablePrefix = '', $dropCurrentTables = true
+ ) {
$this->db = $db;
$this->tablesToClone = $tablesToClone;
$this->newTablePrefix = $newTablePrefix;
* Interface for classes that implement or wrap DatabaseBase
* @ingroup Database
*/
-interface IDatabase {}
+interface IDatabase {
+}
/**
* Database abstraction object
/**
* Clear a flag for this connection
*
- * @param $flag: same as setFlag()'s $flag param
+ * @param $flag : same as setFlag()'s $flag param
*/
public function clearFlag( $flag ) {
global $wgDebugDBTransactions;
/**
* Returns a boolean whether the flag $flag is set for this connection
*
- * @param $flag: same as setFlag()'s $flag param
+ * @param $flag : same as setFlag()'s $flag param
* @return Boolean
*/
public function getFlag( $flag ) {
/**
* Given a DB type, construct the name of the appropriate child class of
* DatabaseBase. This is designed to replace all of the manual stuff like:
- * $class = 'Database' . ucfirst( strtolower( $dbType ) );
+ * $class = 'Database' . ucfirst( strtolower( $dbType ) );
* as well as validate against the canonical list of DB types we have
*
* This factory function is mostly useful for when you need to connect to a
*/
final public static function factory( $dbType, $p = array() ) {
$canonicalDBTypes = array(
- 'mysql' => array( 'mysqli', 'mysql' ),
+ 'mysql' => array( 'mysqli', 'mysql' ),
'postgres' => array(),
- 'sqlite' => array(),
- 'oracle' => array(),
- 'mssql' => array(),
+ 'sqlite' => array(),
+ 'oracle' => array(),
+ 'mssql' => array(),
);
$driver = false;
'tablePrefix' => isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global',
'foreign' => isset( $p['foreign'] ) ? $p['foreign'] : false
);
+
return new $class( $params );
} else {
return null;
if ( $this->mPHPError ) {
$error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
$error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
+
return $error;
} else {
return false;
$ret = $this->closeConnection();
$this->mConn = false;
+
return $ret;
} else {
return true;
# If DBO_TRX is set, start a transaction
if ( ( $this->mFlags & DBO_TRX ) && !$this->mTrxLevel &&
- $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
- {
+ $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
+ ) {
# Avoid establishing transactions for SHOW and SET statements too -
# that would delay transaction initializations to once connection
# is really used by application
: $options['HAVING'];
$sql .= ' HAVING ' . $having;
}
+
return $sql;
}
$ob = is_array( $options['ORDER BY'] )
? implode( ',', $options['ORDER BY'] )
: $options['ORDER BY'];
+
return ' ORDER BY ' . $ob;
}
+
return '';
}
* @see DatabaseBase::select()
*/
public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
- $options = array(), $join_conds = array() )
- {
+ $options = array(), $join_conds = array()
+ ) {
if ( is_array( $vars ) ) {
$vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
}
* @return object|bool
*/
public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
- $options = array(), $join_conds = array() )
- {
+ $options = array(), $join_conds = array()
+ ) {
$options = (array)$options;
$options['LIMIT'] = 1;
$res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
* @return Integer: row count
*/
public function estimateRowCount( $table, $vars = '*', $conds = '',
- $fname = __METHOD__, $options = array() )
- {
+ $fname = __METHOD__, $options = array()
+ ) {
$rows = 0;
$res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
* @param $table String name of the table to UPDATE. This will be passed through
* DatabaseBase::tableName().
*
- * @param array $values An array of values to SET. For each array element,
+ * @param array $values An array of values to SET. For each array element,
* the key gives the field name, and the value gives the data
* to set that field to. The data will be quoted by
* DatabaseBase::addQuotes().
$delim, $table, $field, $conds = '', $join_conds = array()
) {
$fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
+
return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
}
# if your database engine supports a concept similar to MySQL's
# databases you may as well.
$this->mDBname = $db;
+
return true;
}
}
$retval[] = $this->tableNameWithAlias( $table, $alias );
}
+
return $retval;
}
}
$retval[] = $this->fieldNameWithAlias( $field, $alias );
}
+
return $retval;
}
* @throws DBUnexpectedError
*/
public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
- $fname = __METHOD__ )
- {
+ $fname = __METHOD__
+ ) {
if ( !$conds ) {
throw new DBUnexpectedError( $this,
'DatabaseBase::deleteJoin() called with empty $conds' );
*/
public function insertSelect( $destTable, $srcTable, $varMap, $conds,
$fname = __METHOD__,
- $insertOptions = array(), $selectOptions = array() )
- {
+ $insertOptions = array(), $selectOptions = array()
+ ) {
$destTable = $this->tableName( $destTable );
if ( is_array( $insertOptions ) ) {
if ( !is_numeric( $limit ) ) {
throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
}
+
return "$sql LIMIT "
. ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
. "{$limit} ";
*/
public function unionQueries( $sqls, $all ) {
$glue = $all ? ') UNION ALL (' : ') UNION (';
+
return '(' . implode( $glue, $sqls ) . ')';
}
if ( is_array( $cond ) ) {
$cond = $this->makeList( $cond, LIST_AND );
}
+
return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
}
if ( $tries <= 0 ) {
$this->rollback( __METHOD__ );
$this->reportQueryError( $error, $errno, $sql, $fname );
+
return false;
} else {
$this->commit( __METHOD__ );
+
return $retVal;
}
}
if ( $wait > $timeout * 1e6 ) {
wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
wfProfileOut( __METHOD__ );
+
return -1;
} elseif ( $wait > 0 ) {
wfDebug( "Fake slave waiting $wait us\n" );
usleep( $wait );
wfProfileOut( __METHOD__ );
+
return 1;
} else {
wfDebug( "Fake slave up to date ($wait us)\n" );
wfProfileOut( __METHOD__ );
+
return 0;
}
}
if ( !is_null( $this->mFakeSlaveLag ) ) {
$pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag );
wfDebug( __METHOD__ . ": fake slave pos = $pos\n" );
+
return $pos;
} else {
# Stub
$this->clearFlag( DBO_TRX ); // make each query its own transaction
call_user_func( $phpCallback );
$this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
- } catch ( Exception $e ) {}
+ } catch ( Exception $e ) {
+ }
}
} while ( count( $this->mTrxIdleCallbacks ) );
try {
list( $phpCallback ) = $callback;
call_user_func( $phpCallback );
- } catch ( Exception $e ) {}
+ } catch ( Exception $e ) {
+ }
}
} while ( count( $this->mTrxPreCommitCallbacks ) );
* For caching purposes the list of all views should be stored in
* $this->allViews. The process cache can be cleared with clearViewsCache()
*
- * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
- * @param string $fname Name of calling function
+ * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
+ * @param string $fname Name of calling function
* @throws MWException
* @since 1.22
*/
try {
$error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
- }
- catch ( MWException $e ) {
+ } catch ( MWException $e ) {
fclose( $fp );
throw $e;
}
* @return bool|string
*/
public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
- $fname = __METHOD__, $inputCallback = false )
- {
+ $fname = __METHOD__, $inputCallback = false
+ ) {
$cmd = '';
while ( !feof( $fp ) ) {
if ( false === $res ) {
$err = $this->lastError();
+
return "Query \"{$cmd}\" failed with error code \"$err\".\n";
}
}
return true;
}
}
+
return false;
}
// replace /*$var*/
$ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
}
+
return $ins;
}
if ( $this->cascadingDeletes() ) {
$sql .= " CASCADE";
}
+
return $this->query( $sql, $fName );
}
$callers = array();
foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
$callers[] = $callbackInfo[1];
-
}
$callers = implode( ', ', $callers );
trigger_error( "DB transaction callbacks still pending (from $callers)." );
* @ingroup Database
*/
class DBError extends MWException {
-
/**
* @var DatabaseBase
*/
} else {
$message = $fallback;
}
+
return wfMsgReplaceArgs( $message, $args );
}
// Output cached page with notices on bottom and re-close body
echo "{$cache}<hr />{$this->getHTML()}</body></html>";
+
return;
}
} catch ( MWException $e ) {
</p>
</form>
EOT;
+
return $trygoogle;
}
'databaseerror-function' => 'Function: $1',
'databaseerror-error' => 'Error: $1',
);
+
return $messages[$key];
}
-
}
/**
* @ingroup Database
*/
-class DBUnexpectedError extends DBError {}
+class DBUnexpectedError extends DBError {
+}
wfDebug( "DB connection error\n" );
wfDebug( "Server: $server, Database: $dbName, User: $user, Password: " . substr( $password, 0, 3 ) . "...\n" );
wfDebug( $this->lastError() . "\n" );
+
return false;
}
$this->mOpened = true;
+
return $this->mConn;
}
// if it is a SELECT statement, or an insert with a request to output something we want to return a row.
if ( ( preg_match( '#\bSELECT\s#i', $sql ) ) ||
- ( preg_match( '#\bINSERT\s#i', $sql ) && preg_match( '#\bOUTPUT\s+INSERTED\b#i', $sql ) ) ) {
+ ( preg_match( '#\bINSERT\s#i', $sql ) && preg_match( '#\bOUTPUT\s+INSERTED\b#i', $sql ) )
+ ) {
// this is essentially a rowset, but Mediawiki calls these 'result'
// the rowset owns freeing the statement
$res = new MssqlResult( $stmt );
// otherwise we simply return it was successful, failure throws an exception
$res = true;
}
+
return $res;
}
$res = $res->result;
}
$row = $res->fetch( 'OBJECT' );
+
return $row;
}
} else {
$strRet = "No errors found";
}
+
return $strRet;
}
$res = $res->result;
}
$row = $res->fetch( SQLSRV_FETCH_BOTH );
+
return $row;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return ( $res ) ? $res->numrows() : 0;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return ( $res ) ? $res->numfields() : 0;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return ( $res ) ? $res->fieldname( $n ) : 0;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return ( $res ) ? $res->seek( $row ) : false;
}
* @param array $options associative array of options (e.g. array('GROUP BY' => 'page_title')),
* see Database::makeSelectOptions code for list of supported stuff
* @param $join_conds Array: Associative array of table join conditions (optional)
- * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
+ * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
* @return Mixed: database result resource (feed to Database::fetchObject or whatever), or false on failure
*/
- function select( $table, $vars, $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array() )
- {
+ function select( $table, $vars, $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array() ) {
$sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
if ( isset( $options['EXPLAIN'] ) ) {
sqlsrv_query( $this->mConn, "SET SHOWPLAN_ALL ON;" );
$ret = $this->query( $sql, $fname );
sqlsrv_query( $this->mConn, "SET SHOWPLAN_ALL OFF;" );
+
return $ret;
}
+
return $this->query( $sql, $fname );
}
* @param $vars Mixed: Array or string, field name(s) to be retrieved
* @param $conds Mixed: Array or string, condition(s) for WHERE
* @param $fname String: Calling function name (use __METHOD__) for logs/profiling
- * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
+ * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
* see Database::makeSelectOptions code for list of supported stuff
* @param $join_conds Array: Associative array of table join conditions (optional)
* (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
if ( isset( $options['EXPLAIN'] ) ) {
unset( $options['EXPLAIN'] );
}
+
return parent::selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
}
* @return int
*/
function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array() ) {
- $options['EXPLAIN'] = true;// http://msdn2.microsoft.com/en-us/library/aa259203.aspx
+ // http://msdn2.microsoft.com/en-us/library/aa259203.aspx
+ $options['EXPLAIN'] = true;
$res = $this->select( $table, $vars, $conds, $fname, $options );
$rows = -1;
$rows = $row['EstimateRows'];
}
}
+
return $rows;
}
}
}
}
+
return empty( $result ) ? false : $result;
}
$table = $this->tableName( $table );
- if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) {// Not multi row
- $arrToInsert = array( 0 => $arrToInsert );// make everything multi row compatible
+ if ( !( isset( $arrToInsert[0] ) && is_array( $arrToInsert[0] ) ) ) { // Not multi row
+ $arrToInsert = array( 0 => $arrToInsert ); // make everything multi row compatible
}
$allOk = true;
// there is a value being passed to us, we need to turn on and off inserted identity
$sqlPre = "SET IDENTITY_INSERT $table ON;";
$sqlPost = ";SET IDENTITY_INSERT $table OFF;";
-
} else {
// we can't insert NULL into an identity column, so remove the column from the insert.
unset( $a[$k] );
}
$allOk = false;
}
+
return $allOk;
}
} elseif ( $ret != null ) {
// remember number of rows affected
$this->mAffectedRows = sqlsrv_rows_affected( $ret );
+
return $ret;
}
+
return null;
}
}
sqlsrv_query( $this->mConn, "INSERT INTO [sequence_$seqName] (junk) VALUES ('')" );
$ret = sqlsrv_query( $this->mConn, "SELECT TOP 1 id FROM [sequence_$seqName] ORDER BY id DESC" );
- $row = sqlsrv_fetch_array( $ret, SQLSRV_FETCH_ASSOC );// KEEP ASSOC THERE, weird weird bug dealing with the return value if you don't
+ $row = sqlsrv_fetch_array( $ret, SQLSRV_FETCH_ASSOC ); // KEEP ASSOC THERE, weird weird bug dealing with the return value if you don't
sqlsrv_free_stmt( $ret );
$this->mInsertId = $row['id'];
+
return $row['id'];
}
if ( $ret !== false ) {
$row = sqlsrv_fetch_array( $ret );
sqlsrv_free_stmt( $ret );
+
return $row['id'];
} else {
return $this->nextSequenceValue( $seqName );
if ( strtolower( $row['DATA_TYPE'] ) != 'text' ) {
$size = $row['CHARACTER_MAXIMUM_LENGTH'];
}
+
return $size;
}
) as sub2
) AS sub3
WHERE line3 BETWEEN ' . ( $offset + 1 ) . ' AND ' . ( $offset + $limit );
+
return $sql;
}
}
$row_count = $matches[4];
// offset = $matches[3] OR $matches[6]
$offset = $matches[3] or
- $offset = $matches[6] or
- $offset = false;
+ $offset = $matches[6] or
+ $offset = false;
// strip the matching LIMIT clause out
$sql = str_replace( $matches[0], '', $sql );
+
return $this->limitResult( $sql, $row_count, $offset );
}
+
return $sql;
}
if ( isset( $server_info['SQLServerVersion'] ) ) {
$version = $server_info['SQLServerVersion'];
}
+
return $version;
}
WHERE table_type='BASE TABLE' AND table_name = '$table'" );
if ( $res === false ) {
print "Error in tableExists query: " . $this->getErrors();
+
return false;
}
if ( sqlsrv_fetch( $res ) ) {
WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
if ( $res === false ) {
print "Error in fieldExists query: " . $this->getErrors();
+
return false;
}
if ( sqlsrv_fetch( $res ) ) {
WHERE TABLE_NAME = '$table' AND COLUMN_NAME = '$field'" );
if ( $res === false ) {
print "Error in fieldInfo query: " . $this->getErrors();
+
return false;
}
$meta = $this->fetchRow( $res );
if ( $meta ) {
return new MssqlField( $meta );
}
+
return false;
}
// It may be allowed if you quoted with double quotation marks, but that would break if QUOTED_IDENTIFIER is OFF
throw new MWException( "You can't use square brackers in the identifier '$identifier'" );
}
+
return "[$identifier]";
}
}
function encodeBlob( $b ) {
- // we can't have zero's and such, this is a simple encoding to make sure we don't barf
+ // we can't have zero's and such, this is a simple encoding to make sure we don't barf
return base64_encode( $b );
}
function decodeBlob( $b ) {
- // we can't have zero's and such, this is a simple encoding to make sure we don't barf
- return base64_decode( $b );
+ // we can't have zero's and such, this is a simple encoding to make sure we don't barf
+ return base64_decode( $b );
}
/**
// We can't separate explicit JOIN clauses with ',', use ' ' for those
$straightJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
$otherJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
+
// Compile our final table clause
return implode( ' ', array( $straightJoins, $otherJoins ) );
}
public function getInfinity() {
return '3000-01-31 00:00:00.000';
}
-
} // end DatabaseMssql class
/**
*/
class MssqlField implements Field {
private $name, $tablename, $default, $max_length, $nullable, $type;
+
function __construct( $info ) {
$this->name = $info['COLUMN_NAME'];
$this->tablename = $info['TABLE_NAME'];
foreach ( $rows as $row ) {
if ( $row !== null ) {
foreach ( $row as $k => $v ) {
- if ( is_object( $v ) && method_exists( $v, 'format' ) ) {// DateTime Object
+ if ( is_object( $v ) && method_exists( $v, 'format' ) ) { // DateTime Object
$row[$k] = $v->format( "Y-m-d\TH:i:s\Z" );
}
}
- $this->mRows[] = $row;// read results into memory, cursors are not supported
+ $this->mRows[] = $row; // read results into memory, cursors are not supported
}
}
$this->mRowCount = count( $this->mRows );
}
}
}
+
return $obj;
}
}
$this->mCursor++;
+
return $ret;
}
public function fieldname( $nr ) {
$arrKeys = array_keys( $this->mRows[0] );
+
return $arrKeys[$nr];
}
default:
$strType = $intType;
}
+
return $strType;
}
* @see Database
*/
class DatabaseMysql extends DatabaseMysqlBase {
-
/**
* @param $sql string
* @return resource
} else {
$ret = mysql_unbuffered_query( $sql, $this->mConn );
}
+
return $ret;
}
*/
function selectDB( $db ) {
$this->mDBname = $db;
+
return mysql_select_db( $db, $this->mConn );
}
substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
wfProfileOut( __METHOD__ );
+
return $this->reportConnectionError( $error );
}
"from client host " . wfHostname() . "\n" );
wfProfileOut( __METHOD__ );
+
return $this->reportConnectionError( "Error selecting database $dbName" );
}
}
$this->mOpened = true;
wfProfileOut( __METHOD__ );
+
return true;
}
if ( $errno == 2000 || $errno == 2013 ) {
throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
}
+
return $row;
}
if ( $errno == 2000 || $errno == 2013 ) {
throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
}
+
return $row;
}
wfSuppressWarnings();
$n = $this->mysqlNumRows( $res );
wfRestoreWarnings();
+
// Unfortunately, mysql_num_rows does not reset the last errno.
// We are not checking for any errors here, since
// these are no errors mysql_num_rows can cause.
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return $this->mysqlNumFields( $res );
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return $this->mysqlFieldName( $res, $n );
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return $this->mysqlDataSeek( $res, $row );
}
if ( $error ) {
$error .= ' (' . $this->mServer . ')';
}
+
return $error;
}
foreach ( $res as $plan ) {
$rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
}
+
return $rows;
}
return new MySQLField( $meta );
}
}
+
return false;
}
$result[] = $row;
}
}
+
return empty( $result ) ? false : $result;
}
$this->ping();
$sQuoted = $this->mysqlRealEscapeString( $s );
}
+
return $sQuoted;
}
$this->mOpened = false;
$this->mConn = false;
$this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
+
return true;
}
function getLag() {
if ( !is_null( $this->mFakeSlaveLag ) ) {
wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
+
return $this->mFakeSlaveLag;
}
$row->State != 'Waiting to reconnect after a failed master event read' &&
$row->State != 'Reconnecting after a failed master event read' &&
$row->State != 'Registering slave on master'
- ) {
+ ) {
# This is it, return the time (except -ve)
if ( $row->Time > 0x7fffffff ) {
return false;
}
}
}
+
return false;
}
if ( !is_null( $this->mFakeSlaveLag ) ) {
$status = parent::masterPosWait( $pos, $timeout );
wfProfileOut( __METHOD__ );
+
return $status;
}
}
wfProfileOut( __METHOD__ );
+
return $status;
}
if ( $row ) {
$pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
+
return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
} else {
return false;
$this->delimiter = $m[1];
$newLine = '';
}
+
return parent::streamStatementEnd( $sql, $newLine );
}
$lockName = $this->addQuotes( $lockName );
$result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
$row = $this->fetchObject( $result );
+
return ( $row->lockstatus == 1 );
}
return true;
} else {
wfDebug( __METHOD__ . " failed to acquire lock\n" );
+
return false;
}
}
$lockName = $this->addQuotes( $lockName );
$result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
$row = $this->fetchObject( $result );
+
return ( $row->lockstatus == 1 );
}
foreach ( $write as $table ) {
$tbl = $this->tableName( $table ) .
- ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
- ' WRITE';
+ ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
+ ' WRITE';
$items[] = $tbl;
}
foreach ( $read as $table ) {
}
$sql = "LOCK TABLES " . implode( ',', $items );
$this->query( $sql, $method );
+
return true;
}
*/
public function unlockTables( $method ) {
$this->query( "UNLOCK TABLES", $method );
+
return true;
}
*/
function getServerUptime() {
$vars = $this->getMysqlStatus( 'Uptime' );
+
return (int)$vars['Uptime'];
}
if ( !$this->tableExists( $tableName, $fName ) ) {
return false;
}
+
return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
}
$vars = parent::getDefaultSchemaVars();
$vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
$vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
+
return $vars;
}
/**
* Lists VIEWs in the database
*
- * @param string $prefix Only show VIEWs with this prefix, eg.
+ * @param string $prefix Only show VIEWs with this prefix, eg.
* unit_test_, or $wgDBprefix. Default: null, would return all views.
- * @param string $fname Name of calling function
+ * @param string $fname Name of calling function
* @return array
* @since 1.22
*/
array_push( $filteredViews, $viewName );
}
}
+
return $filteredViews;
}
public function isView( $name, $prefix = null ) {
return in_array( $name, $this->listViews( $prefix ) );
}
-
}
-
-
/**
* Utility class.
* @ingroup Database
if ( preg_match( '!\.(\d+)/(\d+)$!', (string)$this, $m ) ) {
return array( (int)$m[1], (int)$m[2] );
}
+
return false;
}
function hasReached( MySQLMasterPos $pos ) {
$thisPos = $this->getCoordinates();
$thatPos = $pos->getCoordinates();
+
return ( $thisPos && $thatPos && $thisPos >= $thatPos );
}
}
* @see Database
*/
class DatabaseMysqli extends DatabaseMysqlBase {
-
/**
* @param $sql string
* @return resource
} else {
$ret = $this->mConn->query( $sql, MYSQLI_USE_RESULT );
}
+
return $ret;
}
usleep( 1000 );
}
if ( $mysqli->real_connect( $realServer, $this->mUser,
- $this->mPassword, $this->mDBname, null, null, $connFlags ) )
- {
+ $this->mPassword, $this->mDBname, null, null, $connFlags )
+ ) {
return $mysqli;
}
}
*/
function selectDB( $db ) {
$this->mDBname = $db;
+
return $this->mConn->select_db( $db );
}
protected function mysqlFreeResult( $res ) {
$res->free_result();
+
return true;
}
if ( $object === null ) {
return false;
}
+
return $object;
}
if ( $array === null ) {
return false;
}
+
return $array;
}
$field->unique_key = $field->flags & MYSQLI_UNIQUE_KEY_FLAG;
$field->multiple_key = $field->flags & MYSQLI_MULTIPLE_KEY_FLAG;
$field->binary = $field->flags & MYSQLI_BINARY_FLAG;
+
return $field;
}
protected function mysqlFieldName( $res, $n ) {
$field = $res->fetch_field_direct( $n );
+
return $field->name;
}
protected function mysqlPing() {
return $this->mConn->ping();
}
-
}
function __construct( &$db, $stmt, $unique = false ) {
$this->db =& $db;
- if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, - 1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
+ if ( ( $this->nrows = oci_fetch_all( $stmt, $this->rows, 0, -1, OCI_FETCHSTATEMENT_BY_ROW | OCI_NUM ) ) === false ) {
$e = oci_error( $stmt );
$db->reportQueryError( $e['message'], $e['code'], '', __METHOD__ );
$this->free();
+
return;
}
$ret[$lc] = $v;
$ret[$k] = $v;
}
+
return $ret;
}
}
function cascadingDeletes() {
return true;
}
+
function cleanupTriggers() {
return true;
}
+
function strictIPs() {
return true;
}
+
function realTimestamps() {
return true;
}
+
function implicitGroupby() {
return false;
}
+
function implicitOrderby() {
return false;
}
+
function searchableIPs() {
return true;
}
$this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
$this->doQuery( 'ALTER SESSION SET NLS_TIMESTAMP_TZ_FORMAT=\'DD-MM-YYYY HH24:MI:SS.FF6\'' );
$this->doQuery( 'ALTER SESSION SET NLS_NUMERIC_CHARACTERS=\'.,\'' );
+
return $this->mConn;
}
if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
$e = oci_error( $this->mConn );
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
}
$e = oci_error( $stmt );
if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
}
}
return new ORAResult( $this, $stmt, $union_unique );
} else {
$this->mAffectedRows = oci_num_rows( $stmt );
+
return true;
}
}
} else {
$e = oci_error( $this->mConn );
}
+
return $e['message'];
}
} else {
$e = oci_error( $this->mConn );
}
+
return $e['code'];
}
if ( is_numeric( $col ) ) {
$bind = $val;
$val = null;
+
return $bind;
} elseif ( $includeCol ) {
$bind = "$col = ";
if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
$e = oci_error( $this->mConn );
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
}
foreach ( $row as $col => &$val ) {
if ( oci_bind_by_name( $stmt, ":$col", $val, -1, SQLT_CHR ) === false ) {
$e = oci_error( $stmt );
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
}
} else {
if ( $col_type == 'BLOB' ) {
$lob[$col]->writeTemporary( $val, OCI_TEMP_BLOB );
- oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_BLOB );
+ oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_BLOB );
} else {
$lob[$col]->writeTemporary( $val, OCI_TEMP_CLOB );
- oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
+ oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
}
}
}
$e = oci_error( $stmt );
if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
} else {
$this->mAffectedRows = oci_num_rows( $stmt );
}
function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
- $insertOptions = array(), $selectOptions = array() )
- {
+ $insertOptions = array(), $selectOptions = array()
+ ) {
$destTable = $this->tableName( $destTable );
if ( !is_array( $selectOptions ) ) {
$selectOptions = array( $selectOptions );
}
if ( ( $sequenceData = $this->getSequenceData( $destTable ) ) !== false &&
- !isset( $varMap[$sequenceData['column']] ) )
- {
+ !isset( $varMap[$sequenceData['column']] )
+ ) {
$varMap[$sequenceData['column']] = 'GET_SEQUENCE_VALUE(\'' . $sequenceData['sequence'] . '\')';
}
function tableNameInternal( $name ) {
$name = $this->tableName( $name );
+
return preg_replace( '/.*\.(.*)/', '$1', $name );
}
+
/**
* Return the next in a sequence, save the value for retrieval via insertId()
* @return null
$res = $this->query( "SELECT $seqName.nextval FROM dual" );
$row = $this->fetchRow( $res );
$this->mInsertId = $row[0];
+
return $this->mInsertId;
}
}
}
$table = strtolower( $this->removeIdentifierQuotes( $this->tableName( $table ) ) );
+
return ( isset( $this->sequenceData[$table] ) ) ? $this->sequenceData[$table] : false;
}
# Returns the size of a text field, or -1 for "unlimited"
function textFieldSize( $table, $field ) {
$fieldInfoData = $this->fieldInfo( $table, $field );
+
return $fieldInfoData->maxLength();
}
if ( $offset === false ) {
$offset = 0;
}
+
return "SELECT * FROM ($sql) WHERE rownum >= (1 + $offset) AND rownum < (1 + $limit + $offset)";
}
if ( $b instanceof Blob ) {
$b = $b->fetch();
}
+
return $b;
}
function unionQueries( $sqls, $all ) {
$glue = ' UNION ALL ';
+
return 'SELECT * ' . ( $all ? '' : '/* UNION_UNIQUE */ ' ) . 'FROM (' . implode( $glue, $sqls ) . ')';
}
if ( !( $row = $rset->fetchRow() ) ) {
return oci_server_version( $this->mConn );
}
+
return $row['version'];
}
} else {
$count = 0;
}
+
return $count != 0;
}
}
$res->free();
+
return $exists;
}
if ( oci_execute( $fieldInfoStmt, $this->execFlags() ) === false ) {
$e = oci_error( $fieldInfoStmt );
$this->reportQueryError( $e['message'], $e['code'], 'fieldInfo QUERY', __METHOD__ );
+
return false;
}
$res = new ORAResult( $this, $fieldInfoStmt );
$this->mFieldInfoCache["$table.$field"] = $fieldInfoTemp;
}
$res->free();
+
return $fieldInfoTemp;
}
if ( is_array( $table ) ) {
throw new DBUnexpectedError( $this, 'DatabaseOracle::fieldInfo called with table array!' );
}
+
return $this->fieldInfoMulti( $table, $field );
}
$replacements = array();
- while ( ! feof( $fp ) ) {
+ while ( !feof( $fp ) ) {
if ( $lineCallback ) {
call_user_func( $lineCallback );
}
if ( $sl < 0 ) {
continue;
}
- if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
+ if ( '-' == $line{0} && '-' == $line{1} ) {
continue;
}
$dollarquote = true;
}
} elseif ( !$dollarquote ) {
- if ( ';' == $line { $sl } && ( $sl < 2 || ';' != $line { $sl - 1 } ) ) {
+ if ( ';' == $line{$sl} && ( $sl < 2 || ';' != $line{$sl - 1} ) ) {
$done = true;
$line = substr( $line, 0, $sl );
}
if ( false === $res ) {
$err = $this->lastError();
+
return "Query \"{$cmd}\" failed with error code \"$err\".\n";
}
}
$done = false;
}
}
+
return true;
}
if ( $e['code'] != '1435' ) {
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
}
+
return false;
}
+
return true;
}
if ( isset( $wgContLang->mLoaded ) && $wgContLang->mLoaded ) {
$s = $wgContLang->checkTitleEncoding( $s );
}
+
return "'" . $this->strencode( $s ) . "'";
}
if ( !$this->getFlag( DBO_DDLMODE ) ) {
$s = '/*Q*/' . $s;
}
+
return $s;
}
$conds2[$col] = $val;
}
}
+
return $conds2;
}
if ( is_array( $conds ) ) {
$conds = $this->wrapConditionsForWhere( $table, $conds );
}
+
return parent::selectRow( $table, $vars, $conds, $fname, $options, $join_conds );
}
$startOpts .= 'DISTINCT';
}
- if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
+ if ( isset( $options['USE INDEX'] ) && !is_array( $options['USE INDEX'] ) ) {
$useIndex = $this->useIndexClause( $options['USE INDEX'] );
} else {
$useIndex = '';
// all deletions on these tables have transactions so final failure rollbacks these updates
$table = $this->tableName( $table );
if ( $table == $this->tableName( 'user' ) ) {
- $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
- $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
- $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
- $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
- $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
- $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
- $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
- $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
- $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
+ $this->update( 'archive', array( 'ar_user' => 0 ), array( 'ar_user' => $conds['user_id'] ), $fname );
+ $this->update( 'ipblocks', array( 'ipb_user' => 0 ), array( 'ipb_user' => $conds['user_id'] ), $fname );
+ $this->update( 'image', array( 'img_user' => 0 ), array( 'img_user' => $conds['user_id'] ), $fname );
+ $this->update( 'oldimage', array( 'oi_user' => 0 ), array( 'oi_user' => $conds['user_id'] ), $fname );
+ $this->update( 'filearchive', array( 'fa_deleted_user' => 0 ), array( 'fa_deleted_user' => $conds['user_id'] ), $fname );
+ $this->update( 'filearchive', array( 'fa_user' => 0 ), array( 'fa_user' => $conds['user_id'] ), $fname );
+ $this->update( 'uploadstash', array( 'us_user' => 0 ), array( 'us_user' => $conds['user_id'] ), $fname );
+ $this->update( 'recentchanges', array( 'rc_user' => 0 ), array( 'rc_user' => $conds['user_id'] ), $fname );
+ $this->update( 'logging', array( 'log_user' => 0 ), array( 'log_user' => $conds['user_id'] ), $fname );
} elseif ( $table == $this->tableName( 'image' ) ) {
- $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
+ $this->update( 'oldimage', array( 'oi_name' => 0 ), array( 'oi_name' => $conds['img_name'] ), $fname );
}
+
return parent::delete( $table, $conds, $fname );
}
if ( ( $this->mLastResult = $stmt = oci_parse( $this->mConn, $sql ) ) === false ) {
$e = oci_error( $this->mConn );
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
}
foreach ( $values as $col => &$val ) {
if ( oci_bind_by_name( $stmt, ":$col", $val ) === false ) {
$e = oci_error( $stmt );
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
}
} else {
if ( $col_type == 'BLOB' ) {
$lob[$col]->writeTemporary( $val );
- oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, SQLT_BLOB );
+ oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, SQLT_BLOB );
} else {
$lob[$col]->writeTemporary( $val );
- oci_bind_by_name( $stmt, ":$col", $lob[$col], - 1, OCI_B_CLOB );
+ oci_bind_by_name( $stmt, ":$col", $lob[$col], -1, OCI_B_CLOB );
}
}
}
$e = oci_error( $stmt );
if ( !$this->ignore_DUP_VAL_ON_INDEX || $e['code'] != '1' ) {
$this->reportQueryError( $e['message'], $e['code'], $sql, __METHOD__ );
+
return false;
} else {
$this->mAffectedRows = oci_num_rows( $stmt );
$delim, $table, $field, $conds = '', $join_conds = array()
) {
$fld = "LISTAGG($field," . $this->addQuotes( $delim ) . ") WITHIN GROUP (ORDER BY $field)";
+
return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
}
public function getInfinity() {
return '31-12-2030 12:00:00.000000';
}
-
} // end DatabaseOracle class
$n->conname = $row->conname;
$n->has_default = ( $row->atthasdef === 't' );
$n->default = $row->adsrc;
+
return $n;
}
function conname() {
return $this->conname;
}
+
/**
* @since 1.19
*/
return false;
}
}
-
}
/**
}
$old = next( $this->mCurrentState );
$new = next( $this->mNewState );
-
}
}
}
$this->didbegin = false;
/* If we are not in a transaction, we need to be for savepoint trickery */
if ( !$dbw->trxLevel() ) {
- $dbw->begin( "FOR SAVEPOINT" );
- $this->didbegin = true;
+ $dbw->begin( "FOR SAVEPOINT" );
+ $this->didbegin = true;
}
}
global $wgDebugDBTransactions;
if ( $this->dbw->doQuery( $keyword . " " . $this->id ) !== false ) {
if ( $wgDebugDBTransactions ) {
- wfDebug( sprintf ( $msg_ok, $this->id ) );
+ wfDebug( sprintf( $msg_ok, $this->id ) );
}
} else {
- wfDebug( sprintf ( $msg_failed, $this->id ) );
+ wfDebug( sprintf( $msg_failed, $this->id ) );
}
}
function cascadingDeletes() {
return true;
}
+
function cleanupTriggers() {
return true;
}
+
function strictIPs() {
return true;
}
+
function realTimestamps() {
return true;
}
+
function implicitGroupby() {
return false;
}
+
function implicitOrderby() {
return false;
}
+
function searchableIPs() {
return true;
}
+
function functionalIndexes() {
return true;
}
function hasConstraint( $name ) {
$SQL = "SELECT 1 FROM pg_catalog.pg_constraint c, pg_catalog.pg_namespace n WHERE c.connamespace = n.oid AND conname = '" .
- pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $this->getCoreSchema() ) . "'";
+ pg_escape_string( $this->mConn, $name ) . "' AND n.nspname = '" . pg_escape_string( $this->mConn, $this->getCoreSchema() ) . "'";
$res = $this->doQuery( $SQL );
+
return $this->numRows( $res );
}
foreach ( $vars as $name => $value ) {
$s .= "$name='" . str_replace( "'", "\\'", $value ) . "' ";
}
+
return $s;
}
if ( pg_result_error( $this->mLastResult ) ) {
return false;
}
+
return $this->mLastResult;
}
protected function dumpError() {
- $diags = array( PGSQL_DIAG_SEVERITY,
- PGSQL_DIAG_SQLSTATE,
- PGSQL_DIAG_MESSAGE_PRIMARY,
- PGSQL_DIAG_MESSAGE_DETAIL,
- PGSQL_DIAG_MESSAGE_HINT,
- PGSQL_DIAG_STATEMENT_POSITION,
- PGSQL_DIAG_INTERNAL_POSITION,
- PGSQL_DIAG_INTERNAL_QUERY,
- PGSQL_DIAG_CONTEXT,
- PGSQL_DIAG_SOURCE_FILE,
- PGSQL_DIAG_SOURCE_LINE,
- PGSQL_DIAG_SOURCE_FUNCTION );
+ $diags = array(
+ PGSQL_DIAG_SEVERITY,
+ PGSQL_DIAG_SQLSTATE,
+ PGSQL_DIAG_MESSAGE_PRIMARY,
+ PGSQL_DIAG_MESSAGE_DETAIL,
+ PGSQL_DIAG_MESSAGE_HINT,
+ PGSQL_DIAG_STATEMENT_POSITION,
+ PGSQL_DIAG_INTERNAL_POSITION,
+ PGSQL_DIAG_INTERNAL_QUERY,
+ PGSQL_DIAG_CONTEXT,
+ PGSQL_DIAG_SOURCE_FILE,
+ PGSQL_DIAG_SOURCE_LINE,
+ PGSQL_DIAG_SOURCE_FUNCTION
+ );
foreach ( $diags as $d ) {
wfDebug( sprintf( "PgSQL ERROR(%d): %s\n", $d, pg_result_error_field( $this->mLastResult, $d ) ) );
}
/* Check for constraint violation */
if ( $errno === '23505' ) {
parent::reportQueryError( $error, $errno, $sql, $fname, $tempIgnore );
+
return;
}
}
if ( pg_last_error( $this->mConn ) ) {
throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
}
+
return $row;
}
if ( pg_last_error( $this->mConn ) ) {
throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
}
+
return $row;
}
if ( pg_last_error( $this->mConn ) ) {
throw new DBUnexpectedError( $this, 'SQL error: ' . htmlspecialchars( pg_last_error( $this->mConn ) ) );
}
+
return $n;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return pg_num_fields( $res );
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return pg_field_name( $res, $n );
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return pg_result_seek( $res, $row );
}
return 'No database connection';
}
}
+
function lastErrno() {
if ( $this->mLastResult ) {
return pg_result_error_field( $this->mLastResult, PGSQL_DIAG_SQLSTATE );
if ( empty( $this->mLastResult ) ) {
return 0;
}
+
return pg_affected_rows( $this->mLastResult );
}
$rows = $count[1];
}
}
+
return $rows;
}
return $row;
}
}
+
return false;
}
} else {
return null;
}
+
return $a;
}
foreach ( $res as $row ) {
return true;
}
+
return false;
}
* @return bool
*/
function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = __METHOD__,
- $insertOptions = array(), $selectOptions = array() )
- {
+ $insertOptions = array(), $selectOptions = array() ) {
$destTable = $this->tableName( $destTable );
if ( !is_array( $insertOptions ) ) {
}
$sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
- " SELECT $startOpts " . implode( ',', $varMap ) .
- " FROM $srcTable $useIndex";
+ " SELECT $startOpts " . implode( ',', $varMap ) .
+ " FROM $srcTable $useIndex";
if ( $conds != '*' ) {
$sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
$res = $this->query( "SELECT nextval('$safeseq')" );
$row = $this->fetchRow( $res );
$this->mInsertId = $row[0];
+
return $this->mInsertId;
}
$res = $this->query( "SELECT currval('$safeseq')" );
$row = $this->fetchRow( $res );
$currval = $row[0];
+
return $currval;
}
} else {
$size = $row->size;
}
+
return $size;
}
function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__ ) {
$newName = $this->addIdentifierQuotes( $newName );
$oldName = $this->addIdentifierQuotes( $oldName );
+
return $this->query( 'CREATE ' . ( $temporary ? 'TEMPORARY ' : '' ) . " TABLE $newName (LIKE $oldName INCLUDING DEFAULTS)", $fname );
}
$text, $match, 0, $offset );
$offset += strlen( $match[0] );
$output[] = ( '"' != $match[1][0]
- ? $match[1]
- : stripcslashes( substr( $match[1], 1, -1 ) ) );
+ ? $match[1]
+ : stripcslashes( substr( $match[1], 1, -1 ) ) );
if ( '},' == $match[3] ) {
return $output;
}
$offset = $this->pg_array_parse( $text, $output, $limit, $offset + 1 );
}
} while ( $limit > $offset );
+
return $output;
}
function getCurrentSchema() {
$res = $this->query( "SELECT current_schema()", __METHOD__ );
$row = $this->fetchRow( $res );
+
return $row[0];
}
$res = $this->query( "SELECT current_schemas(false)", __METHOD__ );
$row = $this->fetchRow( $res );
$schemas = array();
+
/* PHP pgsql support does not support array type, "{a,b}" string is returned */
+
return $this->pg_array_parse( $row[0], $schemas );
}
function getSearchPath() {
$res = $this->query( "SHOW search_path", __METHOD__ );
$row = $this->fetchRow( $res );
+
/* PostgreSQL returns SHOW values as strings */
+
return explode( ",", $row[0] );
}
*/
$search_path = $this->getSearchPath();
array_unshift( $search_path,
- $this->addIdentifierQuotes( $desired_schema ));
+ $this->addIdentifierQuotes( $desired_schema ) );
$this->setSearchPath( $search_path );
$this->mCoreSchema = $desired_schema;
wfDebug( "Schema \"" . $desired_schema . "\" added to the search path\n" );
$this->numeric_version = pg_parameter_status( $this->mConn, 'server_version' );
}
}
+
return $this->numeric_version;
}
. "AND c.relkind IN ('" . implode( "','", $types ) . "')";
$res = $this->query( $SQL );
$count = $res ? $res->numRows() : 0;
+
return (bool)$count;
}
return null;
}
$rows = $res->numRows();
+
return $rows;
}
'schemaname' => $this->getCoreSchema()
)
);
+
return $exists === $rule;
}
function constraintExists( $table, $constraint ) {
$SQL = sprintf( "SELECT 1 FROM information_schema.table_constraints " .
- "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
+ "WHERE constraint_schema = %s AND table_name = %s AND constraint_name = %s",
$this->addQuotes( $this->getCoreSchema() ),
$this->addQuotes( $table ),
$this->addQuotes( $constraint )
return null;
}
$rows = $res->numRows();
+
return $rows;
}
function schemaExists( $schema ) {
$exists = $this->selectField( '"pg_catalog"."pg_namespace"', 1,
array( 'nspname' => $schema ), __METHOD__ );
+
return (bool)$exists;
}
function roleExists( $roleName ) {
$exists = $this->selectField( '"pg_catalog"."pg_roles"', 1,
array( 'rolname' => $roleName ), __METHOD__ );
+
return (bool)$exists;
}
if ( $res instanceof ResultWrapper ) {
$res = $res->result;
}
+
return pg_field_type( $res, $index );
}
if ( $b instanceof Blob ) {
$b = $b->fetch();
}
+
return pg_unescape_bytea( $b );
}
} elseif ( $s instanceof Blob ) {
return "'" . $s->fetch( $s ) . "'";
}
+
return "'" . pg_escape_string( $this->mConn, $s ) . "'";
}
$delimiter, $table, $field, $conds = '', $options = array(), $join_conds = array()
) {
$fld = "array_to_string(array_agg($field)," . $this->addQuotes( $delimiter ) . ')';
+
return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
}
if ( substr( $newLine, 0, 4 ) == '$mw$' ) {
if ( $this->delimiter ) {
$this->delimiter = false;
- }
- else {
+ } else {
$this->delimiter = ';';
}
}
+
return parent::streamStatementEnd( $sql, $newLine );
}
$result = $this->query( "SELECT (CASE(pg_try_advisory_lock($key))
WHEN 'f' THEN 'f' ELSE pg_advisory_unlock($key) END) AS lockstatus", $method );
$row = $this->fetchObject( $result );
+
return ( $row->lockstatus === 't' );
}
}
}
wfDebug( __METHOD__ . " failed to acquire lock\n" );
+
return false;
}
$key = $this->addQuotes( $this->bigintFromLockName( $lockName ) );
$result = $this->query( "SELECT pg_advisory_unlock($key) as lockstatus", $method );
$row = $this->fetchObject( $result );
+
return ( $row->lockstatus === 't' );
}
* @ingroup Database
*/
class DatabaseSqlite extends DatabaseBase {
-
private static $fulltextEnabled = null;
var $mAffectedRows;
throw new DBConnectionError( $this, "SQLite database not accessible" );
}
$this->openFile( $fileName );
+
return $this->mConn;
}
$this->mConn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT );
# Enforce LIKE to be case sensitive, just like MySQL
$this->query( 'PRAGMA case_sensitive_like = 1' );
+
return true;
}
}
*/
protected function closeConnection() {
$this->mConn = null;
+
return true;
}
self::$fulltextEnabled = stristr( $row['sql'], 'fts' ) !== false;
}
}
+
return self::$fulltextEnabled;
}
$cachedResult = 'FTS3';
}
$db->close();
+
return $cachedResult;
}
$file = self::generateFileName( $wgSQLiteDataDir, $name );
}
$file = $this->addQuotes( $file );
+
return $this->query( "ATTACH DATABASE $file AS $name", $fname );
}
$this->mAffectedRows = $r->rowCount();
$res = new ResultWrapper( $this, $r->fetchAll() );
}
+
return $res;
}
return $obj;
}
+
return false;
}
$cur = current( $r );
if ( is_array( $cur ) ) {
next( $r );
+
return $cur;
}
+
return false;
}
*/
function numRows( $res ) {
$r = $res instanceof ResultWrapper ? $res->result : $res;
+
return count( $r );
}
*/
function numFields( $res ) {
$r = $res instanceof ResultWrapper ? $res->result : $res;
+
return is_array( $r ) ? count( $r[0] ) : 0;
}
$r = $res instanceof ResultWrapper ? $res->result : $res;
if ( is_array( $r ) ) {
$keys = array_keys( $r[0] );
+
return $keys[$n];
}
+
return false;
}
if ( strpos( $name, 'sqlite_' ) === 0 ) {
return $name;
}
+
return str_replace( '"', '', parent::tableName( $name, $format ) );
}
return "Cannot return last error, no db connection";
}
$e = $this->mConn->errorInfo();
+
return isset( $e[2] ) ? $e[2] : '';
}
return "Cannot return last error, no db connection";
} else {
$info = $this->mConn->errorInfo();
+
return $info[1];
}
}
foreach ( $res as $row ) {
$info[] = $row->name;
}
+
return $info;
}
}
$firstPart = substr( $row->sql, 0, $indexPos );
$options = explode( ' ', $firstPart );
+
return in_array( 'UNIQUE', $options );
}
$options[$k] = '';
}
}
+
return parent::makeSelectOptions( $options );
}
*/
function makeUpdateOptions( $options ) {
$options = self::fixIgnore( $options );
+
return parent::makeUpdateOptions( $options );
}
$options[$k] = 'OR IGNORE';
}
}
+
return $options;
}
*/
function makeInsertOptions( $options ) {
$options = self::fixIgnore( $options );
+
return parent::makeInsertOptions( $options );
}
*/
function unionQueries( $sqls, $all ) {
$glue = $all ? ' UNION ALL ' : ' UNION ';
+
return implode( $glue, $sqls );
}
*/
function getServerVersion() {
$ver = $this->mConn->getAttribute( PDO::ATTR_SERVER_VERSION );
+
return $ver;
}
return new SQLiteField( $row, $tableName );
}
}
+
return false;
}
* @return string
*/
function strencode( $s ) {
- return substr( $this->addQuotes( $s ), 1, - 1 );
+ return substr( $this->addQuotes( $s ), 1, -1 );
}
/**
if ( $b instanceof Blob ) {
$b = $b->fetch();
}
+
return $b;
}
if ( count( $params ) > 0 && is_array( $params[0] ) ) {
$params = $params[0];
}
+
return parent::buildLike( $params ) . "ESCAPE '\' ";
}
public function deadlockLoop( /*...*/ ) {
$args = func_get_args();
$function = array_shift( $args );
+
return call_user_func_array( $function, $args );
}
// DROP INDEX is database-wide, not table-specific, so no ON <table> clause.
$s = preg_replace( '/\sON\s+[^\s]*/i', '', $s );
}
+
return $s;
}
$delim, $table, $field, $conds = '', $join_conds = array()
) {
$fld = "group_concat($field," . $this->addQuotes( $delim ) . ')';
+
return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
}
$sql = str_replace( 'CREATE TABLE', 'CREATE TEMPORARY TABLE', $sql );
}
}
+
return $this->query( $sql, $fname );
}
if ( strpos( $table, 'sqlite_' ) !== 0 ) {
$endArray[] = $table;
}
-
}
}
return $endArray;
}
-
} // end DatabaseSqlite class
/**
*/
class SQLiteField implements Field {
private $info, $tableName;
+
function __construct( $info, $tableName ) {
$this->info = $info;
$this->tableName = $tableName;
return str_replace( "''", "'", $this->info->dflt_value );
}
}
+
return $this->info->dflt_value;
}
function type() {
return $this->info->type;
}
-
} // end SQLiteField
if ( is_null( $this->currentRow ) ) {
$this->next();
}
+
return $this->currentRow;
}
function next() {
$this->pos++;
$this->currentRow = $this->fetchObject();
+
return $this->currentRow;
}
*/
interface IORMRow {
-
/**
* Load the specified fields from the database.
*
* @return IORMTable
*/
public function getTable();
-
}
*/
interface IORMTable {
-
/**
* Returns the name of the database table objects of this type are stored in.
*
* @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode)
*/
public function select( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null );
+ array $options = array(), $functionName = null );
/**
* Selects the the specified fields of the records matching the provided
* @return array of self
*/
public function selectObjects( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null );
+ array $options = array(), $functionName = null );
/**
* Do the actual select.
* @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode)
*/
public function rawSelect( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null );
+ array $options = array(), $functionName = null );
/**
* Selects the the specified fields of the records matching the provided
* @return array of array
*/
public function selectFields( $fields = null, array $conditions = array(),
- array $options = array(), $collapse = true, $functionName = null );
+ array $options = array(), $collapse = true, $functionName = null );
/**
* Selects the the specified fields of the first matching record.
* @return IORMRow|bool False on failure
*/
public function selectRow( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null );
+ array $options = array(), $functionName = null );
/**
* Selects the the specified fields of the records matching the provided
* @return ResultWrapper
*/
public function rawSelectRow( array $fields, array $conditions = array(),
- array $options = array(), $functionName = null );
+ array $options = array(), $functionName = null );
/**
* Selects the the specified fields of the first record matching the provided
* @return mixed|array|bool False on failure
*/
public function selectFieldsRow( $fields = null, array $conditions = array(),
- array $options = array(), $collapse = true, $functionName = null );
+ array $options = array(), $collapse = true, $functionName = null );
/**
* Returns if there is at least one record matching the provided conditions.
* @return boolean
*/
public function canHaveField( $name );
-
}
* @ingroup Database
*/
abstract class LBFactory {
-
/**
* @var LBFactory
*/
$class = $wgLBFactoryConf['class'];
self::$instance = new $class( $wgLBFactoryConf );
}
+
return self::$instance;
}
'type' => $wgDBtype,
'load' => 1,
'flags' => $flags
- ));
+ ) );
}
return new LoadBalancer( array(
'servers' => $servers,
'masterWaitTimeout' => $wgMasterWaitTimeout
- ));
+ ) );
}
/**
$this->mainLB->parentInfo( array( 'id' => 'main' ) );
$this->chronProt->initLB( $this->mainLB );
}
+
return $this->mainLB;
}
if ( !isset( $wgExternalServers[$cluster] ) ) {
throw new MWException( __METHOD__ . ": Unknown cluster \"$cluster\"" );
}
+
return new LoadBalancer( array(
'servers' => $wgExternalServers[$cluster]
- ));
+ ) );
}
/**
$this->extLBs[$cluster]->parentInfo( array( 'id' => "ext-$cluster" ) );
$this->chronProt->initLB( $this->extLBs[$cluster] );
}
+
return $this->extLBs[$cluster];
}
}
$this->lastSection = $section;
$this->lastWiki = $wiki;
+
return $section;
}
if ( isset( $this->groupLoadsBySection[$section] ) ) {
$groupLoads = array_merge_recursive( $groupLoads, $this->groupLoadsBySection[$section] );
}
+
return $this->newLoadBalancer( $this->serverTemplate, $this->sectionLoads[$section], $groupLoads );
}
$this->chronProt->initLB( $lb );
$this->mainLBs[$section] = $lb;
}
+
return $this->mainLBs[$section];
}
if ( isset( $this->templateOverridesByCluster[$cluster] ) ) {
$template = $this->templateOverridesByCluster[$cluster] + $template;
}
+
return $this->newLoadBalancer( $template, $this->externalLoads[$cluster], array() );
}
$this->extLBs[$cluster]->parentInfo( array( 'id' => "ext-$cluster" ) );
$this->chronProt->initLB( $this->extLBs[$cluster] );
}
+
return $this->extLBs[$cluster];
}
$lb = new LoadBalancer( array(
'servers' => $servers,
'masterWaitTimeout' => $wgMasterWaitTimeout
- ));
+ ) );
+
return $lb;
}
$serverInfo['load'] = $load;
$servers[] = $serverInfo;
}
+
return $servers;
}
$reindexed[$server][$group] = $load;
}
}
+
return $reindexed;
}
function getDBNameAndPrefix( $wiki = false ) {
if ( $wiki === false ) {
global $wgDBname, $wgDBprefix;
+
return array( $wgDBname, $wgDBprefix );
} else {
return wfSplitWikiID( $wiki );
$class = $this->mLoadMonitorClass;
$this->mLoadMonitor = new $class( $this );
}
+
return $this->mLoadMonitor;
}
# No loads for this group, return false and the caller can use some other group
wfDebug( __METHOD__ . ": no loads for group $group\n" );
wfProfileOut( __METHOD__ );
+
return false;
}
} else {
# wants us to return false.
wfDebugLog( 'connect', __METHOD__ . ": pickRandom() returned false\n" );
wfProfileOut( __METHOD__ );
+
return false;
}
}
}
wfProfileOut( __METHOD__ );
+
return $i;
}
wfDebug( __METHOD__ . ": waiting $t us\n" );
usleep( $t );
wfProfileOut( __METHOD__ );
+
return $t;
}
return reset( $conns[$i] );
}
}
+
return false;
}
if ( !$conn ) {
if ( !$open ) {
wfDebug( __METHOD__ . ": no connection open\n" );
+
return false;
} else {
$conn = $this->openConnection( $index, '' );
if ( !$conn ) {
wfDebug( __METHOD__ . ": failed to open connection\n" );
+
return false;
}
}
if ( $result == -1 || is_null( $result ) ) {
# Timed out waiting for slave, use master instead
wfDebug( __METHOD__ . ": Timed out waiting for slave #$index pos {$this->mWaitForPos}\n" );
+
return false;
} else {
wfDebug( __METHOD__ . ": Done\n" );
+
return true;
}
}
if ( $i === false ) {
$this->mLastError = 'No working slave server: ' . $this->mLastError;
wfProfileOut( __METHOD__ );
+
return $this->reportConnectionError();
}
}
$conn = $this->openConnection( $i, $wiki );
if ( !$conn ) {
wfProfileOut( __METHOD__ );
+
return $this->reportConnectionError();
}
wfProfileOut( __METHOD__ );
+
return $conn;
}
}
if ( $serverIndex === null || $refCount === null ) {
wfDebug( __METHOD__ . ": this connection was not opened as a foreign connection\n" );
+
/**
* This can happen in code like:
* foreach ( $dbs as $db ) {
* When a connection to the local DB is opened in this way, reuseConnection()
* should be ignored
*/
+
return;
}
if ( $this->mConns['foreignUsed'][$serverIndex][$wiki] !== $conn ) {
if ( $wiki !== false ) {
$conn = $this->openForeignConnection( $i, $wiki );
wfProfileOut( __METHOD__ );
+
return $conn;
}
if ( isset( $this->mConns['local'][$i][0] ) ) {
}
}
wfProfileOut( __METHOD__ );
+
return $conn;
}
$conn->setLBInfo( 'foreignPoolRefCount', $refCount + 1 );
}
wfProfileOut( __METHOD__ );
+
return $conn;
}
if ( !is_integer( $index ) ) {
return false;
}
+
return (bool)$this->getAnyOpenConnection( $index );
}
if ( isset( $server['fakeMaster'] ) ) {
$db->setFakeMaster( true );
}
+
return $db;
}
wfLogDBError( "Connection error: {$this->mLastError} ({$server})\n" );
$conn->reportConnectionError( "{$this->mLastError} ({$server})" ); // throws DBConnectionError
}
+
return false; /* not reached */
}
$conn = $this->getAnyOpenConnection( $i );
if ( $conn ) {
wfDebug( "Master pos fetched from slave\n" );
+
return $conn->getSlavePos();
}
}
} else {
wfDebug( "Master pos fetched from master\n" );
+
return $masterConn->getMasterPos();
}
+
return false;
}
return $this->mAllowLagged;
}
$this->mAllowLagged = $mode;
+
return $this->mAllowLagged;
}
}
}
}
+
return $success;
}
}
}
}
+
return array( $host, $maxLag, $maxIndex );
}
$this->mLagTimes = $this->getLoadMonitor()->getLagTimes(
array_keys( $this->mServers ), $wiki );
}
+
return $this->mLagTimes;
}
list( $db, $groups, $wiki ) = $this->params;
$this->conn = $this->lb->getConnection( $db, $groups, $wiki );
}
+
return call_user_func_array( array( $this->conn, $name ), $arguments );
}
if ( mt_rand( 0, $chance ) != 0 ) {
unset( $times['timestamp'] ); // hide from caller
wfProfileOut( __METHOD__ );
+
return $times;
}
wfIncrStats( 'lag_cache_miss_expired' );
# Cache key missing or expired
if ( $wgMemc->add( "$memcKey:lock", 1, 10 ) ) {
# Let this process alone update the cache value
- $unlocker = new ScopedCallback( function() use ( $wgMemc, $memcKey ) {
+ $unlocker = new ScopedCallback( function () use ( $wgMemc, $memcKey ) {
$wgMemc->delete( $memcKey );
} );
} elseif ( is_array( $times ) ) {
# Could not acquire lock but an old cache exists, so use it
unset( $times['timestamp'] ); // hide from caller
wfProfileOut( __METHOD__ );
+
return $times;
}
unset( $times['timestamp'] ); // hide from caller
wfProfileOut( __METHOD__ );
+
return $times;
}
if ( $status['Threads_running'] > $threshold ) {
$server = $conn->getProperty( 'mServer' );
wfLogDBError( "LB backoff from $server - Threads_running = {$status['Threads_running']}\n" );
+
return $status['Threads_connected'];
} else {
return 0;
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
interface ORMIterator extends Iterator {
-
}
*/
class ORMResult implements ORMIterator {
-
/**
* @var ResultWrapper
*/
public function valid() {
return $this->current !== false;
}
-
}
*/
class ORMRow implements IORMRow {
-
/**
* The fields of the object.
* field name (w/o prefix) => value
if ( $result !== false ) {
$this->setFields( $this->table->getFieldsFromDBResult( $result ), $override );
+
return true;
}
+
return false;
}
* @return boolean
*/
public function hasIdField() {
- return $this->hasField( 'id' )
- && !is_null( $this->getField( 'id' ) );
+ return $this->hasField( 'id' ) && !is_null( $this->getField( 'id' ) );
}
/**
$value = $this->fields[$name];
// Skip null id fields so that the DBMS can set the default.
- if ( $name === 'id' && is_null ( $value ) ) {
+ if ( $name === 'id' && is_null( $value ) ) {
continue;
}
* @param array|string|null $summaryFields
*/
public function loadSummaryFields( $summaryFields = null ) {
-
}
/**
public function getTable() {
return $this->table;
}
-
}
*/
class ORMTable extends DBAccessBase implements IORMTable {
-
/**
* Cache for instances, used by the singleton method.
*
* @return ORMResult
*/
public function select( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null ) {
+ array $options = array(), $functionName = null
+ ) {
$res = $this->rawSelect( $fields, $conditions, $options, $functionName );
+
return new ORMResult( $this, $res );
}
* @throws DBQueryError if the query failed (even if the database was in ignoreErrors mode).
*/
public function selectObjects( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null ) {
+ array $options = array(), $functionName = null
+ ) {
$result = $this->selectFields( $fields, $conditions, $options, false, $functionName );
$objects = array();
* @since 1.20
*
* @param null|string|array $fields
- * @param array $conditions
- * @param array $options
- * @param null|string $functionName
+ * @param array $conditions
+ * @param array $options
+ * @param null|string $functionName
*
* @return ResultWrapper
* @throws DBQueryError if the quey failed (even if the database was in ignoreErrors mode).
*/
public function rawSelect( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null ) {
+ array $options = array(), $functionName = null
+ ) {
if ( is_null( $fields ) ) {
$fields = array_keys( $this->getFields() );
- }
- else {
+ } else {
$fields = (array)$fields;
}
* @return array of array
*/
public function selectFields( $fields = null, array $conditions = array(),
- array $options = array(), $collapse = true, $functionName = null ) {
+ array $options = array(), $collapse = true, $functionName = null
+ ) {
$objects = array();
$result = $this->rawSelect( $fields, $conditions, $options, $functionName );
if ( $collapse ) {
if ( count( $fields ) === 1 ) {
$objects = array_map( 'array_shift', $objects );
- }
- elseif ( count( $fields ) === 2 ) {
+ } elseif ( count( $fields ) === 2 ) {
$o = array();
foreach ( $objects as $object ) {
* @return IORMRow|bool False on failure
*/
public function selectRow( $fields = null, array $conditions = array(),
- array $options = array(), $functionName = null ) {
+ array $options = array(), $functionName = null
+ ) {
$options['LIMIT'] = 1;
$objects = $this->select( $fields, $conditions, $options, $functionName );
* @return ResultWrapper
*/
public function rawSelectRow( array $fields, array $conditions = array(),
- array $options = array(), $functionName = null ) {
+ array $options = array(), $functionName = null
+ ) {
$dbr = $this->getReadDbConnection();
$result = $dbr->selectRow(
);
$this->releaseConnection( $dbr );
+
return $result;
}
* @return mixed|array|bool False on failure
*/
public function selectFieldsRow( $fields = null, array $conditions = array(),
- array $options = array(), $collapse = true, $functionName = null ) {
+ array $options = array(), $collapse = true, $functionName = null
+ ) {
$options['LIMIT'] = 1;
$objects = $this->selectFields( $fields, $conditions, $options, $collapse, $functionName );
) !== false; // DatabaseBase::delete does not always return true for success as documented...
$this->releaseConnection( $dbw );
+
return $result;
}
) !== false; // DatabaseBase::update does not always return true for success as documented...
$this->releaseConnection( $dbw );
+
return $result;
}
if ( is_array( $value ) ) {
$field = $value[0];
$value = $value[1];
- }
- else {
+ } else {
$value = explode( ' ', $value, 2 );
$value[0] = $this->getPrefixedField( $value[0] );
$prefixedValues[] = implode( ' ', $value );
return $success;
}
-
}