This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 62
/
postgres.go
78 lines (63 loc) · 2.17 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
package config
import (
"fmt"
"github.com/flyteorg/flytestdlib/promutils"
"gorm.io/driver/postgres"
_ "gorm.io/driver/postgres" // Required to import database driver.
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
const Postgres = "postgres"
// Generic interface for providing a config necessary to open a database connection.
type DbConnectionConfigProvider interface {
// Returns database dialector
GetDialector() gorm.Dialector
GetDBConfig() DbConfig
GetDSN() string
}
type BaseConfig struct {
LogLevel logger.LogLevel `json:"log_level"`
DisableForeignKeyConstraintWhenMigrating bool
}
// PostgreSQL implementation for DbConnectionConfigProvider.
type PostgresConfigProvider struct {
config DbConfig
scope promutils.Scope
}
// TODO : Make the Config provider itself env based
func NewPostgresConfigProvider(config DbConfig, scope promutils.Scope) DbConnectionConfigProvider {
return &PostgresConfigProvider{
config: config,
scope: scope,
}
}
func (p *PostgresConfigProvider) GetType() string {
return Postgres
}
func (p *PostgresConfigProvider) GetDSN() string {
if p.config.Password == "" {
// Switch for development
return fmt.Sprintf("host=%s port=%d dbname=%s user=%s sslmode=disable",
p.config.Host, p.config.Port, p.config.DbName, p.config.User)
}
return fmt.Sprintf("host=%s port=%d dbname=%s user=%s password=%s %s",
p.config.Host, p.config.Port, p.config.DbName, p.config.User, p.config.Password, p.config.ExtraOptions)
}
func (p *PostgresConfigProvider) GetDialector() gorm.Dialector {
return postgres.Open(p.GetDSN())
}
func (p *PostgresConfigProvider) GetDBConfig() DbConfig {
return p.config
}
// Opens a connection to the database specified in the config.
// You must call CloseDbConnection at the end of your session!
func OpenDbConnection(config DbConnectionConfigProvider) (*gorm.DB, error) {
db, err := gorm.Open(postgres.Open(config.GetDSN()), &gorm.Config{
Logger: logger.Default.LogMode(config.GetDBConfig().LogLevel),
DisableForeignKeyConstraintWhenMigrating: config.GetDBConfig().DisableForeignKeyConstraintWhenMigrating,
})
if err != nil {
return nil, err
}
return db, nil
}