-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
search.go
68 lines (56 loc) · 1.45 KB
/
search.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
package filter
import (
"fmt"
"strings"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"gorm.io/gorm/schema"
)
// Search structured representation of a search query.
type Search struct {
Query string
Operator *Operator
Fields []string
}
// Scope returns the GORM scopes with the search query.
func (s *Search) Scope(schema *schema.Schema) func(*gorm.DB) *gorm.DB {
if len(s.Fields) == 0 {
return nil
}
return func(tx *gorm.DB) *gorm.DB {
searchQuery := tx.Session(&gorm.Session{NewDB: true})
for _, field := range s.Fields {
f, sch, joinName := getField(field, schema, nil)
if f == nil {
continue
}
dataType := getDataType(f)
if dataType == DataTypeUnsupported {
continue
}
if joinName != "" {
if err := tx.Statement.Parse(tx.Statement.Model); err != nil {
tx.AddError(err)
return tx
}
tx = join(tx, joinName, schema)
}
filter := &Filter{
Field: f.DBName,
Operator: s.Operator,
Args: []string{s.Query},
Or: true,
}
table := tx.Statement.Quote(tableFromJoinName(sch.Table, joinName))
computed := f.StructField.Tag.Get("computed")
var fieldExpr string
if computed != "" {
fieldExpr = fmt.Sprintf("(%s)", strings.ReplaceAll(computed, clause.CurrentTable, table))
} else {
fieldExpr = table + "." + tx.Statement.Quote(f.DBName)
}
searchQuery = s.Operator.Function(searchQuery, filter, fieldExpr, dataType)
}
return tx.Where(searchQuery)
}
}