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.

4
  • Very interesting ordering technique, btw... Finally, a use case for arrays in PostgreSQL :-) Commented Dec 6, 2014 at 19:01
  • 1
    This is to sort version numbers directly in the DB. It's Postgres and it's awesome :-) Commented Dec 6, 2014 at 19:03
  • Yes, PostgreSQL seems to enhance the SQL:2011 standard, which specifies in 8.2 <comparison predicate>, General Rules, 1) b) ii) that the < comparison operation is not defined for arrays... I wonder if PostgreSQL makes such guarantees, though... it seems to be the case Commented Dec 6, 2014 at 19:15
  • yep, it is Commented Dec 6, 2014 at 19:22

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.