Print Shortlink

A DSL query in Groovy

DSL, Domain Specific Languages is a fascinating subject. Reams of articles have been written on this topic. Groovy provides a fluent syntax to create DSLs. Let’s use the meta-programming and closure concepts and build a simple DSL.

Say you have a database ‘personsdb‘ in mysql with a table ‘persons‘. The table has three columns id, name and age. You want to display name and age of all the persons using this syntax in Groovy.

display "name,age" from "persons

This is a short form for writing

display("name,age").from("persons")

The display method will construct a select query. The from method will add the “from” clause in the query and execute it in the database.

String.metaClass.from = {table ->
	String query =  "${delegate} from ${table}"
	def sql = Sql.newInstance("jdbc:mysql://localhost/personsdb", "username",
                      "password", "com.mysql.jdbc.Driver")
	sql.eachRow(query) {
		println "${it.name}, ${it.age}" 
	}
}
def display(columns){
	String sql = "select "
	columns.split(",").each {
		sql += it + ","
	}
	sql = sql[0..-2]
	return sql
}

display method returns a String. The “from” method is injected into the String class using meta-programming. The from methods constructs a complete SQL select query and executes it in the personsdb database. The delegate keyword is used to access the invoking object.

You can exploit the capabilities of the Groovy language and build your own DSLs that look like plain English text.

Leave a Reply