查询
$use_connection_type 默认不传为自动判断,可传true/false,若传字符串(只支持a-z0-9的字符串),则可以切换到另外一个连接,比如传other,则可以连接到$this->_connection_other_id所对应的ID的连接
Database_Driver_Postgre_Result Driver_Database_Driver_Postgre::query( string $sql [, string $as_object = null , boolean $use_connection_type = null ] )
参数列表
参数 类型 描述 默认值 $sql
string
查询语句 $as_object
string
是否返回对象 null $use_connection_type
boolean
是否使用主数据库,不设置则自动判断 null
Database_Driver_Postgre_Result
public function query($sql, $as_object=null, $use_connection_type=null)
{
$sql = trim($sql);
if (preg_match('#^([a-z]+)(:? |\n|\r)#i', $sql, $m))
{
$type = strtoupper($m[1]);
}
$typeArr = array
(
'SELECT',
'SHOW', //显示表
'EXPLAIN', //分析
'DESCRIBE', //显示结结构
'INSERT',
'REPLACE',
'UPDATE',
'DELETE',
);
if (!in_array($type, $typeArr))
{
$type = 'MASTER';
}
$slaverType = array('SELECT', 'SHOW', 'EXPLAIN');
if ($type!='MASTER' && in_array($type, $slaverType))
{
if (true===$use_connection_type)
{
$use_connection_type = 'master';
}
else if (is_string($use_connection_type))
{
if (!preg_match('#^[a-z0-9_]+$#i',$use_connection_type))$use_connection_type = 'master';
}
else
{
$use_connection_type = 'slaver';
}
}
else
{
$use_connection_type = 'master';
}
# 设置连接类型
$this->_set_connection_type($use_connection_type);
# 连接数据库
$connection = $this->connection();
# 记录调试
if(IS_DEBUG)
{
Core::debug()->info($sql, 'Postgre');
static $is_sql_debug = null;
if (null === $is_sql_debug) $is_sql_debug = (bool)Core::debug()->profiler('sql')->is_open();
if ($is_sql_debug)
{
$host = $this->_get_hostname_by_connection_hash($this->connection_id());
$benchmark = Core::debug()->profiler('sql')->start('Database', 'postgre://' . ($host['username']?$host['username'].'@':'') . $host['hostname'] . ($host['port'] && $host['port'] != '3306' ? ':' . $host['port'] : '') . $host['database']);
}
}
// Execute the query
if (($result = pg_query($connection, $sql)) === false)
{
if (isset($benchmark))
{
// This benchmark is worthless
$benchmark->delete();
}
if (IS_DEBUG)
{
$err = 'Error:' . pg_last_error($connection) . '. PostgreSQL:' . $sql;
}
else
{
$err = pg_last_error($connection);
}
throw new Exception($err);
}
if (isset($benchmark))
{
Core::debug()->profiler('sql')->stop();
}
// Set the last query
$this->last_query = $sql;
if ($type === 'INSERT' || $type === 'REPLACE')
{
// Return a list of insert id and rows created
return array
(
$this->_insert_id($connection),
pg_affected_rows($connection)
);
}
elseif ($type === 'UPDATE' || $type === 'DELETE')
{
// Return the number of rows affected
return pg_affected_rows($connection);
}
else
{
// Return an iterator of results
return new Database_Driver_Postgre_Result($result, $sql, $as_object ,$this->config);
}
}