Debian Codegraph @

expression.go

raw symbols SCIP
1 // Copyright 2016 Qiang Xue. All rights reserved.
2 // Use of this source code is governed by a MIT-style
3 // license that can be found in the LICENSE file.
4
5 package dbx
6
7 import (
8 "fmt"
9 "sort"
10 "strings"
11 )
12
13 // Expression represents a DB expression that can be embedded in a SQL statement.
14 type Expression interface {
15 // Build converts an expression into a SQL fragment.
16 // If the expression contains binding parameters, they will be added to the given Params.
17 Build(*DB, Params) string
18 }
19
20 // HashExp represents a hash expression.
21 //
22 // A hash expression is a map whose keys are DB column names which need to be filtered according
23 // to the corresponding values. For example, HashExp{"level": 2, "dept": 10} will generate
24 // the SQL: "level"=2 AND "dept"=10.
25 //
26 // HashExp also handles nil values and slice values. For example, HashExp{"level": []interface{}{1, 2}, "dept": nil}
27 // will generate: "level" IN (1, 2) AND "dept" IS NULL.
28 type HashExp map[string]interface{}
29
30 // NewExp generates an expression with the specified SQL fragment and the optional binding parameters.
31 func NewExp(e string, params ...Params) Expression {
32 if len(params) > 0 {
33 return &Exp{e, params[0]}
34 }
35 return &Exp{e, nil}
36 }
37
38 // Not generates a NOT expression which prefixes "NOT" to the specified expression.
39 func Not(e Expression) Expression {
40 return &NotExp{e}
41 }
42
43 // And generates an AND expression which concatenates the given expressions with "AND".
44 func And(exps ...Expression) Expression {
45 return &AndOrExp{exps, "AND"}
46 }
47
48 // Or generates an OR expression which concatenates the given expressions with "OR".
49 func Or(exps ...Expression) Expression {
50 return &AndOrExp{exps, "OR"}
51 }
52
53 // In generates an IN expression for the specified column and the list of allowed values.
54 // If values is empty, a SQL "0=1" will be generated which represents a false expression.
55 func In(col string, values ...interface{}) Expression {
56 return &InExp{col, values, false}
57 }
58
59 // NotIn generates an NOT IN expression for the specified column and the list of disallowed values.
60 // If values is empty, an empty string will be returned indicating a true expression.
61 func NotIn(col string, values ...interface{}) Expression {
62 return &InExp{col, values, true}
63 }
64
65 // DefaultLikeEscape specifies the default special character escaping for LIKE expressions
66 // The strings at 2i positions are the special characters to be escaped while those at 2i+1 positions
67 // are the corresponding escaped versions.
68 var DefaultLikeEscape = []string{"\\", "\\\\", "%", "\\%", "_", "\\_"}
69
70 // Like generates a LIKE expression for the specified column and the possible strings that the column should be like.
71 // If multiple values are present, the column should be like *all* of them. For example, Like("name", "key", "word")
72 // will generate a SQL expression: "name" LIKE "%key%" AND "name" LIKE "%word%".
73 //
74 // By default, each value will be surrounded by "%" to enable partial matching. If a value contains special characters
75 // such as "%", "\", "_", they will also be properly escaped.
76 //
77 // You may call Escape() and/or Match() to change the default behavior. For example, Like("name", "key").Match(false, true)
78 // generates "name" LIKE "key%".
79 func Like(col string, values ...string) *LikeExp {
80 return &LikeExp{
81 left: true,
82 right: true,
83 col: col,
84 values: values,
85 escape: DefaultLikeEscape,
86 Like: "LIKE",
87 }
88 }
89
90 // NotLike generates a NOT LIKE expression.
91 // For example, NotLike("name", "key", "word") will generate a SQL expression:
92 // "name" NOT LIKE "%key%" AND "name" NOT LIKE "%word%". Please see Like() for more details.
93 func NotLike(col string, values ...string) *LikeExp {
94 return &LikeExp{
95 left: true,
96 right: true,
97 col: col,
98 values: values,
99 escape: DefaultLikeEscape,
100 Like: "NOT LIKE",
101 }
102 }
103
104 // OrLike generates an OR LIKE expression.
105 // This is similar to Like() except that the column should be like one of the possible values.
106 // For example, OrLike("name", "key", "word") will generate a SQL expression:
107 // "name" LIKE "%key%" OR "name" LIKE "%word%". Please see Like() for more details.
108 func OrLike(col string, values ...string) *LikeExp {
109 return &LikeExp{
110 or: true,
111 left: true,
112 right: true,
113 col: col,
114 values: values,
115 escape: DefaultLikeEscape,
116 Like: "LIKE",
117 }
118 }
119
120 // OrNotLike generates an OR NOT LIKE expression.
121 // For example, OrNotLike("name", "key", "word") will generate a SQL expression:
122 // "name" NOT LIKE "%key%" OR "name" NOT LIKE "%word%". Please see Like() for more details.
123 func OrNotLike(col string, values ...string) *LikeExp {
124 return &LikeExp{
125 or: true,
126 left: true,
127 right: true,
128 col: col,
129 values: values,
130 escape: DefaultLikeEscape,
131 Like: "NOT LIKE",
132 }
133 }
134
135 // Exists generates an EXISTS expression by prefixing "EXISTS" to the given expression.
136 func Exists(exp Expression) Expression {
137 return &ExistsExp{exp, false}
138 }
139
140 // NotExists generates an EXISTS expression by prefixing "NOT EXISTS" to the given expression.
141 func NotExists(exp Expression) Expression {
142 return &ExistsExp{exp, true}
143 }
144
145 // Between generates a BETWEEN expression.
146 // For example, Between("age", 10, 30) generates: "age" BETWEEN 10 AND 30
147 func Between(col string, from, to interface{}) Expression {
148 return &BetweenExp{col, from, to, false}
149 }
150
151 // NotBetween generates a NOT BETWEEN expression.
152 // For example, NotBetween("age", 10, 30) generates: "age" NOT BETWEEN 10 AND 30
153 func NotBetween(col string, from, to interface{}) Expression {
154 return &BetweenExp{col, from, to, true}
155 }
156
157 // Exp represents an expression with a SQL fragment and a list of optional binding parameters.
158 type Exp struct {
159 e string
160 params Params
161 }
162
163 // Build converts an expression into a SQL fragment.
164 func (e *Exp) Build(db *DB, params Params) string {
165 if len(e.params) == 0 {
166 return e.e
167 }
168 for k, v := range e.params {
169 params[k] = v
170 }
171 return e.e
172 }
173
174 // Build converts an expression into a SQL fragment.
175 func (e HashExp) Build(db *DB, params Params) string {
176 if len(e) == 0 {
177 return ""
178 }
179
180 // ensure the hash exp generates the same SQL for different runs
181 names := []string{}
182 for name := range e {
183 names = append(names, name)
184 }
185 sort.Strings(names)
186
187 var parts []string
188 for _, name := range names {
189 value := e[name]
190 switch value.(type) {
191 case nil:
192 name = db.QuoteColumnName(name)
193 parts = append(parts, name+" IS NULL")
194 case Expression:
195 if sql := value.(Expression).Build(db, params); sql != "" {
196 parts = append(parts, "("+sql+")")
197 }
198 case []interface{}:
199 in := In(name, value.([]interface{})...)
200 if sql := in.Build(db, params); sql != "" {
201 parts = append(parts, sql)
202 }
203 default:
204 pn := fmt.Sprintf("p%v", len(params))
205 name = db.QuoteColumnName(name)
206 parts = append(parts, name+"={:"+pn+"}")
207 params[pn] = value
208 }
209 }
210 if len(parts) == 1 {
211 return parts[0]
212 }
213 return strings.Join(parts, " AND ")
214 }
215
216 // NotExp represents an expression that should prefix "NOT" to a specified expression.
217 type NotExp struct {
218 e Expression
219 }
220
221 // Build converts an expression into a SQL fragment.
222 func (e *NotExp) Build(db *DB, params Params) string {
223 if sql := e.e.Build(db, params); sql != "" {
224 return "NOT (" + sql + ")"
225 }
226 return ""
227 }
228
229 // AndOrExp represents an expression that concatenates multiple expressions using either "AND" or "OR".
230 type AndOrExp struct {
231 exps []Expression
232 op string
233 }
234
235 // Build converts an expression into a SQL fragment.
236 func (e *AndOrExp) Build(db *DB, params Params) string {
237 if len(e.exps) == 0 {
238 return ""
239 }
240
241 var parts []string
242 for _, a := range e.exps {
243 if a == nil {
244 continue
245 }
246 if sql := a.Build(db, params); sql != "" {
247 parts = append(parts, sql)
248 }
249 }
250 if len(parts) == 1 {
251 return parts[0]
252 }
253 return "(" + strings.Join(parts, ") "+e.op+" (") + ")"
254 }
255
256 // InExp represents an "IN" or "NOT IN" expression.
257 type InExp struct {
258 col string
259 values []interface{}
260 not bool
261 }
262
263 // Build converts an expression into a SQL fragment.
264 func (e *InExp) Build(db *DB, params Params) string {
265 if len(e.values) == 0 {
266 if e.not {
267 return ""
268 }
269 return "0=1"
270 }
271
272 var values []string
273 for _, value := range e.values {
274 switch value.(type) {
275 case nil:
276 values = append(values, "NULL")
277 case Expression:
278 sql := value.(Expression).Build(db, params)
279 values = append(values, sql)
280 default:
281 name := fmt.Sprintf("p%v", len(params))
282 params[name] = value
283 values = append(values, "{:"+name+"}")
284 }
285 }
286 col := db.QuoteColumnName(e.col)
287 if len(values) == 1 {
288 if e.not {
289 return col + "<>" + values[0]
290 }
291 return col + "=" + values[0]
292 }
293 in := "IN"
294 if e.not {
295 in = "NOT IN"
296 }
297 return fmt.Sprintf("%v %v (%v)", col, in, strings.Join(values, ", "))
298 }
299
300 // LikeExp represents a variant of LIKE expressions.
301 type LikeExp struct {
302 or bool
303 left, right bool
304 col string
305 values []string
306 escape []string
307
308 // Like stores the LIKE operator. It can be "LIKE", "NOT LIKE".
309 // It may also be customized as something like "ILIKE".
310 Like string
311 }
312
313 // Escape specifies how a LIKE expression should be escaped.
314 // Each string at position 2i represents a special character and the string at position 2i+1 is
315 // the corresponding escaped version.
316 func (e *LikeExp) Escape(chars ...string) *LikeExp {
317 e.escape = chars
318 return e
319 }
320
321 // Match specifies whether to do wildcard matching on the left and/or right of given strings.
322 func (e *LikeExp) Match(left, right bool) *LikeExp {
323 e.left, e.right = left, right
324 return e
325 }
326
327 // Build converts an expression into a SQL fragment.
328 func (e *LikeExp) Build(db *DB, params Params) string {
329 if len(e.values) == 0 {
330 return ""
331 }
332
333 if len(e.escape)%2 != 0 {
334 panic("LikeExp.Escape must be a slice of even number of strings")
335 }
336
337 var parts []string
338 col := db.QuoteColumnName(e.col)
339 for _, value := range e.values {
340 name := fmt.Sprintf("p%v", len(params))
341 for i := 0; i < len(e.escape); i += 2 {
342 value = strings.Replace(value, e.escape[i], e.escape[i+1], -1)
343 }
344 if e.left {
345 value = "%" + value
346 }
347 if e.right {
348 value += "%"
349 }
350 params[name] = value
351 parts = append(parts, fmt.Sprintf("%v %v {:%v}", col, e.Like, name))
352 }
353
354 if e.or {
355 return strings.Join(parts, " OR ")
356 }
357 return strings.Join(parts, " AND ")
358 }
359
360 // ExistsExp represents an EXISTS or NOT EXISTS expression.
361 type ExistsExp struct {
362 exp Expression
363 not bool
364 }
365
366 // Build converts an expression into a SQL fragment.
367 func (e *ExistsExp) Build(db *DB, params Params) string {
368 sql := e.exp.Build(db, params)
369 if sql == "" {
370 if e.not {
371 return ""
372 }
373 return "0=1"
374 }
375 if e.not {
376 return "NOT EXISTS (" + sql + ")"
377 }
378 return "EXISTS (" + sql + ")"
379 }
380
381 // BetweenExp represents a BETWEEN or a NOT BETWEEN expression.
382 type BetweenExp struct {
383 col string
384 from, to interface{}
385 not bool
386 }
387
388 // Build converts an expression into a SQL fragment.
389 func (e *BetweenExp) Build(db *DB, params Params) string {
390 between := "BETWEEN"
391 if e.not {
392 between = "NOT BETWEEN"
393 }
394 name1 := fmt.Sprintf("p%v", len(params))
395 name2 := fmt.Sprintf("p%v", len(params)+1)
396 params[name1] = e.from
397 params[name2] = e.to
398 col := db.QuoteColumnName(e.col)
399 return fmt.Sprintf("%v %v {:%v} AND {:%v}", col, between, name1, name2)
400 }
401
402 // Enclose surrounds the provided nonempty expression with parenthesis "()".
403 func Enclose(exp Expression) Expression {
404 return &EncloseExp{exp}
405 }
406
407 // EncloseExp represents a parenthesis enclosed expression.
408 type EncloseExp struct {
409 exp Expression
410 }
411
412 // Build converts an expression into a SQL fragment.
413 func (e *EncloseExp) Build(db *DB, params Params) string {
414 str := e.exp.Build(db, params)
415
416 if str == "" {
417 return ""
418 }
419
420 return "(" + str + ")"
421 }