2

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

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Yang Lu
  • 21
  • 2

2 Answers2

1

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

Java Devil
  • 10,629
  • 7
  • 33
  • 48
  • Thanks. This way would work for the example that I give. My acutal prolbem is a bit more complicated than this. Basically the "where" can change for difference case. It is not fixed. i.e. not always is Key1, sometime could be key2 or others. That means, it can't be hardcoded in the code. I could parse the string and then get from map again. But I wonder is there any better way to do it, and the code doesn't have to know what the key is? – Yang Lu Jun 17 '13 at 00:59
1

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()
Mark
  • 600
  • 3
  • 9