Tuesday, January 17, 2012

Grails, blobs and postgres 'bytea_output'

Grails has great support for storing binary data into any database, Postgres included. It is usually simple to use but today it gave me problems.

I have an application originally developed on pg 8.4 and grails 1.3.6 which stores images in a database table and used to work fine until I upgraded the database to 9.1. It turns out that with version 9 Postgres by default will return data to the client using a new hex format, instead of the escape format used in versions < 9. This, of course, confuses the client which returns garbage to the browser, hence the corrupted image.

The solution is, luckily, quite simple: just tell postgres to revert to the old behaviour. It seems that this behaviour can be tuned per database, so you could have one database using the new format and another the old one:

ALTER DATABASE dbname SET bytea_output='escape';

I should point out that I could also have updated the jdbc driver (now I'm using postgresql-8.3-603.jdbc3.jar), but that seems more risky and would probably break backwards compatibility with 8.x.

No comments: