-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
filter.go
73 lines (60 loc) · 1.69 KB
/
filter.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
package filter
import (
"fmt"
"strings"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)
// Filter structured representation of a filter query.
// The generic parameter is the type pointer type of the model.
type Filter struct {
Field string
Operator *Operator
Args []string
Or bool
}
// Scope returns the GORM scope to use in order to apply this filter.
func (f *Filter) Scope(blacklist Blacklist, sch *schema.Schema) (func(*gorm.DB) *gorm.DB, func(*gorm.DB) *gorm.DB) {
field, s, joinName := getField(f.Field, sch, &blacklist)
if field == nil {
return nil, nil
}
dataType := getDataType(field)
joinScope := func(tx *gorm.DB) *gorm.DB {
if dataType == DataTypeUnsupported {
return tx
}
if joinName != "" {
if err := tx.Statement.Parse(tx.Statement.Model); err != nil {
tx.AddError(err)
return tx
}
tx = join(tx, joinName, sch)
}
return tx
}
computed := field.StructField.Tag.Get("computed")
conditionScope := func(tx *gorm.DB) *gorm.DB {
if dataType == DataTypeUnsupported {
return tx
}
table := tx.Statement.Quote(tableFromJoinName(s.Table, joinName))
var fieldExpr string
if computed != "" {
fieldExpr = fmt.Sprintf("(%s)", strings.ReplaceAll(computed, clause.CurrentTable, table))
} else {
fieldExpr = table + "." + tx.Statement.Quote(field.DBName)
}
return f.Operator.Function(tx, f, fieldExpr, dataType)
}
return joinScope, conditionScope
}
// Where applies a condition to given transaction, automatically taking the "Or"
// filter value into account.
func (f *Filter) Where(tx *gorm.DB, query string, args ...any) *gorm.DB {
if f.Or {
return tx.Or(query, args...)
}
return tx.Where(query, args...)
}