-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
99 lines (79 loc) · 1.83 KB
/
utils.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
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"strings"
)
//...
func getQueryResults(database, query string, params []string, dsn string) ([]string, [][]string, error) {
//isPrepared := true
// Open database
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, nil, err
}
defer db.Close()
if len(database) > 0 {
_, err = db.Exec(fmt.Sprintf("USE %s;", database))
if err != nil {
return nil, nil, err
}
}
// Prepare params
var interfaceSlice = make([]interface{}, len(params))
for i, d := range params {
interfaceSlice[i] = d
}
// Execute query
rows, err := db.Query(query, interfaceSlice...)
if err != nil {
return nil, nil, err
}
// Get result columns
columns, err := rows.Columns()
if err != nil {
return nil, nil, err
}
// Make a slice for the values
values := make([]sql.RawBytes, len(columns))
// rows.Scan wants '[]interface{}' as an argument, so we must copy the
// references into such a slice
// See http://code.google.com/p/go-wiki/wiki/InterfaceSlice for details
scanArgs := make([]interface{}, len(values))
for i := range values {
scanArgs[i] = &values[i]
}
resultRows := [][]string{}
// Fetch rows
for rows.Next() {
tableRow := make([]string, len(columns))
// get RawBytes from data
err = rows.Scan(scanArgs...)
if err != nil {
return nil, nil, err
}
var value string
for i, col := range values {
if col == nil {
value = "NULL"
} else {
value = string(col)
}
tableRow[i] = value
}
resultRows = append(resultRows, tableRow)
}
if err = rows.Err(); err != nil {
return nil, nil, err
}
return columns, resultRows, nil
}
func getUseDatabaseValue(query string) string {
var db = ""
words := strings.Fields(query)
if len(words) == 2 && strings.ToUpper(words[0]) == "USE" {
db = words[1]
}
return db
}