tags:

views:

6387

answers:

8

Is there a good open-source Java library for parsing SQL statements?

If possible, it should be customizable or flexible enough to also be able to parse (or at least ignore) vendor-specific syntax (such as Oracle tablespace definitions or MySQL's LIMIT clause).

If not, strict adherence to the SQL standard is also fine.

Update: I need this for two things:

  • providing an SQL interface to a non-SQL database (mapping to internal API calls)
  • rewriting SQL before it goes to the actual database (e.g. Oracle)
+8  A: 

ANTLR has an ANSI SQL grammar available. You can use that to create your own parser.

duffymo
Why use ANTLR when you can implement your own parser generator?
01
Why generate your own parser generator when you can use ANTLR?
duffymo
+1  A: 

What you want to do with the parsed SQL? I can recommend a few Java implementation of Lex/Yacc (BYACC/J, Java Cup) that you can use an existing SQL grammar with.

If you want to actually do something with the resulting parsed grammar, I might suggest looking at Derby, an open source SQL database written in Java.

Thomas Jones-Low
Is the SQL parser used in Derby available as an independent JAR ?
Lluis Martinez
I don't know. I've never looked at the source for Derby.
Thomas Jones-Low
+4  A: 

Parser

If you need a parser there should be a parser in the code base of Apache Derby.

Dealing with vendor-specific SQL

You may want to look at the .native() method on the jdbc Connection object which you can pass it vendor neutral queries that will get postprocessed into vendor specific queries.

Elijah
That native() method looks interesting. Are there any examples as to how it can be used? What kind of conversions are possible there?
Thilo
A: 

jparsec

Ron
+3  A: 

JSqlParser

David Phillips
+2  A: 

Try Zql

HonorGod
+1  A: 

Try http://jsqlparser.sourceforge.net/

Kevin
A: 

Did you find a good solution? I want also to do some SQL rewriting...

Christophe
Did you check out the ones listed for yourself?
duffymo