-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_test.go
114 lines (87 loc) · 2.37 KB
/
json_test.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
113
114
/* Copyright (C) 2021 Pankaj Kargirwar <[email protected]>
This file is part of prosql-agent
prosql-agent is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
prosql-agent is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with prosql-agent. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"testing"
"time"
"unicode/utf8"
_ "github.com/go-sql-driver/mysql"
)
func TestJson(t *testing.T) {
var pool *sql.DB
pool, err := sql.Open("mysql", "server:dev-server@tcp(127.0.0.1:3306)/test-generico")
if err != nil {
t.Errorf("%s\n", err.Error())
}
defer pool.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
if err := pool.PingContext(ctx); err != nil {
t.Errorf("%s\n", err.Error())
}
data := fetchAll(t, ctx, pool)
fmt.Println(data)
res := &Response{
Data: data,
}
str, err := json.Marshal(res)
if err != nil {
t.Errorf("%s\n", err.Error())
}
fmt.Println(string(str))
}
func fetchAll(t *testing.T, ctx context.Context, pool *sql.DB) [][]string {
rows, err := pool.QueryContext(ctx, "select description from vouchers where id = 606")
if err != nil {
t.Fatalf("%s\n", err.Error())
}
cols, err := rows.Columns()
if err != nil {
t.Fatalf("%s\n", err.Error())
}
vals := make([]interface{}, len(cols))
var results [][]string
for rows.Next() {
for i := range cols {
vals[i] = &vals[i]
}
err = rows.Scan(vals...)
if err != nil {
t.Fatalf("%s\n", err.Error())
}
var r []string
for i, c := range cols {
r = append(r, c)
var v string
if vals[i] == nil {
v = "NULL"
} else {
b, _ := vals[i].([]byte)
v = string(b)
}
fmt.Printf("byte len %d\n", len(v))
fmt.Printf("rune len %d\n", utf8.RuneCountInString(v))
r = append(r, v)
}
results = append(results, r)
}
if rows.Err() != nil {
t.Fatalf("%s\n", err.Error())
}
return results
}