Skip to content

Add support for json_agg_strict (PostgreSQL only) #892

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/query-builder/function-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -739,6 +739,40 @@ export interface FunctionModule<DB, TB extends keyof DB> {
: never
>

/**
* Creates a json_agg_strict function call.
*
* This function is only available on PostgreSQL.
*
* ```ts
* db.selectFrom('person')
* .innerJoin('pet', 'pet.owner_id', 'person.id')
* .select((eb) => ['first_name', eb.fn.jsonAggStrict('pet').as('pets')])
* .groupBy('person.first_name')
* .execute()
* ```
*
* The generated SQL (PostgreSQL):
*
* ```sql
* select "first_name", json_agg_strict("pet") as "pets"
* from "person"
* inner join "pet" on "pet"."owner_id" = "person"."id"
* group by "person"."first_name"
* ```
*/
jsonAggStrict<T extends (TB & string) | Expression<unknown>>(
table: T,
): AggregateFunctionBuilder<
DB,
TB,
T extends TB
? Selectable<DB[T]>[]
: T extends Expression<infer O>
? O[]
: never
>

/**
* Creates a to_json function call.
*
Expand Down Expand Up @@ -850,6 +884,14 @@ export function createFunctionModule<DB, TB extends keyof DB>(): FunctionModule<
})
},

jsonAggStrict(table: string | Expression<unknown>): any {
return new AggregateFunctionBuilder({
aggregateFunctionNode: AggregateFunctionNode.create('json_agg_strict', [
isString(table) ? parseTable(table) : table.toOperationNode(),
]),
})
},

toJson(table: string | Expression<unknown>): any {
return new ExpressionWrapper(
FunctionNode.create('to_json', [
Expand Down
133 changes: 133 additions & 0 deletions test/node/src/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,139 @@ for (const dialect of DIALECTS) {
])
})

it('should aggregate a joined table using json_agg_strict', async () => {
const res = await db
.selectFrom('person')
.innerJoin('pet', 'pet.owner_id', 'person.id')
.select((eb) => ['first_name', eb.fn.jsonAggStrict('pet').as('pets')])
.groupBy('person.first_name')
.execute()

expect(res).to.have.length(3)
expect(res).to.containSubset([
{
first_name: 'Jennifer',
pets: [{ name: 'Catto', species: 'cat' }],
},
{
first_name: 'Arnold',
pets: [
{
name: 'Doggo',
species: 'dog',
},
],
},
{
first_name: 'Sylvester',
pets: [{ name: 'Hammo', species: 'hamster' }],
},
])
})

it('should aggregate a joined table using json_agg_strict and distinct', async () => {
const res = await db
.selectFrom('person')
.innerJoin('pet', 'pet.owner_id', 'person.id')
.select((eb) => [
'first_name',
eb.fn.jsonAggStrict('pet').distinct().as('pets'),
])
.groupBy('person.first_name')
.execute()

expect(res).to.have.length(3)
expect(res).to.containSubset([
{
first_name: 'Jennifer',
pets: [{ name: 'Catto', species: 'cat' }],
},
{
first_name: 'Arnold',
pets: [
{
name: 'Doggo',
species: 'dog',
},
],
},
{
first_name: 'Sylvester',
pets: [{ name: 'Hammo', species: 'hamster' }],
},
])
})

it('should aggregate a subquery using json_agg_strict', async () => {
const res = await db
.selectFrom('person')
.select((eb) => [
'first_name',
eb
.selectFrom('pet')
.select((eb) => eb.fn.jsonAggStrict('pet').as('pet'))
.whereRef('pet.owner_id', '=', 'person.id')
.as('pets'),
])
.execute()

expect(res).to.have.length(3)
expect(res).to.containSubset([
{
first_name: 'Jennifer',
pets: [{ name: 'Catto', species: 'cat' }],
},
{
first_name: 'Arnold',
pets: [
{
name: 'Doggo',
species: 'dog',
},
],
},
{
first_name: 'Sylvester',
pets: [{ name: 'Hammo', species: 'hamster' }],
},
])
})

it('should aggregate a subquery using json_agg_strict and eb.table', async () => {
const res = await db
.selectFrom('person')
.select((eb) => [
'first_name',
eb
.selectFrom('pet')
.select((eb) => eb.fn.jsonAggStrict(eb.table('pet')).as('pet'))
.whereRef('pet.owner_id', '=', 'person.id')
.as('pets'),
])
.execute()

expect(res).to.have.length(3)
expect(res).to.containSubset([
{
first_name: 'Jennifer',
pets: [{ name: 'Catto', species: 'cat' }],
},
{
first_name: 'Arnold',
pets: [
{
name: 'Doggo',
species: 'dog',
},
],
},
{
first_name: 'Sylvester',
pets: [{ name: 'Hammo', species: 'hamster' }],
},
])
})

it('should jsonify a joined table using to_json', async () => {
const res = await db
.selectFrom('person')
Expand Down
95 changes: 95 additions & 0 deletions test/typings/test-d/postgres-json.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,101 @@ async function testPostgresJsonAgg(db: Kysely<Database>) {
}>(r4)
}

async function testPostgresJsonAggStrict(db: Kysely<Database>) {
const r1 = await db
.selectFrom('person')
.innerJoin('pet', 'pet.owner_id', 'person.id')
.select((eb) => ['first_name', eb.fn.jsonAggStrict('pet').as('pets')])
.groupBy('person.first_name')
.execute()

expectType<
{
first_name: string
pets: Selectable<Pet>[]
}[]
>(r1)

const r2 = await db
.selectFrom('person')
.select((eb) => [
'first_name',
eb
.selectFrom('pet')
.select((eb) => eb.fn.jsonAgg('pet').as('pet'))
.whereRef('pet.owner_id', '=', 'person.id')
.as('pets'),
])
.execute()

expectType<
{
first_name: string
pets: Selectable<Pet>[] | null
}[]
>(r2)

const r3 = await db
.selectFrom('person')
.select((eb) => [
'first_name',
eb
.selectFrom('pet')
.select((eb) => eb.fn.jsonAgg(eb.table('pet')).as('pet'))
.whereRef('pet.owner_id', '=', 'person.id')
.as('pets'),
])
.execute()

expectType<
{
first_name: string
pets: Selectable<Pet>[] | null
}[]
>(r3)

const db2 = db.withTables<{
acquisition: {
id: number
}
transaction: {
id: number
acquisitionId: number
status: string
}
}>()

const r4 = await db2
.selectFrom('acquisition')
.leftJoin('transaction', 'transaction.acquisitionId', 'acquisition.id')
.select(({ ref, fn }) => [
'acquisition.id',
fn
.coalesce(
fn
.jsonAgg(
jsonBuildObject({
id: ref('transaction.id').$notNull(),
status: ref('transaction.status'),
}),
)
.filterWhere('transaction.id', 'is not', null),
sql`'[]'`,
)
.as('transactions'),
])
.groupBy('acquisition.id')
.executeTakeFirstOrThrow()

expectType<{
id: number
transactions: {
id: number
status: string | null
}[]
}>(r4)
}

async function testPostgresToJson(db: Kysely<Database>) {
const r1 = await db
.selectFrom('person')
Expand Down