-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
112 lines (98 loc) · 2.5 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"database/sql"
"encoding/json"
"fmt"
"reflect"
"github.com/go-sql-driver/mysql"
_ "github.com/prestodb/presto-go-client/presto"
)
func main() {
prestoUrl := "http://user@localhost:8080?catalog=mysql&schema=test"
sqlExe := "select * from mysql.test.Persons"
content, _ := ExePrestoSqlQuery(prestoUrl, sqlExe)
fmt.Println("query result : ", string(content))
}
type jsonNullInt64 struct {
sql.NullInt64
}
func (v jsonNullInt64) MarshalJSON() ([]byte, error) {
if !v.Valid {
return json.Marshal(nil)
}
return json.Marshal(v.Int64)
}
type jsonNullFloat64 struct {
sql.NullFloat64
}
func (v jsonNullFloat64) MarshalJSON() ([]byte, error) {
if !v.Valid {
return json.Marshal(nil)
}
return json.Marshal(v.Float64)
}
type jsonNullTime struct {
mysql.NullTime
}
func (v jsonNullTime) MarshalJSON() ([]byte, error) {
if !v.Valid {
return json.Marshal(nil)
}
return json.Marshal(v.Time)
}
var jsonNullInt64Type = reflect.TypeOf(jsonNullInt64{})
var jsonNullFloat64Type = reflect.TypeOf(jsonNullFloat64{})
var jsonNullTimeType = reflect.TypeOf(jsonNullTime{})
var nullInt64Type = reflect.TypeOf(sql.NullInt64{})
var nullFloat64Type = reflect.TypeOf(sql.NullFloat64{})
var nullTimeType = reflect.TypeOf(mysql.NullTime{})
func ExePrestoSqlQuery(prestoUrl string, sqlExe string) ([]byte, error) {
db, err := sql.Open("presto", prestoUrl)
if err != nil {
return nil, fmt.Errorf("can't connect to presto error: %v", err)
}
rows, err := db.Query(sqlExe)
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return nil, fmt.Errorf("column error: %v", err)
}
ct, err := rows.ColumnTypes()
if err != nil {
return nil, fmt.Errorf("column type error: %v", err)
}
types := make([]reflect.Type, len(ct))
for i, tp := range ct {
st := tp.ScanType()
if st == nil {
return nil, fmt.Errorf("scantype is null for column: %v", err)
}
switch st {
case nullInt64Type:
types[i] = jsonNullInt64Type
case nullFloat64Type:
types[i] = jsonNullFloat64Type
case nullTimeType:
types[i] = jsonNullTimeType
default:
types[i] = st
}
}
values := make([]interface{}, len(ct))
var slice []map[string]interface{}
for rows.Next() {
for i := range values {
values[i] = reflect.New(types[i]).Interface()
}
err = rows.Scan(values...)
if err != nil {
return nil, fmt.Errorf("failed to scan values: %v", err)
}
data := make(map[string]interface{})
for i, v := range values {
data[columns[i]] = v
}
slice = append(slice, data)
}
return json.Marshal(slice)
}