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
2017-09-24 17:30:01 -07:00

82 lines
1.5 KiB
Go

package postgres
import (
_ "github.com/lib/pq"
"bytes"
"database/sql"
"text/template"
"github.com/kcotugno/tacitus"
)
const connStr = `user={{.User}} dbname={{.Name}} sslmode={{.SslMode}}`
type Client struct {
Name string
User string
SslMode string
tradeService TradeService
logger tacitus.Logger
db *sql.DB
}
func NewClient() *Client {
c := Client{}
c.tradeService.client = &c
c.SslMode = "disable"
return &c
}
func (c *Client) SetLogger(logger tacitus.Logger) {
c.logger = logger
}
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 {
c.log(`Failed to connect to postgres. params=%v`, buf.String())
return err
}
if err = db.Ping(); err != nil {
c.log(`Failed to connect to postgres. params=%v`, buf.String())
return err
}
c.log(`Conntected to postgres. params="%v"`, buf.String())
c.db = db
return nil
}
func (c *Client) Close() error {
err := c.db.Close()
c.log("Closed postgres connection")
return err
}
func (c *Client) TradeService() tacitus.TradeService {
return &c.tradeService
}
func (c *Client) log(format string, params ...interface{}) {
if c.logger != nil {
c.logger.Info(format, params...)
}
}
func (c *Client) logQuery(sql string, params ...interface{}) {
c.log(`SQL query="%v" params="%v"`, sql, params)
}
func (c *Client) logError(sql string, err error, params ...interface{}) {
c.log(`SQL FAIL query="%v" params="%v" error="%v"`, sql, params, err)
}