graphile-engine icon indicating copy to clipboard operation
graphile-engine copied to clipboard

Feature: `@pgAggregate` directive for specifying custom aggregations

Open marshall007 opened this issue 6 years ago • 2 comments

As a solution to https://github.com/graphile/postgraphile/issues/685, it would be nice if we could leverage makeExtendSchemaPlugin to specify custom aggregations. This would be very similar to existing usage of the @pgQuery directive.

For example:

extend type PetsConnection {
  dogCount: Int @pgAggregate(
    withQueryBuilder: ${embed((queryBuilder) => queryBuilder
      .select(sql.fragment`count(1)`)
      .where(sql.fragment`${queryBuilder.getTableAlias()}.type = 'dog'`),
    )}
  )
  catCount: Int @pgAggregate(
    withQueryBuilder: ${embed((queryBuilder) => queryBuilder
      .select(sql.fragment`count(1)`)
      .where(sql.fragment`${queryBuilder.getTableAlias()}.type = 'cat'`),
    )}
  )
}

marshall007 avatar May 24 '19 15:05 marshall007

As couple "nice-to-haves" on top of this:

  • [ ] QueryBuilder.where(...) to optionally accept a plain object (e.g. .where({ type: 'cat' }), automatically prefixing the table alias and wrapping key/value pairs in sql.identifier/value respectively
  • [ ] leverage ^ to expose shorthand helpers as an alternative to withQueryBuilder
    • @pgAggregate(count: { type: 'cat' })
    • @pgAggregate(sum: 'quantity')

marshall007 avatar May 24 '19 16:05 marshall007

👍 I prefer @pgCount(where: {type: "cat"}) and @pgSum(column: "quantity"); effectively @pgAggregate will be the do-all that powers these simpler helpers.

benjie avatar May 24 '19 16:05 benjie

Better to use pg-aggregates where possible; or the new aggregation setup that V5 enables.

benjie avatar Sep 27 '23 17:09 benjie