Search code examples
postgresqljooq

Approaches to execute PostgreSQL's concat() instead of || in JOOQ?


The ||-operator and the concat(...)-function in PostgreSQL behave differently.

select 'ABC'||NULL||'def';
-- Result: NULL

select concat('ABC', NULL, 'def');
-- Result: 'ABCdef'

concat(...) ignores NULL values, but a NULL whithin a || expression makes the whole result become NULL.

In JOOQ, the DSL.concat() in the PostgreSQL dialect renders expressions using the ||-operator:

Java: dsl.select(
        DSL.concat(
          DSL.inline("ABC"), 
          DSL.inline(null, SQLDataType.VARCHAR), 
          DSL.inline("def"))
      ).execute();
SQL: select ('ABC' || null || 'def')
Result: NULL

I am looking for (elegant?) ways to invoke the concat(...)-function instead of the ||-operator via JOOQ in PostgreSQL:

Java: dsl.select(???).execute();
SQL: select concat('ABC', null, 'def')
Result: 'ABCdef'

Solution

  • I found two ways to achieve the posed objective.

    Approach #1:

    dsl.select(
      field(
        "concat({0})",
        SQLDataType.VARCHAR,
        list(
          inline("ABC"), 
          inline(null, SQLDataType.VARCHAR), 
          inline("def")
        )
      )
    ).execute();
    

    This has the intended behavior, but necessitates the in my eyes ugly "concat({0})". A more elegant approach from my point of view is:

    Approach #2:

    dsl.select(
      function(
        "concat", 
        SQLDataType.VARCHAR, 
        inline("ABC"), 
        inline(null, SQLDataType.VARCHAR), 
        inline("def")
      )
    ).execute();
    

    This solution does not involve inline SQL with placeholders as approach #1. Why JOOQ generates || instead of concat(...) in the first place is still to be expounded, though.