Friday, June 12, 2009

Groovy GString/ STring

A few Gotchas that I've been getting stung with in Groovy.

GStrings and Strings

Be careful with Groovy Strings and Sql.

Make sure you know the rules of when Strings become GStrings, and therefore can support dynamic variable replacements.

GString docs can be found

These rules are listed here: (Note this doc is aproposal for changnig GString)

For example in the code below, if you simply use "def" to declare your variable, you will not see explicitly which types get converted to GStrings and which get converted to plain Strings.

By been explicit in your definitions however you can see that sql6 will not cast by default to a GString. This is becausei t is a multiline java.lang.String (see rules in link above). You will get this exception.

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object "..." with class 'java.lang.String' to class 'groovy.lang.GString'

To fix it.

Date startDate = new Date() -1;
Date endDate = new Date();
def Format = "yyyy-MM-dd"
def OFormat = "YYYY-MM-DD"
String startString = startDate.format(Format);
String endString = endDate.format(Format);
println "Running between $startString and $endString";
def sql = []
def sql1 ="""
select * from prov_auditing_master m where EVENTTIMECOMPLETED > to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql2 =""> to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql3 =""> to_date($startString,$OFormat)"+
" and EVENTTIMECOMPLETED < sql4 =""> to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql5 =" "> to_date($startString,$OFormat) and EVENTTIMECOMPLETED < sql6 = ""> to_date($startString,$OFormat)"+
" and EVENTTIMECOMPLETED < db =" int" i="1">
println i+": $sq"

To fix

GString sql7 = "$sql6" ;
sql <<>

No comments: