Search code examples
jooq

jOOQ: Can you force LIMIT to be rendered as ROW_NUMBER() window function?


I see this bit in the jOOQ docs:

https://github.com/jOOQ/jOOQ/blob/d727e6c476e8b1cbed1c91fd3724936c73cd9126/jOOQ/src/main/java/org/jooq/SelectLimitStep.java#L135-L147

    /**
     * Add a <code>LIMIT</code> clause to the query
     * <p>
     * If there is no <code>LIMIT</code> or <code>TOP</code> clause in your
     * RDBMS, this may be emulated with a <code>ROW_NUMBER()</code> window
     * function and nested <code>SELECT</code> statements.
     * <p>
     * This is the same as calling {@link #limit(Number, Number)} with offset = 0, or
     * calling <code>.limit(numberOfRows).offset(0)</code>
     */

I'm wondering if there is a setting to force-enable this option?

There seems to be a setting for the opposite, to convert ROW_NUMBER to LIMIT, but not LIMIT to ROW_NUMBER.

To get around this, I've written the below but if the ability exists in the codebase (and is probably implemented better) I'd like to take advantage of it:

fun wrapQueryInRowNumberSubquery(
    stmt: SelectFinalStep<Record>,
    limit: Int = 0,
    offset: Int = 0
): SelectConditionStep<Record> {
    stmt.query.addSelect(
        DSL.rowNumber().over()
            .partitionBy(DSL.field("*")) // custom logic here
            .orderBy(DSL.field("*")) // custom logic here
            .`as`("row_num")
    )
    return DSL.select(DSL.asterisk()).from(stmt)
        .where(
            DSL.field("row_num").greaterThan(
                DSL.inline(offset)
            )
        )
        .and(
            DSL.field("row_num").lessThan(
                DSL.inline(offset + limit)
            )
        )
}

Solution

  • There are currently (jOOQ 3.17) no flags to enable / disable individual emulations independently of the SQL dialect.