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

104 lines
2.1 KiB
Go

package postgres
import (
_ "github.com/lib/pq"
"bytes"
"database/sql"
"text/template"
"github.com/kcotugno/tacitus"
)
const connStr = `host={{.Host}} dbname={{.Name}} port={{.Port}} user={{.User}} ` +
`password={{.Password}} sslmode={{.SslMode}}`
type Client struct {
Host string
Port int
Name string
User string
SslMode string
Password string
tradeService TradeService
confirmationService ConfirmationService
aggregationService AggregationService
logger tacitus.Logger
db *sql.DB
}
func NewClient() *Client {
c := Client{}
c.tradeService.client = &c
c.confirmationService.client = &c
c.aggregationService.client = &c
c.Host = "localhost"
c.Port = 5432
c.Name = "postgres"
c.User = "postgres"
c.Password = `""`
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) ConfirmationService() tacitus.ConfirmationService {
return &c.confirmationService
}
func (c *Client) AggregationService() tacitus.AggregationService {
return &c.aggregationService
}
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)
}