forked from xwb1989/sqlparser
-
Notifications
You must be signed in to change notification settings - Fork 2
/
rewriter.go
40 lines (36 loc) · 944 Bytes
/
rewriter.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
package sqlparser
import (
_ "fmt"
"reflect"
)
var typeOfBytes = reflect.TypeOf([]byte(nil))
var typeOfSQLNode = reflect.TypeOf((*SQLNode)(nil)).Elem()
type Rewriter func([]byte) []byte
func Rewrite(node SQLNode, rewriter Rewriter) {
rewrite(reflect.ValueOf(node), rewriter)
}
func rewrite(nodeVal reflect.Value, rewriter Rewriter) {
if !nodeVal.IsValid() {
return
}
nodeTyp := nodeVal.Type()
switch nodeTyp.Kind() {
case reflect.Slice:
if nodeTyp == typeOfBytes && !nodeVal.IsNil() {
val := rewriter(nodeVal.Bytes()) //use rewriter to rewrite the bytes
nodeVal.SetBytes(val)
} else if nodeTyp.Implements(typeOfSQLNode) {
for i := 0; i < nodeVal.Len(); i++ {
m := nodeVal.Index(i)
rewrite(m, rewriter)
}
}
case reflect.Struct:
for i := 0; i < nodeVal.NumField(); i++ {
f := nodeVal.Field(i)
rewrite(f, rewriter)
}
case reflect.Ptr, reflect.Interface:
rewrite(nodeVal.Elem(), rewriter)
}
}