question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

More aggregate functions such as `array_agg` and `json_agg`

See original GitHub issue

It seems like this library currently only supports a subset of aggregate functions like count, max and min. Would it be possible to support array_agg or json_agg?

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Reactions:1
  • Comments:7 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
rliangcommented, Dec 12, 2021

Thanks for the help. My use case is mostly within subqueries. After fiddling around, I came up with the following generic wrapper, which seems to produce both correct SQL and Typescript types:

function json_agg<DB, TB extends keyof DB, O = {}>(qb: QueryBuilder<DB, TB, O>) {
  return db.raw<O[]>(`coalesce((select jsonb_agg(x) from (??) x), '[]'::jsonb)`, [qb]);
}

await db
    .selectFrom("person")
    .select([
      "id",
      (qb) =>
        json_agg(
          qb
            .subQuery("pet")
            .whereRef("pet.owner_id", "=", "person.id")
            .select("pet.name")
        ).as("pets"),
    ])
    .executeTakeFirst() // type is { id: string, pets: { name: string }[] }
1reaction
koskimascommented, Dec 7, 2021

I don’t know. Maybe. That’s the thing. It’s really difficult to write helpers that work in all cases, but pretty easy to write helpers that work for your own use case. For example, you could write this type-safe helper:

function json_agg<T extends keyof Database>(table: T): RawBuilder<Array<Database[T]>> {
  return db.raw(`json_agg(${table})`)
}

where Database is from Kysely<Database>.

await db
  .selectFrom('person')
  .innerJoin('pet', 'pet.owner_id', 'person.id')
  .select(json_agg('pet').as('pets'))
Read more comments on GitHub >

github_iconTop Results From Across the Web

Documentation: 9.5: Aggregate Functions - PostgreSQL
The aggregate functions array_agg , json_agg , jsonb_agg , json_object_agg ... out merely to avoid cluttering the listing of more-commonly-used aggregates.
Read more >
array_agg(), string_agg(), jsonb_agg(), jsonb_object_agg()
This aggregate function, together with json_agg() , are described fully in the jsonb_agg() section within the overall JSON section. ... Purpose: Returns a...
Read more >
Aggregate functions | BigQuery - Google Cloud
To learn about the syntax for aggregate function calls, see Aggregate ... SELECT ARRAY_AGG(x) AS array_agg FROM UNNEST([2, 1,-2, 3, -2, 1, 2])...
Read more >
Have multiple aggregations in a query always the same order?
Given an sql query with multiple aggregates, especially array_agg , is the order of the aggregated values deterministic? Example: SELECT ...
Read more >
9.21. Aggregate Functions - Crunchy Data
Collects all the input values, including nulls, into an array. No. array_agg ( anyarray ) → anyarray. Concatenates all the input arrays into...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found