-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsondb.go
64 lines (56 loc) · 1.11 KB
/
jsondb.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
package jsondb
import (
"database/sql"
"encoding/json"
"errors"
"log"
)
type JsonDB struct {
db *sql.DB
}
func NewJsonDB(db *sql.DB) (*JsonDB, error) {
if db == nil {
return nil, errors.New("The database connection must be already initialized")
}
j := &JsonDB{db: db}
return j, nil
}
func (j JsonDB) Json(statement string) string {
rows, err := j.db.Query(statement)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
log.Fatal(err)
}
count := len(columns)
tableData := make([]map[string]interface{}, 0)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for rows.Next() {
for i := 0; i < count; i++ {
valuePtrs[i] = &values[i]
}
rows.Scan(valuePtrs...)
entry := make(map[string]interface{})
for i, col := range columns {
var v interface{}
val := values[i]
b, ok := val.([]byte)
if ok {
v = string(b)
} else {
v = val
}
entry[col] = v
}
tableData = append(tableData, entry)
}
jsonData, err := json.Marshal(tableData)
if err != nil {
log.Fatal(err)
}
return string(jsonData)
}