-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathLambda2Sql.java
More file actions
45 lines (38 loc) · 1.56 KB
/
Lambda2Sql.java
File metadata and controls
45 lines (38 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package lambda2sql;
import static java.lang.System.getProperty;
import static java.nio.file.Files.createTempDirectory;
import static java.util.Objects.requireNonNull;
import java.io.IOException;
import java.util.function.Predicate;
import com.trigersoft.jaque.expression.LambdaExpression;
/**
* A utility class for converting java lambdas to SQL.
* It must be initializes with {@link #init()} before any lambdas are created.
*/
public class Lambda2Sql {
private static final String DUMP_CLASSES_PROP = "jdk.internal.lambda.dumpProxyClasses";
/**
* Initializes the jdk.internal.lambda.dumpProxyClasses system property with a temporary directory.
* See https://bugs.openjdk.java.net/browse/JDK-8023524
*/
public static void init() {
try {
if( System.getProperty(DUMP_CLASSES_PROP) == null )
System.setProperty(DUMP_CLASSES_PROP, createTempDirectory("lambda").toString());
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
/**
* Converts a predicate lambda to SQL. Make sure to {@link Lamda2Sql#init()} before creating the predicate.<br/>
* <pre>{@code person -> person.getAge() > 50 && person.isActive() }</pre>
* Becomes a string:
* <pre>{@code "age > 50 AND active" }</pre>
* Supported operators: >,>=,<,<=,=,!=,&&,||,!
*/
public static <T> String toSql(Predicate<T> predicate) {
requireNonNull(getProperty(DUMP_CLASSES_PROP), "Call init() before creating the predicate.");
LambdaExpression<Predicate<T>> lambdaExpression = LambdaExpression.parse(predicate);
return lambdaExpression.accept(new ToSqlVisitor()).toString();
}
}