protected function _connect()
{
$database = $hostname = $port = $socket = $username = $password = $persistent = $schema = null;
extract($this->config['connection']);
if (!$port>0)
{
$port = 5432;
}
# 检查下是否已经有连接连上去了
if (Database_Driver_Postgre::$_connection_instance)
{
if (is_array($hostname))
{
$hostconfig = $hostname[$this->_connection_type];
if (!$hostconfig)
{
throw new Exception('指定的数据库连接主从配置中('.$this->_connection_type.')不存在,请检查配置');
}
if (!is_array($hostconfig))
{
$hostconfig = array($hostconfig);
}
}
else
{
$hostconfig = array
(
$hostname
);
}
# 先检查是否已经有相同的连接连上了数据库
foreach ($hostconfig as $host)
{
$_connection_id = $this->_get_connection_hash($host, $port, $username, array('database'=>$database));
if (isset(Database_Driver_Postgre::$_connection_instance[$_connection_id]))
{
$this->_connection_ids[$this->_connection_type] = $_connection_id;
return;
}
}
}
# 错误服务器
static $error_host = array();
$last_error = null;
while (true)
{
$hostname = $this->_get_rand_host($error_host);
if (false===$hostname)
{
Core::debug()->error($error_host, 'error_host');
if ($last_error)throw $last_error;
throw new Exception('connect postgre server error.');
}
$_connection_id = $this->_get_connection_hash($hostname, $port, $username, array('database'=>$database));
Database_Driver_Postgre::$_current_connection_id_to_hostname[$_connection_id] = $hostname.':'.$port;
try
{
$dsn = Database_Driver_Postgre::_get_dsn($database, $hostname, $port, $socket, $username, $password, $persistent, $this->config['connection']);
$time = microtime(true);
try
{
if ($persistent)
{
# 持久连接
$tmplink = pg_pconnect($dsn);
if ($tmplink && pg_connection_status($tmplink) === PGSQL_CONNECTION_BAD && false===pg_ping($tmplink))
{
throw new Exception('postgre pconnect server error.');
}
}
else
{
$tmplink = pg_connect($dsn);
}
}
catch (Exception $e)
{
$tmplink = false;
}
if (false===$tmplink)
{
if (IS_DEBUG)throw $e;
throw new Exception('connect postgre server error.');
}
if ($schema)
{
@pg_query($tmplink, 'SET search_path TO '.$schema.',public');
}
Core::debug()->info('postgre://'.$username.'@'.$hostname.':'.$port.'/'.$database.'/ connection time:' . (microtime(true) - $time));
# 连接ID
$this->_connection_ids[$this->_connection_type] = $_connection_id;
Database_Driver_Postgre::$_connection_instance[$_connection_id] = $tmplink;
Database_Driver_Postgre::$_current_databases[$_connection_id] = $database;
unset($tmplink);
break;
}
catch (Exception $e)
{
if (IS_DEBUG)
{
Core::debug()->error($username.'@'.$hostname.':'.$port.'.Msg:'.strip_tags($e->getMessage(),'').'.Code:'.$e->getCode(), 'connect postgre server error');
$last_error = new Exception($e->getMessage(), $e->getCode());
}
else
{
$last_error = new Exception('connect postgre server error', $e->getCode());
}
if (!in_array($hostname, $error_host))
{
$error_host[] = $hostname;
}
}
}
}