From c2561dc00a5948ee8a07987cd9a93fc75c7d3a20 Mon Sep 17 00:00:00 2001 From: BoykoAlex Date: Thu, 24 Sep 2026 19:39:17 -0700 Subject: [PATCH] Allow overriding sql dialect parser via settings Signed-off-by: BoykoAlex --- ...blemSeverityPreferityPageFromMetadata.java | 9 + .../plugin.xml | 22 ++ .../ls/commands/SetConfigurationHandler.java | 64 +++++ .../CategoryProblemsSeverityPrefsPage.java | 10 +- .../reconcile/ProblemTypeParameter.java | 15 + .../ide/vscode/boot/app/BootJavaConfig.java | 9 + .../ide/vscode/boot/app/JdtConfig.java | 6 +- .../ide/vscode/boot/app/SpringDataConfig.java | 16 +- .../boot/common/SpringProblemCategories.java | 24 +- .../jpa/queries/QueryJdtAstReconciler.java | 41 ++- .../queries/SqlDialectQuickFixProvider.java | 129 +++++++++ .../data/jpa/queries/SqlDialectResolver.java | 97 +++++++ .../boot/java/data/jpa/queries/SqlType.java | 31 ++- .../src/main/resources/problem-types.json | 14 + .../data/jpa/queries/QueryReconcilerTest.java | 139 +++++++++- .../SqlDialectQuickFixProviderTest.java | 257 +++++++++++++++++ .../vscode/boot/test/ProblemTypesToJson.java | 15 +- .../.mvn/wrapper/maven-wrapper.properties | 19 ++ .../boot-mariadb-postgresql/mvnw | 259 ++++++++++++++++++ .../boot-mariadb-postgresql/mvnw.cmd | 149 ++++++++++ .../boot-mariadb-postgresql/pom.xml | 43 +++ .../vscode-spring-boot/lib/Main.ts | 12 + .../vscode-spring-boot/package.json | 10 + 23 files changed, 1345 insertions(+), 45 deletions(-) create mode 100644 eclipse-language-servers/org.springframework.tooling.boot.ls/src/org/springframework/tooling/boot/ls/commands/SetConfigurationHandler.java create mode 100644 headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProvider.java create mode 100644 headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectResolver.java create mode 100644 headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProviderTest.java create mode 100644 headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/.mvn/wrapper/maven-wrapper.properties create mode 100755 headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw create mode 100644 headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw.cmd create mode 100644 headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/pom.xml diff --git a/eclipse-language-servers/org.springframework.ide.eclipse.editor.support/src/org/springframework/ide/eclipse/editor/support/preferences/ProblemSeverityPreferityPageFromMetadata.java b/eclipse-language-servers/org.springframework.ide.eclipse.editor.support/src/org/springframework/ide/eclipse/editor/support/preferences/ProblemSeverityPreferityPageFromMetadata.java index 15dde1391e..73292f24ea 100644 --- a/eclipse-language-servers/org.springframework.ide.eclipse.editor.support/src/org/springframework/ide/eclipse/editor/support/preferences/ProblemSeverityPreferityPageFromMetadata.java +++ b/eclipse-language-servers/org.springframework.ide.eclipse.editor.support/src/org/springframework/ide/eclipse/editor/support/preferences/ProblemSeverityPreferityPageFromMetadata.java @@ -41,6 +41,7 @@ public static class ProblemParameterData { private String description; private String type; private String defaultValue; + private String[] enumValues; public ProblemParameterData() {} @@ -83,6 +84,14 @@ public String getDefaultValue() { public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } + + public String[] getEnumValues() { + return enumValues; + } + + public void setEnumValues(String[] enumValues) { + this.enumValues = enumValues; + } } public static class ProblemTypeData implements ProblemType { diff --git a/eclipse-language-servers/org.springframework.tooling.boot.ls/plugin.xml b/eclipse-language-servers/org.springframework.tooling.boot.ls/plugin.xml index 7d0fec1bb7..6a0f3c2341 100644 --- a/eclipse-language-servers/org.springframework.tooling.boot.ls/plugin.xml +++ b/eclipse-language-servers/org.springframework.tooling.boot.ls/plugin.xml @@ -285,6 +285,10 @@ class="org.springframework.tooling.boot.ls.commands.ConvertBootPropertiesHanlder$ConvertPropertiesToYamlHandler" commandId="org.springframework.tooling.boot.ls.properties.convert-props-to-yaml"> + + @@ -322,6 +326,24 @@ typeId="org.eclipse.lsp4e.pathParameterType"> + + + + + + + * The key is the language server's own dotted setting name (as sent to it + * over {@code workspace/didChangeConfiguration}). Settings relayed through + * the {@code spring-boot.ls.problem}/{@code spring-boot.ls.problem-parameters} + * mechanism (see {@code DelegatingStreamConnectionProvider}) are stored + * locally without that prefix, so it's stripped here to get the actual + * preference key. + */ +@SuppressWarnings("restriction") +public class SetConfigurationHandler extends AbstractHandler { + + private static final String PROBLEM_SETTINGS_PREFIX = "spring-boot.ls."; + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + try { + String p = event.getParameter(LSPCommandHandler.LSP_COMMAND_PARAMETER_ID); + Command cmd = new Gson().fromJson(p, Command.class); + if (cmd != null && cmd.getArguments() != null && cmd.getArguments().size() >= 2) { + String key = cmd.getArguments().get(0).toString(); + String value = cmd.getArguments().get(1).toString(); + String prefKey = key.startsWith(PROBLEM_SETTINGS_PREFIX) ? key.substring(PROBLEM_SETTINGS_PREFIX.length()) : key; + IPreferenceStore preferenceStore = BootLanguageServerPlugin.getDefault().getPreferenceStore(); + preferenceStore.setValue(prefKey, value); + } + return null; + } catch (Exception e) { + throw new ExecutionException("Failed to execute Set Configuration command", e); + } + } + +} diff --git a/eclipse-language-servers/org.springframework.tooling.boot.ls/src/org/springframework/tooling/boot/ls/prefs/CategoryProblemsSeverityPrefsPage.java b/eclipse-language-servers/org.springframework.tooling.boot.ls/src/org/springframework/tooling/boot/ls/prefs/CategoryProblemsSeverityPrefsPage.java index 367b2343d7..41371b856a 100644 --- a/eclipse-language-servers/org.springframework.tooling.boot.ls/src/org/springframework/tooling/boot/ls/prefs/CategoryProblemsSeverityPrefsPage.java +++ b/eclipse-language-servers/org.springframework.tooling.boot.ls/src/org/springframework/tooling/boot/ls/prefs/CategoryProblemsSeverityPrefsPage.java @@ -66,9 +66,9 @@ protected void initializeDefaults() { defaults.put(getProblemParametersPreferencePrefix() + param.getKey(), param.getDefaultValue()); } } - super.initializeDefaults(); + super.initializeDefaults(); } - + @Override protected void createFieldEditors() { if (category.getToggle() != null) { @@ -84,7 +84,9 @@ protected void createFieldEditors() { if (category.getParameters() != null) { for (ProblemParameterData param : category.getParameters()) { String prefKey = getProblemParametersPreferencePrefix() + param.getKey(); - if ("boolean".equals(param.getType())) { + if (param.getEnumValues() != null) { + addField(new ComboFieldEditor(prefKey, param.getLabel(), createToggleValues(param.getEnumValues()), getFieldEditorParent())); + } else if ("boolean".equals(param.getType())) { addField(new BooleanFieldEditor(prefKey, param.getLabel(), getFieldEditorParent())); } else if ("integer".equals(param.getType())) { addField(new IntegerFieldEditor(prefKey, param.getLabel(), getFieldEditorParent())); @@ -95,7 +97,7 @@ protected void createFieldEditors() { } super.createFieldEditors(); } - + private static String[][] createToggleValues(String[] values) { String[][] res = new String[values.length][2]; for (int i = 0; i < values.length; i++) { diff --git a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/reconcile/ProblemTypeParameter.java b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/reconcile/ProblemTypeParameter.java index 6f507d31c3..e60e818c9e 100644 --- a/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/reconcile/ProblemTypeParameter.java +++ b/headless-services/commons/commons-language-server/src/main/java/org/springframework/ide/vscode/commons/languageserver/reconcile/ProblemTypeParameter.java @@ -27,13 +27,24 @@ public enum ValueType { private final String description; private final ValueType type; private final String defaultValue; + private final String[] enumValues; public ProblemTypeParameter(String key, String label, String description, ValueType type, String defaultValue) { + this(key, label, description, type, defaultValue, null); + } + + /** + * @param enumValues when non-null, this parameter is rendered as a fixed + * choice among these raw values, rather than a free-form field for {@code type} + */ + public ProblemTypeParameter(String key, String label, String description, ValueType type, String defaultValue, + String[] enumValues) { this.key = key; this.label = label; this.description = description; this.type = type; this.defaultValue = defaultValue; + this.enumValues = enumValues; } public String getKey() { @@ -56,4 +67,8 @@ public String getDefaultValue() { return defaultValue; } + public String[] getEnumValues() { + return enumValues; + } + } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootJavaConfig.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootJavaConfig.java index f0c20b97ba..f884edb286 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootJavaConfig.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/BootJavaConfig.java @@ -203,6 +203,15 @@ public void addListener(Consumer l) { listeners.add(l); } + /** + * The global override for the SQL dialect used to validate native + * {@code @Query} statements: {@code auto} (default), {@code mysql}, or + * {@code postgresql}. See {@code SqlDialectResolver}. + */ + public String getSqlDialect() { + return settings.getString("spring-boot", "ls", "problem-parameters", "data-query", "sql-dialect"); + } + @Override public void afterPropertiesSet() throws Exception { settingsStore.onDidChange(this::handleConfigurationChange); diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/JdtConfig.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/JdtConfig.java index 1e5d239313..228956eb45 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/JdtConfig.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/JdtConfig.java @@ -38,6 +38,7 @@ import org.springframework.ide.vscode.boot.java.data.jpa.queries.JpqlSemanticTokens; import org.springframework.ide.vscode.boot.java.data.jpa.queries.JpqlSupportState; import org.springframework.ide.vscode.boot.java.data.jpa.queries.QueryJdtAstReconciler; +import org.springframework.ide.vscode.boot.java.data.jpa.queries.SqlDialectResolver; import org.springframework.ide.vscode.boot.java.handlers.Reconciler; import org.springframework.ide.vscode.boot.java.reconcilers.AddConfigurationIfBeansPresentReconciler; import org.springframework.ide.vscode.boot.java.reconcilers.ApplicationModuleListenerReconciler; @@ -263,8 +264,9 @@ public class JdtConfig { @Bean QueryJdtAstReconciler dataQueryReconciler( @Qualifier("hqlReconciler") Reconciler hqlReconciler, @Qualifier("jpqlReconciler") Reconciler jpqlReconciler, - Optional spelReconciler) { - return new QueryJdtAstReconciler(hqlReconciler, jpqlReconciler, spelReconciler); + Optional spelReconciler, + SqlDialectResolver sqlDialectResolver) { + return new QueryJdtAstReconciler(hqlReconciler, jpqlReconciler, spelReconciler, sqlDialectResolver); } @Bean EmbeddedLanguagesSemanticTokensSupport embbededLanguagesSyntaxHighlighting(SimpleLanguageServer server, BootJavaConfig config) { diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringDataConfig.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringDataConfig.java index 4c9f62bc8b..acbcb04dae 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringDataConfig.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/app/SpringDataConfig.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2024 Broadcom, Inc. + * Copyright (c) 2024, 2026 Broadcom, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -18,6 +18,8 @@ import org.springframework.ide.vscode.boot.java.data.jpa.queries.JpqlSemanticTokens; import org.springframework.ide.vscode.boot.java.data.jpa.queries.JpqlSupportState; import org.springframework.ide.vscode.boot.java.data.jpa.queries.QueryProblemType; +import org.springframework.ide.vscode.boot.java.data.jpa.queries.SqlDialectQuickFixProvider; +import org.springframework.ide.vscode.boot.java.data.jpa.queries.SqlDialectResolver; import org.springframework.ide.vscode.boot.java.embedded.lang.AntlrReconcilerWithSpel; import org.springframework.ide.vscode.boot.java.spel.SpelReconciler; import org.springframework.ide.vscode.boot.java.spel.SpelSemanticTokens; @@ -55,5 +57,15 @@ AntlrReconcilerWithSpel jpqlReconciler(Optional spelReconciler) JpqlSupportState jpqlSupportState(SimpleLanguageServer server, ProjectObserver projectObserver, BootJavaConfig config) { return new JpqlSupportState(server, projectObserver, config); } - + + @Bean + SqlDialectResolver sqlDialectResolver(BootJavaConfig config) { + return new SqlDialectResolver(config); + } + + @Bean + SqlDialectQuickFixProvider sqlDialectQuickFixProvider(SqlDialectResolver sqlDialectResolver) { + return new SqlDialectQuickFixProvider(sqlDialectResolver); + } + } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/common/SpringProblemCategories.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/common/SpringProblemCategories.java index 1a64badec3..37f60e6da9 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/common/SpringProblemCategories.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/common/SpringProblemCategories.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2022, 2025 VMware, Inc. + * Copyright (c) 2022, 2026 VMware, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -20,7 +20,21 @@ import static org.springframework.ide.vscode.commons.languageserver.reconcile.ProblemCategory.Toggle.Option.*; public class SpringProblemCategories { - + + private static final String PROBLEM_PARAMETERS_SETTING_PREFIX = "spring-boot.ls.problem-parameters"; + + /** + * The full, dotted setting name a {@code category}'s parameter is read + * from - the same {@code spring-boot.ls.problem-parameters..} + * path {@code ProblemTypesToJson} and Eclipse's {@code DelegatingStreamConnectionProvider} + * already derive independently, computed here instead of duplicated as a + * literal, so a quick fix can reference a parameter's setting name without + * hardcoding it. + */ + public static String problemParameterSettingKey(ProblemCategory category, String parameterKey) { + return PROBLEM_PARAMETERS_SETTING_PREFIX + "." + category.getId() + "." + parameterKey; + } + public static final ProblemCategory BOOT_2 = new ProblemCategory("boot2", "Boot 2.x Best Practices & Optimizations", new Toggle("Enablement", EnumSet.allOf(Toggle.Option.class), AUTO, "boot-java.validation.java.boot2")); @@ -45,7 +59,11 @@ public class SpringProblemCategories { List.of(new ProblemTypeParameter("use-project-build-file", "Check project repositories for available versions", "When enabled, uses the Maven repositories configured in the project build file to look up available Spring Boot versions. Falls back to spring.io if the repositories cannot be queried.", ProblemTypeParameter.ValueType.BOOLEAN, "true"))); public static final ProblemCategory DATA_QUERY = new ProblemCategory("data-query", "Data Queries", - new Toggle("Enablement", EnumSet.of(OFF, ON), ON, "boot-java.validation.data-query")); + new Toggle("Enablement", EnumSet.of(OFF, ON), ON, "boot-java.validation.data-query"), + List.of(new ProblemTypeParameter("sql-dialect", "SQL Dialect", + "Overrides the SQL dialect used to validate native @Query SQL statements. By default the dialect is inferred from JDBC driver dependencies (MySQL/MariaDB take precedence over PostgreSQL when both are present).", + ProblemTypeParameter.ValueType.STRING, "auto", + new String[] { "auto", "mysql", "postgresql" }))); public static final ProblemCategory CRON = new ProblemCategory("cron", "CRON Expressions", new Toggle("Enablement", EnumSet.of(OFF, ON), ON, "boot-java.validation.cron")); diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryJdtAstReconciler.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryJdtAstReconciler.java index 4afdda2d3c..9a26d1eb45 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryJdtAstReconciler.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryJdtAstReconciler.java @@ -41,13 +41,15 @@ public class QueryJdtAstReconciler implements JdtAstReconciler { private final Reconciler hqlReconciler; private final Reconciler jpqlReconciler; private final Map sqlReconcilers; + private final SqlDialectResolver sqlDialectResolver; + - public QueryJdtAstReconciler(Reconciler hqlReconciler, Reconciler jpqlReconciler, - Optional spelReconciler) { + Optional spelReconciler, SqlDialectResolver sqlDialectResolver) { this.hqlReconciler = hqlReconciler; this.jpqlReconciler = jpqlReconciler; - + this.sqlDialectResolver = sqlDialectResolver; + this.sqlReconcilers = new LinkedHashMap<>(); this.sqlReconcilers.put(SqlType.MYSQL, new AntlrReconcilerWithSpel("MySQL", MySqlParser.class, MySqlLexer.class, "sqlStatements", QueryProblemType.SQL_SYNTAX, spelReconciler, MySqlLexer.SPEL)); this.sqlReconcilers.put(SqlType.POSTGRESQL, new AntlrReconcilerWithSpel("PostgreSQL", PostgreSqlParser.class, PostgreSqlLexer.class, "root", QueryProblemType.SQL_SYNTAX, spelReconciler, PostgreSqlLexer.SPEL)); @@ -62,8 +64,7 @@ public Optional createVisitor(IJavaProject project, URI docURI, Comp public boolean visit(NormalAnnotation node) { EmbeddedQueryExpression q = JdtQueryVisitorUtils.extractQueryExpression(annotationHierarchies, node); if (q != null) { - Optional reconcilerOpt = q.isNative() ? getSqlReconciler(project) : Optional.of(getQueryReconciler(project)); - reconcilerOpt.ifPresent(r -> r.reconcile(q.query().getText(), q.query()::toSingleJavaRange, context.getProblemCollector())); + reconcileQuery(project, q, context); } return super.visit(node); } @@ -72,8 +73,7 @@ public boolean visit(NormalAnnotation node) { public boolean visit(SingleMemberAnnotation node) { EmbeddedQueryExpression q = JdtQueryVisitorUtils.extractQueryExpression(annotationHierarchies, node); if (q != null) { - Optional reconcilerOpt = q.isNative() ? getSqlReconciler(project) : Optional.of(getQueryReconciler(project)); - reconcilerOpt.ifPresent(r -> r.reconcile(q.query().getText(), q.query()::toSingleJavaRange, context.getProblemCollector())); + reconcileQuery(project, q, context); } return super.visit(node); } @@ -96,7 +96,19 @@ public boolean visit(MethodInvocation node) { private Reconciler getQueryReconciler(IJavaProject project) { return SpringProjectUtil.hasDependencyStartingWith(project, "hibernate-core", null) ? hqlReconciler : jpqlReconciler; } - + + private void reconcileQuery(IJavaProject project, EmbeddedQueryExpression q, ReconcilingContext context) { + if (q.isNative()) { + SqlType resolved = sqlDialectResolver.resolve(project); + if (resolved == null) { + return; + } + sqlReconcilers.get(resolved).reconcile(q.query().getText(), q.query()::toSingleJavaRange, context.getProblemCollector()); + } else { + getQueryReconciler(project).reconcile(q.query().getText(), q.query()::toSingleJavaRange, context.getProblemCollector()); + } + } + // public static void reconcileExpression(Reconciler reconciler, Expression valueExp, IProblemCollector problemCollector) { // String query = null; // int offset = 0; @@ -125,18 +137,5 @@ public boolean isApplicable(IJavaProject project) { public ProblemType getProblemType() { return QueryProblemType.JPQL_SYNTAX; } - - private Optional getSqlReconciler(IJavaProject project) { - if (SpringProjectUtil.hasDependencyStartingWith(project, "mysql-connector", null) - || SpringProjectUtil.hasDependencyStartingWith(project, "mariadb-java-client", null)) { - return Optional.of(sqlReconcilers.get(SqlType.MYSQL)); - } else if (SpringProjectUtil.hasDependencyStartingWith(project, "postgresql", null)) { - return Optional.of(sqlReconcilers.get(SqlType.POSTGRESQL)); - } else if (SpringProjectUtil.hasDependencyStartingWith(project, "h2", null)) { - // Keep H2 the last as it might be added in combination with other DB clients - return Optional.of(sqlReconcilers.get(SqlType.POSTGRESQL)); - } - return Optional.empty(); - } } diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProvider.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProvider.java new file mode 100644 index 0000000000..7a58a6dd81 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProvider.java @@ -0,0 +1,129 @@ +/******************************************************************************* + * Copyright (c) 2026 Broadcom, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.data.jpa.queries; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.eclipse.lsp4j.CodeAction; +import org.eclipse.lsp4j.CodeActionCapabilities; +import org.eclipse.lsp4j.CodeActionContext; +import org.eclipse.lsp4j.CodeActionKind; +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.jsonrpc.CancelChecker; +import org.eclipse.lsp4j.jsonrpc.messages.Either; +import org.springframework.ide.vscode.boot.common.SpringProblemCategories; +import org.springframework.ide.vscode.boot.java.handlers.JavaCodeActionHandler; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.util.text.IRegion; +import org.springframework.ide.vscode.commons.util.text.TextDocument; + +/** + * Offers a quick fix on a {@link QueryProblemType#SQL_SYNTAX} diagnostic to + * switch the global {@code spring-boot.ls.problem-parameters.data-query.sql-dialect} setting, in + * exactly the two cases where a syntax error is plausibly a dialect problem + * rather than a real mistake in the query: + *
    + *
  • the classpath is genuinely ambiguous (more than one recognized JDBC + * driver present) - offer every applicable dialect plus "auto", minus + * whichever is currently selected;
  • + *
  • the classpath is unambiguous but the current override doesn't match + * it - offer switching back to "auto".
  • + *
+ * An unambiguous syntax error with no override is presumably a real mistake + * in the query, so nothing is offered. Each fix is a plain client-side + * {@link Command} (not a {@code WorkspaceEdit}) that invokes the generic + * {@value #SET_CONFIGURATION_COMMAND_ID} command with the setting's full + * dotted name and the new value - both VSCode (a registered command in the + * extension) and Eclipse (a handler in the {@code boot.ls} plugin) implement + * it client-side, always against the global/workspace scope. + */ +public class SqlDialectQuickFixProvider implements JavaCodeActionHandler { + + /** + * Generic "set a configuration value" command, reusable by any future + * quick fix - not specific to the SQL dialect setting. Takes the setting's + * full dotted name and the new value as its two arguments. + */ + public static final String SET_CONFIGURATION_COMMAND_ID = "boot-ls.client.set-configuration"; + + private static final String SQL_DIALECT_SETTING_KEY = SpringProblemCategories + .problemParameterSettingKey(SpringProblemCategories.DATA_QUERY, "sql-dialect"); + + private final SqlDialectResolver sqlDialectResolver; + + public SqlDialectQuickFixProvider(SqlDialectResolver sqlDialectResolver) { + this.sqlDialectResolver = sqlDialectResolver; + } + + @Override + public List> handle(IJavaProject project, CancelChecker cancelToken, + CodeActionCapabilities capabilities, CodeActionContext context, TextDocument doc, IRegion region) { + if (context == null || context.getDiagnostics() == null) { + return List.of(); + } + + List syntaxErrors = context.getDiagnostics().stream() + .filter(d -> d.getCode() != null && d.getCode().isLeft() + && QueryProblemType.SQL_SYNTAX.getCode().equals(d.getCode().getLeft())) + .toList(); + if (syntaxErrors.isEmpty()) { + return List.of(); + } + + List applicable = sqlDialectResolver.applicableDialects(project); + Optional override = sqlDialectResolver.getOverride(); + String selectedSettingValue = override.map(SqlType::getSettingValue) + .orElse(SqlDialectResolver.AUTO_SETTING_VALUE); + + List candidates; + if (applicable.size() > 1) { + // Ambiguous classpath: every applicable dialect, plus auto. + candidates = new ArrayList<>(); + for (SqlType type : applicable) { + candidates.add(new SqlDialectResolver.DialectOption(type.getLabel(), type.getSettingValue())); + } + candidates.add(new SqlDialectResolver.DialectOption("Auto", SqlDialectResolver.AUTO_SETTING_VALUE)); + } else if (override.isPresent() && !applicable.contains(override.get())) { + // Unambiguous classpath, but the override doesn't match it: only offer reverting to auto. + candidates = List.of(new SqlDialectResolver.DialectOption("Auto", SqlDialectResolver.AUTO_SETTING_VALUE)); + } else { + return List.of(); + } + + List> fixes = new ArrayList<>(); + for (SqlDialectResolver.DialectOption option : candidates) { + if (option.settingValue().equals(selectedSettingValue)) { + continue; + } + String title = "Set SQL dialect to " + option.label(); + fixes.add(Either.forRight(createCodeAction(syntaxErrors, title, option.settingValue()))); + } + return fixes; + } + + private CodeAction createCodeAction(List diagnostics, String title, String dialectSettingValue) { + Command cmd = new Command(); + cmd.setTitle(title); + cmd.setCommand(SET_CONFIGURATION_COMMAND_ID); + cmd.setArguments(List.of(SQL_DIALECT_SETTING_KEY, dialectSettingValue)); + + CodeAction ca = new CodeAction(); + ca.setTitle(title); + ca.setKind(CodeActionKind.QuickFix); + ca.setDiagnostics(diagnostics); + ca.setCommand(cmd); + return ca; + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectResolver.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectResolver.java new file mode 100644 index 0000000000..aa3fac3888 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectResolver.java @@ -0,0 +1,97 @@ +/******************************************************************************* + * Copyright (c) 2026 Broadcom, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.data.jpa.queries; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import org.springframework.ide.vscode.boot.app.BootJavaConfig; +import org.springframework.ide.vscode.commons.java.IJavaProject; +import org.springframework.ide.vscode.commons.java.SpringProjectUtil; + +/** + * Resolves the SQL dialect used to validate native {@code @Query} statements: + * a global {@code spring-boot.ls.problem-parameters.data-query.sql-dialect} setting (read via + * {@link BootJavaConfig}, same as every other global setting - no per-project + * override, no separate client round trip) combined with what the project's + * classpath itself indicates. + */ +public class SqlDialectResolver { + + public static final String AUTO_SETTING_VALUE = "auto"; + + /** + * A settable value for {@code spring-boot.ls.problem-parameters.data-query.sql-dialect} + * ({@link BootJavaConfig#getSqlDialect()}): either + * {@link #AUTO_SETTING_VALUE} (no override - infer from the classpath) + * or a concrete {@link SqlType}'s {@link SqlType#getSettingValue()}. + */ + public record DialectOption(String label, String settingValue) {} + + private final BootJavaConfig config; + + public SqlDialectResolver(BootJavaConfig config) { + this.config = config; + } + + public Optional getOverride() { + String value = config.getSqlDialect(); + for (SqlType type : SqlType.values()) { + if (type.getSettingValue().equalsIgnoreCase(value)) { + return Optional.of(type); + } + } + return Optional.empty(); + } + + /** + * The SQL dialects a project's classpath actually supports, in + * preference order (i.e. the order {@link QueryJdtAstReconciler} would + * pick from when there is no explicit override). Zero entries means no + * recognized JDBC driver was found at all; more than one means the + * classpath is ambiguous (both a MySQL/MariaDB and a PostgreSQL driver + * present). + *

+ * H2 is only counted as evidence for {@link SqlType#POSTGRESQL} when no + * MySQL/MariaDB driver is present - it's a common test-scope addition + * alongside a "real" driver and shouldn't by itself make the classpath + * look ambiguous. + */ + public List applicableDialects(IJavaProject project) { + boolean hasMysqlDriver = SpringProjectUtil.hasDependencyStartingWith(project, "mysql-connector", null) + || SpringProjectUtil.hasDependencyStartingWith(project, "mariadb-java-client", null); + boolean hasPostgresDriver = SpringProjectUtil.hasDependencyStartingWith(project, "postgresql", null); + boolean hasH2Driver = SpringProjectUtil.hasDependencyStartingWith(project, "h2", null); + + List result = new ArrayList<>(); + if (hasMysqlDriver) { + result.add(SqlType.MYSQL); + } + if (hasPostgresDriver || (!hasMysqlDriver && hasH2Driver)) { + result.add(SqlType.POSTGRESQL); + } + return result; + } + + /** + * Combines the global override (if any) with the classpath-applicable + * dialects into the reconciler to actually use - {@code null} if there's + * no override and the classpath has no recognized JDBC driver either. + */ + public SqlType resolve(IJavaProject project) { + return getOverride().orElseGet(() -> { + List applicable = applicableDialects(project); + return applicable.isEmpty() ? null : applicable.get(0); + }); + } + +} diff --git a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlType.java b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlType.java index 7ba603e994..c0a0fef7cd 100644 --- a/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlType.java +++ b/headless-services/spring-boot-language-server/src/main/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlType.java @@ -1,5 +1,5 @@ /******************************************************************************* - * Copyright (c) 2024 Broadcom, Inc. + * Copyright (c) 2024, 2026 Broadcom, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at @@ -11,8 +11,31 @@ package org.springframework.ide.vscode.boot.java.data.jpa.queries; public enum SqlType { - - MYSQL, - POSTGRESQL + + MYSQL("MySQL", "mysql"), + POSTGRESQL("PostgreSQL", "postgresql"); + + private final String label; + private final String settingValue; + + SqlType(String label, String settingValue) { + this.label = label; + this.settingValue = settingValue; + } + + /** + * Human-readable name, e.g. for diagnostic messages and quick fix titles. + */ + public String getLabel() { + return label; + } + + /** + * The value this dialect is represented by in the + * {@code spring-boot.ls.problem-parameters.data-query.sql-dialect} setting. + */ + public String getSettingValue() { + return settingValue; + } } diff --git a/headless-services/spring-boot-language-server/src/main/resources/problem-types.json b/headless-services/spring-boot-language-server/src/main/resources/problem-types.json index d299ad2684..858709396f 100644 --- a/headless-services/spring-boot-language-server/src/main/resources/problem-types.json +++ b/headless-services/spring-boot-language-server/src/main/resources/problem-types.json @@ -547,6 +547,20 @@ "preferenceKey": "boot-java.validation.data-query", "defaultValue": "ON" }, + "parameters": [ + { + "key": "sql-dialect", + "label": "SQL Dialect", + "description": "Overrides the SQL dialect used to validate native @Query SQL statements. By default the dialect is inferred from JDBC driver dependencies (MySQL/MariaDB take precedence over PostgreSQL when both are present).", + "type": "string", + "defaultValue": "auto", + "enumValues": [ + "auto", + "mysql", + "postgresql" + ] + } + ], "order": 9, "problemTypes": [ { diff --git a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryReconcilerTest.java b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryReconcilerTest.java index 32e37c947e..65a902c204 100644 --- a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryReconcilerTest.java +++ b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/QueryReconcilerTest.java @@ -246,7 +246,7 @@ public interface OwnerRepository extends Repository { Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); editor.assertProblems("SELECTX|MySQL: mismatched input 'SELECTX' expecting {'ALTER',"); } - + @Test void nativePostgreSql() throws Exception { directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-postgresql/").toURI()); @@ -272,7 +272,7 @@ public interface OwnerRepository extends Repository { Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); editor.assertProblems("SELECTX|PostgreSQL: mismatched input 'SELECTX'"); } - + @Test void noErrorForHql() throws Exception { String source = """ @@ -402,7 +402,7 @@ public interface OwnerRepository extends CrudRepository { Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); editor.assertProblems("SELECTX|PostgreSQL: mismatched input 'SELECTX' expecting {"); } - + @Test void jdbcOnlyProjectNoReconcilingWithoutDbConnector() throws Exception { directory = new File(ProjectsHarness.class.getResource("/test-projects/aot-data-repositories-jdbc/").toURI()); @@ -444,8 +444,8 @@ void queryMariaDbNoProblems() throws Exception { public interface OwnerRepository extends CrudRepository { @Query(value = ""\" - INSERT INTO `user_settings` (`user_id`, `theme_color`) - VALUES (101, 'dark') + INSERT INTO `user_settings` (`user_id`, `theme_color`) + VALUES (101, 'dark') ON DUPLICATE KEY UPDATE `theme_color` = 'dark'; ""\") List findByLastName(String lastName); @@ -474,9 +474,9 @@ void queryMariaWithPogreSqlQuery() throws Exception { public interface OwnerRepository extends CrudRepository { @Query(value = ""\" - INSERT INTO "user_settings" ("user_id", "theme_color") - VALUES (101, 'dark') - ON CONFLICT ("user_id") + INSERT INTO "user_settings" ("user_id", "theme_color") + VALUES (101, 'dark') + ON CONFLICT ("user_id") DO UPDATE SET "theme_color" = EXCLUDED.theme_color; ""\") List findByLastName(String lastName); @@ -488,4 +488,127 @@ ON CONFLICT ("user_id") Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); editor.assertProblems("CONFLICT|MySQL: no viable alternative at input 'INSERT INTO"); } + + // https://github.com/spring-projects/spring-tools/issues/1975 + @Test + void queryWithBothMariaDbAndPostgresqlDriversMisdetectedAsMySql() throws Exception { + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mariadb-postgresql/").toURI()); + String projectDir = directory.toURI().toString(); + // trigger project creation + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface MachineRepository extends CrudRepository { + + @Query(value = "SELECT * FROM machine WHERE management_ip = CAST(:managementIp AS inet)", nativeQuery = true) + List findByManagementIp(String managementIp); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/MachineRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + // Valid PostgreSQL syntax, but since a MariaDB driver is also on the classpath, + // the query is incorrectly validated against the MySQL grammar instead of PostgreSQL. + editor.assertProblems("inet|MySQL: no viable alternative at input 'SELECT * FROM machine WHERE management_ip = CAST(:managementIp AS inet'"); + } + + @Test + void queryDialectOverrideIsUsedForAmbiguousClasspath() throws Exception { + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mariadb-postgresql/").toURI()); + String projectDir = directory.toURI().toString(); + // trigger project creation + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + harness.changeConfiguration(""" + { + "spring-boot": { + "ls": { + "problem": { + "data-query": { + "SQL_SYNTAX": "ERROR" + } + }, + "problem-parameters": { + "data-query": { + "sql-dialect": "postgresql" + } + } + } + } + } + """); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface MachineRepository extends CrudRepository { + + @Query(value = "SELECT * FROM machine WHERE management_ip = CAST(:managementIp AS inet)", nativeQuery = true) + List findByManagementIp(String managementIp); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/MachineRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + // The global override wins over the ambiguous classpath: PostgreSQL grammar is used, + // so the valid PostgreSQL query no longer raises a (bogus) syntax error. + editor.assertProblems(); + } + + @Test + void queryDialectOverrideIsUsedEvenWhenClasspathUnambiguouslyDisagrees() throws Exception { + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mariadb-h2/").toURI()); + String projectDir = directory.toURI().toString(); + // trigger project creation + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + // The classpath here unambiguously resolves to MySQL (mariadb + h2, see + // queryMariaDbNoProblems above), but the user has explicitly forced PostgreSQL. + harness.changeConfiguration(""" + { + "spring-boot": { + "ls": { + "problem": { + "data-query": { + "SQL_SYNTAX": "ERROR" + } + }, + "problem-parameters": { + "data-query": { + "sql-dialect": "postgresql" + } + } + } + } + } + """); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface OwnerRepository extends CrudRepository { + + @Query(value = "INSERT INTO \\"user_settings\\" (\\"user_id\\", \\"theme_color\\") VALUES (101, 'dark') ON CONFLICT (\\"user_id\\") DO UPDATE SET \\"theme_color\\" = EXCLUDED.theme_color;") + List findByLastName(String lastName); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/OwnerRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + // The override always wins for reconciliation, regardless of what the classpath + // alone would resolve to: valid PostgreSQL syntax, so no syntax error. + editor.assertProblems(); + } } diff --git a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProviderTest.java b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProviderTest.java new file mode 100644 index 0000000000..f556551319 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/java/data/jpa/queries/SqlDialectQuickFixProviderTest.java @@ -0,0 +1,257 @@ +/******************************************************************************* + * Copyright (c) 2026 Broadcom, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * https://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Broadcom, Inc. - initial API and implementation + *******************************************************************************/ +package org.springframework.ide.vscode.boot.java.data.jpa.queries; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.io.File; +import java.util.List; + +import org.eclipse.lsp4j.Command; +import org.eclipse.lsp4j.Diagnostic; +import org.eclipse.lsp4j.TextDocumentIdentifier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Import; +import org.springframework.ide.vscode.boot.bootiful.BootLanguageServerTest; +import org.springframework.ide.vscode.boot.bootiful.IndexerTestConf; +import org.springframework.ide.vscode.commons.languageserver.java.JavaProjectFinder; +import org.springframework.ide.vscode.commons.util.text.LanguageId; +import org.springframework.ide.vscode.languageserver.testharness.CodeAction; +import org.springframework.ide.vscode.languageserver.testharness.Editor; +import org.springframework.ide.vscode.project.harness.BootLanguageServerHarness; +import org.springframework.ide.vscode.project.harness.ProjectsHarness; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +@ExtendWith(SpringExtension.class) +@BootLanguageServerTest +@Import(IndexerTestConf.class) +public class SqlDialectQuickFixProviderTest { + + @Autowired + private BootLanguageServerHarness harness; + @Autowired + private JavaProjectFinder projectFinder; + + private File directory; + + @BeforeEach + public void setup() throws Exception { + harness.intialize(null); + harness.changeConfiguration(""" + { + "spring-boot": { + "ls": { + "problem": { + "data-query": { + "SQL_SYNTAX": "ERROR" + } + } + } + } + } + """); + } + + private Diagnostic findProblem(Editor editor, QueryProblemType type) throws Exception { + return editor.reconcile().stream() + .filter(d -> d.getCode() != null && d.getCode().isLeft() && type.getCode().equals(d.getCode().getLeft())) + .findFirst() + .orElse(null); + } + + private static List dialectActionsOnly(List actions) { + return actions.stream() + .filter(ca -> ca.getLabel() != null && ca.getLabel().startsWith("Set SQL dialect to ")) + .toList(); + } + + @Test + void syntaxErrorAloneOffersNoDialectSwitchFixWhenUnambiguous() throws Exception { + // boot-mysql: unambiguous, resolves to MySQL with no override. A syntax error here is + // presumably a real mistake in the query, not a dialect problem, so nothing is offered. + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mysql/").toURI()); + String projectDir = directory.toURI().toString(); + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface OwnerRepository extends CrudRepository { + + @Query("SELECTX * FROM owner WHERE last_name = :lastName") + List findByLastName(String lastName); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/OwnerRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + + Diagnostic syntaxError = findProblem(editor, QueryProblemType.SQL_SYNTAX); + assertTrue(syntaxError != null, "Expected a SQL_SYNTAX diagnostic"); + + List dialectActions = dialectActionsOnly(editor.getCodeActions(syntaxError)); + assertEquals(0, dialectActions.size()); + } + + @Test + void syntaxErrorOffersEveryOtherApplicableDialectWhenClasspathAmbiguousAndAutoSelected() throws Exception { + // boot-mariadb-postgresql: both MySQL/MariaDB and PostgreSQL drivers present, no + // override (so "auto" is the current selection), so a real syntax error (misdetected + // against the wrong of the two candidate grammars) should let the user pick between + // the dialects actually found - "auto" itself is excluded since it's already selected. + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mariadb-postgresql/").toURI()); + String projectDir = directory.toURI().toString(); + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface MachineRepository extends CrudRepository { + + @Query("SELECTX * FROM machine") + List findAll(); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/MachineRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + + Diagnostic syntaxError = findProblem(editor, QueryProblemType.SQL_SYNTAX); + assertTrue(syntaxError != null, "Expected a SQL_SYNTAX diagnostic"); + + List dialectActions = dialectActionsOnly(editor.getCodeActions(syntaxError)); + assertEquals(2, dialectActions.size()); + assertEquals("Set SQL dialect to MySQL", dialectActions.get(0).getLabel()); + assertEquals("Set SQL dialect to PostgreSQL", dialectActions.get(1).getLabel()); + } + + @Test + void syntaxErrorOffersRemainingApplicableDialectPlusAutoWhenClasspathAmbiguousAndOneIsSelected() throws Exception { + // Same ambiguous classpath, but the user has explicitly forced MySQL - so the + // candidates are the other applicable dialect (PostgreSQL) plus "auto", excluding + // MySQL itself since it's already selected. + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mariadb-postgresql/").toURI()); + String projectDir = directory.toURI().toString(); + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + harness.changeConfiguration(""" + { + "spring-boot": { + "ls": { + "problem": { + "data-query": { + "SQL_SYNTAX": "ERROR" + } + }, + "problem-parameters": { + "data-query": { + "sql-dialect": "mysql" + } + } + } + } + } + """); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface MachineRepository extends CrudRepository { + + @Query("SELECTX * FROM machine") + List findAll(); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/MachineRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + + Diagnostic syntaxError = findProblem(editor, QueryProblemType.SQL_SYNTAX); + assertTrue(syntaxError != null, "Expected a SQL_SYNTAX diagnostic"); + + List dialectActions = dialectActionsOnly(editor.getCodeActions(syntaxError)); + assertEquals(2, dialectActions.size()); + assertEquals("Set SQL dialect to PostgreSQL", dialectActions.get(0).getLabel()); + assertEquals("Set SQL dialect to Auto", dialectActions.get(1).getLabel()); + } + + @Test + void syntaxErrorOffersOnlyAutoWhenOverrideMismatchesUnambiguousClasspath() throws Exception { + // boot-mariadb-h2 unambiguously resolves to MySQL, but the user has explicitly forced + // PostgreSQL, so the override itself is used for reconciliation (a genuine syntax error + // against PostgreSQL grammar is raised), and the only offered fix is reverting to auto. + directory = new File(ProjectsHarness.class.getResource("/test-projects/boot-mariadb-h2/").toURI()); + String projectDir = directory.toURI().toString(); + projectFinder.find(new TextDocumentIdentifier(projectDir)).get(); + harness.changeConfiguration(""" + { + "spring-boot": { + "ls": { + "problem": { + "data-query": { + "SQL_SYNTAX": "ERROR" + } + }, + "problem-parameters": { + "data-query": { + "sql-dialect": "postgresql" + } + } + } + } + } + """); + + String source = """ + package example.demo; + + import org.springframework.data.jdbc.repository.query.Query; + import org.springframework.data.repository.CrudRepository; + + public interface OwnerRepository extends CrudRepository { + + @Query("SELECTX * FROM owner") + List findAll(); + + } + """; + String docUri = directory.toPath().resolve("src/main/java/example/demo/OwnerRepository.java").toUri() + .toString(); + Editor editor = harness.newEditor(LanguageId.JAVA, source, docUri); + + Diagnostic syntaxError = findProblem(editor, QueryProblemType.SQL_SYNTAX); + assertTrue(syntaxError != null, "Expected a SQL_SYNTAX diagnostic"); + + List dialectActions = dialectActionsOnly(editor.getCodeActions(syntaxError)); + assertEquals(1, dialectActions.size()); + assertEquals("Set SQL dialect to Auto", dialectActions.get(0).getLabel()); + + Command command = dialectActions.get(0).getCommand(); + assertEquals(SqlDialectQuickFixProvider.SET_CONFIGURATION_COMMAND_ID, command.getCommand()); + assertEquals(List.of("spring-boot.ls.problem-parameters.data-query.sql-dialect", "auto"), command.getArguments()); + } + +} diff --git a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/test/ProblemTypesToJson.java b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/test/ProblemTypesToJson.java index 17983f3e4c..021374793d 100644 --- a/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/test/ProblemTypesToJson.java +++ b/headless-services/spring-boot-language-server/src/test/java/org/springframework/ide/vscode/boot/test/ProblemTypesToJson.java @@ -83,6 +83,7 @@ public static class ProblemTypeParameterData { String description; String type; String defaultValue; + String[] enumValues; public ProblemTypeParameterData() {} @@ -92,6 +93,7 @@ public ProblemTypeParameterData(ProblemTypeParameter p) { this.description = p.getDescription(); this.type = p.getType().name().toLowerCase(); this.defaultValue = p.getDefaultValue(); + this.enumValues = p.getEnumValues(); } public String getKey() { @@ -113,8 +115,12 @@ public String getType() { public String getDefaultValue() { return defaultValue; } + + public String[] getEnumValues() { + return enumValues; + } } - + public static class ProblemTypeData { String code; String label; @@ -454,6 +460,13 @@ private static void addCategoryParameterPropertySchemas(JsonObject props, Proble } else { schema.addProperty("type", "string"); schema.addProperty("default", param.getDefaultValue()); + if (param.getEnumValues() != null) { + JsonArray enumVals = new JsonArray(); + for (String v : param.getEnumValues()) { + enumVals.add(v); + } + schema.add("enum", enumVals); + } } schema.addProperty("description", param.getDescription()); props.add(fullKey, schema); diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/.mvn/wrapper/maven-wrapper.properties b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..654af46a70 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw new file mode 100755 index 0000000000..d7c358e5a2 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw.cmd b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw.cmd new file mode 100644 index 0000000000..6f779cff20 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/pom.xml b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/pom.xml new file mode 100644 index 0000000000..3e967195d3 --- /dev/null +++ b/headless-services/spring-boot-language-server/src/test/resources/test-projects/boot-mariadb-postgresql/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 4.0.3 + + + + boot-mariadb-postgresql + + + 17 + + + + + + org.springframework.boot + spring-boot-starter + + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + + org.mariadb.jdbc + mariadb-java-client + runtime + + + org.postgresql + postgresql + runtime + + + + + diff --git a/vscode-extensions/vscode-spring-boot/lib/Main.ts b/vscode-extensions/vscode-spring-boot/lib/Main.ts index 253d60e257..927c5a45f3 100644 --- a/vscode-extensions/vscode-spring-boot/lib/Main.ts +++ b/vscode-extensions/vscode-spring-boot/lib/Main.ts @@ -5,6 +5,7 @@ import { commands, window, workspace, + ConfigurationTarget, ExtensionContext, Uri, TextDocumentContentProvider @@ -230,6 +231,17 @@ function registerMiscCommands(context: ExtensionContext) { const browserCommand = openWithExternalBrowser ? "vscode.open" : "simpleBrowser.api.open"; return commands.executeCommand(browserCommand, Uri.parse(openUrl)); }), + + // Generic "set a configuration value" command the language server invokes from quick + // fixes (e.g. the SQL dialect quick fix) - reusable for future settings without a + // dedicated command per setting. Always targets the workspace scope. + commands.registerCommand('boot-ls.client.set-configuration', async (key: string, value: any) => { + const lastDot = key.lastIndexOf('.'); + const section = key.substring(0, lastDot); + const settingName = key.substring(lastDot + 1); + const config = workspace.getConfiguration(section); + await config.update(settingName, value, ConfigurationTarget.Global); + }), ); } diff --git a/vscode-extensions/vscode-spring-boot/package.json b/vscode-extensions/vscode-spring-boot/package.json index 62e0cea997..e3b0bceca3 100644 --- a/vscode-extensions/vscode-spring-boot/package.json +++ b/vscode-extensions/vscode-spring-boot/package.json @@ -1664,6 +1664,16 @@ "HINT", "ERROR" ] + }, + "spring-boot.ls.problem-parameters.data-query.sql-dialect": { + "type": "string", + "default": "auto", + "enum": [ + "auto", + "mysql", + "postgresql" + ], + "description": "Overrides the SQL dialect used to validate native @Query SQL statements. By default the dialect is inferred from JDBC driver dependencies (MySQL/MariaDB take precedence over PostgreSQL when both are present)." } } },