Skip to content

feat: Support Postgres json_agg/json_build_object aggregate functions - #4798

Open
wilkinson4 wants to merge 1 commit into
elixir-ecto:masterfrom
wilkinson4:ww/add-json-functions
Open

wilkinson4 wants to merge 1 commit into
elixir-ecto:masterfrom
wilkinson4:ww/add-json-functions

Conversation

@wilkinson4

Copy link
Copy Markdown
Contributor

Introduce json_build_object/1 with literal-map input and json_agg/1,2 with aggregate-local ordering.

These functions make database-side JSON construction composable in Ecto queries without handwritten SQL fragments. Aggregating related rows into JSON can reduce repeated parent data transferred from the database and avoid application-side grouping and object assembly.

Sometimes it makes sense not to use preloads for performance reasons. It is nice to not have to use fragments when we don't have to. In these situations, the combined usage of json_agg + json_build_object Postgres aggregate functions has been a nice solution for the grouping problem when trying to build an array of objects for each row in the results.

Example:

from(a in Appointment
  as: :appointment,
  select: %{
    id: a.id,
    participants:
      fragment(
        """
          select json_agg(json_build_object('primary' , sub.primary , 'name' , sub.full_name))
          from (
            select p.primary
              , u.full_name
            from appointment_participants p
              join users u on u.id = p.user_id
            where p.appointment_id = ?
            order by p.primary desc
        ) sub
        """,
        a.id
      )
  }
)
|> Repo.all()

…ions

Introduce json_build_object/1 with literal-map input and json_agg/1,2
with aggregate-local ordering.

These functions make database-side JSON construction composable in
Ecto queries without handwritten SQL fragments. Aggregating related
rows into JSON can reduce repeated parent data transferred from the
database and avoid application-side grouping and object assembly.
@josevalim

Copy link
Copy Markdown
Member

Thanks for the PR but we will likely not go down this path given it will lead to jsonb_agg, json_object_agg and so on. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants