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

问题描述 投票:0回答:6

我已经四处寻找这个问题,但找不到解决方案。

目前我有一个database.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

有人知道这需要什么秘方吗?我无休无止地用谷歌搜索,但没有找到任何东西。这一定是可能的,因为应用程序当前通过套接字连接。

提前致谢,

rails-activerecord
6个回答
29
投票

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

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

postgresql:///dbname?host=/var/lib/postgresql

postgresql://%2Fvar%2Flib%2Fpostgresql/dbname

24
投票

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

postgres://username@/dbname

或者简单地

postgres:///dbname

这适用于 psql > 9.2。

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


2
投票

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

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

2
投票

如果一般使用

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 解析代码(或更改 activerecord),似乎无法解决此问题。


1
投票

在 Archlinux 上,默认路径为

unix_socket_directories
:

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

0
投票

我的解析服务器也遇到同样的问题。

该死的。

使用node-postgres,我可以传递socket://var/run/postgresql?db=parse,它工作得很好。但解析服务器代码将“socket”一词解释为“mongodb”。

© www.soinside.com 2019 - 2024. All rights reserved.