2015-10-27 11:04:19 +01:00
|
|
|
package postgresql
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"fmt"
|
2015-12-21 10:54:24 +01:00
|
|
|
|
2015-10-27 11:04:19 +01:00
|
|
|
_ "github.com/lib/pq" //PostgreSQL db
|
|
|
|
)
|
|
|
|
|
|
|
|
// Config - provider config
|
|
|
|
type Config struct {
|
|
|
|
Host string
|
|
|
|
Port int
|
|
|
|
Username string
|
|
|
|
Password string
|
2016-04-04 17:40:28 +02:00
|
|
|
SslMode string
|
2016-11-28 17:52:10 +01:00
|
|
|
Timeout int
|
2015-10-27 11:04:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Client struct holding connection string
|
|
|
|
type Client struct {
|
|
|
|
username string
|
|
|
|
connStr string
|
|
|
|
}
|
|
|
|
|
2016-09-06 00:04:48 +02:00
|
|
|
// NewClient returns new client config
|
2015-10-27 11:04:19 +01:00
|
|
|
func (c *Config) NewClient() (*Client, error) {
|
2016-11-28 17:52:10 +01:00
|
|
|
connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=postgres sslmode=%s connect_timeout=%d", c.Host, c.Port, c.Username, c.Password, c.SslMode, c.Timeout)
|
2015-10-27 11:04:19 +01:00
|
|
|
|
|
|
|
client := Client{
|
|
|
|
connStr: connStr,
|
|
|
|
username: c.Username,
|
|
|
|
}
|
|
|
|
|
|
|
|
return &client, nil
|
|
|
|
}
|
|
|
|
|
2016-09-06 00:04:48 +02:00
|
|
|
// Connect will manually connect/disconnect to prevent a large
|
|
|
|
// number or db connections being made
|
2015-10-27 11:04:19 +01:00
|
|
|
func (c *Client) Connect() (*sql.DB, error) {
|
|
|
|
db, err := sql.Open("postgres", c.connStr)
|
|
|
|
if err != nil {
|
2016-09-06 00:04:48 +02:00
|
|
|
return nil, fmt.Errorf("Error connecting to PostgreSQL server: %s", err)
|
2015-10-27 11:04:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return db, nil
|
|
|
|
}
|