add ParseDSN function

pull/76/head
deoxxa 2015-04-08 14:50:56 +10:00
parent 472929b247
commit 7e2886c576
1 changed files with 33 additions and 0 deletions

33
conn.go
View File

@ -14,6 +14,7 @@ import (
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
@ -282,6 +283,38 @@ func ParseURI(uri string) (ConnConfig, error) {
return cp, nil
}
var dsn_regexp = regexp.MustCompile(`([a-z]+)=((?:"[^"]+")|(?:[^ ]+))`)
// ParseDSN parses a database DSN (data source name) into a ConnConfig
//
// e.g. ParseDSN("user=username password=password host=1.2.3.4 port=5432 dbname=mydb")
func ParseDSN(s string) (ConnConfig, error) {
var cp ConnConfig
m := dsn_regexp.FindAllStringSubmatch(s, -1)
for _, b := range m {
switch b[1] {
case "user":
cp.User = b[2]
case "password":
cp.Password = b[2]
case "host":
cp.Host = b[2]
case "port":
if p, err := strconv.ParseUint(b[2], 10, 16); err != nil {
return cp, err
} else {
cp.Port = uint16(p)
}
case "dbname":
cp.Database = b[2]
}
}
return cp, nil
}
// Prepare creates a prepared statement with name and sql. sql can contain placeholders
// for bound parameters. These placeholders are referenced positional as $1, $2, etc.
func (c *Conn) Prepare(name, sql string) (ps *PreparedStatement, err error) {