/
postgres.go
72 lines (58 loc) · 1.77 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
package postgres
import (
"database/sql"
"fmt"
"github.com/alexsniffin/go-api-example/internal/api/config"
_ "github.com/lib/pq"
"github.com/rs/zerolog/log"
)
//PostgresClient todo
type PostgresClient struct {
connection *sql.DB
}
//NewPostgresClient todo
func NewPostgresClient(config *config.Config) *PostgresClient {
postgresClient := &PostgresClient{}
db, err := postgresClient.CreateConnection(config)
if err != nil {
log.Panic().Msg("Failed to initialize postgres connection")
}
for i := 0; i < len(config.Cfg.Database.Tables); i++ {
var check interface{}
err = db.QueryRow("SELECT to_regclass($1)", config.Cfg.Database.Tables[i]).Scan(&check)
if err != nil {
log.Panic().Err(err).Msgf("Failed to check if %s table exists", config.Cfg.Database.Tables[i])
}
if check == nil {
log.Panic().Err(err).Msg(fmt.Sprintf("Missing required table on postgresdb: host=%s dbname=%s", config.Cfg.Database.Host, config.Cfg.Database.DbName))
} else {
log.Info().Msg(fmt.Sprintf("Existing table found on postgresdb: host=%s dbname=%s", config.Cfg.Database.Host, config.Cfg.Database.DbName))
}
}
postgresClient.connection = db
return postgresClient
}
//GetConnection todo
func (p *PostgresClient) GetConnection() *sql.DB {
return p.connection
}
//CreateConnection todo
func (p *PostgresClient) CreateConnection(config *config.Config) (*sql.DB, error) {
connStr := fmt.Sprintf(
"user=%s dbname=%s password=%s host=%s port=%d sslmode=disable",
config.Cfg.Database.User,
config.Cfg.Database.DbName,
config.Cfg.Database.Password,
config.Cfg.Database.Host,
config.Cfg.Database.Port,
)
return sql.Open("postgres", connStr)
}
//Shutdown todo
func (p *PostgresClient) Shutdown() error {
err := p.connection.Close()
if err != nil {
return err
}
return nil
}