Tobias Marschall
Tobias Marschall

Reputation: 2579

Using PosgreSQL array_agg with join alias in JOOQ DSL

I want to convert this SQL query to JOOQ DSL.

select "p".*, array_agg("pmu") as projectmemberusers
from "Projects" as "p"
join "ProjectMemberUsers" as "pmu" on "pmu"."projectId" = "p"."id"
group by "p"."id";

Currently i have tried doing something like this using JOOQ:

val p = PROJECTS.`as`("p")
val pmu = PROJECTMEMBERUSERS.`as`("pmu")
val query = db.select(p.asterisk(), DSL.arrayAgg(pmu))
        .from(p.join(pmu).on(p.ID.eq(pmu.PROJECTID)))
        .groupBy(p.ID)

This does not work because DSL.arrayAgg expects something of type Field<T> as input.

I am new to JOOQ and not an SQL professional. Detailed explanations and impovement suggestions are highly appreciated.

Upvotes: 4

Views: 1822

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 220952

What you're looking for is a way to express PostgreSQL's "anonymous" nested records through the jOOQ API, similar to what is requested in this feature request: https://github.com/jOOQ/jOOQ/issues/2360

This is currently not possible in the jOOQ API as of version 3.11, but it definitely will be in the future.

Workaround 1

You could try using the experimental DSL.rowField() methods on a Row[N]<...> representation of your table type. This may or may not work yet, as the feature is currently not supported.

Workaround 2

A workaround is to create a type:

create type my_type as (...) -- Same row type as your table

And a view:

create view x as
select "p".*, array_agg("pmu"::my_type) as projectmemberusers
from "Projects" as "p"
join "ProjectMemberUsers" as "pmu" on "pmu"."projectId" = "p"."id"
group by "p"."id";

And then use the code generator to pick up the resulting type.

Upvotes: 2

Alexey Soshin
Alexey Soshin

Reputation: 17721

First of all, the syntax indeed works, checked this in SQL Fiddle: http://sqlfiddle.com/#!17/e45b7/3

But it's not documented in detail: https://www.postgresql.org/docs/9.5/static/functions-aggregate.html https://www.postgresql.org/docs/current/static/rowtypes.html#ROWTYPES-USAGE

That's probably the reason jOOQ doesn't support this currently: https://github.com/jOOQ/jOOQ/blob/master/jOOQ/src/main/java/org/jooq/impl/DSL.java#L16856

The only syntax that will work currently is with a single field: DSL.arrayAgg(pmu.field(1))

Upvotes: 4

Related Questions