-
Notifications
You must be signed in to change notification settings - Fork 0
/
postgres.go
84 lines (75 loc) · 2.14 KB
/
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package postgres
import (
"database/sql"
"os"
"strconv"
_ "github.com/lib/pq"
)
type PostgresDatabase interface {
Open() (db *sql.DB, err error)
Close(db *sql.DB) (err error)
BeginTx(db *sql.DB) (tx *sql.Tx, err error)
Commit(tx *sql.Tx) (err error)
Rollback(tx *sql.Tx) (err error)
Exec(tx *sql.Tx, query string, args ...interface{}) (result sql.Result, err error)
Query(tx *sql.Tx, query string, args ...interface{}) (rows *sql.Rows, err error)
}
type PostgresConfiguration struct {
Host string
Port int
User string
Password string
Database string
}
func NewPostgresConfiguration(host string, port int, user string, password string, database string) (configuration *PostgresConfiguration) {
configuration = &PostgresConfiguration{
Host: host,
Port: port,
User: user,
Password: password,
Database: database,
}
return
}
func NewDefaultPostgresConfiguration() (configuration *PostgresConfiguration) {
configuration = &PostgresConfiguration{
Host: "localhost",
Port: 5432,
User: "postgres",
Password: "postgres",
Database: "stori-challenge-db",
}
return
}
func NewPostgresConfigurationFromEnv() (configuration *PostgresConfiguration) {
host := os.Getenv("POSTGRES_HOST")
if host == "" {
// return default configuration
return NewDefaultPostgresConfiguration()
}
port, err := strconv.Atoi(os.Getenv("POSTGRES_PORT"))
if err != nil {
// return default configuration
return NewDefaultPostgresConfiguration()
}
user := os.Getenv("POSTGRES_USER")
password := os.Getenv("POSTGRES_PASSWORD")
database := os.Getenv("POSTGRES_DATABASE")
configuration = &PostgresConfiguration{
Host: host,
Port: port,
User: user,
Password: password,
Database: database,
}
return
}
func (configuration *PostgresConfiguration) GetDataSourceName() (dataSourceName string) {
dataSourceName = "host=" + configuration.Host
dataSourceName += " port=" + strconv.Itoa(configuration.Port)
dataSourceName += " user=" + configuration.User
dataSourceName += " password=" + configuration.Password
dataSourceName += " dbname=" + configuration.Database
dataSourceName += " sslmode=disable"
return
}