Skip to content

Commit c56851c

Browse files
christophstroblmp911de
authored andcommitted
Add configuration option to disable usage of JSqlParser for native queries.
This commit introduces the spring.data.jpa.query.native.parser property that allows to switch native query parsing to the default internal parser for scenarios where JSqlParser is on the classpath but should not be used by spring-data. Closes #2989 Original pull request: #3623
1 parent f474af7 commit c56851c

File tree

7 files changed

+450
-17
lines changed

7 files changed

+450
-17
lines changed

spring-data-jpa/pom.xml

+6
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,12 @@
8686
<optional>true</optional>
8787
</dependency>
8888

89+
<dependency>
90+
<groupId>org.junit.platform</groupId>
91+
<artifactId>junit-platform-launcher</artifactId>
92+
<scope>test</scope>
93+
</dependency>
94+
8995
<dependency>
9096
<groupId>org.hsqldb</groupId>
9197
<artifactId>hsqldb</artifactId>

spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryEnhancerFactory.java

+59-16
Original file line numberDiff line numberDiff line change
@@ -17,29 +17,29 @@
1717

1818
import org.apache.commons.logging.Log;
1919
import org.apache.commons.logging.LogFactory;
20+
import org.springframework.core.SpringProperties;
2021
import org.springframework.data.jpa.provider.PersistenceProvider;
22+
import org.springframework.lang.Nullable;
2123
import org.springframework.util.ClassUtils;
24+
import org.springframework.util.StringUtils;
2225

2326
/**
2427
* Encapsulates different strategies for the creation of a {@link QueryEnhancer} from a {@link DeclaredQuery}.
2528
*
2629
* @author Diego Krupitza
2730
* @author Greg Turnquist
2831
* @author Mark Paluch
32+
* @author Christoph Strobl
2933
* @since 2.7.0
3034
*/
3135
public final class QueryEnhancerFactory {
3236

3337
private static final Log LOG = LogFactory.getLog(QueryEnhancerFactory.class);
34-
35-
private static final boolean jSqlParserPresent = ClassUtils.isPresent("net.sf.jsqlparser.parser.JSqlParser",
36-
QueryEnhancerFactory.class.getClassLoader());
38+
private static final NativeQueryEnhancer NATIVE_QUERY_ENHANCER;
3739

3840
static {
3941

40-
if (jSqlParserPresent) {
41-
LOG.info("JSqlParser is in classpath; If applicable, JSqlParser will be used");
42-
}
42+
NATIVE_QUERY_ENHANCER = NativeQueryEnhancer.select(QueryEnhancerFactory.class.getClassLoader());
4343

4444
if (PersistenceProvider.ECLIPSELINK.isPresent()) {
4545
LOG.info("EclipseLink is in classpath; If applicable, EQL parser will be used.");
@@ -48,7 +48,6 @@ public final class QueryEnhancerFactory {
4848
if (PersistenceProvider.HIBERNATE.isPresent()) {
4949
LOG.info("Hibernate is in classpath; If applicable, HQL parser will be used.");
5050
}
51-
5251
}
5352

5453
private QueryEnhancerFactory() {}
@@ -62,15 +61,7 @@ private QueryEnhancerFactory() {}
6261
public static QueryEnhancer forQuery(DeclaredQuery query) {
6362

6463
if (query.isNativeQuery()) {
65-
66-
if (jSqlParserPresent) {
67-
/*
68-
* If JSqlParser fails, throw some alert signaling that people should write a custom Impl.
69-
*/
70-
return new JSqlParserQueryEnhancer(query);
71-
}
72-
73-
return new DefaultQueryEnhancer(query);
64+
return getNativeQueryEnhancer(query);
7465
}
7566

7667
if (PersistenceProvider.HIBERNATE.isPresent()) {
@@ -82,4 +73,56 @@ public static QueryEnhancer forQuery(DeclaredQuery query) {
8273
}
8374
}
8475

76+
/**
77+
* Get the native query enhancer for the given {@link DeclaredQuery query} based on {@link #NATIVE_QUERY_ENHANCER}.
78+
*
79+
* @param query the declared query.
80+
* @return new instance of {@link QueryEnhancer}.
81+
*/
82+
private static QueryEnhancer getNativeQueryEnhancer(DeclaredQuery query) {
83+
84+
if (NATIVE_QUERY_ENHANCER.equals(NativeQueryEnhancer.JSQL)) {
85+
return new JSqlParserQueryEnhancer(query);
86+
}
87+
return new DefaultQueryEnhancer(query);
88+
}
89+
90+
/**
91+
* Possible choices for the {@link #NATIVE_PARSER_PROPERTY}. Read current selection via {@link #select(ClassLoader)}.
92+
*/
93+
enum NativeQueryEnhancer {
94+
95+
AUTO, DEFAULT, JSQL;
96+
97+
static final String NATIVE_PARSER_PROPERTY = "spring.data.jpa.query.native.parser";
98+
99+
private static NativeQueryEnhancer from(@Nullable String name) {
100+
if (!StringUtils.hasText(name)) {
101+
return AUTO;
102+
}
103+
return NativeQueryEnhancer.valueOf(name.toUpperCase());
104+
}
105+
106+
/**
107+
* @param classLoader ClassLoader to look up available libraries.
108+
* @return the current selection considering classpath avialability and user selection via
109+
* {@link #NATIVE_PARSER_PROPERTY}.
110+
*/
111+
static NativeQueryEnhancer select(ClassLoader classLoader) {
112+
113+
if (!ClassUtils.isPresent("net.sf.jsqlparser.parser.JSqlParser", classLoader)) {
114+
return NativeQueryEnhancer.DEFAULT;
115+
}
116+
117+
NativeQueryEnhancer selected = NativeQueryEnhancer.from(SpringProperties.getProperty(NATIVE_PARSER_PROPERTY));
118+
if (selected.equals(NativeQueryEnhancer.AUTO) || selected.equals(NativeQueryEnhancer.JSQL)) {
119+
LOG.info("JSqlParser is in classpath; If applicable, JSqlParser will be used.");
120+
return NativeQueryEnhancer.JSQL;
121+
}
122+
123+
LOG.info("JSqlParser is in classpath but won't be used due to user choice.");
124+
return selected;
125+
}
126+
}
127+
85128
}

spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/QueryEnhancerFactoryUnitTests.java

+62-1
Original file line numberDiff line numberDiff line change
@@ -15,15 +15,24 @@
1515
*/
1616
package org.springframework.data.jpa.repository.query;
1717

18-
import static org.assertj.core.api.Assertions.*;
18+
import static org.assertj.core.api.Assertions.assertThat;
19+
20+
import java.util.stream.Stream;
1921

2022
import org.junit.jupiter.api.Test;
23+
import org.junit.jupiter.params.ParameterizedTest;
24+
import org.junit.jupiter.params.provider.Arguments;
25+
import org.junit.jupiter.params.provider.MethodSource;
26+
import org.springframework.data.jpa.repository.query.QueryEnhancerFactory.NativeQueryEnhancer;
27+
import org.springframework.data.jpa.util.ClassPathExclusions;
28+
import org.springframework.lang.Nullable;
2129

2230
/**
2331
* Unit tests for {@link QueryEnhancerFactory}.
2432
*
2533
* @author Diego Krupitza
2634
* @author Greg Turnquist
35+
* @author Christoph Strobl
2736
*/
2837
class QueryEnhancerFactoryUnitTests {
2938

@@ -52,4 +61,56 @@ void createsJSqlImplementationForNativeQuery() {
5261
assertThat(queryEnhancer) //
5362
.isInstanceOf(JSqlParserQueryEnhancer.class);
5463
}
64+
65+
@ParameterizedTest // GH-2989
66+
@MethodSource("nativeEnhancerSelectionArgs")
67+
void createsNativeImplementationAccordingToUserChoice(@Nullable String selection, NativeQueryEnhancer enhancer) {
68+
69+
withSystemProperty(NativeQueryEnhancer.NATIVE_PARSER_PROPERTY, selection, () -> {
70+
assertThat(NativeQueryEnhancer.select(this.getClass().getClassLoader())).isEqualTo(enhancer);
71+
});
72+
}
73+
74+
@Test // GH-2989
75+
@ClassPathExclusions(packages = { "net.sf.jsqlparser.parser" })
76+
void selectedDefaultImplementationIfJsqlNotAvailable() {
77+
78+
assertThat(assertThat(NativeQueryEnhancer.select(this.getClass().getClassLoader()))
79+
.isEqualTo(NativeQueryEnhancer.DEFAULT));
80+
}
81+
82+
@Test // GH-2989
83+
@ClassPathExclusions(packages = { "net.sf.jsqlparser.parser" })
84+
void selectedDefaultImplementationIfJsqlNotAvailableEvenIfExplicitlyStated/* or should we raise an error? */() {
85+
86+
withSystemProperty(NativeQueryEnhancer.NATIVE_PARSER_PROPERTY, "jsql", () -> {
87+
assertThat(NativeQueryEnhancer.select(this.getClass().getClassLoader())).isEqualTo(NativeQueryEnhancer.DEFAULT);
88+
});
89+
}
90+
91+
void withSystemProperty(String property, @Nullable String value, Runnable exeution) {
92+
93+
String currentValue = System.getProperty(property);
94+
if (value != null) {
95+
System.setProperty(property, value);
96+
} else {
97+
System.clearProperty(property);
98+
}
99+
try {
100+
exeution.run();
101+
} finally {
102+
if (currentValue != null) {
103+
System.setProperty(property, currentValue);
104+
} else {
105+
System.clearProperty(property);
106+
}
107+
}
108+
109+
}
110+
111+
static Stream<Arguments> nativeEnhancerSelectionArgs() {
112+
return Stream.of(Arguments.of(null, NativeQueryEnhancer.JSQL), Arguments.of("", NativeQueryEnhancer.JSQL),
113+
Arguments.of("auto", NativeQueryEnhancer.JSQL), Arguments.of("default", NativeQueryEnhancer.DEFAULT),
114+
Arguments.of("jsql", NativeQueryEnhancer.JSQL));
115+
}
55116
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/*
2+
* Copyright 2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.jpa.util;
17+
18+
import java.lang.annotation.Documented;
19+
import java.lang.annotation.ElementType;
20+
import java.lang.annotation.Retention;
21+
import java.lang.annotation.RetentionPolicy;
22+
import java.lang.annotation.Target;
23+
24+
import org.junit.jupiter.api.extension.ExtendWith;
25+
26+
/**
27+
* Annotation used to exclude entries from the classpath. Simplified version of <a href=
28+
* "https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ClassPathExclusions.java">ClassPathExclusions</a>.
29+
*
30+
* @author Christoph Strobl
31+
*/
32+
@Retention(RetentionPolicy.RUNTIME)
33+
@Target({ ElementType.TYPE, ElementType.METHOD })
34+
@Documented
35+
@ExtendWith(ClassPathExclusionsExtension.class)
36+
public @interface ClassPathExclusions {
37+
38+
/**
39+
* One or more packages that should be excluded from the classpath.
40+
*
41+
* @return the excluded packages
42+
*/
43+
String[] packages();
44+
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
/*
2+
* Copyright 2024 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.jpa.util;
17+
18+
import java.lang.reflect.Method;
19+
20+
import org.junit.jupiter.api.extension.ExtensionContext;
21+
import org.junit.jupiter.api.extension.InvocationInterceptor;
22+
import org.junit.jupiter.api.extension.ReflectiveInvocationContext;
23+
import org.junit.platform.engine.discovery.DiscoverySelectors;
24+
import org.junit.platform.launcher.Launcher;
25+
import org.junit.platform.launcher.LauncherDiscoveryRequest;
26+
import org.junit.platform.launcher.TestPlan;
27+
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
28+
import org.junit.platform.launcher.core.LauncherFactory;
29+
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
30+
import org.junit.platform.launcher.listeners.TestExecutionSummary;
31+
import org.springframework.util.CollectionUtils;
32+
33+
/**
34+
* Simplified version of <a href=
35+
* "https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-tools/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/ModifiedClassPathClassLoader.java">ModifiedClassPathExtension</a>.
36+
*
37+
* @author Christoph Strobl
38+
*/
39+
class ClassPathExclusionsExtension implements InvocationInterceptor {
40+
41+
@Override
42+
public void interceptBeforeAllMethod(Invocation<Void> invocation,
43+
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
44+
intercept(invocation, extensionContext);
45+
}
46+
47+
@Override
48+
public void interceptBeforeEachMethod(Invocation<Void> invocation,
49+
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
50+
intercept(invocation, extensionContext);
51+
}
52+
53+
@Override
54+
public void interceptAfterEachMethod(Invocation<Void> invocation,
55+
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
56+
intercept(invocation, extensionContext);
57+
}
58+
59+
@Override
60+
public void interceptAfterAllMethod(Invocation<Void> invocation,
61+
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
62+
intercept(invocation, extensionContext);
63+
}
64+
65+
@Override
66+
public void interceptTestMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
67+
ExtensionContext extensionContext) throws Throwable {
68+
interceptMethod(invocation, invocationContext, extensionContext);
69+
}
70+
71+
@Override
72+
public void interceptTestTemplateMethod(Invocation<Void> invocation,
73+
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext) throws Throwable {
74+
interceptMethod(invocation, invocationContext, extensionContext);
75+
}
76+
77+
private void interceptMethod(Invocation<Void> invocation, ReflectiveInvocationContext<Method> invocationContext,
78+
ExtensionContext extensionContext) throws Throwable {
79+
80+
if (isModifiedClassPathClassLoader(extensionContext)) {
81+
invocation.proceed();
82+
return;
83+
}
84+
85+
Class<?> testClass = extensionContext.getRequiredTestClass();
86+
Method testMethod = invocationContext.getExecutable();
87+
PackageExcludingClassLoader modifiedClassLoader = PackageExcludingClassLoader.get(testClass, testMethod);
88+
if (modifiedClassLoader == null) {
89+
invocation.proceed();
90+
return;
91+
}
92+
invocation.skip();
93+
ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
94+
Thread.currentThread().setContextClassLoader(modifiedClassLoader);
95+
try {
96+
runTest(extensionContext.getUniqueId());
97+
} finally {
98+
Thread.currentThread().setContextClassLoader(originalClassLoader);
99+
}
100+
}
101+
102+
private void runTest(String testId) throws Throwable {
103+
104+
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
105+
.selectors(DiscoverySelectors.selectUniqueId(testId)).build();
106+
Launcher launcher = LauncherFactory.create();
107+
TestPlan testPlan = launcher.discover(request);
108+
SummaryGeneratingListener listener = new SummaryGeneratingListener();
109+
launcher.registerTestExecutionListeners(listener);
110+
launcher.execute(testPlan);
111+
TestExecutionSummary summary = listener.getSummary();
112+
if (!CollectionUtils.isEmpty(summary.getFailures())) {
113+
throw summary.getFailures().get(0).getException();
114+
}
115+
}
116+
117+
private void intercept(Invocation<Void> invocation, ExtensionContext extensionContext) throws Throwable {
118+
if (isModifiedClassPathClassLoader(extensionContext)) {
119+
invocation.proceed();
120+
return;
121+
}
122+
invocation.skip();
123+
}
124+
125+
private boolean isModifiedClassPathClassLoader(ExtensionContext extensionContext) {
126+
Class<?> testClass = extensionContext.getRequiredTestClass();
127+
ClassLoader classLoader = testClass.getClassLoader();
128+
return classLoader.getClass().getName().equals(PackageExcludingClassLoader.class.getName());
129+
}
130+
}

0 commit comments

Comments
 (0)