This repository has been archived by the owner on Jul 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
chserver.go
85 lines (70 loc) · 1.72 KB
/
chserver.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
package main
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/ClickHouse/clickhouse-go"
)
type chserver struct {
conn *sql.DB
clickhouseHosts string
clickhouseHostname string
clickhousePort string
clickhouseUsername string
clickhousePassword string
clickhouseDebugFlag string
initialized bool
}
func (ch *chserver) connect() error {
if ch.initialized {
return nil
}
// hosts := []string{}
cHosts := strings.Split(ch.clickhouseHosts, ",")
if ch.clickhouseUsername == "" {
ch.clickhouseUsername = "default"
}
uri := fmt.Sprintf(
"tcp://%s:%s?debug=%s&username=%s&password=%s",
cHosts[0], ch.clickhousePort, ch.clickhouseDebugFlag, ch.clickhouseUsername, ch.clickhousePassword,
)
connect, err := sql.Open("clickhouse", uri)
if err != nil {
infoLogger.Fatalln("Encountered an error while creating ClickHouse client")
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err = connect.PingContext(ctx); err != nil {
if exception, ok := err.(*clickhouse.Exception); ok {
errLogger.Printf("[%d] %s \n%s\n", exception.Code, exception.Message, exception.StackTrace)
} else {
errLogger.Printf("client ping")
}
return err
}
ch.conn = connect
ch.initialized = true
return nil
}
func (ch *chserver) query(query string) (*sql.Rows, error) {
rows, err := ch.conn.Query(query)
if err != nil {
return nil, err
}
return rows, nil
}
func parseServerOptions(opt Options) *chserver {
ch := &chserver{}
for key, value := range opt {
if key == "host" {
ch.clickhouseHosts = value
} else if key == "port" {
ch.clickhousePort = value
}
}
ch.clickhouseDebugFlag = "true"
return ch
}