-
Notifications
You must be signed in to change notification settings - Fork 18
/
query.go
62 lines (46 loc) · 1.28 KB
/
query.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
package clickhouse
import (
"context"
"github.com/balerter/balerter/internal/datasource/converter"
lua "github.com/yuin/gopher-lua"
"go.uber.org/zap"
)
func (m *Clickhouse) query(luaState *lua.LState) int {
q := luaState.Get(1).String()
m.logger.Debug("call clickhouse query", zap.String("query", q))
ctx, ctxCancel := context.WithTimeout(context.Background(), m.timeout)
defer ctxCancel()
rows, err := m.db.QueryContext(ctx, q)
if err != nil {
m.logger.Error("error clickhouse query", zap.String("query", q), zap.Error(err))
luaState.Push(lua.LNil)
luaState.Push(lua.LString(err.Error()))
return 2
}
defer rows.Close()
cct, _ := rows.ColumnTypes()
dest := make([]interface{}, 0)
ffs := make([]func(v interface{}) lua.LValue, 0)
for range cct {
dest = append(dest, new([]byte))
ffs = append(ffs, converter.FromDateBytes)
}
result := &lua.LTable{}
for rows.Next() {
if err := rows.Scan(dest...); err != nil {
m.logger.Error("error scan", zap.Error(err))
luaState.Push(lua.LNil)
luaState.Push(lua.LString("error scan: " + err.Error()))
return 2
}
row := &lua.LTable{}
for idx, c := range cct {
v := ffs[idx](dest[idx])
row.RawSet(lua.LString(c.Name()), v)
}
result.Append(row)
}
luaState.Push(result)
luaState.Push(lua.LNil)
return 2
}