This repository has been archived by the owner on Oct 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 215
/
client.go
79 lines (67 loc) · 1.75 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package postgres
import (
"database/sql"
"net/url"
"github.com/compose/transporter/client"
_ "github.com/lib/pq" // import pq driver
)
const (
// DefaultURI is the default endpoint of Postgres on the local machine.
// Primarily used when initializing a new Client without a specific URI.
DefaultURI = "postgres://postgres@transporter-db:5432?sslmode=disable"
)
var (
_ client.Client = &Client{}
)
// ClientOptionFunc is a function that configures a Client.
// It is used in NewClient.
type ClientOptionFunc func(*Client) error
// Client represents a client to the underlying File source.
type Client struct {
uri string
db string
pqSession *sql.DB
}
// NewClient creates a default file client
func NewClient(options ...ClientOptionFunc) (*Client, error) {
// Set up the client
c := &Client{
uri: DefaultURI,
db: "postgres",
}
// Run the options on it
for _, option := range options {
if err := option(c); err != nil {
return nil, err
}
}
return c, nil
}
// WithURI defines the full connection string for the Postgres connection
func WithURI(uri string) ClientOptionFunc {
return func(c *Client) error {
_, err := url.Parse(uri)
c.uri = uri
return err
}
}
// Close implements necessary calls to cleanup the underlying *sql.DB
func (c *Client) Close() {
if c.pqSession != nil {
c.pqSession.Close()
}
}
// Connect initializes the Postgres connection
func (c *Client) Connect() (client.Session, error) {
if c.pqSession == nil {
// there's really no way for this to error because we know the driver we're passing is
// available.
c.pqSession, _ = sql.Open("postgres", c.uri)
uri, _ := url.Parse(c.uri)
if uri.Path != "" {
c.db = uri.Path[1:]
}
}
err := c.pqSession.Ping()
return &Session{c.pqSession, c.db}, err
}