/
clickhouse.go
55 lines (48 loc) · 1.28 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
package clickhouse
import (
"database/sql"
"github.com/ClickHouse/clickhouse-go/v2"
"time"
)
type Client interface {
GetRow(userID, videoID uint32) (UserVideoTimesRow, error)
}
type UserVideoTimesRow struct {
UserID uint32
EventTime time.Time
EventType string //Enum8('watch' = 0, 'scroll' = 1),
VideoID uint32
VideoTimestamp uint32
}
type clickhouseClient struct {
conn *sql.DB
}
func (c clickhouseClient) GetRow(userID, videoID uint32) (res UserVideoTimesRow, err error) {
row := c.conn.QueryRow(
"SELECT * FROM user_video_times WHERE user_id=$1 AND video_id=$2 ORDER BY event_time DESC LIMIT 1",
userID, videoID)
err = row.Scan(&res.UserID, &res.EventTime, &res.EventType, &res.VideoID, &res.VideoTimestamp)
return
}
func Init(host, user, password string) Client {
conn := clickhouse.OpenDB(&clickhouse.Options{
Addr: []string{host},
Auth: clickhouse.Auth{
Database: "default",
Username: user,
Password: password,
},
Settings: clickhouse.Settings{
"max_execution_time": 60,
},
DialTimeout: 5 * time.Second,
Compression: &clickhouse.Compression{
Method: clickhouse.CompressionLZ4,
},
Debug: false,
})
conn.SetMaxIdleConns(5)
conn.SetMaxOpenConns(10)
conn.SetConnMaxLifetime(time.Hour)
return clickhouseClient{conn: conn}
}