Using jOOQ 3.11.2 and Postgres 9.4, I am trying to re-use one jOOQ CTE in the definition of a second CTE.
The following is incorrect per StackOverflow question How to re-use one CTE in another CTE in jOOQ
CommonTableExpression<...> cteTwo = name().fields().as(select( with(cteOne ... ).from(cteOne) );
Based on the above answer I omitted the with(cteOne) clause in cteTwo completely. I tried:
import static org.jooq.impl.DSL.*;
CommonTableExpression<...> cteOne = name().fields().as(select(...);
CommonTableExpression<...> cteTwo = name().fields().as(select().from(cteOne) ); // seem to need with(cteOne) here.
List<someDTO> result = create
.with(cteOne)
.with(CteTwo)
.select(...)
.from(cteTwo)
.fetchInto(someDTO.class);
The above compiles but runs with error: 'jooq: bad SQL grammar. ... ERROR: relation \"cteOne\" does not exist.' Looking at the generated SQL, there is no reference to cteOne within cteTwo.
Then I tried putting with(cteOne)
clause in different places within inside the cteTwo definition. There are only three more places before the SELECT clause to try. None were correct:
CommonTableExpression<...> cteTwo = with(cteOne).name().fields().as(select( ... ).from(cteOne) );
CommonTableExpression<...> cteTwo = name() with(cteOne).fields().as(select( ... ).from(cteOne) );
CommonTableExpression<...> cteTwo = name().fields().with(cteOne).as(select( ... ).from(cteOne) );
Please note that this different from defining several CTE's and then using each CTE in a final select statement like so:
CommonTableExpression<...> cteAlpha = name(...).fields(...).as(select(...);
CommonTableExpression<...> cteBeta = name(...).fields(...).as(select(...);
List<SomeDTO> list = create
.with(cteAlpha)
.with(cteBeta)
.select(...) from(cteAlpha, cteBeta).fetchInto(SomeDTO.class);
I haven't found documentation or examples covering this precise point. How should this be done?