-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdatabase.go
More file actions
107 lines (92 loc) · 2.45 KB
/
database.go
File metadata and controls
107 lines (92 loc) · 2.45 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package database
import (
"errors"
"fmt"
"time"
"github.com/RTradeLtd/config/v2"
"github.com/RTradeLtd/database/v2/models"
"github.com/jinzhu/gorm"
// import our postgres dialect used to talk with a postgres databse
_ "github.com/jinzhu/gorm/dialects/postgres"
)
// Manager is used to manage databases
type Manager struct {
DB *gorm.DB
Upload *models.UploadManager
}
// Options is used to configure a connection to the database
type Options struct {
RunMigrations bool
SSLModeDisable bool
LogMode bool
Logger Logger
}
// New is used to init our connection to a database, and return a manager struct
func New(cfg *config.TemporalConfig, opts Options) (*Manager, error) {
if cfg == nil {
return nil, errors.New("invalid configuration provided")
}
db, err := openDBConnection(dbOptions{
User: cfg.Database.Username,
Password: cfg.Database.Password,
Address: cfg.Database.URL,
Port: cfg.Database.Port,
SSLModeDisable: opts.SSLModeDisable,
})
if err != nil {
return nil, err
}
if opts.Logger != nil {
db.SetLogger(opts.Logger)
}
db.LogMode(opts.LogMode)
var dbm = Manager{DB: db}
if opts.RunMigrations {
dbm.RunMigrations()
}
return &dbm, nil
}
// RunMigrations runs all migrations
func (dbm *Manager) RunMigrations() {
for _, t := range []interface{}{
&models.Upload{},
&models.EncryptedUpload{},
&models.User{},
&models.Payments{},
&models.IPNS{},
&models.HostedNetwork{},
&models.Zone{},
&models.Record{},
&models.Usage{},
&models.Organization{},
} {
dbm.DB.AutoMigrate(t)
}
}
// Close shuts down database connection
func (dbm *Manager) Close() error { return dbm.DB.Close() }
// dbOptions declares options for opening a database connection
type dbOptions struct {
User string
Password string
Address string
Port string
SSLModeDisable bool
}
// openDBConnection is used to create a database connection
func openDBConnection(opts dbOptions) (*gorm.DB, error) {
if opts.User == "" {
opts.User = "postgres"
}
dbConnURL := fmt.Sprintf("host=%s port=%s user=%s dbname=temporal password=%s",
opts.Address, opts.Port, opts.User, opts.Password)
if opts.SSLModeDisable {
dbConnURL = "sslmode=disable " + dbConnURL
}
db, err := gorm.Open("postgres", dbConnURL)
if err != nil {
return nil, fmt.Errorf("failed to establish connection with database: %s", err.Error())
}
db.DB().SetConnMaxLifetime(time.Minute * 60)
return db, nil
}