Tuesday, February 26, 2008

Damn you DBUnit!

I simply can't get over how powerful the Groovy XML and SQL support is, especially when you combine the two. Did you ever find yourself in the position where you wanted to convert a Hypersonic database to a DBUnit dataset? I did, and I told my co-worker, somewhat disgruntled, that "I bet this could be done with 30 lines of Groovy". Well, it could:


import groovy.sql.Sql
import groovy.xml.MarkupBuilder

def sql = Sql.newInstance("jdbc:hsqldb:my_db", "sa", "", "org.hsqldb.jdbcDriver")

def sw = new StringWriter()
def xml = new MarkupBuilder(sw)

xml.dataset {
sql.eachRow "select * from system_tables where table_type != 'SYSTEM TABLE'", {
table(name:it.TABLE_NAME.toLowerCase()) {
sql.rows("select * from ${t}", { md ->
md.columnCount.times {
column md.getColumnName(it + 1).toLowerCase() ?: ""
}
}).each { r ->
row {
r.size().times {
value r[it]
}
}
}
}
}
}

println sw

This is why I like Groovy - it's powerful, yet elegant.

No comments: