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) } func (c *Client) log(format string, params ...interface{}) { if c.Logger != nil { c.Logger.Info(format, params...) } }