ThinkPHP 不能直接通过内置 pgsql 驱动连接 openGauss,因其协议细节存在 runtime 不兼容:强制 sha256 认证、系统视图结构差异、SQL 函数返回格式不一致及 standard_conforming_strings 默认关闭,导致连接中断或查询异常;必须使用 openGauss 官方 opengauss.so 扩展并手动封装自定义驱动类,覆盖 connect() 和 getDsn() 方法,配合服务端 pg_hba.conf、postgresql.conf 和防火墙配置方可稳定运行。

mysql 或 pgsql 驱动连接 openGauss —— 它不识别 openGauss 的协议差异,强行配成 pgsql 类型会报错或查询异常。
openGauss 虽然兼容 PostgreSQL 协议,但实际行为有关键偏离:默认开启 sha256 密码认证、部分系统视图结构不同、pg_type 枚举处理更严格。ThinkPHP 的 PDO PostgreSQL 驱动未适配这些细节,直接复用会导致连接中断或 SQLSTATE[08006] [7] 类错误。
为什么不能直接把 openGauss 当作 PostgreSQL 配置
ThinkPHP 的 pgsql 驱动底层调用的是 PHP 原生 pdo_pgsql 扩展,它依赖 PostgreSQL 官方协议栈。而 openGauss 在以下几点与标准 PostgreSQL 存在 runtime 不兼容:
- 认证阶段强制
sha256(PostgreSQL 10+ 默认scram-sha-256,旧版可 fallback 到md5); -
pg_stat_activity等监控视图字段名或类型有微小差异,ThinkPHP 的 schema 检测逻辑可能失败; - 某些 SQL 函数如
current_database()返回值格式不一致,影响多库切换逻辑; - openGauss 默认关闭
standard_conforming_strings,导致带反斜杠的字符串解析出错。
你改 type 为 pgsql 后能连上,但执行 Db::table('user')->select() 很可能卡在 getFields() 或抛出 PDOException: SQLSTATE[42703]: Undefined column。
必须启用 openGauss 官方 PHP 扩展(非 PDO)
openGauss 提供了独立的 opengauss.so 扩展(非 pdo_opengauss),它绕过 PDO 层,直连 openGauss 协议栈,支持完整认证流程和类型映射。这是目前唯一稳定方式:
- 确认已从 openGauss 官网 下载对应 PHP 版本的
opengauss.so(注意区分 x86_64 / aarch64 和 PHP 8.1/8.2/8.3); - 将扩展放入
extension_dir,并在php.ini中添加:extension=opengauss.so; - 重启 PHP-FPM 或 Apache,运行
php -m | grep opengauss验证加载成功; - 该扩展不提供 PDO 接口,因此 ThinkPHP 无法原生识别 —— 必须封装为自定义驱动。
手动注册 OpenGauss 驱动类(ThinkPHP 6.x)
你需要新建一个驱动类,继承 think\db\connector\Pgsql 并覆盖关键方法,让 ThinkPHP “以为”这是 PostgreSQL,但底层用 openGauss 扩展连接:
- 在
app/common/db/connector/OpenGauss.php创建类,namespace app\common\db\connector;; - 重写
connect()方法:不用new \PDO(),改用og_connect($dsn)(openGauss 扩展函数); - 重写
getDsn():返回形如host=127.0.0.1 port=5432 dbname=test user=omm password=xxx的字符串,**不要加pgsql:前缀**; - 在
config/database.php中设置:'type' => 'app\common\db\connector\OpenGauss'; - 务必在
connect()内显式调用og_set_client_encoding($this->link, 'UTF8'),否则中文乱码。
示例片段:
public function connect($config = [], $linkNum = 0)
{
$this->config = array_merge($this->config, $config);
$dsn = $this->getDsn();
$this->link = og_connect($dsn);
if (!$this->link) {
throw new Exception('OpenGauss connect error: ' . og_last_error());
}
og_set_client_encoding($this->link, 'UTF8');
return $this->link;
}
远程连接前必须检查的三项配置
即使驱动写对,openGauss 服务端拒绝连接仍是高频问题:
-
pg_hba.conf中必须有匹配行:host all all 0.0.0.0/0 sha256,且该行位置不能被更严格的规则挡住; -
postgresql.conf中listen_addresses必须包含客户端 IP 所在网段,例如'192.168.1.0/24'或临时设为'0.0.0.0'; - Linux 防火墙必须放行 5432 端口:
firewall-cmd --permanent --add-port=5432/tcp && firewall-cmd --reload。
漏掉任意一项,og_connect() 都会超时或返回空链接,错误信息极不明确 —— 这是调试中最容易卡住的地方。



















