sparty02
sparty02

Reputation: 606

Get table/column metadata from JOOQ parser result

Using the JOOQ parser API, I'm able to parse the following query and get the parameters map from the resulting Query object. From this, I can tell that there is one parameter, and it's name is "something".

However, I haven't been able to figure out how to determine that the parameter "something" is assigned to a column named "BAZ" and that column is part of the table "BAR".

Does the parser API have a way to get the table/column metadata associated to each parameter?

String sql = "SELECT A.FOO FROM BAR A WHERE A.BAZ = :something";

DSLContext context = DSL.using...
Parser parser = context.parser();
Query query = parser.parseQuery(sql);


Map<String, Param<?>> params = query.getParams();

Upvotes: 2

Views: 770

Answers (1)

Lukas Eder
Lukas Eder

Reputation: 221145

Starting from jOOQ 3.16

jOOQ 3.16 introduced a new, experimental (as of 3.16) query object model API, which can be traversed, see:

Specifically, you can write:

List<QueryPart> parts = query.$traverse(
    Traversers.findingAll(q -> q instanceof Param)
);

Or, to conveniently produce exactly the type you wanted:

Map<String, Param<?>> params = query.$traverse(Traversers.collecting(
    Collectors.filtering(q -> q instanceof Param,
        Collectors.toMap(
            q -> ((Param<?>) q).getParamName(),
            q -> (Param<?>) q
        )
    )
));

The Collectors.toMap() call could include a mergeFunction, in case you have the same param name twice.

Pre jOOQ 3.16

As of jOOQ 3.11, the SPI that can be used to access the internal expression tree is the VisitListener SPI, which you have to attach to your context.configuration() prior to parsing. It will then be invoked whenever you traverse that expression tree, e.g. on your query.getParams() call.

However, there's quite a bit of manual plumbing that needs to be done. For example, the VisitListener will only see A.BAZ as a column reference without knowing directly that A is the renamed table BAR. You will have to keep track of such renaming yourself when you visit the BAR A expression.

Upvotes: 2

Related Questions