/
postgres.go
51 lines (43 loc) · 901 Bytes
/
postgres.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package postgres
import (
"database/sql"
"fmt"
"time"
)
type Config struct {
Password string
User string
Name string
Host string
SSLMode string
}
type psqlService struct {
db *sql.DB
}
// Open opens a postgres database and returns a service to interact with it.
func Open(config Config) (*psqlService, error) {
connStr := fmt.Sprintf(
"user=%s password=%s dbname=%s host=%s sslmode=%s",
config.User,
config.Password,
config.Name,
config.Host,
config.SSLMode,
)
db, err := sql.Open("postgres", connStr)
if err != nil {
return nil, err
}
return &psqlService{db}, nil
}
func (psql *psqlService) Close() error {
return psql.db.Close()
}
func (psql *psqlService) QueryNow() (time.Time, error) {
var currentTime time.Time
err := psql.db.QueryRow("SELECT NOW()").Scan(¤tTime)
if err != nil {
return time.Time{}, err
}
return currentTime, err
}