2

How can this statement be expressed with jOOQ?

SELECT version FROM abc ORDER BY string_to_array(version, '.', '')::int[] desc limit 1

I am struggling with the function and cast combination.

Axel Fontaine
  • 32,887
  • 14
  • 101
  • 134

1 Answers1

6

You have various options.

Be lazy and wrap everything in a single plain SQL expression:

Field<Integer[]> f1 = 
    DSL.field("string_to_array(version, '.', '')::int[]", Integer[].class);

Create a re-usable function:

Field<Integer[]> stringToIntArray(Field<String> arg1, String arg2, String arg3) {
    return DSL.field("string_to_array({0}, {1}, {2})::int[]", Integer[].class,
        arg1, DSL.val(arg2), DSL.val(arg3));
}

// and then...
Field<Integer[]> f2 = stringToIntArray(ABC.VERSION, ".", "");

Use the code generator to generate the built-in function, and cast it explicitly:

Field<Integer[]> f3 = Routines.stringToArray(ABC.VERSION, DSL.val("."), DSL.val(""))
                              .cast(Integer[].class);

The built-in function is part of the pg_catalog schema in the postgres database.

Put it together

DSL.using(configuration)
   .select(ABC.VERSION)
   .from(ABC)
   .orderBy(fN.desc()) // place any of f1, f2, f3 here
   .limit(1)
   .fetch();
Lukas Eder
  • 196,412
  • 123
  • 648
  • 1,411