Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use JOOQ as an SQL parser?

Tags:

java

jooq

I'm trying to parse a SELECT statement in Java. I'm familiar with JOOQ, and was hoping to use that. I know it's not explicitly designed as an SQL parser—it's actually a lot more than that, so I was thinking there might be a way to use its internal parsers to parse SELECT queries.

I saw some information on how to access some of JOOQ's internals using the Visitor pattern, but I need to navigate inside the query using a tree-like structure that will allow access to each part of the query individually. I don't want to use the Visitor pattern for all use cases.

Is this possible? How would I go about doing it?

like image 417
dblike Avatar asked Mar 26 '19 11:03

dblike


People also ask

What is SQL Query Parser?

The SQL Parser parses a SQL query in a string field. When parsing a query, the processor generates fields based on the fields defined in the SQL query and specifies the CRUD operation, table, and schema information in record header attributes.

What is parser in SQL Server?

PARSE() function in SQL Server PARSE() function can convert any string value to Numeric or Date/Time format. If passed string value cannot be converted to Numeric or Date/Time format, it will result to an error. PARSE() function relies on Common Language Runtime to convert the string value.

What is parser and optimizer in SQL?

The MySQL server receives queries in the SQL format. Once a query is received, it first needs to be parsed, which involves translating it from what is essentially a textual format into a combination of internal binary structures that can be easily manipulated by the optimizer.


Video Answer


2 Answers

As of jOOQ 3.11, while you can indeed extract the expression tree using a VisitListener and some tweaking of the internals (mainly depending on internal types via reflection), what you want to do is currently not possible. It will be addressed in the future, when the expression tree might be made accessible through public API (and cleanly separated from the SQL generation logic), but no promises yet.

like image 75
Lukas Eder Avatar answered Sep 18 '22 03:09

Lukas Eder


A full-fledged SQL parser is available from DSLContext.parser() and from DSLContext.parsingConnection() (see the manual's section about parsing connections for the latter).

The SQL Parsing API page gives this trivial example:

ResultQuery<?> query = 
DSL.using(configuration)
   .parser()
   .parseResultQuery("SELECT * FROM (VALUES (1, 'a'), (2, 'b')) t(a, b)");

parseResultQuery is the method you need for a single SELECT query, use parse(String) if you may have multiple queries.

like image 43
Alexey Romanov Avatar answered Sep 20 '22 03:09

Alexey Romanov