-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery.go
More file actions
85 lines (72 loc) · 1.46 KB
/
query.go
File metadata and controls
85 lines (72 loc) · 1.46 KB
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 (
"database/sql"
"fmt"
"log"
"net/http"
"time"
"github.com/gorilla/mux"
)
func HandleQuery(w http.ResponseWriter, r *http.Request, info *DbInfo) {
qr := &QueryResult{}
n := time.Now()
dbn := mux.Vars(r)["db"]
query := mux.Vars(r)["query"]
log.Printf("[DATABASE] %q [QUERY] %q\n", dbn, query)
db, s, e := open(dbn, info)
if e != nil {
log.Println(e)
w.WriteHeader(s)
fmt.Fprintln(w, e)
return
}
s = qr.fetchQuery(db, query)
e = WriteToJSON(w, s, qr)
if e != nil {
log.Println(e)
}
log.Printf("(Query rendered in %v)\n", time.Now().Sub(n))
}
func (qr *QueryResult) fetchQuery(db *sql.DB, query string) int {
rs, e := db.Query(query)
if e != nil {
log.Println(e)
qr.Error = fmt.Sprintf("%s", e)
return http.StatusBadRequest
}
defer rs.Close()
cs, e := rs.Columns()
if e != nil {
log.Println(e)
qr.Error = fmt.Sprintf("%s", e)
return http.StatusInternalServerError
}
var res [][]*string
tmpr := make([][]byte, len(cs))
tmpi := make([]interface{}, len(cs))
for i, _ := range tmpr {
tmpi[i] = &tmpr[i]
}
for rs.Next() {
raw := make([]*string, len(cs))
e = rs.Scan(tmpi...)
if e != nil {
log.Println(e)
qr.Error = fmt.Sprintf("%s", e)
return http.StatusInternalServerError
}
for i, v := range tmpr {
switch v {
case nil:
raw[i] = nil
default:
t := string(tmpr[i])
raw[i] = &t
}
}
res = append(res, raw)
}
qr.Data = res
qr.Columns = cs
return http.StatusOK
}