-
Notifications
You must be signed in to change notification settings - Fork 489
/
digester.go
438 lines (394 loc) · 9.56 KB
/
digester.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
// Copyright 2019 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package parser
import (
"bytes"
"crypto/sha256"
"encoding/hex"
hash2 "hash"
"reflect"
"strings"
"sync"
"unicode"
"unsafe"
"github.com/pingcap/parser/charset"
)
type Digest struct {
b []byte
str string
}
// NewDigest returns a new digest.
func NewDigest(b []byte) *Digest {
return &Digest{
b: b,
str: hex.EncodeToString(b),
}
}
// String returns the digest hex string.
func (d *Digest) String() string {
return d.str
}
// Bytes returns the digest byte slice.
func (d *Digest) Bytes() []byte {
return d.b
}
// DigestHash generates the digest of statements.
// it will generate a hash on normalized form of statement text
// which removes general property of a statement but keeps specific property.
//
// for example: both DigestHash('select 1') and DigestHash('select 2') => e1c71d1661ae46e09b7aaec1c390957f0d6260410df4e4bc71b9c8d681021471
//
// Deprecated: It is logically consistent with NormalizeDigest.
func DigestHash(sql string) (digest *Digest) {
d := digesterPool.Get().(*sqlDigester)
digest = d.doDigest(sql)
digesterPool.Put(d)
return
}
// DigestNormalized generates the digest of a normalized sql.
// it will generate a hash on a normalized sql.
// Normalize + DigestNormalized equals to NormalizeDigest.
//
// for example: DigestNormalized('select ?')
// DigestNormalized should be called with a normalized SQL string (like 'select ?') generated by function Normalize.
// do not call with SQL which is not normalized, DigestNormalized('select 1') and DigestNormalized('select 2') is not the same
func DigestNormalized(normalized string) (digest *Digest) {
d := digesterPool.Get().(*sqlDigester)
digest = d.doDigestNormalized(normalized)
digesterPool.Put(d)
return
}
// Normalize generates the normalized statements.
// it will get normalized form of statement text
// which removes general property of a statement but keeps specific property.
//
// for example: Normalize('select 1 from b where a = 1') => 'select ? from b where a = ?'
func Normalize(sql string) (result string) {
d := digesterPool.Get().(*sqlDigester)
result = d.doNormalize(sql)
digesterPool.Put(d)
return
}
// NormalizeDigest combines Normalize and DigestNormalized into one method.
func NormalizeDigest(sql string) (normalized string, digest *Digest) {
d := digesterPool.Get().(*sqlDigester)
normalized, digest = d.doNormalizeDigest(sql)
digesterPool.Put(d)
return
}
var digesterPool = sync.Pool{
New: func() interface{} {
return &sqlDigester{
lexer: NewScanner(""),
hasher: sha256.New(),
}
},
}
// sqlDigester is used to compute DigestHash or Normalize for sql.
type sqlDigester struct {
buffer bytes.Buffer
lexer *Scanner
hasher hash2.Hash
tokens tokenDeque
}
func (d *sqlDigester) doDigestNormalized(normalized string) (digest *Digest) {
hdr := *(*reflect.StringHeader)(unsafe.Pointer(&normalized))
b := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: hdr.Data,
Len: hdr.Len,
Cap: hdr.Len,
}))
d.hasher.Write(b)
digest = NewDigest(d.hasher.Sum(nil))
d.hasher.Reset()
return
}
func (d *sqlDigester) doDigest(sql string) (digest *Digest) {
d.normalize(sql)
d.hasher.Write(d.buffer.Bytes())
d.buffer.Reset()
digest = NewDigest(d.hasher.Sum(nil))
d.hasher.Reset()
return
}
func (d *sqlDigester) doNormalize(sql string) (result string) {
d.normalize(sql)
result = d.buffer.String()
d.buffer.Reset()
return
}
func (d *sqlDigester) doNormalizeDigest(sql string) (normalized string, digest *Digest) {
d.normalize(sql)
normalized = d.buffer.String()
d.hasher.Write(d.buffer.Bytes())
d.buffer.Reset()
digest = NewDigest(d.hasher.Sum(nil))
d.hasher.Reset()
return
}
const (
// genericSymbol presents parameter holder ("?") in statement
// it can be any value as long as it is not repeated with other tokens.
genericSymbol = -1
// genericSymbolList presents parameter holder lists ("?, ?, ...") in statement
// it can be any value as long as it is not repeated with other tokens.
genericSymbolList = -2
)
func (d *sqlDigester) normalize(sql string) {
d.lexer.reset(sql)
for {
tok, pos, lit := d.lexer.scan()
if tok == invalid {
break
}
if tok == unicode.ReplacementChar && d.lexer.r.eof() {
break
}
if pos.Offset == len(sql) {
break
}
currTok := token{tok, strings.ToLower(lit)}
if d.reduceOptimizerHint(&currTok) {
continue
}
d.reduceLit(&currTok)
if currTok.tok == identifier {
if strings.HasPrefix(currTok.lit, "_") {
_, err := charset.GetCharsetInfo(currTok.lit[1:])
if err == nil {
currTok.tok = underscoreCS
goto APPEND
}
}
if tok1 := d.lexer.isTokenIdentifier(currTok.lit, pos.Offset); tok1 != 0 {
currTok.tok = tok1
}
}
APPEND:
d.tokens.pushBack(currTok)
}
d.lexer.reset("")
for i, token := range d.tokens {
if i > 0 {
d.buffer.WriteRune(' ')
}
if token.tok == singleAtIdentifier {
d.buffer.WriteString("@")
d.buffer.WriteString(token.lit)
} else if token.tok == underscoreCS {
d.buffer.WriteString("(_charset)")
} else if token.tok == identifier || token.tok == quotedIdentifier {
d.buffer.WriteByte('`')
d.buffer.WriteString(token.lit)
d.buffer.WriteByte('`')
} else {
d.buffer.WriteString(token.lit)
}
}
d.tokens.reset()
}
func (d *sqlDigester) reduceOptimizerHint(tok *token) (reduced bool) {
// ignore /*+..*/
if tok.tok == hintComment {
return
}
// ignore force/use/ignore index(x)
if tok.lit == "index" {
toks := d.tokens.back(1)
if len(toks) > 0 {
switch strings.ToLower(toks[0].lit) {
case "force", "use", "ignore":
for {
tok, _, lit := d.lexer.scan()
if tok == 0 || (tok == unicode.ReplacementChar && d.lexer.r.eof()) {
break
}
if lit == ")" {
reduced = true
d.tokens.popBack(1)
break
}
}
return
}
}
}
// ignore straight_join
if tok.lit == "straight_join" {
tok.lit = "join"
return
}
return
}
func (d *sqlDigester) reduceLit(currTok *token) {
if !d.isLit(*currTok) {
return
}
// count(*) => count(?)
if currTok.lit == "*" {
if d.isStarParam() {
currTok.tok = genericSymbol
currTok.lit = "?"
}
return
}
// "-x" or "+x" => "x"
if d.isPrefixByUnary(currTok.tok) {
d.tokens.popBack(1)
}
// "?, ?, ?, ?" => "..."
last2 := d.tokens.back(2)
if d.isGenericList(last2) {
d.tokens.popBack(2)
currTok.tok = genericSymbolList
currTok.lit = "..."
return
}
// order by n => order by n
if currTok.tok == intLit {
if d.isOrderOrGroupBy() {
return
}
}
// 2 => ?
currTok.tok = genericSymbol
currTok.lit = "?"
}
func (d *sqlDigester) isPrefixByUnary(currTok int) (isUnary bool) {
if !d.isNumLit(currTok) {
return
}
last := d.tokens.back(1)
if last == nil {
return
}
// a[0] != '-' and a[0] != '+'
if last[0].lit != "-" && last[0].lit != "+" {
return
}
last2 := d.tokens.back(2)
if last2 == nil {
isUnary = true
return
}
// '(-x' or ',-x' or ',+x' or '--x' or '+-x'
switch last2[0].lit {
case "(", ",", "+", "-", ">=", "is", "<=", "=", "<", ">":
isUnary = true
default:
}
// select -x or select +x
last2Lit := strings.ToLower(last2[0].lit)
if last2Lit == "select" {
isUnary = true
}
return
}
func (d *sqlDigester) isGenericList(last2 []token) (generic bool) {
if len(last2) < 2 {
return false
}
if !d.isComma(last2[1]) {
return false
}
switch last2[0].tok {
case genericSymbol, genericSymbolList:
generic = true
default:
}
return
}
func (d *sqlDigester) isOrderOrGroupBy() (orderOrGroupBy bool) {
var (
last []token
n int
)
// skip number item lists, e.g. "order by 1, 2, 3" should NOT convert to "order by ?, ?, ?"
for n = 2; ; n += 2 {
last = d.tokens.back(n)
if len(last) < 2 {
return false
}
if !d.isComma(last[1]) {
break
}
}
// handle group by number item list surround by "()", e.g. "group by (1, 2)" should not convert to "group by (?, ?)"
if last[1].lit == "(" {
last = d.tokens.back(n + 1)
if len(last) < 2 {
return false
}
}
orderOrGroupBy = (last[0].lit == "order" || last[0].lit == "group") && last[1].lit == "by"
return
}
func (d *sqlDigester) isStarParam() (starParam bool) {
last := d.tokens.back(1)
if last == nil {
starParam = false
return
}
starParam = last[0].lit == "("
return
}
func (d *sqlDigester) isLit(t token) (beLit bool) {
tok := t.tok
if d.isNumLit(tok) || tok == stringLit || tok == bitLit || tok == paramMarker {
beLit = true
} else if t.lit == "*" {
beLit = true
} else if tok == null || (tok == identifier && strings.ToLower(t.lit) == "null") {
beLit = true
}
return
}
func (d *sqlDigester) isNumLit(tok int) (beNum bool) {
switch tok {
case intLit, decLit, floatLit, hexLit:
beNum = true
default:
}
return
}
func (d *sqlDigester) isComma(tok token) (isComma bool) {
isComma = tok.lit == ","
return
}
type token struct {
tok int
lit string
}
type tokenDeque []token
func (s *tokenDeque) reset() {
*s = (*s)[:0]
}
func (s *tokenDeque) pushBack(t token) {
*s = append(*s, t)
}
func (s *tokenDeque) popBack(n int) (t []token) {
if len(*s) < n {
t = nil
return
}
t = (*s)[len(*s)-n:]
*s = (*s)[:len(*s)-n]
return
}
func (s *tokenDeque) back(n int) (t []token) {
if len(*s)-n < 0 {
return
}
t = (*s)[len(*s)-n:]
return
}