SQL parser library for Java

JavaSqlParsing

Java Problem Overview


Is there an 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)

Java Solutions


Solution 1 - Java

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

ANTLR4 has a SQL grammar.

Solution 2 - Java

  • JSqlParser

  • Trino's parser is written using ANTLR4 and has its own immutable AST classes that are built from the parser. The AST has a visitor and pretty printer.

Solution 3 - Java

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.

Solution 4 - Java

General SQL Parser for Java is not open source, but is exactly what you are looking after.

Solution 5 - Java

Try Zql

Solution 6 - Java

Hibernate uses ANTLR for sql and hql parsing.

JSqlParser is also a good option.although it has some bugs(or some features not implemented) while parsing oracle pl/sql. see its forum for detail.

so if you're parsing oracle pl/sql, ANTLR is recommended.

Solution 7 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThiloView Question on Stackoverflow
Solution 1 - JavaduffymoView Answer on Stackoverflow
Solution 2 - JavaDavid PhillipsView Answer on Stackoverflow
Solution 3 - JavaElijahView Answer on Stackoverflow
Solution 4 - JavaJamesView Answer on Stackoverflow
Solution 5 - JavajagamotView Answer on Stackoverflow
Solution 6 - JavaHan ZhengView Answer on Stackoverflow
Solution 7 - JavaThomas Jones-LowView Answer on Stackoverflow