forked from btnguyen2k/prom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_mssql_json.go
280 lines (246 loc) · 7.65 KB
/
example_mssql_json.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"reflect"
"strconv"
"strings"
"time"
"github.com/btnguyen2k/prom/sql"
_ "github.com/denisenkom/go-mssqldb"
)
// construct an 'prom.SqlConnect' instance
func createSqlConnectMssqlJson() *sql.SqlConnect {
driver := "sqlserver"
dsn := "sqlserver://sa:Password1@localhost:1433?database=tempdb"
if os.Getenv("MSSQL_URL") != "" {
dsn = strings.ReplaceAll(os.Getenv("MSSQL_URL"), `"`, "")
}
sqlConnect, err := sql.NewSqlConnectWithFlavor(driver, dsn, 10000, nil, sql.FlavorMsSql)
if sqlConnect == nil || err != nil {
if err != nil {
fmt.Println("Error:", err)
}
if sqlConnect == nil {
panic("error creating [prom.SqlConnect] instance")
}
}
return sqlConnect
}
var colsMssqlJson = []string{"id", "data_map", "data_list"}
func printRowMssqlJson(row map[string]interface{}) {
id := row["id"]
fmt.Printf("\t\tRow [%v]\n", id)
for _, n := range colsMssqlJson {
v := row[n]
if reflect.TypeOf(v).String() == "[]uint8" {
fmt.Println("\t\t\t", n, "[", reflect.TypeOf(v), "] = ", string(v.([]byte)))
} else {
fmt.Println("\t\t\t", n, "[", reflect.TypeOf(v), "] = ", v)
}
}
}
func main() {
rand.Seed(time.Now().UnixNano())
SEP := "======================================================================"
sqlConnect := createSqlConnectMssqlJson()
defer sqlConnect.Close()
{
fmt.Println("-== Database & Ping info ==-")
// get the database object and send ping command
db := sqlConnect.GetDB()
fmt.Println("\tCurrent database:", db)
fmt.Println("\tIs connected :", sqlConnect.IsConnected())
err := sqlConnect.Ping(nil)
if err != nil {
fmt.Println("\tPing error :", err)
} else {
fmt.Println("\tPing ok")
}
fmt.Println(SEP)
}
{
fmt.Println("-== Drop/Create Table ==-")
// setting up
sql := "DROP TABLE IF EXISTS tbl_demojson"
_, err := sqlConnect.GetDB().Exec(sql)
if err != nil {
fmt.Printf("\tError while executing query [%s]: %s\n", sql, err)
} else {
fmt.Println("\tDropped table [tbl_demojson]")
types := []string{"INT", "NTEXT", "NTEXT"}
sql := "CREATE TABLE tbl_demojson ("
for i := range colsMssqlJson {
sql += colsMssqlJson[i] + " " + types[i] + ","
}
sql += "PRIMARY KEY(id))"
fmt.Println("\tQuery:" + sql)
_, err := sqlConnect.GetDB().Exec(sql)
if err != nil {
fmt.Printf("\tError while executing query: %s\n", err)
} else {
fmt.Println("\tCreated table [colsMssqlJson]")
}
}
fmt.Println(SEP)
}
{
fmt.Println("-== Insert Rows to Table ==-")
loc, _ := time.LoadLocation("Asia/Ho_Chi_Minh")
// insert some rows
sql := "INSERT INTO tbl_demojson ("
sql += strings.Join(colsMssqlJson, ",")
sql += ") VALUES ("
for k := range colsMssqlJson {
sql += "@p" + strconv.Itoa(k+1) + ","
}
sql = sql[0 : len(sql)-1]
sql += ")"
n := 100
fmt.Printf("\tInserting %d rows to table [tbl_demojson]\n", n)
for i := 1; i <= n; i++ {
t := time.Unix(int64(rand.Int31()), rand.Int63()%1000000000).In(loc)
id := i
username := t.String()
email := strconv.Itoa(int(rand.Int31n(int32(n)))) + "@" + strconv.Itoa(int(rand.Int31n(9999))) + ".com"
dataInt := rand.Int31()
dataBool := strconv.Itoa(int(dataInt % 2))
dataFloat := rand.Float64()
dataDatetime := t
dataMap := map[string]interface{}{"username": username, "email": email, "int": dataInt, "bool": dataBool, "float": dataFloat, "datetime": dataDatetime}
dataList := []interface{}{username, email, dataInt, dataBool, dataFloat, dataDatetime}
val1, err := json.Marshal(dataMap)
if err != nil {
fmt.Println("\t\tError:", err)
}
val2, err := json.Marshal(dataList)
if err != nil {
fmt.Println("\t\tError:", err)
}
_, err = sqlConnect.GetDB().Exec(sql, id, string(val1), string(val2))
if err != nil {
fmt.Println("\t\tError:", err)
}
}
fmt.Println(SEP)
}
{
fmt.Println("-== Query Single Row from Table ==-")
// query single row
sql := "SELECT * FROM tbl_demojson WHERE id=@p1"
id := rand.Intn(100) + 1
fmt.Printf("\tFetching row id %d from table [tbl_demojson]\n", id)
dbRow := sqlConnect.GetDB().QueryRow(sql, id)
data, err := sqlConnect.FetchRow(dbRow, len(colsMssqlJson))
if err != nil {
fmt.Printf("\tError fetching row %d from table [tbl_demojson]: %s\n", id, err)
} else if data == nil {
fmt.Println("\t\tRow not found")
} else {
for _, v := range data {
switch v.(type) {
case []byte:
fmt.Println("\t\t", reflect.TypeOf(v), string(v.([]byte)))
default:
fmt.Println("\t\t", reflect.TypeOf(v), v)
}
}
}
id = 999
fmt.Printf("\tFetching row id %d from table [tbl_demojson]\n", id)
dbRow = sqlConnect.GetDB().QueryRow(sql, id)
data, err = sqlConnect.FetchRow(dbRow, len(colsMssqlJson))
if err != nil {
fmt.Printf("\tError fetching row %d from table [tbl_demojson]: %s\n", id, err)
} else if data == nil {
fmt.Println("\t\tNo row matches query")
} else {
for _, v := range data {
switch v.(type) {
case []byte:
fmt.Println("\t\t", reflect.TypeOf(v), string(v.([]byte)))
default:
fmt.Println("\t\t", reflect.TypeOf(v), v)
}
}
}
fmt.Println(SEP)
}
{
fmt.Println("-== Query Multiple Rows from Table ==-")
// query multiple rows: https://docs.microsoft.com/en-us/sql/t-sql/queries/select-order-by-clause-transact-sql?view=sql-server-2017
// (SQL Server 2012+ only)
sql := "SELECT * FROM tbl_demojson WHERE id>=@p1 ORDER BY id OFFSET 0 ROWS FETCH NEXT 4 ROWS ONLY"
id := rand.Intn(100) + 1
fmt.Printf("\tFetching rows starting at %d from table [tbl_demojson]\n", id)
dbRows1, err := sqlConnect.GetDB().Query(sql, id)
defer dbRows1.Close()
if err != nil {
fmt.Printf("\tE\trror while executing query: %s\n", err)
} else {
rows, err := sqlConnect.FetchRows(dbRows1)
if err != nil {
fmt.Printf("\t\tError while fetching rows from table [tbl_demojson]: %s\n", err)
} else if len(rows) > 0 {
for _, r := range rows {
printRowMssqlJson(r)
}
} else {
fmt.Println("\t\tNo row matches query")
}
}
id = 999
fmt.Printf("\tFetching rows starting at %d from table [tbl_demojson]\n", id)
dbRows2, err := sqlConnect.GetDB().Query(sql, id)
defer dbRows2.Close()
if err != nil {
fmt.Printf("\t\tError while executing query: %s\n", err)
} else {
rows, err := sqlConnect.FetchRows(dbRows2)
if err != nil {
fmt.Printf("\t\tError while fetching rows from table [tbl_demojson]: %s\n", err)
} else if len(rows) > 0 {
for _, r := range rows {
printRowMssqlJson(r)
}
} else {
fmt.Println("\t\tNo row matches query")
}
}
fmt.Println(SEP)
}
{
fmt.Println("-== Query Multiple Rows from Table (using callback) ==-")
// query multiple rows with callback function
sql := "SELECT * FROM tbl_demojson WHERE id>=@p1 ORDER BY id OFFSET 0 ROWS FETCH NEXT 4 ROWS ONLY"
callback := func(row map[string]interface{}, err error) bool {
if err != nil {
fmt.Printf("\t\tError while fetching rows from table [tbl_demojson]: %s\n", err)
} else {
printRowMssqlJson(row)
}
return true
}
id := rand.Intn(100) + 1
fmt.Printf("\tFetching rows starting at %d from table [tbl_demojson]\n", id)
dbRows1, err := sqlConnect.GetDB().Query(sql, id)
defer dbRows1.Close()
if err != nil {
fmt.Printf("\t\tError while executing query: %s\n", err)
} else {
sqlConnect.FetchRowsCallback(dbRows1, callback)
}
id = 999
fmt.Printf("\tFetching rows starting at %d from table [tbl_demojson]\n", id)
dbRows2, err := sqlConnect.GetDB().Query(sql, id)
defer dbRows2.Close()
if err != nil {
fmt.Printf("\t\tError while executing query: %s\n", err)
} else {
sqlConnect.FetchRowsCallback(dbRows2, callback)
}
fmt.Println(SEP)
}
}