-
Notifications
You must be signed in to change notification settings - Fork 18
/
clickhouse.go
99 lines (79 loc) · 2.06 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
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
package clickhouse
import (
"context"
"crypto/tls"
"crypto/x509"
"fmt"
"github.com/ClickHouse/clickhouse-go"
"github.com/balerter/balerter/internal/config"
"github.com/balerter/balerter/internal/script/script"
"github.com/jmoiron/sqlx"
lua "github.com/yuin/gopher-lua"
"go.uber.org/zap"
"io/ioutil"
"time"
)
type Clickhouse struct {
name string
logger *zap.Logger
db *sqlx.DB
}
func New(cfg config.DataSourceClickhouse, logger *zap.Logger) (*Clickhouse, error) {
c := &Clickhouse{
name: "clickhouse." + cfg.Name,
logger: logger,
}
chSecureString := "secure=false"
if cfg.SSLCertPath != "" {
caCertPool := x509.NewCertPool()
caCert, err := ioutil.ReadFile(cfg.SSLCertPath)
if err != nil {
return nil, fmt.Errorf("error load clickhouse cert file, %v", err)
}
caCertPool.AppendCertsFromPEM(caCert)
if err := clickhouse.RegisterTLSConfig("chtls", &tls.Config{
RootCAs: caCertPool,
}); err != nil {
return nil, fmt.Errorf("error register tls config, %v", err)
}
chSecureString = "secure=true&tls_config=chtls"
}
connString := fmt.Sprintf("tcp://%s:%d?username=%s&password=%s&database=%s&%s",
cfg.Host,
cfg.Port,
cfg.Username,
cfg.Password,
cfg.Database,
chSecureString,
)
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second)
defer ctxCancel()
var err error
if c.db, err = sqlx.ConnectContext(ctx, "clickhouse", connString); err != nil {
return nil, fmt.Errorf("error connect to clickhouse, %v", err)
}
if err := c.db.Ping(); err != nil {
return nil, fmt.Errorf("error ping clickhouse, %v", err)
}
return c, nil
}
func (m *Clickhouse) Stop() error {
return m.db.Close()
}
func (m *Clickhouse) Name() string {
return m.name
}
func (m *Clickhouse) GetLoader(_ *script.Script) lua.LGFunction {
return m.loader
}
func (m *Clickhouse) loader(L *lua.LState) int {
var exports = map[string]lua.LGFunction{
"query": m.query,
}
mod := L.SetFuncs(L.NewTable(), exports)
// register other stuff
//L.SetField(mod, "name", lua.LString("value"))
// returns the module
L.Push(mod)
return 1
}