tags:

views:

196

answers:

4

I have some legacy SQL and I want to split it up into it's constituent parts & then add more criteria, an order by clause, etc.

Are there any existing Java libraries out there that interpret SQL like this?

So I want to do something like

deconstructedSQL.getCriteria().add("price > 100");

or

deconstructedSQL.getOrderBy().add("price");

or

String select = deconstructedSQL.getSelect();
if ("*".equals(select))
{
    deconstructedSQL.setSelect("my_table.*");
}

I can use Dialects from Hibernate to add info specific to my database for paging (setFirstResult & setMaxResult), but I'd like to take it a step further.

+1  A: 

You may want to checkout the SQL Builder library. It is a builder pattern based library for building SQL statements. I'm not positive if it has a deconstruction piece to it where you can give it a SQL statement and have it break it down into parts though.

Rob Di Marco
Harry Lime
+1  A: 

I would use a sql parser (javacc, jparsec, antlr) to break up the string into an AST. Once you have it in this kind of structure you can play with it as you describe and emit the modified version as a string in the end.

Ron
"SQL Parser" was the phrase that eluded me when googling this. Having a look at Zql now - http://www.gibello.com/code/zql/
Harry Lime
A: 

The Zsql framework matches exactly with your description (not tested).

Laurent Simon
A: 

Hi Harry, Did you ever find something that worked well for you?

Mike
hi Mike. I ended up just parsing the statement into objects representing the SELECT, FROM, WHERE, GROUP BY and ORDER BY clauses - which was enough to cover what I needed. On those objects then I have methods to add parameters, etc as well as a simple mechanism to reconstitute the SQL statement.It's by no means perfect (or complete!), but it got the job done for us - for now.
Harry Lime