Calculation using nested relationship fails

I have the following calculation in my resource:

    calculate :total_lessons_in_class, :integer do
      calculation expr(count(classes.lessons, query: [filter: expr(class_id == ^arg(:class_id))]))

      argument :class_id, :string, allow_nil?: false
    end

As you can see, it will access this relationship:

  many_to_many :classes, Feedbacks.Class do
      through Feedbacks.StudentClass
      join_relationship :student_classes

      source_attribute_on_join_resource :student_id
      destination_attribute_on_join_resource :class_id
    end

And in that resource, the relationship:

has_many :lessons, Feedbacks.Lesson

When I try to load that calculation with:

%{id: "02vlizzA0fPRIsWh2ThIpi"} |> Core.Feedbacks.Student.get!(actor: actor) |> Ash.load!([total_lessons_in_class: %{class_id: "02vDK4Hfw3xc8jL4g0lOXd"}])

I get the following error:

** (Ecto.Query.CompileError) alias `1` already exists
    (ash_postgres 1.5.17) lib/join.ex:721: AshPostgres.Join.join_relationship/8
    (ash_postgres 1.5.17) lib/join.ex:142: anonymous fn/10 in AshPostgres.Join.join_all_relationships/10
    (elixir 1.16.1) lib/enum.ex:4842: Enumerable.List.reduce/3
    (elixir 1.16.1) lib/enum.ex:2582: Enum.reduce_while/3
    (ash_postgres 1.5.17) lib/aggregate.ex:286: anonymous fn/9 in AshPostgres.Aggregate.add_aggregates/6
    (ash_postgres 1.5.17) lib/join.ex:244: AshPostgres.Join.related_subquery/3
    (ash_postgres 1.5.17) lib/aggregate.ex:151: anonymous fn/6 in AshPostgres.Aggregate.add_aggregates/6
    (elixir 1.16.1) lib/enum.ex:4842: Enumerable.List.reduce/3
    (elixir 1.16.1) lib/enum.ex:2582: Enum.reduce_while/3
    (ash_postgres 1.5.17) lib/aggregate.ex:80: AshPostgres.Aggregate.add_aggregates/6
    (ash_postgres 1.5.17) lib/calculation.ex:49: AshPostgres.Calculation.add_calculations/5
    (ash 2.19.14) lib/ash/actions/read/read.ex:703: Ash.Actions.Read.reselect_and_load/6
    (ash 2.19.14) lib/ash/actions/read/read.ex:207: Ash.Actions.Read.do_run/3
    (ash 2.19.14) lib/ash/actions/read/read.ex:49: anonymous fn/3 in Ash.Actions.Read.run/3
    (ash 2.19.14) lib/ash/actions/read/read.ex:48: Ash.Actions.Read.run/3
    (ash 2.19.14) lib/ash/api/api.ex:2447: Ash.Api.load/4
    (ash 2.19.14) lib/ash/api/api.ex:2416: Ash.Api.load!/4

I believe this was working fine before, so it is probably a regression in one of the new Ash versions

And you’re on the latest ash_postgres version?

ash                         2.19.14  2.19.14  Up-to-date       
ash_postgres                1.5.17   1.5.17   Up-to-date

can you try ash_postgres main? Issue should be resolved there.

1 Like

Yep, using main fixed it