-
Notifications
You must be signed in to change notification settings - Fork 0
/
timescaledb.go
107 lines (91 loc) · 2.31 KB
/
timescaledb.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
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 testing
import (
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/tanimutomo/sqlfile"
_ "github.com/jackc/pgx/v5/stdlib"
)
type TimescaledbptionsData struct {
Host string
Username string
Password string
DB string
Schema string
SSLMode string
Port int
MigrationFile string
}
type TimescaledbOptions interface {
GetOptions() TimescaledbptionsData
}
var (
tsdbClient *sql.DB
timescaledbOnce sync.Once
)
func CreateTimescaledb(t testing.TB, optMaker TimescaledbOptions) (*sql.DB, string) {
opts := optMaker.GetOptions()
dbName := strings.ReplaceAll(t.Name(), "/", "_") + "_" + strconv.FormatInt(time.Now().UTC().UnixMilli(), 10)
dbName = strings.ToLower(dbName)
var err error
timescaledbOnce.Do(func() {
tsdbClient, err = sql.Open("pgx", fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s",
opts.Username,
opts.Password,
opts.Host,
opts.Port,
opts.DB,
))
if err != nil {
t.Error("Failed to connect to timescaledb", err)
t.FailNow()
}
})
if _, err = tsdbClient.Exec(fmt.Sprintf("CREATE DATABASE %s;", dbName)); err != nil {
t.Errorf("Failed to create database with name %s: %v", dbName, err)
t.FailNow()
}
var client *sql.DB
t.Cleanup(func() {
if client != nil {
_ = client.Close()
}
_, err = tsdbClient.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s;", dbName))
if err != nil {
t.Errorf("failed to delete database %s: %v", dbName, err)
}
})
if _, err = tsdbClient.Exec(fmt.Sprintf("GRANT ALL ON DATABASE %s TO %s;", dbName, opts.Username)); err != nil {
t.Errorf("Failed to grant privileges for database %s to user %s: %v", dbName, opts.Username, err)
t.FailNow()
}
// switch databases
client, err = sql.Open("pgx", fmt.Sprintf(
"postgres://%s:%s@%s:%d/%s",
opts.Username,
opts.Password,
opts.Host,
opts.Port,
dbName,
))
if err != nil {
t.Error("Failed to connect to timescaledb", err)
t.FailNow()
}
s := sqlfile.New()
err = s.File(opts.MigrationFile)
if err != nil {
t.Errorf("failed to read Timescaledb migrations file (DIR=%s): %v", opts.MigrationFile, err)
t.FailNow()
}
if _, err = s.Exec(client); err != nil {
t.Errorf("failed to exec Timescaledb migrations file (DIR=%s): %v", opts.MigrationFile, err)
t.FailNow()
}
return client, dbName
}