-
Notifications
You must be signed in to change notification settings - Fork 0
/
migrations.go
80 lines (73 loc) · 2.29 KB
/
migrations.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
package migrations
import (
"context"
"database/sql"
"embed"
"fmt"
"os"
"time"
"github.com/ClickHouse/clickhouse-go/v2"
"github.com/pressly/goose/v3"
)
// registerFuncs is a list of functions that register migrations.
// Each migration file should have an init function that appends their register function to this list.
// This is different from the goose registration which is public for all packages.
var registerFuncs = []func(){}
// ClickhouseConfig is the configuration for connecting to a clickhouse database.
type ClickhouseConfig struct {
Host string `yaml:"CLICKHOUSE_HOST"`
Port string `yaml:"CLICKHOUSE_PORT"`
User string `yaml:"CLICKHOUSE_USER"`
Password string `yaml:"CLICKHOUSE_PASSWORD"`
DataBase string `yaml:"CLICKHOUSE_DATABASE"`
}
// SetMigrations sets the migrations for the goose tool.
// this will reset the global migrations and FS to avoid any unwanted migrations registers.
func SetMigrations() {
emptyFs := embed.FS{}
goose.SetBaseFS(emptyFs)
goose.ResetGlobalMigrations()
for _, regFunc := range registerFuncs {
regFunc()
}
}
// RunGoose runs the goose command with the provided arguments.
// args should be the command and the arguments to pass to goose.
// eg RunGoose(ctx, []string{"up", "-v"}, db).
func RunGoose(ctx context.Context, gooseArgs []string, db *sql.DB) error {
if len(gooseArgs) == 0 {
return fmt.Errorf("command not provided")
}
cmd := gooseArgs[0]
var args []string
if len(gooseArgs) > 1 {
args = os.Args[1:]
}
// err := initMigrations(ctx, db)
// if err != nil {
// return fmt.Errorf("failed to init migrations for clickhouse cluster: %w", err)
// }
SetMigrations()
if err := goose.SetDialect("clickhouse"); err != nil {
return fmt.Errorf("failed to set dialect: %w", err)
}
err := goose.RunContext(ctx, cmd, db, ".", args...)
if err != nil {
return fmt.Errorf("failed to run goose command: %w", err)
}
return nil
}
// GetClickhouseDB returns a sql.DB connection to clickhouse.
func GetClickhouseDB(config ClickhouseConfig) *sql.DB {
addr := fmt.Sprintf("%s:%s", config.Host, config.Port)
conn := clickhouse.OpenDB(&clickhouse.Options{
Addr: []string{addr},
Auth: clickhouse.Auth{
Username: config.User,
Password: config.Password,
Database: config.DataBase,
},
DialTimeout: time.Minute * 30,
})
return conn
}