A Functional Programming Approach to Dynamic SQL With jOOQ
When it comes to dynamic SQL, all jOOQ statements are dynamic. You can also look to functional programming-optimized tricks like the Strategy Pattern to help.
Join the DZone community and get the full member experience.
Join For FreeTypesafe embedded DSLs like jOOQ are extremely powerful for dynamic SQL because the query you’re constructing with the jOOQ DSL is a dynamic query by nature. You’re constructing a query expression tree using a convenient API (the “DSL”), even if you think your SQL statement is static. For instance:
for (Record rec : ctx.select(ACTOR.FIRST_NAME, ACTOR.LAST_NAME)
.from(ACTOR)
.where(ACTOR.FIRST_NAME.like("A%")))
System.out.println(rec.get(ACTOR.FIRST_NAME)
+ " " + rec.get(ACTOR.LAST_NAME));
FOR rec IN (
SELECT first_name, last_name
FROM actor
WHERE first_name LIKE 'A%'
) LOOP
dbms_output.put_line(rec.first_name
|| ' ' || rec.last_name);
END LOOP;
org.jooq.Select
object, step by step (
more about how the DSL works here).
Using jOOQ for Actual Dynamic SQL
As we’ve seen before, all jOOQ statements are dynamic statements, even if they “feel” static. Sometimes, you actually want a dynamic SQL query, e.g. when the user is allowed to specify custom predicates. In this case, you could do something like this:
// By default, make the dynamic predicate "TRUE"
Condition condition = DSL.trueCondition();
// If the user entered something in the text search field...
if (hasFirstNameSearch())
condition = condition.and(FIRST_NAME.like(firstNameSearch()));
// If the user entered something in another text search field...
if (hasLastNameSearch())
condition = condition.and(LAST_NAME.like(lastNameSearch()));
// The query now uses a dynamically created predicate
for (Record rec : ctx.select(ACTOR.FIRST_NAME, ACTOR.LAST_NAME)
.from(ACTOR)
.where(condition))
System.out.println(rec.get(ACTOR.FIRST_NAME)
+ " " + rec.get(ACTOR.LAST_NAME));
The above is not possible with PL/SQL easily, you’d have to resort to the dynamic SQL API called DBMS_SQL
, which is about as verbose (and error-prone) as JDBC, as you’re concatenating SQL strings.
Adding Functional Programming to the Mix
If you’re able to construct the entire query in a local scope, e.g. inside of a method, the above imperative style is quite sufficient. But sometimes, you may have something like a “base” query that you want to re-use all the time, and only sometimes, you want to add a custom predicate, or JOIN operation, etc.
In this case, using a more functional approach is optimal. For instance, you could offer a convenience API that produces a query fetching actor first and last names, with custom predicates:
// Higher order, SQL query producing function:
public static ResultQuery<Record2<String, String>> actors(
Function<Actor, Condition> where
) {
return ctx.select(ACTOR.FIRST_NAME, ACTOR.LAST_NAME)
.from(ACTOR)
.where(where.apply(ACTOR)));
}
How do you call the above utility? Easy!
// Get only actors whose first name starts with "A"
for (Record rec : actors(a -> a.FIRST_NAME.like("A%")))
System.out.println(rec);
@SafeVarargs
public static ResultQuery<Record2<String, String>> actors(
Function<Actor, Condition>... where
) {
return dsl().select(ACTOR.FIRST_NAME, ACTOR.LAST_NAME)
.from(ACTOR)
.where(Arrays.stream(where)
.map(f -> f.apply(ACTOR))
.collect(Collectors.toList()));
}
We can now call this with any number of input functions to form dynamic predicates. E.g.:
// Get all actors
for (Record rec : actors())
System.out.println(rec);
// Get only actors whose first name starts with "A"
for (Record rec : actors(a -> a.FIRST_NAME.like("A%"))) {
System.out.println(rec);
// Get actors whose first/last name matches "A% B%"
for (Record rec : actors(
a -> a.FIRST_NAME.like("A%"),
a -> a.LAST_NAME.like("B%"))) {
System.out.println(rec);
Conclusion
The idea is that jOOQ is an extremely powerful SQL expression tree API, which allows you to dynamically construct SQL queries of arbitrary complexity. If you’re running a static query, this just means that all of your SQL expressions are constant every time you execute the query.
There are no limits to how far you can push this. We’ve seen jOOQ users write queries that dynamically assemble dozens of common table expressions with several levels of dynamically nested derived tables, too. If you have a crazy example to share, we’re looking forward to it!
Published at DZone with permission of Lukas Eder. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments