-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
102 lines (80 loc) · 2.08 KB
/
query.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
package gormcase
import (
"fmt"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
const tagName = "gormcase"
func (d *gormCase) queryCallback(db *gorm.DB) {
// If we only want to use case-insensitivity when explicitly set to true, we back out early if anything's amiss
settingValue, settingOk := db.Get(tagName)
if d.conditionalSetting && !settingOk {
return
}
if settingOk {
if boolValue, _ := settingValue.(bool); !boolValue {
return
}
}
exp, ok := db.Statement.Clauses["WHERE"].Expression.(clause.Where)
if !ok {
return
}
for index, cond := range exp.Exprs {
switch cond := cond.(type) {
case clause.Eq:
if d.conditionalTag {
columnName, ok := cond.Column.(string)
if !ok {
continue
}
value := db.Statement.Schema.FieldsByDBName[columnName].Tag.Get(tagName)
// Ignore if there's no valid tag value
if value != "true" {
continue
}
}
value, ok := cond.Value.(string)
if !ok {
continue
}
condition := fmt.Sprintf("UPPER(%s) = UPPER(?)", cond.Column)
exp.Exprs[index] = db.Session(&gorm.Session{NewDB: true}).Where(condition, value).Statement.Clauses["WHERE"].Expression
case clause.IN:
if d.conditionalTag {
columnName, ok := cond.Column.(string)
if !ok {
continue
}
value := db.Statement.Schema.FieldsByDBName[columnName].Tag.Get(tagName)
// Ignore if there's no valid tag value
if value != "true" {
continue
}
}
var caseCounter int
var useOr bool
query := db.Session(&gorm.Session{NewDB: true})
for _, value := range cond.Values {
value, ok := value.(string)
if !ok {
continue
}
caseCounter++
condition := fmt.Sprintf("UPPER(%s) = UPPER(?)", cond.Column)
if useOr {
query = query.Or(condition, value)
continue
}
query = query.Where(condition, value)
useOr = true
}
// Do nothing if no changes were made
if caseCounter == 0 {
continue
}
// TODO: Determine whether this is efficient
exp.Exprs[index] = db.Session(&gorm.Session{NewDB: true}).Where(query).Statement.Clauses["WHERE"].Expression
}
}
}