通过 Rails 中的 database_url 和 Unix 套接字连接到 Postgres



我已经为此四处寻找,只是找不到解决方案。

目前,我有一个数据库.yml成功连接到Unix套接字上的本地pgbouncer服务器。但是,我正在过渡到将其设置为database_url环境变量,并且根本无法弄清楚如何通过Unix套接字连接到本地Postgres服务器。本地主机显然工作正常。

我正在查看一个看起来像这样的 URL,因为显然您可以将其与 Postgres (http://www.postgresql.org/docs/9.2/interactive/libpq-connect.html) 一起使用:

export DATABASE_URL="postgresql://username@%Fvar%Frun%Fpostgresql%F.s.PGSQL.6432/dbname"

但是,这不会通过 URI 警察:

rubies/ruby-2.1.5/lib/ruby/2.1.0/uri/common.rb:176:in `split': bad URI(is not URI?): postgresql://username@%Fvar%Frun%Fpostgresql%F.s.PGSQL.6432/dbname

有没有人知道这需要的秘诀?我无休止地谷歌,什么也没找到。这必须是可能的,因为应用程序当前现在通过套接字连接。

提前感谢,

31.1.1.2. 连接 URI

连接 URI 的一般形式为:

postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]`

URI 方案指示符可以是 postgresql://的,也可以是 postgres://的。 每个 URI 部分都是可选的。以下示例说明 有效的 URI 语法使用:

postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb 
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp

URI 的分层部分的组件也可以作为 参数。例如:

postgresql:///mydb?host=localhost&port=5433

百分比编码可用于包含具有特殊含义的符号 在任何 URI 部分中。

与 中列出的关键字不对应的任何连接参数 忽略第 31.1.2 节,并向 斯特德。

为了改进与 JDBC 连接 URI 的兼容性,实例 参数ssl=true转换为sslmode=require

主机部分可以是主机名或 IP 地址。要指定 IPv6 主机地址,将其括在方括号中:

postgresql://[2001:db8::1234]/database
主机

组件将按照参数主机的说明进行解释。 特别是,如果主机 部分为空或以斜杠开头,否则为 TCP/IP 连接已启动。但请注意,斜杠是保留的 URI 的分层部分中的字符。因此,要指定一个非标准Unix域套接字目录,要么省略主机URI 中的规范,并将主机指定为参数,或URI 的主机组件中的路径进行百分比编码:

postgresql:///dbname?host=/var/lib/postgresql
postgresql://%2Fvar%2Flib%2Fpostgresql/dbname

您必须省略主机才能使用 unix 套接字,如下所示:

postgres://username@/dbname

或者干脆

postgres:///dbname

这适用于 psql> 9.2。

我不确定它是否适用于数据库 URL 的轨道处理。

您可以将套接字作为查询参数传递:

postgresql://user@host/database?socket=/path/to/socket

如果一般使用libpq,@blnc提供的答案是正确的。但是,如果您使用的是Activerecord或RubyonRails,至少在版本3.2.21中,该模块会将URI解析为Ruby的URI.parse,而不是直接将其交给libpq。URI.parse 无法处理此处的空主机名。

irb(main):020:0> URI.parse "postgresql://user:pass@host/dbname"
=> #<URI::Generic:0x7f72b17f04d8 URL:postgresql://user:pass@host/dbname>

但是,没有主机:

irb(main):021:0> URI.parse "postgresql://user:pass@/dbname"
URI::InvalidURIError: the scheme postgresql does not accept registry part: user:pass@ (or bad hostname?)
        from /usr/lib/ruby/1.8/uri/generic.rb:195:in `initialize'
        from /usr/lib/ruby/1.8/uri/common.rb:492:in `new'
        from /usr/lib/ruby/1.8/uri/common.rb:492:in `parse'
        from (irb):21
        from /usr/lib/ruby/1.8/uri/generic.rb:556

如果不添加自定义 URI 解析代码(或更改活动记录),似乎无法解决此问题。

在具有默认路径的 Archlinux 上unix_socket_directories

postgres:///<dbname>?host=/run/postgresql/

最新更新