Skip to content

Named query aggregate used in a filter or sort raises "struct does not have the key :aggregate_0" #273

Closed

Description

@yosalama

Code of Conduct

  • I agree to follow this project's Code of Conduct

AI Policy

  • I agree to follow this project's AI Policy, or I agree that AI was not used while creating this issue.

Versions

Elixir 1.20.4, Erlang/OTP 29
ash 3.36.1
ash_postgres 2.14.5
ash_sql 0.8.1
PostgreSQL 18

Works on ash_sql 0.7.6. Fails from #264 (0ef973c) on, including 0.8.1.

Operating system

Linux

Current Behavior

When a query aggregate added with Ash.Query.aggregate/4 is used in a filter or sort, the read raises:

** (Ash.Error.Unknown)
* ** (ArgumentError) struct AshPostgres.Test.Post does not have the key :aggregate_0

Reproduction

Add this test to the AshPostgres test suite and run mix test:

defmodule AshPostgres.QueryAggregateReproTest do
use AshPostgres.RepoCase, async: false
require Ash.Query
alias AshPostgres.Test.{Comment, Post}

setup do
  post = Ash.create!(Post, %{title: "post"})
  Ash.create!(Comment, %{title: "comment", post_id: post.id})

  query = Ash.Query.aggregate(Post, "count", :count, :comments)
  %{query: query, ref: %Ash.Query.Ref{attribute:    query.aggregates["count"], resource: Post}}
end

test "filter by a query aggregate", %{query: query, ref: ref} do
  assert [%{aggregates: %{"count" => 1}}] = query |> Ash.Query.filter(^ref > 0) |> Ash.read!()
end

test "sort by a query aggregate", %{query: query} do
  assert [%{aggregates: %{"count" => 1}}] = query |> Ash.Query.sort([{query.aggregates["count"], :desc}]) |> Ash.read!()
end
end

Expected Behavior

The read should return the post with aggregates["count"] == 1.

Possible fix, with tests: yosalama@791ffc1 (written with AI help). I can open it as a PR if it's useful

Activity

  1. added theissue type on Oct 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions