Debian Codegraph @

normalizer.go

raw symbols SCIP
1 /*
2 Copyright 2017 Google Inc.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package sqlparser
18
19 import (
20 "fmt"
21
22 "github.com/xwb1989/sqlparser/dependency/sqltypes"
23
24 "github.com/xwb1989/sqlparser/dependency/querypb"
25 )
26
27 // Normalize changes the statement to use bind values, and
28 // updates the bind vars to those values. The supplied prefix
29 // is used to generate the bind var names. The function ensures
30 // that there are no collisions with existing bind vars.
31 // Within Select constructs, bind vars are deduped. This allows
32 // us to identify vindex equality. Otherwise, every value is
33 // treated as distinct.
34 func Normalize(stmt Statement, bindVars map[string]*querypb.BindVariable, prefix string) {
35 nz := newNormalizer(stmt, bindVars, prefix)
36 _ = Walk(nz.WalkStatement, stmt)
37 }
38
39 type normalizer struct {
40 stmt Statement
41 bindVars map[string]*querypb.BindVariable
42 prefix string
43 reserved map[string]struct{}
44 counter int
45 vals map[string]string
46 }
47
48 func newNormalizer(stmt Statement, bindVars map[string]*querypb.BindVariable, prefix string) *normalizer {
49 return &normalizer{
50 stmt: stmt,
51 bindVars: bindVars,
52 prefix: prefix,
53 reserved: GetBindvars(stmt),
54 counter: 1,
55 vals: make(map[string]string),
56 }
57 }
58
59 // WalkStatement is the top level walk function.
60 // If it encounters a Select, it switches to a mode
61 // where variables are deduped.
62 func (nz *normalizer) WalkStatement(node SQLNode) (bool, error) {
63 switch node := node.(type) {
64 case *Select:
65 _ = Walk(nz.WalkSelect, node)
66 // Don't continue
67 return false, nil
68 case *SQLVal:
69 nz.convertSQLVal(node)
70 case *ComparisonExpr:
71 nz.convertComparison(node)
72 }
73 return true, nil
74 }
75
76 // WalkSelect normalizes the AST in Select mode.
77 func (nz *normalizer) WalkSelect(node SQLNode) (bool, error) {
78 switch node := node.(type) {
79 case *SQLVal:
80 nz.convertSQLValDedup(node)
81 case *ComparisonExpr:
82 nz.convertComparison(node)
83 }
84 return true, nil
85 }
86
87 func (nz *normalizer) convertSQLValDedup(node *SQLVal) {
88 // If value is too long, don't dedup.
89 // Such values are most likely not for vindexes.
90 // We save a lot of CPU because we avoid building
91 // the key for them.
92 if len(node.Val) > 256 {
93 nz.convertSQLVal(node)
94 return
95 }
96
97 // Make the bindvar
98 bval := nz.sqlToBindvar(node)
99 if bval == nil {
100 return
101 }
102
103 // Check if there's a bindvar for that value already.
104 var key string
105 if bval.Type == sqltypes.VarBinary {
106 // Prefixing strings with "'" ensures that a string
107 // and number that have the same representation don't
108 // collide.
109 key = "'" + string(node.Val)
110 } else {
111 key = string(node.Val)
112 }
113 bvname, ok := nz.vals[key]
114 if !ok {
115 // If there's no such bindvar, make a new one.
116 bvname = nz.newName()
117 nz.vals[key] = bvname
118 nz.bindVars[bvname] = bval
119 }
120
121 // Modify the AST node to a bindvar.
122 node.Type = ValArg
123 node.Val = append([]byte(":"), bvname...)
124 }
125
126 // convertSQLVal converts an SQLVal without the dedup.
127 func (nz *normalizer) convertSQLVal(node *SQLVal) {
128 bval := nz.sqlToBindvar(node)
129 if bval == nil {
130 return
131 }
132
133 bvname := nz.newName()
134 nz.bindVars[bvname] = bval
135
136 node.Type = ValArg
137 node.Val = append([]byte(":"), bvname...)
138 }
139
140 // convertComparison attempts to convert IN clauses to
141 // use the list bind var construct. If it fails, it returns
142 // with no change made. The walk function will then continue
143 // and iterate on converting each individual value into separate
144 // bind vars.
145 func (nz *normalizer) convertComparison(node *ComparisonExpr) {
146 if node.Operator != InStr && node.Operator != NotInStr {
147 return
148 }
149 tupleVals, ok := node.Right.(ValTuple)
150 if !ok {
151 return
152 }
153 // The RHS is a tuple of values.
154 // Make a list bindvar.
155 bvals := &querypb.BindVariable{
156 Type: querypb.Type_TUPLE,
157 }
158 for _, val := range tupleVals {
159 bval := nz.sqlToBindvar(val)
160 if bval == nil {
161 return
162 }
163 bvals.Values = append(bvals.Values, &querypb.Value{
164 Type: bval.Type,
165 Value: bval.Value,
166 })
167 }
168 bvname := nz.newName()
169 nz.bindVars[bvname] = bvals
170 // Modify RHS to be a list bindvar.
171 node.Right = ListArg(append([]byte("::"), bvname...))
172 }
173
174 func (nz *normalizer) sqlToBindvar(node SQLNode) *querypb.BindVariable {
175 if node, ok := node.(*SQLVal); ok {
176 var v sqltypes.Value
177 var err error
178 switch node.Type {
179 case StrVal:
180 v, err = sqltypes.NewValue(sqltypes.VarBinary, node.Val)
181 case IntVal:
182 v, err = sqltypes.NewValue(sqltypes.Int64, node.Val)
183 case FloatVal:
184 v, err = sqltypes.NewValue(sqltypes.Float64, node.Val)
185 default:
186 return nil
187 }
188 if err != nil {
189 return nil
190 }
191 return sqltypes.ValueBindVariable(v)
192 }
193 return nil
194 }
195
196 func (nz *normalizer) newName() string {
197 for {
198 newName := fmt.Sprintf("%s%d", nz.prefix, nz.counter)
199 if _, ok := nz.reserved[newName]; !ok {
200 nz.reserved[newName] = struct{}{}
201 return newName
202 }
203 nz.counter++
204 }
205 }
206
207 // GetBindvars returns a map of the bind vars referenced in the statement.
208 // TODO(sougou); This function gets called again from vtgate/planbuilder.
209 // Ideally, this should be done only once.
210 func GetBindvars(stmt Statement) map[string]struct{} {
211 bindvars := make(map[string]struct{})
212 _ = Walk(func(node SQLNode) (kontinue bool, err error) {
213 switch node := node.(type) {
214 case *SQLVal:
215 if node.Type == ValArg {
216 bindvars[string(node.Val[1:])] = struct{}{}
217 }
218 case ListArg:
219 bindvars[string(node[2:])] = struct{}{}
220 }
221 return true, nil
222 }, stmt)
223 return bindvars
224 }