Search code examples
javadynamic-sqljooq

jOOQ - Building a dynamic `CASE WHEN` with DSL


I'm working with jOOQ and want to construct a dynamic CASE WHEN expression using the DSL. The desired outcome is a structure like this:

var myCase = DSL.case_()
  .when(condition1, result1)
  .when(condition2, result2)
  // ... additional WHEN clauses
  .else_(defaultValue);

However, a naive approach using a loop and subsequent .when calls encounters an issue. Since the return type of DSL.case_() changes after the first .when, adding a dummy initial condition like DSL.falseCondition() becomes necessary. This code below works, but feels clunky:

var myCase = DSL.case_()
  .when(DSL.falseCondition(), null); // Hack to change myCase's type

for (var entry:conditions)
  myCase.when( entry.getKey(), entry.getValue() )

return myCase.else_(defaultValue)

Is there a way to avoid this hack and build a dynamic CASE WHEN expression in jOOQ using the DSL?


Solution

  • Do this:

    if (conditions.isEmpty())
        return defaultValue;
    
    CaseConditionStep<T> c = null;
    
    for (var entry : conditions)
        c = c == null 
            ? DSL.when(entry.getKey(), getValue()) 
            : c.when(entry.getKey(), getValue());
    
    return c.else_(defaultValue);