forked from ash-project/ash_sql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcalculation.ex
More file actions
218 lines (188 loc) · 6.62 KB
/
calculation.ex
File metadata and controls
218 lines (188 loc) · 6.62 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
214
215
216
217
218
# SPDX-FileCopyrightText: 2024 ash_sql contributors <https://github.com/ash-project/ash_sql/graphs.contributors>
#
# SPDX-License-Identifier: MIT
defmodule AshSql.Calculation do
@moduledoc false
require Ecto.Query
@next_calculation_names Enum.reduce(0..999, %{}, fn i, acc ->
Map.put(acc, :"calculation_#{i}", :"calculation_#{i + 1}")
end)
def add_calculations(query, calculations, resource, source_binding, select? \\ false)
def add_calculations(query, [], _, _, _select?), do: {:ok, query}
def add_calculations(query, calculations, resource, source_binding, select?) do
{:ok, query} =
AshSql.Join.join_all_relationships(
query,
%Ash.Filter{
resource: resource,
expression: Enum.map(calculations, &elem(&1, 1))
},
left_only?: true
)
aggregates =
calculations
|> Enum.flat_map(fn {calculation, expression} ->
expression
|> Ash.Filter.used_aggregates([])
|> Enum.map(&Map.put(&1, :context, calculation.context))
end)
|> Enum.uniq()
{query, calculations} =
Enum.reduce(
calculations,
{query, []},
fn {calculation, expression}, {query, calculations} ->
if is_atom(calculation.name) do
{query, [{calculation, expression} | calculations]}
else
{query, name} = use_calculation_name(query, calculation.name)
{query, [{%{calculation | name: name}, expression} | calculations]}
end
end
)
case AshSql.Aggregate.add_aggregates(
query,
aggregates,
query.__ash_bindings__.resource,
false,
source_binding
) do
{:ok, query} ->
combinations? = query.__ash_bindings__.context[:data_layer][:combination_query?]
if select? || combinations? do
query =
if query.select do
query
else
Ecto.Query.select_merge(query, %{})
end
{dynamics, query} =
Enum.reduce(calculations, {[], query}, fn {calculation, expression}, {list, query} ->
expression =
Ash.Actions.Read.add_calc_context_to_filter(
expression,
calculation.context.actor,
calculation.context.authorize?,
calculation.context.tenant,
calculation.context.tracer,
query.__ash_bindings__[:domain],
query.__ash_bindings__[:resource],
parent_stack: query.__ash_bindings__[:parent_resources] || []
)
expression =
if calculation.context.type do
case expression do
%Ash.Query.Function.Type{arguments: [expression | _]} ->
expression
%Ash.Query.Call{name: :type, args: [expression | _]} ->
expression
_ ->
expression
end
else
expression
end
expression =
if is_nil(calculation.context.type) ||
map_type?(calculation.context.type, calculation.context.constraints || []) do
expression
else
{:ok, expression} =
Ash.Query.Function.Type.new([
expression,
calculation.context.type,
calculation.context.constraints || []
])
expression
end
{expression, acc} =
AshSql.Expr.dynamic_expr(
query,
expression,
Map.put(query.__ash_bindings__, :location, :select),
false,
{calculation.type, Map.get(calculation, :constraints, [])}
)
load =
if combinations? do
calculation.name
else
calculation.load
end
{[{load, calculation.name, expression} | list],
AshSql.Expr.merge_accumulator(query, acc)}
end)
{:ok, add_calculation_selects(query, dynamics)}
else
{:ok, query}
end
{:error, error} ->
{:error, error}
end
end
def next_calculation_name(i) do
@next_calculation_names[i] ||
raise Ash.Error.Framework.AssumptionFailed,
message: """
All 1000 static names for calculations have been used in a single query.
Congratulations, this means that you have gone so wildly beyond our imagination
of how much can fit into a single quer. Please file an issue and we will raise the limit.
"""
end
@doc false
def map_type?({:array, type}, constraints) do
map_type?(type, constraints[:items] || [])
end
def map_type?(type, constraints) when type in [:map, Ash.Type.Map] do
!Keyword.has_key?(constraints, :fields)
end
def map_type?(type, constraints) do
if Ash.Type.NewType.new_type?(type) do
constraints = Ash.Type.NewType.constraints(type, constraints)
type = Ash.Type.NewType.subtype_of(type)
map_type?(type, constraints)
else
false
end
end
defp use_calculation_name(query, aggregate_name) do
{%{
query
| __ash_bindings__: %{
query.__ash_bindings__
| current_calculation_name:
next_calculation_name(query.__ash_bindings__.current_calculation_name),
calculation_names:
Map.put(
query.__ash_bindings__.calculation_names,
aggregate_name,
query.__ash_bindings__.current_calculation_name
)
}
}, query.__ash_bindings__.current_calculation_name}
end
defp add_calculation_selects(query, dynamics) do
{in_calculations, in_body} =
Enum.split_with(dynamics, fn {load, _name, _dynamic} -> is_nil(load) end)
calcs =
in_body
|> Map.new(fn {load, _, dynamic} ->
{load, dynamic}
end)
calcs =
if Enum.empty?(in_calculations) do
calcs
else
Map.put(
calcs,
:calculations,
Map.new(in_calculations, fn {_, name, dynamic} ->
{name, dynamic}
end)
)
end
query = Ecto.Query.select_merge(query, ^calcs)
select_calculations = Map.keys(calcs) |> Enum.reject(&(&1 == :calculations))
put_in(query.__ash_bindings__[:select_calculations], select_calculations)
end
end