databasec.php
来自「php 开发的内容管理系统」· PHP 代码 · 共 1,939 行 · 第 1/4 页
PHP
1,939 行
if ( !$wgCommandLineMode ) {
$message = nl2br( $message );
}
if( $wgCommandLineMode && $wgColorErrors && !wfIsWindows() && posix_isatty(1) ) {
$color = 31; // bright red!
$message = "\x1b[1;{$color}m{$message}\x1b[0m";
}
wfDebugDieBacktrace( $message );
} else {
// this calls wfAbruptExit()
$this->mOut->databaseError( $fname, $sql, $error, $errno );
}
}
$this->ignoreErrors( $ignore );
}
/**
* Intended to be compatible with the PEAR::DB wrapper functions.
* http://pear.php.net/manual/en/package.database.db.intro-execute.php
*
* ? = scalar value, quoted as necessary
* ! = raw SQL bit (a function for instance)
* & = filename; reads the file and inserts as a blob
* (we don't use this though...)
*/
function prepare( $sql, $func = 'Database::prepare' ) {
/* MySQL doesn't support prepared statements (yet), so just
pack up the query for reference. We'll manually replace
the bits later. */
return array( 'query' => $sql, 'func' => $func );
}
function freePrepared( $prepared ) {
/* No-op for MySQL */
}
/**
* Execute a prepared query with the various arguments
* @param string $prepared the prepared sql
* @param mixed $args Either an array here, or put scalars as varargs
*/
function execute( $prepared, $args = null ) {
if( !is_array( $args ) ) {
# Pull the var args
$args = func_get_args();
array_shift( $args );
}
$sql = $this->fillPrepared( $prepared['query'], $args );
return $this->query( $sql, $prepared['func'] );
}
/**
* Prepare & execute an SQL statement, quoting and inserting arguments
* in the appropriate places.
* @param string $query
* @param string $args ...
*/
function safeQuery( $query, $args = null ) {
$prepared = $this->prepare( $query, 'Database::safeQuery' );
if( !is_array( $args ) ) {
# Pull the var args
$args = func_get_args();
array_shift( $args );
}
$retval = $this->execute( $prepared, $args );
$this->freePrepared( $prepared );
return $retval;
}
/**
* For faking prepared SQL statements on DBs that don't support
* it directly.
* @param string $preparedSql - a 'preparable' SQL statement
* @param array $args - array of arguments to fill it with
* @return string executable SQL
*/
function fillPrepared( $preparedQuery, $args ) {
$n = 0;
reset( $args );
$this->preparedArgs =& $args;
return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
array( &$this, 'fillPreparedArg' ), $preparedQuery );
}
/**
* preg_callback func for fillPrepared()
* The arguments should be in $this->preparedArgs and must not be touched
* while we're doing this.
*
* @param array $matches
* @return string
* @access private
*/
function fillPreparedArg( $matches ) {
switch( $matches[1] ) {
case '\\?': return '?';
case '\\!': return '!';
case '\\&': return '&';
}
list( $n, $arg ) = each( $this->preparedArgs );
switch( $matches[1] ) {
case '?': return $this->addQuotes( $arg );
case '!': return $arg;
case '&':
# return $this->addQuotes( file_get_contents( $arg ) );
wfDebugDieBacktrace( '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
default:
wfDebugDieBacktrace( 'Received invalid match. This should never happen!' );
}
}
/**#@+
* @param mixed $res A SQL result
*/
/**
* Free a result object
*/
function freeResult( $res ) {
if ( !@/**/mysql_free_result( $res ) ) {
wfDebugDieBacktrace( "Unable to free MySQL result\n" );
}
}
/**
* Fetch the next row from the given result object, in object form
*/
function fetchObject( $res ) {
@/**/$row = mysql_fetch_object( $res );
if( mysql_errno() ) {
wfDebugDieBacktrace( 'Error in fetchObject(): ' . htmlspecialchars( mysql_error() ) );
}
return $row;
}
/**
* Fetch the next row from the given result object
* Returns an array
*/
function fetchRow( $res ) {
@/**/$row = mysql_fetch_array( $res );
if (mysql_errno() ) {
wfDebugDieBacktrace( 'Error in fetchRow(): ' . htmlspecialchars( mysql_error() ) );
}
return $row;
}
/**
* Get the number of rows in a result object
*/
function numRows( $res ) {
@/**/$n = mysql_num_rows( $res );
if( mysql_errno() ) {
wfDebugDieBacktrace( 'Error in numRows(): ' . htmlspecialchars( mysql_error() ) );
}
return $n;
}
/**
* Get the number of fields in a result object
* See documentation for mysql_num_fields()
*/
function numFields( $res ) { return mysql_num_fields( $res ); }
/**
* Get a field name in a result object
* See documentation for mysql_field_name()
*/
function fieldName( $res, $n ) { return mysql_field_name( $res, $n ); }
/**
* Get the inserted value of an auto-increment row
*
* The value inserted should be fetched from nextSequenceValue()
*
* Example:
* $id = $dbw->nextSequenceValue('page_page_id_seq');
* $dbw->insert('page',array('page_id' => $id));
* $id = $dbw->insertId();
*/
function insertId() { return mysql_insert_id( $this->mConn ); }
/**
* Change the position of the cursor in a result object
* See mysql_data_seek()
*/
function dataSeek( $res, $row ) { return mysql_data_seek( $res, $row ); }
/**
* Get the last error number
* See mysql_errno()
*/
function lastErrno() {
if ( $this->mConn ) {
return mysql_errno( $this->mConn );
} else {
return mysql_errno();
}
}
/**
* Get a description of the last error
* See mysql_error() for more details
*/
function lastError() {
if ( $this->mConn ) {
# Even if it's non-zero, it can still be invalid
wfSuppressWarnings();
$error = mysql_error( $this->mConn );
if ( !$error ) {
$error = mysql_error();
}
wfRestoreWarnings();
} else {
$error = mysql_error();
}
if( $error ) {
$error .= ' (' . $this->mServer . ')';
}
return $error;
}
/**
* Get the number of rows affected by the last write query
* See mysql_affected_rows() for more details
*/
function affectedRows() { return mysql_affected_rows( $this->mConn ); }
/**#@-*/ // end of template : @param $result
/**
* Simple UPDATE wrapper
* Usually aborts on failure
* If errors are explicitly ignored, returns success
*
* This function exists for historical reasons, Database::update() has a more standard
* calling convention and feature set
*/
function set( $table, $var, $value, $cond, $fname = 'Database::set' )
{
$table = $this->tableName( $table );
$sql = "UPDATE $table SET $var = '" .
$this->strencode( $value ) . "' WHERE ($cond)";
return (bool)$this->query( $sql, $fname );
}
/**
* Simple SELECT wrapper, returns a single field, input must be encoded
* Usually aborts on failure
* If errors are explicitly ignored, returns FALSE on failure
*/
function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
if ( !is_array( $options ) ) {
$options = array( $options );
}
$options['LIMIT'] = 1;
$res = $this->select( $table, $var, $cond, $fname, $options );
if ( $res === false || !$this->numRows( $res ) ) {
return false;
}
$row = $this->fetchRow( $res );
if ( $row !== false ) {
$this->freeResult( $res );
return $row[0];
} else {
return false;
}
}
/**
* Returns an optional USE INDEX clause to go after the table, and a
* string to go at the end of the query
*
* @access private
*
* @param array $options an associative array of options to be turned into
* an SQL query, valid keys are listed in the function.
* @return array
*/
function makeSelectOptions( $options ) {
$tailOpts = '';
if ( isset( $options['GROUP BY'] ) ) {
$tailOpts .= " GROUP BY {$options['GROUP BY']}";
}
if ( isset( $options['ORDER BY'] ) ) {
$tailOpts .= " ORDER BY {$options['ORDER BY']}";
}
if (isset($options['LIMIT'])) {
$tailOpts .= $this->limitResult('', $options['LIMIT'],
isset($options['OFFSET']) ? $options['OFFSET'] : false);
}
if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
$tailOpts .= ' FOR UPDATE';
}
if ( is_numeric( array_search( 'LOCK IN SHARE MODE', $options ) ) ) {
$tailOpts .= ' LOCK IN SHARE MODE';
}
if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
$useIndex = $this->useIndexClause( $options['USE INDEX'] );
} else {
$useIndex = '';
}
return array( $useIndex, $tailOpts );
}
/**
* SELECT wrapper
*/
function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
{
if( is_array( $vars ) ) {
$vars = implode( ',', $vars );
}
if( !is_array( $options ) ) {
$options = array( $options );
}
if( is_array( $table ) ) {
if ( @is_array( $options['USE INDEX'] ) )
$from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
else
$from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
} elseif ($table!='') {
$from = ' FROM ' . $this->tableName( $table );
} else {
$from = '';
}
list( $useIndex, $tailOpts ) = $this->makeSelectOptions( $options );
if( !empty( $conds ) ) {
if ( is_array( $conds ) ) {
$conds = $this->makeList( $conds, LIST_AND );
}
$sql = "SELECT $vars $from $useIndex WHERE $conds $tailOpts";
} else {
$sql = "SELECT $vars $from $useIndex $tailOpts";
}
return $this->query( $sql, $fname );
}
/**
* Single row SELECT wrapper
* Aborts or returns FALSE on error
*
* $vars: the selected variables
* $conds: a condition map, terms are ANDed together.
* Items with numeric keys are taken to be literal conditions
* Takes an array of selected variables, and a condition map, which is ANDed
* e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
* NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
* $obj- >page_id is the ID of the Astronomy article
*
* @todo migrate documentation to phpdocumentor format
*/
function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
$options['LIMIT'] = 1;
$res = $this->select( $table, $vars, $conds, $fname, $options );
if ( $res === false )
return false;
if ( !$this->numRows($res) ) {
$this->freeResult($res);
return false;
}
$obj = $this->fetchObject( $res );
$this->freeResult( $res );
return $obj;
}
/**
* Removes most variables from an SQL query and replaces them with X or N for numbers.
* It's only slightly flawed. Don't use for anything important.
*
* @param string $sql A SQL Query
* @static
*/
function generalizeSQL( $sql ) {
# This does the same as the regexp below would do, but in such a way
# as to avoid crashing php on some large strings.
# $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
$sql = str_replace ( "\\\\", '', $sql);
$sql = str_replace ( "\\'", '', $sql);
$sql = str_replace ( "\\\"", '', $sql);
$sql = preg_replace ("/'.*'/s", "'X'", $sql);
$sql = preg_replace ('/".*"/s', "'X'", $sql);
# All newlines, tabs, etc replaced by single space
$sql = preg_replace ( "/\s+/", ' ', $sql);
# All numbers => N
$sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
return $sql;
}
/**
* Determines whether a field exists in a table
* Usually aborts on failure
* If errors are explicitly ignored, returns NULL on failure
*/
function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
$table = $this->tableName( $table );
$res = $this->query( 'DESCRIBE '.$table, $fname );
if ( !$res ) {
return NULL;
}
$found = false;
while ( $row = $this->fetchObject( $res ) ) {
if ( $row->Field == $field ) {
$found = true;
break;
}
}
return $found;
}
/**
* Determines whether an index exists
* Usually aborts on failure
* If errors are explicitly ignored, returns NULL on failure
*/
function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
$info = $this->indexInfo( $table, $index, $fname );
if ( is_null( $info ) ) {
return NULL;
} else {
return $info !== false;
}
}
/**
* Get information about an index into an object
* Returns false if the index does not exist
*/
function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
# SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
# SHOW INDEX should work for 3.x and up:
# http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
$table = $this->tableName( $table );
$sql = 'SHOW INDEX FROM '.$table;
$res = $this->query( $sql, $fname );
if ( !$res ) {
return NULL;
}
while ( $row = $this->fetchObject( $res ) ) {
if ( $row->Key_name == $index ) {
return $row;
}
}
return false;
}
/**
* Query whether a given table exists
*/
function tableExists( $table ) {
$table = $this->tableName( $table );
$old = $this->ignoreErrors( true );
$res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
$this->ignoreErrors( $old );
if( $res ) {
$this->freeResult( $res );
return true;
} else {
return false;
}
}
/**
* mysql_fetch_field() wrapper
* Returns false if the field doesn't exist
*
* @param $table
* @param $field
*/
function fieldInfo( $table, $field ) {
$table = $this->tableName( $table );
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?