2008-03-31

The Impossible Troubleshooting of Groovy GStrings

I came across an issue today when creating dynamic SQL queries to run against a database and I kept getting exceptions from the Oracle JDBC driver saying that the table didn't exist.

So, typical troubleshooting told me to print out the SQL statement and see what table it was trying to query.

The problem is that it was the correct table, and copy and paste into TOAD gave me the expected results.

The problem turned out to be GStrings. My code looked something similar to this:

def mySql = "select * from ${tableName}"
db.eachRow(mySql) {
...
}


I tried several things to troubleshoot this. I even hard-coded the entire sql statement, and to my amazement, it worked.

Finally, I took a look at the API documentation for the Sql class in Groovy and noticed that eachRow is overloaded where one of them takes a GString.

The final fix was to call .toString() after the sql to make sure it hit the appropriate method.

Here's the final code:

def mySql = "select * from ${tableName}"
db.eachRow(mySql.toString()) {
...
}