Search code examples
postgresqlgrailsgrails-orm

Escaping formula for Grails derived properties


Grails offers derived properties to generate a field from a SQL expression using the formula mapping parameter:

static mapping = {
    myfield formula: "field1 + field2"
}

I'm trying to use the formula parameter with a PostgreSQL database to make a concatenated field. The syntax is a little strange since PostgreSQL 8.4 doesn't yet support concat_ws:

static mapping = {
    myfield formula: "array_to_string(array[field1, field2],' ')"
}

The produced SQL shown with loggingSql = true in the DataSource config has the table prefix inserted into some strange places:

select table0_.field1 as field1_19_0_,
       table0_.field2 as field2_19_0_,=
       array_to_string(table0_.array[field1, table0_.field2], ' ') as formula0_0_
from test_table table0_ where table0_.id=?

The table prefix errantly appears before array but not before field1 in the derived formula. Is there a way to escape the prefix or correct this behavior more explicitly?


Solution

  • This is just an issue with parsing the formula syntax. GORM tries to insert the table prefix for unquoted expressions not followed by parens, so the ARRAY[] notation trips it up.

    My solution was to define the concat_ws function:

    CREATE OR REPLACE FUNCTION concat_ws(separator text, variadic str text[])
    RETURNS text as $$
    SELECT array_to_string($2, $1);
    $$ LANGUAGE sql;
    

    The GORM formula parameter can now avoid the ARRAY[] syntax, and works as expected.

    myfield formula: "concat_ws(' ', field1, field2)"