Skip to content

Conversation

griffio
Copy link
Collaborator

@griffio griffio commented Oct 6, 2025

Add JSON Aggregate Functions FILTER useful for working with schema-less column data (similar to #4703)

https://www.postgresql.org/docs/current/functions-aggregate.html

Add missing aggregate object functions

json_object_agg(key, value)
jsonb_object_agg(key, value)

Add json aggregate FILTER clause

SELECT json_agg(data) FILTER (WHERE (data->>'in_stock')::BOOLEAN) FROM SomeTable;

SELECT jsonb_agg(data->'color') FILTER (WHERE data ?? 'color') AS colors FROM SomeTable;

SELECT jsonb_object_agg(key, value ORDER BY key DESC) FILTER (WHERE key IS NOT NULL) FROM SomeTable;

SELECT jsonb_object_agg_strict(key, value) FROM SomeTable;
  • Adds grammar changes
    • Case where expressions could be double colon casted
    • Case where aggregate functions take a table reference or column reference (function expressions only take a column reference)
  • Adds fixture tests for grammar examples
  • Adds integration tests

New Functions in Pg16 - strict functions are same as FILTER ... WHERE key IS NOT NULL except they fail with an error.

json_agg_strict
jsonb_agg_strict

json_object_agg_strict
jsonb_object_agg_strict

json_object_agg_unique
jsonb_object_agg_unique

json_object_agg_unique_strict
jsonb_object_agg_unique_strict

  • CHANGELOG.md's "Unreleased" section has been updated, if applicable.

Add json_agg_stmt and json_object_agg_stmt for aggregate functions
json_agg_stmt takes `any` argument
json_object_agg_stmt takes `any` scalar key and `any` value

The grammar has to handle cases json_expression, tables etc as parameters to aggregate functions.
Add more aggregate functions (strict functions are from Pg16) where they are used without the FILTER clause.

Map the json aggregate statements to JSON type
Example uses of json aggregates
json aggregate functions

json aggregate object functions
@griffio griffio changed the title Add Postgresql Json aggregate function FILTER Add Postgresql Json Aggregate Function FILTER Oct 6, 2025
@griffio griffio marked this pull request as ready for review October 6, 2025 11:34
@griffio griffio merged commit 31270b1 into sqldelight:master Oct 6, 2025
19 checks passed
@griffio griffio deleted the improved-postgresql-json-agg branch October 6, 2025 18:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants