Search code examples
javapostgresqljooquser-defined-types

How to form where clause in jooq when filtering by user defined type


I'm using postgresql (10.2) with jooq (3.8.7), lets say I have a type and a table like:

CREATE TYPE my_type AS (
    id INTEGER,
    name TEXT
);

CREATE table my_table (
    id INTEGER,
    something my_type 
);

Then how do I fetch all records of my_table where my_table.something.name = 'test' by using jooq? I tried doing something like this:

ctx.selectFrom(MY_TABLE)
   .where(MY_TABLE.SOMETHING.NAME.eq("test")) \\ SOMETHING is a TableField 
   ...                                        \\ and does not have NAME field

But that does not work (explained in code comments). This is what I want to do in jooq:

SELECT * FROM my_table WHERE (something).name = 'test';

Solution

  • Accessing user defined type attributes through the DSL is currently not implemented in jOOQ 3.11. The relevant pending feature request is here: https://github.com/jOOQ/jOOQ/issues/228

    As always, when running in such a limitation, you can resort to using plain SQL templating:

    ctx.selectFrom(MY_TABLE)
       .where("{0}.{1} = {2}", MY_TABLE.SOMETHING, MY_TYPE.NAME, DSL.val("test"))
       ...
    

    Of course, if you're doing this more often, you might want to wrap this kind of logic into your own client side templating API to improve reusing similar patterns.