From 0c074b93544f6788b2fc7cecc139c21c0ab5fd78 Mon Sep 17 00:00:00 2001 From: Marc Baloup Date: Sat, 2 Mar 2024 22:14:53 +0100 Subject: [PATCH] DB: custom WHERE expression --- .../java/fr/pandacube/lib/db/SQLWhere.java | 54 ++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLWhere.java b/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLWhere.java index e907552..14a6760 100644 --- a/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLWhere.java +++ b/pandalib-db/src/main/java/fr/pandacube/lib/db/SQLWhere.java @@ -64,6 +64,31 @@ public abstract class SQLWhere> { return new SQLWhereOrBuilder<>(); } + /** + * Create a custom SQL {@code WHERE} expression. + * @param whereExpr the raw SQL {@code WHERE} expression. + * @return a SQL {@code WHERE} expression. + */ + public SQLWhere expression(String whereExpr) { + return expression(whereExpr, List.of()); + } + + /** + * Create a custom SQL {@code WHERE} expression. + * @param whereExpr the raw SQL {@code WHERE} expression. + * @param params the parameters of the provided expression. + * @return a SQL {@code WHERE} expression. + */ + public SQLWhere expression(String whereExpr, List params) { + return new SQLWhereCustomExpression<>(whereExpr, params); + } + + + + + + + /** * A SQL {@code WHERE} expression builder joining multiple expressions with the {@code AND} or {@code OR} operator. @@ -263,7 +288,7 @@ public abstract class SQLWhere> { for (Object v : values) SQLElement.addValueToSQLObjectList(params, field, v); - char[] questions = new char[values.size() == 0 ? 0 : (values.size() * 2 - 1)]; + char[] questions = new char[values.isEmpty() ? 0 : (values.size() * 2 - 1)]; for (int i = 0; i < questions.length; i++) questions[i] = i % 2 == 0 ? '?' : ','; @@ -334,6 +359,33 @@ public abstract class SQLWhere> { + /* package */ static class SQLWhereCustomExpression> extends SQLWhere { + + private final String sqlExpression; + private final List parameters; + + /* package */ SQLWhereCustomExpression(String sqlExpression, List parameters) { + if (sqlExpression == null) + throw new IllegalArgumentException("sqlExpression can't be null"); + if (parameters == null) + parameters = List.of(); + this.sqlExpression = sqlExpression; + this.parameters = parameters; + } + + @Override + /* package */ ParameterizedSQLString toSQL() { + return new ParameterizedSQLString(sqlExpression, parameters); + } + + } + + + + + + + /**