Using PosgreSQL array_agg with join alias in JOOQ DSL

*爱你&永不变心* 提交于 2019-12-10 18:55:04

问题


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.


回答1:


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))




回答2:


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.



来源:https://stackoverflow.com/questions/51753861/using-posgresql-array-agg-with-join-alias-in-jooq-dsl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!