Groovy , how to pass in inline variables,i.e ${variable} statement from file?

2.6k Views Asked by At

I have an interesting problem in Groovy. Hope someone can help me.

Basically I am using Groovy Sql. I need to select multiple tables in different databases. My second query depends on other query's, for example: "select * from table1-in-db1 where key = ${result-of-other-query1}. Groovy works fine if I hardcode this in the function. However, my problem is the sql is defined in a xml file and after I retriev passed in into the the funciton as a string. it doesn't interperate the inline varialbe anymore, even I do have a variable called result-of-other-query1 in the scope.

Here is a piece of sudo code:

doQuery(String squery, String tquery) {

//query db1.
//squery = "select key1 from table1"
db1.rows(squery).each {row->

    //query db2.        
    //tquery ="select * where myKey ='${row.key1}'"
    println tquery

    tdb.rows(tquery).each { row1 ->
       .... // get error here, coz groovy did not replace ${row.key1}       
    }   
  }
}

Is there any way that I can tell Groovy to replace the inline variable even it is a passed in as a string?

Thanks a lot for your help in advance

2

There are 2 best solutions below

1
On

Try

tquery = 'select * where myKey =:foo'

tdb.rows(tquery,[foo:"$row.key1"]).each

you may also want to consider using eachRow as opposed to rows.(query).each

1
On

I think what you need is the simple template engine. Sorry I am on my phone so can't give you an example. ..

OK - here is an example of what I mean. I was talking about the SimpleTemplateEngine (http://groovy.codehaus.org/api/groovy/text/SimpleTemplateEngine.html).

If you load a string from a file it will not be a gstring, it will be a String, but you can use the SimpleTemplateEngine to do a GString type substitution e.g.:

def clause='test'

String testString='this is a ${clause}'

println "As a string: " + testString

// Get an instance of the template engine
def engine = new groovy.text.SimpleTemplateEngine()

def template = engine.createTemplate(testString).make([clause:clause])
println template.toString()