-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathand_query.go
101 lines (71 loc) · 1.74 KB
/
and_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
package GormQueryFromJson
import (
"github.com/goccy/go-json"
"gorm.io/gorm"
)
type AndQuery struct {
Queries []BaseQuery `json:"queries"`
}
func (query *AndQuery) UnmarshalJSON(data []byte) error {
var dataJson []JSON
err := json.Unmarshal(data, &dataJson)
if err != nil {
return err
}
var queries []BaseQuery
for _, d := range dataJson {
q := GetQueryType(d.QueryType)
err := json.Unmarshal(d.Query, q)
if err != nil {
return err
}
queries = append(queries, q)
}
query.Queries = queries
return nil
}
func (query *AndQuery) Query(database *gorm.DB) *gorm.DB {
if len(query.Queries) == 0 {
return database.Session(&gorm.Session{})
}
return database.Where(query.buildAndCondition(database))
}
func (query *AndQuery) buildAndCondition(database *gorm.DB) *gorm.DB {
var conditions []*gorm.DB
for _, q := range query.Queries {
session := database.Session(&gorm.Session{})
conditions = append(conditions, q.Query(session))
}
andCondition := conditions[0] //nolint:nilaway
for i := 1; i < len(conditions); i++ {
andCondition.Where(conditions[i])
}
return andCondition
}
func (query *AndQuery) Type() TypeIdentifier {
return TypeAnd
}
func (query *AndQuery) ColumnUsages() []ColumnUsageInfo {
var columnUsages []ColumnUsageInfo
for _, q := range query.Queries {
columnUsages = append(columnUsages, q.ColumnUsages()...)
}
return columnUsages
}
func (query *AndQuery) Depth() (int, error) {
maxDepth := 0
for _, q := range query.Queries {
qDepth, err := q.Depth()
if err != nil {
return 0, err
}
if qDepth >= maxDepth {
return 0, ErrMaxDepth
}
}
// Remember this is another layer
return maxDepth + 1, nil
}
func (query *AndQuery) GetColumnName() (bool, string) {
return false, ""
}