-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathcom_query_response.go
117 lines (96 loc) · 2.56 KB
/
com_query_response.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
package mysqlproto
import (
"errors"
"fmt"
)
type ResultSet struct {
Columns []Column
conn Conn
}
// https://dev.mysql.com/doc/internals/en/com-query-response.html#column-definition
type Column struct {
Catalog string
Schema string
Table string
OrgTable string
Name string
OrgName string
CharacterSet uint16
ColumnLength uint64
ColumnType Type
Flags uint16
Decimals byte
}
func (r ResultSet) Row() ([]byte, error) {
packet, err := r.conn.NextPacket()
if err != nil {
return nil, err
}
if packet.Payload[0] == EOF_PACKET {
return nil, nil
}
return packet.Payload, nil
}
// https://dev.mysql.com/doc/internals/en/com-query-response.html
func ComQueryResponse(conn Conn) (ResultSet, error) {
read := func() ([]byte, error) {
packet, err := conn.NextPacket()
if err != nil {
return nil, err
}
if len(packet.Payload) == 0 {
return nil, errors.New("mysqlproto: empty payload")
}
if packet.Payload[0] == ERR_PACKET {
return nil, parseError(packet.Payload, conn.CapabilityFlags)
}
return packet.Payload, nil
}
payload, err := read()
if err != nil {
return ResultSet{}, err
}
colCount, _, _ := lenDecInt(payload)
columns := make([]Column, int(colCount))
for i := 0; i < int(colCount); i++ {
payload, err := read()
if err != nil {
return ResultSet{}, err
}
column := Column{}
bytes, offset, _ := ReadRowValue(payload, 0)
column.Catalog = string(bytes)
bytes, offset, _ = ReadRowValue(payload, offset)
column.Schema = string(bytes)
bytes, offset, _ = ReadRowValue(payload, offset)
column.Table = string(bytes)
bytes, offset, _ = ReadRowValue(payload, offset)
column.OrgTable = string(bytes)
bytes, offset, _ = ReadRowValue(payload, offset)
column.Name = string(bytes)
bytes, offset, _ = ReadRowValue(payload, offset)
column.OrgName = string(bytes)
bytes, _, _ = ReadRowValue(payload, offset)
if len(bytes) < 10 {
return ResultSet{}, fmt.Errorf("mysqlproto: invalid column payload: %x", bytes)
}
column.CharacterSet = uint16(bytes[0]) | uint16(bytes[1])<<8
column.ColumnLength = uint64(bytes[2]) | uint64(bytes[3])<<8 | uint64(bytes[4])<<16 | uint64(bytes[5])<<32
column.ColumnType = Type(bytes[6])
column.Flags = uint16(bytes[7]) | uint16(bytes[8])<<8
column.Decimals = bytes[9]
columns[i] = column
}
payload, err = read()
if err != nil {
return ResultSet{}, err
}
if payload[0] != EOF_PACKET {
return ResultSet{}, parseError(payload, conn.CapabilityFlags)
}
rs := ResultSet{
Columns: columns,
conn: conn,
}
return rs, nil
}