/
db.go
72 lines (55 loc) · 1.27 KB
/
db.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 db
import (
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type PostgresDB struct {
Host string
Port int
SSLMode string
User string
Password string
DBName string
TimeZone string
}
func NewPostgresDB(pgdb PostgresDB) (*GormDB, error) {
dsn := fmt.Sprintf(
"host=%s port=%d sslmode=%s user=%s password=%s dbname=%s TimeZone=%s",
pgdb.Host, pgdb.Port, pgdb.SSLMode, pgdb.User, pgdb.Password, pgdb.DBName, pgdb.TimeZone,
)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, fmt.Errorf("error opening db connection: %w", err)
}
return &GormDB{db}, nil
}
type DB interface {
SetupDefaults()
AddSamples(samples ...Samples)
}
type GormDB struct {
db *gorm.DB
}
func (gdb *GormDB) SetupDefaults() {
gdb.setup(&Samples{})
gdb.setup(&Predictor{})
statement := "create_hypertable('samples', 'timestamp')"
gdb.db.Select(statement)
}
func (gdb *GormDB) AddSamples(samples ...Samples) {
gdb.db.Table("samples").Create(samples)
}
func (gdb *GormDB) setup(obj interface{}) {
if err := gdb.db.AutoMigrate(obj); err != nil {
panic(err)
}
}
type TestDB struct {
TestFunc func(...Samples)
}
func (tdb *TestDB) SetupDefaults() {
}
func (tdb *TestDB) AddSamples(samples ...Samples) {
tdb.TestFunc(samples...)
}