-
Notifications
You must be signed in to change notification settings - Fork 0
/
clickhouse.go
54 lines (49 loc) · 1.24 KB
/
clickhouse.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
package db
import (
"context"
"database/sql"
"fmt"
"time"
_ "github.com/ClickHouse/clickhouse-go"
"github.com/sirupsen/logrus"
)
const (
defaultOperationTimeout = 10 * time.Second
)
type ClickhouseConfig struct {
Host string `mapstructure:"host"`
Port string `mapstructure:"port"`
DBName string `mapstructure:"database"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
Debug bool `mapstructure:"debug"`
}
func NewClickHouseClient(cfg ClickhouseConfig) (*sql.DB, error) {
cxDSN := fmt.Sprintf(
"tcp://%s:%s?username=%s&password=%s",
cfg.Host,
cfg.Port,
cfg.Username,
cfg.Password,
)
if cfg.Debug {
cxDSN = fmt.Sprintf("%s&debug=true", cxDSN)
}
cxDB, err := sql.Open("clickhouse", cxDSN)
if err != nil {
return nil, fmt.Errorf(
"cannot connect to the clickhouse database at %s:%s: %w",
cfg.Host, cfg.Port, err,
)
}
ctx, cancel := context.WithTimeout(context.Background(), defaultOperationTimeout)
defer cancel()
if err = cxDB.PingContext(ctx); err != nil {
return nil, fmt.Errorf(
"clickhouse database is unavailable at %s:%s: %w",
cfg.Host, cfg.Port, err,
)
}
logrus.Infof("connected to the clickhouse database at %s:%s", cfg.Host, cfg.Port)
return cxDB, nil
}