From 13a6cdd66c7eabe4313b6f532d77b64f66393fc6 Mon Sep 17 00:00:00 2001 From: Jack Christensen Date: Fri, 9 May 2014 09:36:09 -0500 Subject: [PATCH] Add ParseURI --- connection.go | 29 +++++++++++++++++++++++ connection_test.go | 57 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) diff --git a/connection.go b/connection.go index 6249080f..65ee971e 100644 --- a/connection.go +++ b/connection.go @@ -15,6 +15,7 @@ import ( "io" "io/ioutil" "net" + "net/url" "os/user" "path/filepath" "strconv" @@ -217,6 +218,34 @@ func (c *Connection) Close() (err error) { return err } +// ParseURI parses a database URI into ConnectionParameters +func ParseURI(uri string) (ConnectionParameters, error) { + var cp ConnectionParameters + + url, err := url.Parse(uri) + if err != nil { + return cp, err + } + + if url.User != nil { + cp.User = url.User.Username() + cp.Password, _ = url.User.Password() + } + + parts := strings.SplitN(url.Host, ":", 2) + cp.Host = parts[0] + if len(parts) == 2 { + p, err := strconv.ParseUint(parts[1], 10, 16) + if err != nil { + return cp, err + } + cp.Port = uint16(p) + } + cp.Database = strings.TrimLeft(url.Path, "/") + + return cp, nil +} + // SelectFunc executes sql and for each row returned calls onDataRow. sql can be // either a prepared statement name or an SQL string. arguments will be sanitized // before being interpolated into sql strings. arguments should be referenced diff --git a/connection_test.go b/connection_test.go index 2e424a97..f6a934b2 100644 --- a/connection_test.go +++ b/connection_test.go @@ -158,6 +158,63 @@ func TestConnectWithMD5Password(t *testing.T) { } } +func TestParseURI(t *testing.T) { + tests := []struct { + url string + connParams pgx.ConnectionParameters + }{ + { + url: "postgres://jack:secret@localhost:5432/mydb", + connParams: pgx.ConnectionParameters{ + User: "jack", + Password: "secret", + Host: "localhost", + Port: 5432, + Database: "mydb", + }, + }, + { + url: "postgresql://jack:secret@localhost:5432/mydb", + connParams: pgx.ConnectionParameters{ + User: "jack", + Password: "secret", + Host: "localhost", + Port: 5432, + Database: "mydb", + }, + }, + { + url: "postgres://jack@localhost:5432/mydb", + connParams: pgx.ConnectionParameters{ + User: "jack", + Host: "localhost", + Port: 5432, + Database: "mydb", + }, + }, + { + url: "postgres://jack@localhost/mydb", + connParams: pgx.ConnectionParameters{ + User: "jack", + Host: "localhost", + Database: "mydb", + }, + }, + } + + for i, tt := range tests { + connParams, err := pgx.ParseURI(tt.url) + if err != nil { + t.Errorf("%d. Unexpected error from pgx.ParseURL(%q) => %v", i, tt.url, err) + continue + } + + if connParams != tt.connParams { + t.Errorf("%d. expected %#v got %#v", i, tt.connParams, connParams) + } + } +} + func TestExecute(t *testing.T) { conn := getSharedConnection(t)