This repository has been archived on 2022-11-30. You can view files and clone it, but cannot push or open issues or pull requests.
tacitus/postgres/client.go

75 lines
1.3 KiB
Go
Raw Normal View History

2017-09-07 23:04:47 -07:00
package postgres
import (
_ "github.com/lib/pq"
"bytes"
"database/sql"
"text/template"
"tacitus"
)
const connStr = `user={{.User}} dbname={{.Name}} sslmode={{.SslMode}}`
type Client struct {
Name string
User string
SslMode string
tradeService TradeService
2017-09-10 13:04:02 -07:00
logger tacitus.Logger
2017-09-07 23:04:47 -07:00
db *sql.DB
}
func NewClient() *Client {
c := Client{}
c.tradeService.client = &c
c.SslMode = "disable"
return &c
}
2017-09-10 13:04:02 -07:00
func (c *Client) SetLogger(logger tacitus.Logger) {
c.logger = logger
c.tradeService.Logger = logger
}
2017-09-07 23:04:47 -07:00
func (c *Client) Open() error {
buf := bytes.Buffer{}
tmpl, _ := template.New("conn").Parse(connStr)
tmpl.Execute(&buf, c)
db, err := sql.Open("postgres", buf.String())
if err != nil {
2017-09-10 13:04:02 -07:00
c.log(`Failed to connect to postgres. params=%v`, buf.String())
2017-09-07 23:04:47 -07:00
return err
}
if err = db.Ping(); err != nil {
2017-09-10 13:04:02 -07:00
c.log(`Failed to connect to postgres. params=%v`, buf.String())
2017-09-07 23:04:47 -07:00
return err
}
2017-09-10 13:04:02 -07:00
c.log(`Conntected to postgres. params="%v"`, buf.String())
2017-09-07 23:04:47 -07:00
c.db = db
return nil
}
2017-09-10 13:04:02 -07:00
func (c *Client) Close() error {
err := c.db.Close()
c.log("Closed postgres connection")
return err
}
2017-09-07 23:04:47 -07:00
func (c *Client) TradeService() tacitus.TradeService {
return &c.tradeService
}
2017-09-10 13:04:02 -07:00
func (c *Client) log(format string, params ...interface{}) {
if c.logger != nil {
c.logger.Info(format, params...)
}
}