-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.go
58 lines (45 loc) · 1.19 KB
/
database.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
package db
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/tsmweb/auth-service/config"
_ "github.com/lib/pq"
)
const (
dbDriver = "postgres"
)
// var (
// instance Database
// )
// Database read only interface to access database connection.
type Database interface {
DB() *sql.DB
}
// PostgresDatabase stores a reference to the bank connection pool.
type PostgresDatabase struct {
db *sql.DB
}
// NewPostgresDatabase creates a new instance of PostgresDatabase.
func NewPostgresDatabase() Database {
connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable search_path=%s,public",
config.DBHost(), config.DBPort(), config.DBUser(), config.DBPassword(), config.DBName(), config.DBSchema())
db, err := sql.Open(dbDriver, connStr)
if err != nil {
panic(err.Error())
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err = db.PingContext(ctx); err != nil {
panic(err.Error())
}
db.SetMaxOpenConns(50)
db.SetMaxIdleConns(3)
db.SetConnMaxLifetime(time.Minute * 5)
return &PostgresDatabase{db}
}
// DB get instance of a connection to the database.
func (pd *PostgresDatabase) DB() *sql.DB {
return pd.db
}