/
result.go
455 lines (404 loc) · 11.5 KB
/
result.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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package mymy
import (
"log"
"strconv"
"bytes"
"fmt"
"os"
"math"
)
type Field struct {
Catalog string
Db string
Table string
OrgTable string
Name string
OrgName string
DispLen uint32
// Charset uint16
Flags uint16
Type byte
Scale byte
}
type Result struct {
db *MySQL
binary bool // Binary result expected
FieldCount int
Fields []*Field // Fields table
Map map[string]int // Maps field name to column number
Message []byte
AffectedRows uint64
InsertId uint64
WarningCount int
Status uint16
}
// Result row. Data field is a slice that contains values for any column of
// received row.
//
// If row is a result of ordinary text query, an element of Data field can be
// []byte slice, contained result text or nil if NULL is returned.
//
// If it is result of prepared statement execution, an element of Data field
// can be: intXX, uintXX, floatXX, []byte, *Datetime or nil.
type Row struct {
Data []interface{}
}
// Get the nn-th value and return it as []byte ([]byte{} if NULL)
func (tr *Row) Bin(nn int) (bin []byte) {
switch data := tr.Data[nn].(type) {
case nil:
// bin = []byte{}
case []byte:
bin = data
case *Datetime:
bin = []byte(data.String())
default:
buf := new(bytes.Buffer)
fmt.Fprint(buf, data)
bin = buf.Bytes()
}
return
}
// Get the nn-th value and return it as string ("" if NULL)
func (tr *Row) Str(nn int) (str string) {
switch data := tr.Data[nn].(type) {
case nil:
// str = ""
case []byte:
str = string(data)
case *Datetime:
str = data.String()
default:
str = fmt.Sprint(data)
}
return
}
// Get the nn-th value and return it as int (0 if NULL). Return error if
// conversion is impossible.
func (tr *Row) IntErr(nn int) (val int, err os.Error) {
switch data := tr.Data[nn].(type) {
case nil:
val = 0
case int32:
val = int(data)
case int16:
val = int(data)
case uint16:
val = int(data)
case int8:
val = int(data)
case uint8:
val = int(data)
case []byte:
val, err = strconv.Atoi(string(data))
case uint32:
if _SIZE_OF_INT > 4 {
val = int(data)
} else {
err = &strconv.NumError{fmt.Sprint(data), os.ERANGE}
}
case int64:
if _SIZE_OF_INT > 4 {
val = int(data)
} else {
err = &strconv.NumError{fmt.Sprint(data), os.ERANGE}
}
case uint64:
err = &strconv.NumError{fmt.Sprint(data), os.ERANGE}
default:
err = &strconv.NumError{fmt.Sprint(data), os.EINVAL}
}
return
}
// Get the nn-th value and return it as int (0 if NULL). Panic if conversion is
// impossible.
func (tr *Row) MustInt(nn int) (val int) {
val, err := tr.IntErr(nn)
if err != nil {
panic(err)
}
return
}
// Get the nn-th value and return it as int. Return 0 if value is NULL or
// conversion is impossible.
func (tr *Row) Int(nn int) (val int) {
val, _ = tr.IntErr(nn)
return
}
// Get the nn-th value and return it as uint (0 if NULL). Return error if
// conversion is impossible.
func (tr *Row) UintErr(nn int) (val uint, err os.Error) {
switch data := tr.Data[nn].(type) {
case uint32:
val = uint(data)
case uint16:
val = uint(data)
case uint8:
val = uint(data)
case []byte:
val, err = strconv.Atoui(string(data))
case uint64:
if _SIZE_OF_INT > 4 {
val = uint(data)
} else {
err = &strconv.NumError{fmt.Sprint(data), os.ERANGE}
}
case int8, int16, int32, int64:
err = &strconv.NumError{fmt.Sprint(data), os.ERANGE}
default:
err = &strconv.NumError{fmt.Sprint(data), os.EINVAL}
}
return
}
// Get the nn-th value and return it as uint (0 if NULL). Panic if conversion is
// impossible.
func (tr *Row) MustUint(nn int) (val uint) {
val, err := tr.UintErr(nn)
if err != nil {
panic(err)
}
return
}
// Get the nn-th value and return it as uint. Return 0 if value is NULL or
// conversion is impossible.
func (tr *Row) Uint(nn int) (val uint) {
val, _ = tr.UintErr(nn)
return
}
func (my *MySQL) getResult(res *Result) interface{} {
loop:
pr := my.newPktReader() // New reader for next packet
pkt0 := readByte(pr)
if pkt0 == 255 {
// Error packet
my.getErrorPacket(pr)
}
if res == nil {
switch {
case pkt0 == 0:
// OK packet
return my.getOkPacket(pr)
case pkt0 > 0 && pkt0 < 251:
// Result set header packet
res = my.getResSetHeadPacket(pr)
// Read next packet
goto loop
}
} else {
switch {
case pkt0 == 254:
// EOF packet
res.WarningCount, res.Status = my.getEofPacket(pr)
return res
case pkt0 > 0 && pkt0 < 251 && res.FieldCount < len(res.Fields):
// Field packet
field := my.getFieldPacket(pr)
res.Fields[res.FieldCount] = field
res.Map[field.Name] = res.FieldCount
// Increment field count
res.FieldCount++
// Read next packet
goto loop
case pkt0 < 254 && res.FieldCount == len(res.Fields):
// Row Data Packet
if res.binary {
return my.getBinRowPacket(pr, res)
} else {
return my.getTextRowPacket(pr, res)
}
}
}
panic(UNK_RESULT_PKT_ERROR)
}
func (my *MySQL) getOkPacket(pr *pktReader) (res *Result) {
if my.Debug {
log.Printf("[%2d ->] OK packet:", my.seq - 1)
}
res = new(Result)
// First byte was readed by getResult
res.AffectedRows = readNotNullU64(pr)
res.InsertId = readNotNullU64(pr)
res.Status = readU16(pr)
res.WarningCount = int(readU16(pr))
res.Message = pr.readAll()
pr.checkEof()
if my.Debug {
log.Printf(tab8s + "AffectedRows=%d InsertId=0x%x Status=0x%x " +
"WarningCount=%d Message=\"%s\"", res.AffectedRows, res.InsertId,
res.Status, res.WarningCount, res.Message,
)
}
return
}
func (my *MySQL) getErrorPacket(pr *pktReader) {
if my.Debug {
log.Printf("[%2d ->] Error packet:", my.seq - 1)
}
var err Error
err.Code = readU16(pr)
if readByte(pr) != '#' {
panic(PKT_ERROR)
}
read(pr, 5)
err.Msg = pr.readAll()
pr.checkEof()
if my.Debug {
log.Printf(tab8s + "code=0x%x msg=\"%s\"", err.Code, err.Msg)
}
panic(&err)
}
func (my *MySQL) getEofPacket(pr *pktReader) (warn_count int, status uint16) {
if my.Debug {
log.Printf("[%2d ->] EOF packet:", my.seq - 1)
}
warn_count = int(readU16(pr))
status = readU16(pr)
pr.checkEof()
if my.Debug {
log.Printf(tab8s + "WarningCount=%d Status=0x%x", warn_count, status)
}
return
}
func (my *MySQL) getResSetHeadPacket(pr *pktReader) (res *Result) {
if my.Debug {
log.Printf("[%2d ->] Result set header packet:", my.seq - 1)
}
pr.unreadByte()
field_count := int(readNotNullU64(pr))
pr.checkEof()
res = &Result {
Fields: make([]*Field, field_count),
Map: make(map[string]int),
}
if my.Debug {
log.Printf(tab8s + "FieldCount=%d", field_count)
}
return
}
func (my *MySQL) getFieldPacket(pr *pktReader) (field *Field) {
if my.Debug {
log.Printf("[%2d ->] Field packet:", my.seq - 1)
}
pr.unreadByte()
field = new(Field)
field.Catalog = readNotNullStr(pr)
field.Db = readNotNullStr(pr)
field.Table = readNotNullStr(pr)
field.OrgTable = readNotNullStr(pr)
field.Name = readNotNullStr(pr)
field.OrgName = readNotNullStr(pr)
read(pr, 1 + 2)
//field.Charset= readU16(pr)
field.DispLen = readU32(pr)
field.Type = readByte(pr)
field.Flags = readU16(pr)
field.Scale = readByte(pr)
read(pr, 2)
pr.checkEof()
if my.Debug {
log.Printf(tab8s + "Name=\"%s\" Type=0x%x", field.Name, field.Type)
}
return
}
func (my *MySQL) getTextRowPacket(pr *pktReader, res *Result) *Row {
if my.Debug {
log.Printf("[%2d ->] Text row data packet", my.seq - 1)
}
pr.unreadByte()
row := Row{Data: make([]interface{}, res.FieldCount)}
for ii := 0; ii < res.FieldCount; ii++ {
nbin := readNbin(pr)
if nbin == nil {
row.Data[ii] = nil
} else {
row.Data[ii] = *nbin
}
}
pr.checkEof()
return &row
}
func (my *MySQL) getBinRowPacket(pr *pktReader, res *Result) *Row {
if my.Debug {
log.Printf("[%2d ->] Binary row data packet", my.seq - 1)
}
// First byte was readed by getResult
null_bitmap := make([]byte, (res.FieldCount + 7 + 2) >> 3)
readFull(pr, null_bitmap)
row := Row{Data: make([]interface{}, res.FieldCount)}
for ii, field := range res.Fields {
null_byte := (ii + 2) >> 3
null_mask := byte(1) << uint(2 + ii - (null_byte << 3))
if null_bitmap[null_byte] & null_mask != 0 {
// Null field
row.Data[ii] = nil
continue
}
typ := field.Type
unsigned := (field.Flags & _FLAG_UNSIGNED) != 0
switch typ {
case MYSQL_TYPE_TINY:
if unsigned {
row.Data[ii] = readByte(pr)
} else {
row.Data[ii] = int8(readByte(pr))
}
case MYSQL_TYPE_SHORT:
if unsigned {
row.Data[ii] = readU16(pr)
} else {
row.Data[ii] = int16(readU16(pr))
}
case MYSQL_TYPE_LONG:
if unsigned {
row.Data[ii] = readU32(pr)
} else {
row.Data[ii] = int32(readU32(pr))
}
case MYSQL_TYPE_LONGLONG:
if unsigned {
row.Data[ii] = readU64(pr)
} else {
row.Data[ii] = int64(readU64(pr))
}
case MYSQL_TYPE_INT24:
if unsigned {
row.Data[ii] = readU24(pr)
} else {
row.Data[ii] = int32(readU24(pr))
}
case MYSQL_TYPE_FLOAT:
row.Data[ii] = math.Float32frombits(readU32(pr))
case MYSQL_TYPE_DOUBLE:
row.Data[ii] = math.Float64frombits(readU64(pr))
case MYSQL_TYPE_STRING, MYSQL_TYPE_VAR_STRING, MYSQL_TYPE_DECIMAL,
MYSQL_TYPE_VARCHAR, MYSQL_TYPE_BIT, MYSQL_TYPE_BLOB,
MYSQL_TYPE_TINY_BLOB, MYSQL_TYPE_MEDIUM_BLOB,
MYSQL_TYPE_LONG_BLOB:
row.Data[ii] = readNotNullBin(pr)
case MYSQL_TYPE_DATETIME, MYSQL_TYPE_DATE, MYSQL_TYPE_TIME,
MYSQL_TYPE_TIMESTAMP:
row.Data[ii] = readNotNullDatetime(pr)
// TODO:
// MYSQL_TYPE_NEWDATE, MYSQL_TYPE_NEWDECIMAL, MYSQL_TYPE_ENUM,
// MYSQL_TYPE_SET, MYSQL_TYPE_GEOMETRY
default:
panic(UNK_MYSQL_TYPE_ERROR)
}
}
return &row
}
func (my *MySQL) getResponse() (res *Result) {
res, ok := my.getResult(nil).(*Result)
if !ok {
panic(BAD_RESULT_ERROR)
}
if res.FieldCount == 0 {
// This query was ended (OK result)
my.unlock()
} else {
// This query can return rows
res.db = my
my.unreaded_rows = true
}
return
}