Can I aggregate a calculation?

ok i have a super beginner question again, can i aggregate a calculation? in my machine resource i have an aggregate that suppose to aggregate through my states and sum all the runtimes

  aggregates do
    sum :total_runtime, :states, :runtime
  end

in my state_time resource i have

  calculations do
    calculate :runtime, :integer, {Mes.Core.Calculation.RuntimeCalculation, []} do
      public? true
    end
  end

From my Terminal

{:ok,
 #Mes.Core.StateTime<
   runtime: 2989,
   machine: #Ash.NotLoaded<:relationship, field: :machine>,
   state: #Ash.NotLoaded<:relationship, field: :state>,
   __meta__: #Ecto.Schema.Metadata<:loaded, "statetimes">,
   id: "ca1671fd-fbcc-4e29-aef0-cf2e0cd19296",
   inserted_at: ~U[2024-11-20 18:15:15.086000Z],
   ended_at: nil,
   state_id: "96e82f7d-6bba-4c93-9843-a7e321d2abb8",
   machine_id: "978085ec-b3de-4f7f-9b42-35bd26889a4f",
   aggregates: %{},
   calculations: %{},
   ...
 }
iex(13)> maschine |>
...(13)> Ash.load(:total_runtime)
** (UndefinedFunctionError) function Mes.Core.Calculation.RuntimeCalculation.expression/2 is undefined or private. Did you mean:
      * has_expression?/0
    (mes 0.1.0) Mes.Core.Calculation.RuntimeCalculation.expression([], %Ash.Resource.Calculation.Context{actor: nil, tenant: nil, authorize?: true, tracer: nil, domain: nil, resource: nil, type: Ash.Type.Integer, constraints: [], arguments: %{}, source_context: %{}})
    (ash_sql 0.2.36) lib/aggregate.ex:795: anonymous fn/5 in AshSql.Aggregate.maybe_filter_subquery/6
    (elixir 1.17.3) lib/enum.ex:4858: Enumerable.List.reduce/3
    (elixir 1.17.3) lib/enum.ex:2585: Enum.reduce_while/3
    (ash_sql 0.2.36) lib/aggregate.ex:325: anonymous fn/10 in AshSql.Aggregate.add_aggregates/6
    (ash_sql 0.2.36) lib/join.ex:276: AshSql.Join.related_subquery/3
    (ash_sql 0.2.36) lib/aggregate.ex:171: anonymous fn/7 in AshSql.Aggregate.add_aggregates/6
    (elixir 1.17.3) lib/enum.ex:4858: Enumerable.List.reduce/3
    (elixir 1.17.3) lib/enum.ex:2585: Enum.reduce_while/3
    (ash_sql 0.2.36) lib/aggregate.ex:88: AshSql.Aggregate.add_aggregates/6
    (ash 3.4.35) lib/ash/query/query.ex:2972: Ash.Query.data_layer_query/2
    (ash 3.4.35) lib/ash/actions/read/read.ex:1052: Ash.Actions.Read.reselect_and_load/6
    (ash 3.4.35) lib/ash/actions/read/read.ex:260: Ash.Actions.Read.do_run/3
    (ash 3.4.35) lib/ash/actions/read/read.ex:81: anonymous fn/3 in Ash.Actions.Read.run/3
    (ash 3.4.35) lib/ash.ex:1859: Ash.load/3
    (ash 3.4.35) lib/ash.ex:1813: Ash.load/3
    iex:14: (file)

You can’t aggregate calculations, but you can calculate on other calculations, which will achieve your goal.

2 Likes

ok thanks, i will try that

You can aggregate calculations but only if the are expression calculations or define an expression callback.