-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
index_hint.go
116 lines (96 loc) · 2.45 KB
/
index_hint.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
package hints
import (
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type IndexHint struct {
Type string
Keys []string
}
func (indexHint IndexHint) ModifyStatement(stmt *gorm.Statement) {
for _, name := range []string{"FROM", "UPDATE"} {
clause := stmt.Clauses[name]
if clause.AfterExpression == nil {
clause.AfterExpression = indexHint
} else {
clause.AfterExpression = Exprs{clause.AfterExpression, indexHint}
}
if name == "FROM" {
clause.Builder = IndexHintFromClauseBuilder
}
stmt.Clauses[name] = clause
}
}
func (indexHint IndexHint) Build(builder clause.Builder) {
if len(indexHint.Keys) > 0 {
builder.WriteString(indexHint.Type)
builder.WriteByte('(')
for idx, key := range indexHint.Keys {
if idx > 0 {
builder.WriteByte(',')
}
builder.WriteQuoted(key)
}
builder.WriteByte(')')
}
}
func UseIndex(names ...string) IndexHint {
return IndexHint{Type: "USE INDEX ", Keys: names}
}
func IgnoreIndex(names ...string) IndexHint {
return IndexHint{Type: "IGNORE INDEX ", Keys: names}
}
func ForceIndex(names ...string) IndexHint {
return IndexHint{Type: "FORCE INDEX ", Keys: names}
}
func (indexHint IndexHint) ForJoin() IndexHint {
indexHint.Type += "FOR JOIN "
return indexHint
}
func (indexHint IndexHint) ForOrderBy() IndexHint {
indexHint.Type += "FOR ORDER BY "
return indexHint
}
func (indexHint IndexHint) ForGroupBy() IndexHint {
indexHint.Type += "FOR GROUP BY "
return indexHint
}
func IndexHintFromClauseBuilder(c clause.Clause, builder clause.Builder) {
if c.BeforeExpression != nil {
c.BeforeExpression.Build(builder)
builder.WriteByte(' ')
}
if c.Name != "" {
builder.WriteString(c.Name)
builder.WriteByte(' ')
}
if c.AfterNameExpression != nil {
c.AfterNameExpression.Build(builder)
builder.WriteByte(' ')
}
if from, ok := c.Expression.(clause.From); ok {
joins := from.Joins
from.Joins = nil
from.Build(builder)
// set indexHints in the middle between table and joins
squashExpression(c.AfterExpression, func(expression clause.Expression) {
if indexHint, ok := expression.(IndexHint); ok { // pick
builder.WriteByte(' ')
indexHint.Build(builder)
}
})
for _, join := range joins {
builder.WriteByte(' ')
join.Build(builder)
}
} else {
c.Expression.Build(builder)
}
squashExpression(c.AfterExpression, func(expression clause.Expression) {
if _, ok := expression.(IndexHint); ok {
return
}
builder.WriteByte(' ')
expression.Build(builder)
})
}