Skip to content

Commit 4aafd60

Browse files
authored
docs: explain connecting to unix domain sockets /var/postgresql (#32)
Fixes #27 by adding a FAQ entry to the README explaining how to connect to a server over unix domain socket. Although [the Postgres documentation](https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-HOST) explains that you can use a `?host=%2Fvar%2Fpostgres` connection string option instead of specifying the host in the URL, I didn't know this and I imagine most people also are unfamiliar with this option. And, although the documentation says that you can pass a URL-encoded host in the connection string and just expect it to work, that doesn't happen with `sql.Open` — it always fails. So, thanks @ptman for opening the issue and discovering the solution, this PR just adds that information to the README.
1 parent acc1091 commit 4aafd60

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,32 @@ func TestCustom(t *testing.T) {
639639
}
640640
```
641641

642+
## How do I connect to a database over unix domain socket like `/run/postgresql`?
643+
644+
To connect to a database that is listening on a domain socket, for instance `/run/postgresql`, you
645+
will need to pass the socket path as a `host={socket path}` options parameter.
646+
647+
The [Postgresql documentation](https://www.postgresql.org/docs/current/libpq-connect.html#:~:text=The%20host%20part%20is%20interpreted%20as%20described%20for%20the%20parameter%20host.) describes two ways of connecting to socket paths using a `postgres://...` connection string:
648+
649+
> So, to specify a non-standard Unix-domain socket directory, **either omit the host part of the URI and specify the host as a named parameter**, or percent-encode the path in the host part of the URI
650+
651+
but due to the way the golang `sql.Open` is implemented, percent-encoding the path in the `Config.Host` field won't work.
652+
653+
So, you need to set `host={socket path}` (with appropriate URL encoding) in the `Config.Options` field:
654+
655+
```go
656+
conf := pgtestdb.Config{
657+
// The same approach works for both "postgres" (lib/pq) and "pgx" (pgx)
658+
DriverName: "pgx",
659+
User: "postgres",
660+
Port: "5432",
661+
Password: "password",
662+
// %2F is a url-encoded '/' character
663+
Options: "host=%2Frun%2Fpostgresql",
664+
Database: "postgres",
665+
}
666+
```
667+
642668
## Does this mean I should stop writing unit tests and doing dependency injection?
643669
No! Please keep writing unit tests and doing dependency injection and mocking
644670
and all the other things that make your code well-organized and easily

0 commit comments

Comments
 (0)