-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrelation_aggregate.go
More file actions
213 lines (191 loc) Β· 7.17 KB
/
Copy pathrelation_aggregate.go
File metadata and controls
213 lines (191 loc) Β· 7.17 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package oro
import (
"context"
"strings"
)
// RelationAggregateExpr describes an aggregate subquery over a relation.
type RelationAggregateExpr struct {
Func string
Relation any
Field string
Alias string
Callback func(*RelationQuery)
}
// CountOf selects the count of a relation.
func CountOf(relation any) RelationAggregateExpr {
return RelationAggregateExpr{Func: "count", Relation: relation}
}
// ExistsOf selects whether a relation has at least one row.
func ExistsOf(relation any) RelationAggregateExpr {
return RelationAggregateExpr{Func: "exists", Relation: relation}
}
// SumOf selects the sum of field over a relation.
func SumOf(relation any, field string) RelationAggregateExpr {
return RelationAggregateExpr{Func: "sum", Relation: relation, Field: field}
}
// AvgOf selects the average of field over a relation.
func AvgOf(relation any, field string) RelationAggregateExpr {
return RelationAggregateExpr{Func: "avg", Relation: relation, Field: field}
}
// MinOf selects the minimum of field over a relation.
func MinOf(relation any, field string) RelationAggregateExpr {
return RelationAggregateExpr{Func: "min", Relation: relation, Field: field}
}
// MaxOf selects the maximum of field over a relation.
func MaxOf(relation any, field string) RelationAggregateExpr {
return RelationAggregateExpr{Func: "max", Relation: relation, Field: field}
}
// As aliases the relation aggregate result.
func (expr RelationAggregateExpr) As(alias string) RelationAggregateExpr {
expr.Alias = alias
return expr
}
// Filter customizes the relation query used by the aggregate.
func (expr RelationAggregateExpr) Filter(fn func(*RelationQuery)) RelationAggregateExpr {
expr.Callback = fn
return expr
}
// WithCount appends a relation count select expression.
func (query *ModelQuery[T]) WithCount(relation any, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
return query.withRelationAggregate(CountOf(relation), callbacks...)
}
// WithExists appends a relation exists select expression.
func (query *ModelQuery[T]) WithExists(relation any, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
return query.withRelationAggregate(ExistsOf(relation), callbacks...)
}
// WithSum appends a relation sum select expression.
func (query *ModelQuery[T]) WithSum(relation any, field string, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
return query.withRelationAggregate(SumOf(relation, field), callbacks...)
}
// WithAvg appends a relation average select expression.
func (query *ModelQuery[T]) WithAvg(relation any, field string, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
return query.withRelationAggregate(AvgOf(relation, field), callbacks...)
}
// WithMin appends a relation minimum select expression.
func (query *ModelQuery[T]) WithMin(relation any, field string, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
return query.withRelationAggregate(MinOf(relation, field), callbacks...)
}
// WithMax appends a relation maximum select expression.
func (query *ModelQuery[T]) WithMax(relation any, field string, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
return query.withRelationAggregate(MaxOf(relation, field), callbacks...)
}
func (query *ModelQuery[T]) withRelationAggregate(expr RelationAggregateExpr, callbacks ...func(*RelationQuery)) *ModelQuery[T] {
clone := *query
if len(clone.spec.Select) == 0 {
schema, err := schemaForModel[T](query.db)
if err != nil {
clone.spec.SelectErr = err
return &clone
}
clone.spec.Select = defaultModelSelectExprs(schema)
}
if len(callbacks) > 0 {
expr.Callback = callbacks[0]
}
if expr.Alias == "" {
schema, err := schemaForModel[T](query.db)
if err != nil {
clone.spec.SelectErr = err
return &clone
}
relation, err := resolveRelationFilterSchema(schema, expr.Relation)
if err != nil {
clone.spec.SelectErr = err
return &clone
}
expr.Alias = defaultRelationAggregateAlias(relation, expr)
}
exprs, err := selectExprs([]any{expr})
if err != nil {
clone.spec.SelectErr = err
return &clone
}
clone.spec.Select = append(clone.spec.Select, exprs...)
return &clone
}
func defaultModelSelectExprs(schema *ModelSchema) []SelectExpr {
selects := make([]SelectExpr, 0, len(schema.Fields))
for _, field := range schema.Fields {
if field.Hidden || field.Virtual {
continue
}
selects = append(selects, SelectExpr{Expr: field.Name})
}
return selects
}
func defaultRelationAggregateAlias(relation RelationSchema, expr RelationAggregateExpr) string {
switch expr.Func {
case "count":
return Snake(relation.Name + "Count")
case "exists":
return Snake(relation.Name + "Exists")
default:
return Snake(relation.Name + strings.Title(expr.Field) + strings.Title(expr.Func))
}
}
func resolveModelRelationAggregates(ctx context.Context, db *DB, sourceSchema *ModelSchema, spec *QuerySpec) error {
for index := range spec.Select {
if spec.Select[index].Expr != "__oro_relation_aggregate__" || len(spec.Select[index].Args) == 0 {
continue
}
expr, ok := spec.Select[index].Args[0].(RelationAggregateExpr)
if !ok {
return &Error{Op: "relation_aggregate", Kind: ErrInvalidArgument, Model: sourceSchema.Name}
}
resolved, err := buildRelationAggregateSelect(ctx, db, sourceSchema, *spec, expr)
if err != nil {
return err
}
spec.Select[index] = resolved
}
return nil
}
func buildRelationAggregateSelect(ctx context.Context, db *DB, sourceSchema *ModelSchema, sourceSpec QuerySpec, expr RelationAggregateExpr) (SelectExpr, error) {
relation, err := resolveRelationFilterSchema(sourceSchema, expr.Relation)
if err != nil {
return SelectExpr{}, err
}
if expr.Alias == "" {
expr.Alias = defaultRelationAggregateAlias(relation, expr)
}
targetSchema, err := relationFilterTargetSchema(db, sourceSpec, relation)
if err != nil {
return SelectExpr{}, err
}
subquery, _, err := relationFilterSubquery(ctx, db, sourceSchema, targetSchema, sourceSpec, relation, expr.Callback)
if err != nil {
return SelectExpr{}, err
}
if expr.Func == "exists" {
subquery.spec.Select = []SelectExpr{{Expr: "1", Raw: true}}
subquery.spec.Order = nil
subquery.spec.Limit = nil
subquery.spec.Offset = nil
source := Query(subquery).sourceAST()
return SelectExpr{Expr: "__oro_relation_exists__", Alias: expr.Alias, Raw: true, Args: []any{source}}, nil
}
selectExpr, err := relationAggregateSubquerySelect(targetSchema, expr)
if err != nil {
return SelectExpr{}, err
}
subquery.spec.Select = []SelectExpr{selectExpr}
subquery.spec.Order = nil
subquery.spec.Limit = nil
subquery.spec.Offset = nil
source := Query(subquery).sourceAST()
return SelectExpr{Alias: expr.Alias, Source: &source}, nil
}
func relationAggregateSubquerySelect(schema *ModelSchema, expr RelationAggregateExpr) (SelectExpr, error) {
switch expr.Func {
case "count":
return SelectExpr{Expr: "count(*)", Raw: true}, nil
case "sum", "avg", "min", "max":
field, ok := schema.FieldByGo[expr.Field]
if !ok {
return SelectExpr{}, &Error{Op: "relation_aggregate", Kind: ErrUnknownField, Model: schema.Name, Field: expr.Field}
}
return SelectExpr{Expr: "__oro_aggregate__", Args: []any{AggregateExpr{Func: expr.Func, Field: field.Column}}}, nil
default:
return SelectExpr{}, &Error{Op: "relation_aggregate", Kind: ErrInvalidArgument, Model: schema.Name}
}
}