forked from nim4/DBShield
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql.go
More file actions
102 lines (86 loc) · 1.83 KB
/
sql.go
File metadata and controls
102 lines (86 loc) · 1.83 KB
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
package sql
import (
"bytes"
"encoding/binary"
"sync"
"time"
"github.com/xwb1989/sqlparser"
)
//QueryContext holds information around query
type QueryContext struct {
Query []byte
User []byte
Client []byte
Database []byte
Time time.Time
}
//Unmarshal []byte into QueryContext
func (c *QueryContext) Unmarshal(b []byte) (size uint32) {
n := binary.BigEndian.Uint32(b)
b = b[4:]
c.Query = b[:n]
size = n
b = b[n:]
n = binary.BigEndian.Uint32(b)
b = b[4:]
c.User = b[:n]
size += n
b = b[n:]
n = binary.BigEndian.Uint32(b)
b = b[4:]
c.Client = b[:n]
size += n
b = b[n:]
n = binary.BigEndian.Uint32(b)
b = b[4:]
c.Database = b[:n]
size += n
c.Time.UnmarshalBinary(b[n:])
size += 8
return
}
var bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
//Marshal load []byte into QueryContext
func (c *QueryContext) Marshal() []byte {
buf := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
l := make([]byte, 4)
binary.BigEndian.PutUint32(l, uint32(len(c.Query)))
buf.Write(l)
buf.Write(c.Query)
binary.BigEndian.PutUint32(l, uint32(len(c.User)))
buf.Write(l)
buf.Write(c.User)
binary.BigEndian.PutUint32(l, uint32(len(c.Client)))
buf.Write(l)
buf.Write(c.Client)
binary.BigEndian.PutUint32(l, uint32(len(c.Database)))
buf.Write(l)
buf.Write(c.Database)
t, _ := c.Time.MarshalBinary()
buf.Write(t)
return buf.Bytes()
}
//Pattern returns pattern of given query
func Pattern(query []byte) []byte {
tokenizer := sqlparser.NewStringTokenizer(string(query))
buf := bytes.Buffer{}
l := make([]byte, 4)
for {
typ, val := tokenizer.Scan()
switch typ {
case sqlparser.ID: //table, database, variable & ... names
buf.Write(val)
case 0: //End of query
return buf.Bytes()
default:
binary.BigEndian.PutUint32(l, uint32(typ))
buf.Write(l)
}
}
}