diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 14d599ea194..89336505bb2 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -79,9 +79,14 @@ + + + + + @@ -859,6 +864,11 @@ + + + + + @@ -1207,6 +1217,12 @@ + + + + + + @@ -3113,6 +3129,12 @@ + + + + + + @@ -3588,6 +3610,12 @@ + + + + + + diff --git a/settings.gradle b/settings.gradle index ece525d8266..51caf962ae7 100644 --- a/settings.gradle +++ b/settings.gradle @@ -71,6 +71,7 @@ def subprojects = [ 'groovy-callsite', 'groovy-logging-test', 'groovy-ginq', + 'groovy-ginq-sql', 'groovy-http-builder', 'groovy-markdown', 'groovy-macro', diff --git a/subprojects/groovy-ginq-sql/build.gradle b/subprojects/groovy-ginq-sql/build.gradle new file mode 100644 index 00000000000..41da56021a6 --- /dev/null +++ b/subprojects/groovy-ginq-sql/build.gradle @@ -0,0 +1,46 @@ +/* + * 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 + * + * http://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. + */ +plugins { + id 'org.apache.groovy-library' +} + +dependencies { + api rootProject + api projects.groovyGinq + api projects.groovySql + compileOnly "org.jooq:jooq:${versions.jooq}" // used by the optional jooq-sql provider + testImplementation projects.groovyTest + testImplementation "org.jooq:jooq:${versions.jooq}" + testImplementation "com.h2database:h2:${versions.h2}" +} + +groovyLibrary { + optionalModule() + + withoutBinaryCompatibilityChecks() +} + +// GINQ macros expand at test-compile time using this module's classes, so the +// provider implementation (not just its ABI) is a genuine input; without this, +// compilation avoidance and the build cache can reuse test classes containing +// stale macro expansions +tasks.named('compileTestGroovy') { + inputs.files(tasks.named('compileGroovy').flatMap { it.destinationDirectory }) + .withPropertyName('sqlProviderImplementation') +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/FunctionSupport.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/FunctionSupport.java new file mode 100644 index 00000000000..e60aea107a5 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/FunctionSupport.java @@ -0,0 +1,109 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql; + +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +/** + * Which ANSI functions a dialect can render, including under a different + * spelling. The translator consults this before emitting a {@code SqlFunction}, + * and the renderer consults it again so a function that cannot be rendered is + * never written into SQL. A dialect that lacks a function is not a special + * case in the planner: the name is added to {@link #UNSUPPORTED} and both + * strict mode and mixed mode pick it up. + *

+ * A function that the dialect spells differently but can still render + * ({@code CHAR_LENGTH} as SQLite {@code LENGTH}, {@code GREATEST} as + * {@code MAX}) stays supported. Only functions with no faithful rendering + * belong here. + * + * @since 7.0.0 + */ +@Incubating +public final class FunctionSupport { + private static final Map> UNSUPPORTED = unsupported(); + + private FunctionSupport() { + } + + /** + * Canonical dialect family for a configured name. Unknown names are + * lower-cased and then support every function, which is what a jOOQ + * dialect without a known gap does. + * + * @param dialectName the configured dialect, or {@code null} + * @return the family name used by {@link #supports(String, String)} + */ + public static String canonical(String dialectName) { + if (dialectName == null || dialectName.isEmpty()) { + return "ansi"; + } + switch (dialectName.toLowerCase(Locale.ROOT)) { + case "postgresql": + case "postgres": + return "postgres"; + case "mariadb": + case "mysql": + return "mysql"; + case "sqlite": + return "sqlite"; + case "h2": + return "h2"; + case "default": + case "ansi": + return "ansi"; + default: + return dialectName.toLowerCase(Locale.ROOT); + } + } + + /** + * Whether {@code ansiName} can be rendered for {@code dialectName}. + * + * @param dialectName the configured dialect + * @param ansiName the ANSI function name, for example {@code FLOOR} + * @return {@code false} only when the dialect has no rendering of that function + */ + public static boolean supports(String dialectName, String ansiName) { + if (ansiName == null || ansiName.isEmpty()) { + return false; + } + Set missing = UNSUPPORTED.get(canonical(dialectName)); + return missing == null || !missing.contains(ansiName); + } + + private static Map> unsupported() { + Map> map = new HashMap<>(); + map.put("sqlite", set("FLOOR", "CEILING")); + return Collections.unmodifiableMap(map); + } + + private static Set set(String... names) { + Set values = new HashSet<>(); + Collections.addAll(values, names); + return Collections.unmodifiableSet(values); + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlWalker.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlWalker.groovy new file mode 100644 index 00000000000..17211b1a468 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlWalker.groovy @@ -0,0 +1,607 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope +import org.apache.groovy.ginq.GinqGroovyMethods +import org.apache.groovy.ginq.dsl.GinqAstVisitor +import org.apache.groovy.ginq.dsl.GinqSyntaxError +import org.apache.groovy.ginq.dsl.SyntaxErrorReportable +import org.apache.groovy.ginq.dsl.expression.AbstractGinqExpression +import org.apache.groovy.ginq.dsl.expression.DataSourceExpression +import org.apache.groovy.ginq.dsl.expression.FilterExpression +import org.apache.groovy.ginq.dsl.expression.FromExpression +import org.apache.groovy.ginq.dsl.expression.GinqExpression +import org.apache.groovy.ginq.dsl.expression.GroupExpression +import org.apache.groovy.ginq.dsl.expression.HavingExpression +import org.apache.groovy.ginq.dsl.expression.JoinExpression +import org.apache.groovy.ginq.dsl.expression.LimitExpression +import org.apache.groovy.ginq.dsl.expression.OnExpression +import org.apache.groovy.ginq.dsl.expression.OrderExpression +import org.apache.groovy.ginq.dsl.expression.SelectExpression +import org.apache.groovy.ginq.dsl.expression.SetOperationExpression +import org.apache.groovy.ginq.dsl.expression.ShutdownExpression +import org.apache.groovy.ginq.dsl.expression.WhereExpression +import org.apache.groovy.ginq.provider.collection.GinqAstWalker +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.ir.SqlSetQuery +import org.apache.groovy.ginq.provider.sql.render.AnsiDialect +import org.apache.groovy.ginq.provider.sql.render.Dialect +import org.apache.groovy.ginq.provider.sql.render.Dialects +import org.apache.groovy.ginq.provider.sql.render.RenderedSql +import org.apache.groovy.ginq.provider.sql.render.SqlRenderer +import org.apache.groovy.ginq.provider.sql.runtime.SqlGinqRuntime +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.GroovyBugError +import org.codehaus.groovy.ast.ASTNode +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.ClassNode +import org.codehaus.groovy.ast.expr.BinaryExpression +import org.codehaus.groovy.ast.expr.ClosureExpression +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.ConstructorCallExpression +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.ast.expr.GStringExpression +import org.codehaus.groovy.ast.expr.ExpressionTransformer +import org.codehaus.groovy.ast.expr.ListExpression +import org.codehaus.groovy.ast.expr.MethodCallExpression +import org.codehaus.groovy.ast.expr.TupleExpression +import org.codehaus.groovy.ast.expr.VariableExpression +import org.codehaus.groovy.ast.stmt.BlockStatement +import org.codehaus.groovy.ast.stmt.ExpressionStatement +import org.codehaus.groovy.ast.stmt.ReturnStatement +import org.codehaus.groovy.ast.stmt.Statement +import org.codehaus.groovy.control.SourceUnit + +import static org.codehaus.groovy.ast.tools.GeneralUtils.args +import static org.codehaus.groovy.ast.tools.GeneralUtils.block +import static org.codehaus.groovy.ast.tools.GeneralUtils.callX +import static org.codehaus.groovy.ast.tools.GeneralUtils.classX +import static org.codehaus.groovy.ast.tools.GeneralUtils.constX +import static org.codehaus.groovy.ast.tools.GeneralUtils.declS +import static org.codehaus.groovy.ast.tools.GeneralUtils.lambdaX +import static org.codehaus.groovy.ast.tools.GeneralUtils.localVarX +import static org.codehaus.groovy.ast.tools.GeneralUtils.params +import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS +import static org.codehaus.groovy.ast.tools.GeneralUtils.varX + +/** + * The native SQL provider: transforms a GINQ query into a call executing the + * equivalent SQL, rendered at compile time with all user values bound as + * positional parameters, against the configured {@code dataSource}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class GinqSqlWalker implements GinqAstVisitor, SyntaxErrorReportable { + private final SourceUnit sourceUnit + private Map configuration = [:] + private Map configurationExpressions = [:] + private Dialect dialect = new AnsiDialect() + + GinqSqlWalker(SourceUnit sourceUnit) { + this.sourceUnit = sourceUnit + } + + @Override + SourceUnit getSourceUnit() { + return sourceUnit + } + + @Override + Expression visit(AbstractGinqExpression expression) { + if ('true' == configuration.get(GinqGroovyMethods.CONF_PARALLEL)) { + error("`parallel` is not supported by the ${providerName} provider", expression) + } + if (expression instanceof ShutdownExpression) { + error("`shutdown` is not supported by the ${providerName} provider", expression) + } + Expression dataSourceExpr = configurationExpressions.get(GinqGroovyMethods.CONF_DATA_SOURCE) + if (dataSourceExpr == null) { + error("the ${providerName} provider requires a `dataSource`, e.g. GQ(provider: '${providerName}', dataSource: db) {...}; " + + 'note that `@GQ` does not support `dataSource`', expression) + } + validateOptions(expression) + if (sourceUnit.errorCollector.hasErrors()) { + return constX(null) + } + + if (isMixedMode()) { + return visitMixed(expression, dataSourceExpr) + } + + SqlQueryNode queryNode = translator().translate(expression) + if (queryNode == null || sourceUnit.errorCollector.hasErrors()) { + return constX(null) + } + if (!capabilities().supportsFullOuterJoin()) { + queryNode = MixedSourceLayout.layoutComplete(queryNode) + } + RenderedSql renderedSql = renderSql(queryNode, expression) + if (renderedSql == null) { + return constX(null) + } + return executeExpression(renderedSql, dataSourceExpr, expression, queryNode) + } + + private Expression visitMixed(AbstractGinqExpression expression, Expression dataSourceExpr) { + int before = sourceUnit.errorCollector.errorCount + MixedPlan plan = translator().planMixed(expression) + if (plan == null || sourceUnit.errorCollector.errorCount != before) { + return constX(null) + } + if (plan.fullQuery != null) { + RenderedSql renderedSql = renderSql(plan.fullQuery, expression) + if (renderedSql == null) { + return constX(null) + } + return executeExpression(renderedSql, dataSourceExpr, expression, plan.fullQuery) + } + return emitMixed(plan, expression, dataSourceExpr) + } + + private Expression emitMixed(MixedPlan plan, AbstractGinqExpression expression, Expression dataSourceExpr) { + GinqExpression tail = plan.tail + if (plan.columnCountQueries.isEmpty()) { + RenderedSql prefixSql = renderSql(plan.prefix, expression) + if (prefixSql == null) { + return constX(null) + } + tail.fromExpression.dataSourceExpr = executeExpression(prefixSql, dataSourceExpr, expression) + materializeQuery(tail) + if (sourceUnit.errorCollector.hasErrors()) { + return constX(null) + } + return runCollection(tail) + } + + String rowsName = "__ginqRows${mixedSeq++}" + VariableExpression rowsVar = varX(rowsName) + List layouts = [] + for (SqlQuery countQuery : plan.columnCountQueries) { + RenderedSql rendered = renderSql(countQuery, expression) + if (rendered == null) { + return constX(null) + } + layouts << callX(classX(SQL_GINQ_RUNTIME_TYPE), 'columnLabels', + args(dataSourceExpr, constX(rendered.sql), new ListExpression(rendered.parameters))) + } + RenderedSql prefixSql = renderSql(plan.prefix, expression) + if (prefixSql == null) { + return constX(null) + } + Expression zip = callX(classX(SQL_GINQ_RUNTIME_TYPE), 'zipAliases', args( + dataSourceExpr, + constX(prefixSql.sql), + new ListExpression(prefixSql.parameters), + new ListExpression(layouts), + constX(String.valueOf(identifierQuoteChar())))) + tail.fromExpression.dataSourceExpr = callX(rowsVar, 'get', constX(0)) + for (int i = 0; i < plan.pushedJoins; i++) { + tail.joinExpressionList[i].dataSourceExpr = callX(rowsVar, 'get', constX(i + 1)) + } + materializeQuery(tail) + if (sourceUnit.errorCollector.hasErrors()) { + return constX(null) + } + Expression tailExec = runCollection(tail) + Expression wrapper = callX(lambdaX(params(), block( + declS(localVarX(rowsName), zip), + returnS(tailExec) + )), 'call') + wrapper.setSourcePosition(expression) + return wrapper + } + + private Expression runCollection(GinqExpression tail) { + GinqAstWalker walker = new MixedTailWalker(sourceUnit) + walker.configuration = Collections.emptyMap() + walker.configurationExpressions = Collections.emptyMap() + return (Expression) walker.visit(tail) + } + + private Expression executeExpression(RenderedSql renderedSql, Expression dataSourceExpr, + AbstractGinqExpression expression, SqlQueryNode queryNode = null) { + List probes = starProbes(queryNode) + Expression executeCall + if (probes == null || probes.isEmpty()) { + executeCall = callX( + classX(SQL_GINQ_RUNTIME_TYPE), + 'execute', + args(dataSourceExpr, constX(renderedSql.sql), new ListExpression(renderedSql.parameters))) + } else { + List layouts = [] + for (SqlQuery probe : probes) { + RenderedSql renderedProbe = renderSql(probe, expression) + if (renderedProbe == null) { + return constX(null) + } + layouts.add(callX(classX(SQL_GINQ_RUNTIME_TYPE), 'columnLabels', + args(dataSourceExpr, constX(renderedProbe.sql), new ListExpression(renderedProbe.parameters)))) + } + executeCall = callX( + classX(SQL_GINQ_RUNTIME_TYPE), + 'expandAndExecute', + args(dataSourceExpr, constX(renderedSql.sql), new ListExpression(renderedSql.parameters), + new ListExpression(layouts), constX(String.valueOf(identifierQuoteChar())))) + } + executeCall.setSourcePosition(expression) + return executeCall + } + + private static List starProbes(SqlQueryNode queryNode) { + if (queryNode instanceof SqlQuery) { + return ((SqlQuery) queryNode).starProbes + } + if (queryNode instanceof SqlSetQuery) { + return ((SqlSetQuery) queryNode).starProbes + } + return null + } + + /** + * Quote character the renderer uses for synthetic {@code __ginq} names. + * jOOQ overrides this; MySQL and MariaDB use a backtick. + */ + protected char identifierQuoteChar() { + return dialect.identifierQuote() + } + + private boolean isMixedMode() { + return 'true' == configuration.get(NativeSqlGinqProvider.CONF_MIXED_MODE) + } + + /** + * Returns the provider name used in diagnostics. + */ + protected String getProviderName() { + return 'native-sql' + } + + /** + * Validates provider-specific options. + */ + protected void validateOptions(AbstractGinqExpression expression) { + String dialectName = effectiveDialectName() + if (dialectName != null) { + Dialect resolved = Dialects.resolve(dialectName) + if (resolved == null) { + error("`${dialectName}` is not a native SQL dialect (supported: ${Dialects.SUPPORTED}). " + + "For other databases use `provider: 'jooq-sql'` with a jOOQ SQLDialect name.", expression) + } else { + dialect = resolved + } + } + validateMixedMode(expression) + } + + /** + * The configured dialect, or the family named by a JDBC URL visible on + * the data-source expression. A variable data source stays unspecified + * and full joins are then emulated rather than spelled as + * {@code FULL OUTER JOIN}. + */ + protected String effectiveDialectName() { + String configured = configuration.get(NativeSqlGinqProvider.CONF_DIALECT) + if (configured != null && !configured.isEmpty()) { + return configured + } + return jdbcDialect(configurationExpressions.get(GinqGroovyMethods.CONF_DATA_SOURCE)) + } + + /** + * Dialect family named by a JDBC URL somewhere in {@code expression}, + * or null when no such URL is visible at compile time. + */ + @PackageScope + static String jdbcDialect(Expression expression) { + if (expression == null) { + return null + } + if (expression instanceof ConstantExpression && ((ConstantExpression) expression).value instanceof String) { + return Dialects.fromJdbcUrl((String) ((ConstantExpression) expression).value) + } + if (expression instanceof MethodCallExpression) { + MethodCallExpression call = (MethodCallExpression) expression + String found = jdbcDialect(call.objectExpression) + if (found != null) { + return found + } + return jdbcDialect(call.arguments) + } + if (expression instanceof ConstructorCallExpression) { + return jdbcDialect(((ConstructorCallExpression) expression).arguments) + } + if (expression instanceof TupleExpression) { + for (Expression argument : ((TupleExpression) expression).expressions) { + String found = jdbcDialect(argument) + if (found != null) { + return found + } + } + } + if (expression instanceof BinaryExpression) { + BinaryExpression binary = (BinaryExpression) expression + String found = jdbcDialect(binary.leftExpression) + return found != null ? found : jdbcDialect(binary.rightExpression) + } + if (expression instanceof GStringExpression) { + GStringExpression gstring = (GStringExpression) expression + // Constant pieces carry the scheme: "jdbc:h2:mem:${name}". + for (ConstantExpression part : gstring.strings) { + String found = Dialects.fromJdbcUrl(part.value == null ? null : part.value.toString()) + if (found != null) { + return found + } + } + for (Expression value : gstring.values) { + String found = jdbcDialect(value) + if (found != null) { + return found + } + } + } + return null + } + + /** + * Checks the shared {@code mixedMode} option. Absent means strict mode. + */ + protected void validateMixedMode(AbstractGinqExpression expression) { + String mixedMode = configuration.get(NativeSqlGinqProvider.CONF_MIXED_MODE) + if (mixedMode != null && !('true' == mixedMode || 'false' == mixedMode)) { + error('`mixedMode` must be `true` or `false`', expression) + } + } + + /** + * Renders the translated query to SQL text plus ordered parameters. + */ + protected RenderedSql renderSql(SqlQueryNode queryNode, AbstractGinqExpression expression) { + try { + return new SqlRenderer(dialect).render(queryNode) + } catch (IllegalArgumentException e) { + error(e.message, expression) + return null + } + } + + private GinqToSqlTranslator translator() { + return new GinqToSqlTranslator(sourceUnit, providerName, capabilities()) + } + + /** + * Dialect facts the translator uses while deciding what can be pushed down. + * The jOOQ walker supplies the jOOQ dialect name; both share + * {@link SqlCapabilities}. + */ + protected SqlCapabilities capabilities() { + return SqlCapabilities.of(effectiveDialectName()) + } + + @Override + Expression visitGinqExpression(GinqExpression ginqExpression) { + return visit(ginqExpression) + } + + @Override + Expression visitSetOperationExpression(SetOperationExpression setOperationExpression) { + return visit(setOperationExpression) + } + + @Override + Expression visitShutdownExpression(ShutdownExpression shutdownExpression) { + return visit(shutdownExpression) + } + + @Override + Expression visitFromExpression(FromExpression fromExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitJoinExpression(JoinExpression joinExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitOnExpression(OnExpression onExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitWhereExpression(WhereExpression whereExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitGroupExpression(GroupExpression groupExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitHavingExpression(HavingExpression havingExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitOrderExpression(OrderExpression orderExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitLimitExpression(LimitExpression limitExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + Expression visitSelectExpression(SelectExpression selectExpression) { + throw new GroovyBugError('clauses are translated by GinqToSqlTranslator') + } + + @Override + void setConfiguration(Map configuration) { + this.configuration = configuration + } + + @Override + Map getConfiguration() { + return configuration + } + + @Override + void setConfigurationExpressions(Map configurationExpressions) { + this.configurationExpressions = configurationExpressions + } + + @Override + Map getConfigurationExpressions() { + return configurationExpressions + } + + protected void error(String message, ASTNode node) { + collectSyntaxError(new GinqSyntaxError(message, node.lineNumber, node.columnNumber)) + } + + /** + * Replaces string table names that the in-memory tail would otherwise + * iterate as character sequences. Sources already rewritten to the SQL + * prefix result are left alone. Nested queries stay GINQ so the collection + * provider can correlate them, but their tables are loaded with {@code SELECT *}. + * Those names use the same plain-identifier check and qualified-name + * rendering as a translated {@code from} clause. + */ + private void materializeQuery(GinqExpression ginqExpression) { + materializeSource(ginqExpression.fromExpression) + if (sourceUnit.errorCollector.hasErrors()) { + return + } + for (JoinExpression joinExpression : ginqExpression.joinExpressionList) { + materializeSource(joinExpression) + if (sourceUnit.errorCollector.hasErrors()) { + return + } + if (joinExpression.onExpression != null) { + joinExpression.onExpression.filterExpr = materialize(joinExpression.onExpression.filterExpr) + } + } + materializeFilter(ginqExpression.whereExpression) + GroupExpression groupExpression = ginqExpression.groupExpression + if (groupExpression != null) { + materializeTuple(groupExpression.classifierExpr) + materializeFilter(groupExpression.havingExpression) + } + if (ginqExpression.orderExpression != null) { + materializeTuple(ginqExpression.orderExpression.ordersExpr) + } + if (ginqExpression.limitExpression != null) { + materializeTuple(ginqExpression.limitExpression.offsetAndSizeExpr) + } + materializeTuple(ginqExpression.selectExpression.projectionExpr) + } + + private void materializeSet(SetOperationExpression setOperation) { + AbstractGinqExpression left = setOperation.left + if (left instanceof GinqExpression) { + materializeQuery((GinqExpression) left) + } else if (left instanceof SetOperationExpression) { + materializeSet((SetOperationExpression) left) + } + materializeQuery(setOperation.right) + } + + private void materializeFilter(FilterExpression filter) { + if (filter != null) { + filter.filterExpr = materialize(filter.filterExpr) + } + } + + private void materializeSource(DataSourceExpression source) { + Expression dataSource = source.dataSourceExpr + if (dataSource instanceof ConstantExpression && dataSource.value instanceof String) { + source.dataSourceExpr = selectAll(source, (String) dataSource.value) + } else if (dataSource instanceof GinqExpression) { + materializeQuery((GinqExpression) dataSource) + } else if (dataSource instanceof SetOperationExpression) { + materializeSet((SetOperationExpression) dataSource) + } + } + + private void materializeTuple(Expression expr) { + if (expr instanceof TupleExpression) { + List expressions = ((TupleExpression) expr).expressions + for (int i = 0; i < expressions.size(); i++) { + expressions.set(i, materialize(expressions.get(i))) + } + } + } + + private Expression materialize(Expression expr) { + if (expr == null) { + return null + } + return ((ListExpression) new ListExpression(Collections.singletonList(expr)).transformExpression(new ExpressionTransformer() { + @Override + Expression transform(Expression expression) { + if (expression instanceof GinqExpression) { + materializeQuery((GinqExpression) expression) + return expression + } + if (expression instanceof SetOperationExpression) { + materializeSet((SetOperationExpression) expression) + return expression + } + if (expression instanceof ClosureExpression) { + materializeStatement(((ClosureExpression) expression).code) + return expression + } + return expression.transformExpression(this) + } + })).getExpression(0) + } + + private void materializeStatement(Statement statement) { + if (statement instanceof BlockStatement) { + for (Statement child : ((BlockStatement) statement).statements) { + materializeStatement(child) + } + } else if (statement instanceof ExpressionStatement) { + ((ExpressionStatement) statement).expression = materialize(((ExpressionStatement) statement).expression) + } else if (statement instanceof ReturnStatement) { + ((ReturnStatement) statement).expression = materialize(((ReturnStatement) statement).expression) + } + } + + private Expression selectAll(DataSourceExpression source, String tableName) { + if (!GinqToSqlTranslator.plainTableName(tableName)) { + error(GinqToSqlTranslator.invalidTableNameMessage(tableName), source) + return constX(null) + } + Expression dataSourceExpr = configurationExpressions.get(GinqGroovyMethods.CONF_DATA_SOURCE) + return callX(classX(SQL_GINQ_RUNTIME_TYPE), 'execute', + args(dataSourceExpr, constX('SELECT * FROM ' + dialect.qualifiedName(tableName)), new ListExpression())) + } + + private int mixedSeq + + private static final ClassNode SQL_GINQ_RUNTIME_TYPE = ClassHelper.makeCached(SqlGinqRuntime) +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqToSqlTranslator.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqToSqlTranslator.groovy new file mode 100644 index 00000000000..09e13c58a20 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqToSqlTranslator.groovy @@ -0,0 +1,1496 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope +import org.apache.groovy.ginq.dsl.GinqAstBuilder +import org.apache.groovy.ginq.dsl.GinqSyntaxError +import org.apache.groovy.ginq.dsl.SyntaxErrorReportable +import org.apache.groovy.ginq.dsl.expression.AbstractGinqExpression +import org.apache.groovy.ginq.dsl.expression.DataSourceExpression +import org.apache.groovy.ginq.dsl.expression.FromExpression +import org.apache.groovy.ginq.dsl.expression.GinqExpression +import org.apache.groovy.ginq.dsl.expression.GroupExpression +import org.apache.groovy.ginq.dsl.expression.JoinExpression +import org.apache.groovy.ginq.dsl.expression.SelectExpression +import org.apache.groovy.ginq.dsl.expression.SetOperationExpression +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCaseWhen +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlCountStar +import org.apache.groovy.ginq.provider.sql.ir.SqlDerivedTable +import org.apache.groovy.ginq.provider.sql.ir.SqlExists +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlIn +import org.apache.groovy.ginq.provider.sql.ir.SqlInQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlIsNull +import org.apache.groovy.ginq.provider.sql.ir.SqlJoin +import org.apache.groovy.ginq.provider.sql.ir.SqlLike +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlOrderSpec +import org.apache.groovy.ginq.provider.sql.ir.SqlOrdinal +import org.apache.groovy.ginq.provider.sql.ir.SqlParam +import org.apache.groovy.ginq.provider.sql.ir.SqlProjection +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.ir.SqlScalarQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlSetQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlStar +import org.apache.groovy.ginq.provider.sql.ir.SqlTableRef +import org.apache.groovy.ginq.provider.sql.ir.SqlTableSource +import org.apache.groovy.ginq.provider.sql.ir.SqlUnary +import org.apache.groovy.ginq.provider.sql.runtime.SqlGinqRuntime +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.ast.ASTNode +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.ClassNode +import org.codehaus.groovy.ast.Variable +import org.codehaus.groovy.ast.expr.ArgumentListExpression +import org.codehaus.groovy.ast.expr.BinaryExpression +import org.codehaus.groovy.ast.expr.BooleanExpression +import org.codehaus.groovy.ast.expr.CastExpression +import org.codehaus.groovy.ast.expr.ClassExpression +import org.codehaus.groovy.ast.expr.ClosureExpression +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.ElvisOperatorExpression +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.ast.expr.ListExpression +import org.codehaus.groovy.ast.expr.MethodCallExpression +import org.codehaus.groovy.ast.expr.NotExpression +import org.codehaus.groovy.ast.expr.PropertyExpression +import org.codehaus.groovy.ast.expr.RangeExpression +import org.codehaus.groovy.ast.expr.TernaryExpression +import org.codehaus.groovy.ast.expr.TupleExpression +import org.codehaus.groovy.ast.expr.UnaryMinusExpression +import org.codehaus.groovy.ast.expr.VariableExpression +import org.codehaus.groovy.ast.stmt.BlockStatement +import org.codehaus.groovy.ast.stmt.ExpressionStatement +import org.codehaus.groovy.ast.stmt.ReturnStatement +import org.codehaus.groovy.ast.stmt.Statement +import org.codehaus.groovy.control.SourceUnit +import org.codehaus.groovy.syntax.Types + +import static org.codehaus.groovy.ast.tools.GeneralUtils.callX +import static org.codehaus.groovy.ast.tools.GeneralUtils.castX +import static org.codehaus.groovy.ast.tools.GeneralUtils.classX +import static org.codehaus.groovy.ast.tools.GeneralUtils.constX +import static org.codehaus.groovy.ast.tools.GeneralUtils.minusX +import static org.codehaus.groovy.ast.tools.GeneralUtils.plusX + +/** + * Translates the GINQ AST into the SQL IR. In strict mode every construct + * either translates cleanly or is rejected with a compile-time error. With + * {@link #recoverUntranslatable} set, constructs that have no SQL equivalent + * raise {@link Untranslatable} so mixed mode can move that clause in memory. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class GinqToSqlTranslator implements SyntaxErrorReportable { + private final SourceUnit sourceUnit + private final GinqToSqlTranslator outerScope + private final String providerName + private final List tableAliases = [] + private String groupAlias + private final Map groupKeysByName = [:] + private String aggregateLambdaParam + private boolean recoverUntranslatable + private final SqlCapabilities capabilities + private final SqlFunctionSite calls = new CallSite() + + GinqToSqlTranslator(SourceUnit sourceUnit, String providerName = 'native-sql') { + this(sourceUnit, providerName, null) + } + + GinqToSqlTranslator(SourceUnit sourceUnit, String providerName, SqlCapabilities capabilities) { + this.sourceUnit = sourceUnit + this.outerScope = null + this.providerName = providerName + this.capabilities = capabilities == null ? SqlCapabilities.of(null) : capabilities + } + + private GinqToSqlTranslator(SourceUnit sourceUnit, GinqToSqlTranslator outerScope) { + this.sourceUnit = sourceUnit + this.outerScope = outerScope + this.providerName = outerScope.providerName + this.recoverUntranslatable = outerScope.recoverUntranslatable + this.capabilities = outerScope.capabilities + } + + private GinqToSqlTranslator nest(boolean correlated) { + GinqToSqlTranslator child = correlated + ? new GinqToSqlTranslator(sourceUnit, this) + : new GinqToSqlTranslator(sourceUnit, providerName, capabilities) + child.recoverUntranslatable = recoverUntranslatable + return child + } + + @Override + SourceUnit getSourceUnit() { + return sourceUnit + } + + SqlQueryNode translate(AbstractGinqExpression expression) { + if (expression instanceof SetOperationExpression) { + return translateSetOperation(expression, true) + } + if (expression instanceof GinqExpression) { + return translateQuery(expression, QueryContext.TOP_LEVEL) + } + reject("`${expression.text}` is not supported by the ${providerName} provider", expression) + return null + } + + private SqlSetQuery translateSetOperation(SetOperationExpression setOperationExpression, boolean outermost) { + AbstractGinqExpression leftExpression = setOperationExpression.left + SqlQueryNode left = leftExpression instanceof SetOperationExpression + ? translateSetOperation(leftExpression, false) + : nest(false).translateQuery(requireGinqExpression(leftExpression), QueryContext.INNER_OPERAND) + SqlQuery right = nest(false).translateQuery(setOperationExpression.right, + outermost ? QueryContext.FINAL_OPERAND : QueryContext.INNER_OPERAND) + + SqlSetQuery.SetOp op + switch (setOperationExpression.operation) { + case 'union': op = SqlSetQuery.SetOp.UNION; break + case 'unionall': op = SqlSetQuery.SetOp.UNION_ALL; break + case 'intersect': op = SqlSetQuery.SetOp.INTERSECT; break + case 'minus': op = SqlSetQuery.SetOp.MINUS; break + default: + error("Unknown set operation: ${setOperationExpression.operation}", setOperationExpression) + return null + } + SqlSetQuery setQuery = new SqlSetQuery(left, op, right) + if (outermost) { + hoistOrderAndLimit(setQuery, setOperationExpression.right) + } + return setQuery + } + + /** + * Moves the final operand's {@code orderby}/{@code limit} onto the set operation + * result, matching SQL's trailing {@code ORDER BY} semantics. Order keys must match + * a select-list item and are rendered as ordinals since alias-qualified references + * are not visible after a set operation. + */ + private void hoistOrderAndLimit(SqlSetQuery setQuery, GinqExpression finalOperand) { + SqlQuery right = setQuery.right + if (right.orderBy) { + for (SqlOrderSpec orderSpec : right.orderBy) { + int index = right.projections.findIndexOf { SqlProjection projection -> sameExpr(projection.expr, orderSpec.expr) } + if (index < 0) { + error('`orderby` on a set operation result must reference columns of the final `select` clause', + finalOperand.orderExpression) + } + setQuery.orderBy << new SqlOrderSpec(new SqlOrdinal(index + 1), orderSpec.asc, orderSpec.nullsLast) + } + right.orderBy.clear() + } + setQuery.offset = right.offset + setQuery.fetch = right.fetch + right.offset = null + right.fetch = null + } + + private static boolean sameExpr(SqlExpr a, SqlExpr b) { + if (a.class != b.class) return false + if (a instanceof SqlColumn) { + SqlColumn other = (SqlColumn) b + return a.tableAlias == other.tableAlias && a.column == other.column + } + if (a instanceof SqlCountStar) return true + if (a instanceof SqlStar) return a.tableAlias == ((SqlStar) b).tableAlias + if (a instanceof SqlFunction) { + SqlFunction other = (SqlFunction) b + return a.name == other.name && a.args.size() == other.args.size() && + (0.. sameExpr(a.args[i], other.args[i]) } + } + if (a instanceof SqlBinary) { + SqlBinary other = (SqlBinary) b + return a.op == other.op && sameExpr(a.left, other.left) && sameExpr(a.right, other.right) + } + if (a instanceof SqlUnary) { + SqlUnary other = (SqlUnary) b + return a.op == other.op && sameExpr(a.operand, other.operand) + } + if (a instanceof SqlIsNull) { + SqlIsNull other = (SqlIsNull) b + return a.negated == other.negated && sameExpr(a.expr, other.expr) + } + if (a instanceof SqlCast) { + SqlCast other = (SqlCast) b + return a.sqlType == other.sqlType && sameExpr(a.expr, other.expr) + } + return false // parameters and parameter-bearing expressions are never comparable + } + + private GinqExpression requireGinqExpression(AbstractGinqExpression expression) { + if (!(expression instanceof GinqExpression)) { + error("`${expression.text}` is not supported by the ${providerName} provider", expression) + } + return (GinqExpression) expression + } + + private SqlQuery translateQuery(GinqExpression ginqExpression, QueryContext context) { + SqlQuery query = new SqlQuery() + + query.from = tableSource(ginqExpression.fromExpression) + tableAliases << ginqExpression.fromExpression.aliasExpr.text + + for (JoinExpression joinExpression : ginqExpression.joinExpressionList) { + query.joins << translateJoin(joinExpression) + } + + if (ginqExpression.whereExpression != null) { + query.where = translateExpr(ginqExpression.whereExpression.filterExpr) + } + + GroupExpression groupExpression = ginqExpression.groupExpression + if (groupExpression != null) { + translateGroup(groupExpression, query) + } + + if (ginqExpression.orderExpression != null) { + if (QueryContext.INNER_OPERAND == context) { + error('`orderby` within set operation operands is only supported on the final operand, ' + + 'where it orders the combined result', ginqExpression.orderExpression) + } + translateOrders(ginqExpression.orderExpression.ordersExpr, query) + } + + if (ginqExpression.limitExpression != null) { + if (QueryContext.INNER_OPERAND == context) { + error('`limit` within set operation operands is only supported on the final operand, ' + + 'where it limits the combined result', ginqExpression.limitExpression) + } + translateLimit(ginqExpression.limitExpression.offsetAndSizeExpr, query) + } + + translateSelect(ginqExpression, query) + + return query + } + + private SqlTableSource tableSource(DataSourceExpression dataSourceExpression) { + Expression dataSourceExpr = dataSourceExpression.dataSourceExpr + String alias = dataSourceExpression.aliasExpr.text + if (dataSourceExpr instanceof GinqExpression) { + // no outer scope: standard SQL derived tables cannot be correlated + SqlQuery query = nest(false).translateQuery(dataSourceExpr, QueryContext.TOP_LEVEL) + return new SqlDerivedTable(query, alias) + } + if (dataSourceExpr instanceof AbstractGinqExpression) { + reject("set operations are not supported as table sources by the ${providerName} provider", dataSourceExpr) + return null + } + if (dataSourceExpr instanceof ConstantExpression && dataSourceExpr.value instanceof String) { + String tableName = (String) dataSourceExpr.value + if (!plainTableName(tableName)) { + reject(invalidTableNameMessage(tableName), dataSourceExpr, false) + return null + } + return new SqlTableRef(tableName, alias) + } + reject("table references must be string literals or subqueries with the ${providerName} provider, e.g. `from ${alias} in 'employees'`", dataSourceExpr) + return null + } + + private SqlQuery correlatedSubQuery(GinqExpression ginqExpression) { + return nest(true).translateQuery(ginqExpression, QueryContext.TOP_LEVEL) + } + + private boolean isKnownAlias(String name) { + return name in tableAliases || (outerScope != null && outerScope.isKnownAlias(name)) + } + + private SqlJoin translateJoin(JoinExpression joinExpression) { + SqlJoin.Type type + switch (joinExpression.joinName) { + case 'join': + case 'innerjoin': + case 'innerhashjoin': + type = SqlJoin.Type.INNER; break + case 'leftjoin': + case 'lefthashjoin': + type = SqlJoin.Type.LEFT; break + case 'rightjoin': + case 'righthashjoin': + type = SqlJoin.Type.RIGHT; break + case 'fulljoin': + case 'fullhashjoin': + type = SqlJoin.Type.FULL; break + case 'crossjoin': + type = SqlJoin.Type.CROSS; break + default: + error("Unknown join: ${joinExpression.joinName}", joinExpression) + return null + } + + SqlTableSource table = tableSource(joinExpression) + tableAliases << joinExpression.aliasExpr.text + + SqlExpr on = null + if (joinExpression.onExpression != null) { + on = translateExpr(joinExpression.onExpression.filterExpr) + } else if (SqlJoin.Type.CROSS != type) { + error("`on` clause is expected for `${joinExpression.joinName}`", joinExpression) + } + return new SqlJoin(type, table, on) + } + + private void translateGroup(GroupExpression groupExpression, SqlQuery query) { + groupAlias = groupExpression.intoAlias // null for classic (no `into`) groupby + + for (Expression classifier : ((TupleExpression) groupExpression.classifierExpr).expressions) { + String name + Expression valueExpr + if (classifier instanceof CastExpression) { + name = classifier.type.text + valueExpr = classifier.expression + } else if (classifier instanceof PropertyExpression && classifier.property instanceof ConstantExpression) { + name = classifier.propertyAsString + valueExpr = classifier + } else { + name = classifier.text + valueExpr = classifier + } + SqlExpr keyExpr = translateExpr(valueExpr) + query.groupBy << keyExpr + groupKeysByName[name] = keyExpr + } + + if (groupExpression.havingExpression != null) { + query.having = translateExpr(groupExpression.havingExpression.filterExpr) + } + } + + private void translateOrders(Expression ordersExpr, SqlQuery query) { + for (Expression orderExpr : ((TupleExpression) ordersExpr).expressions) { + Expression target = orderExpr + boolean asc = true + boolean nullsLast = true + if (orderExpr instanceof BinaryExpression && orderExpr.operation.type == Types.KEYWORD_IN) { + target = orderExpr.leftExpression + Expression orderOptionExpr = orderExpr.rightExpression + String orderOption = orderOptionExpr instanceof MethodCallExpression + ? orderOptionExpr.methodAsString + : orderOptionExpr.text + if (orderOption !in ORDER_OPTION_LIST) { + error("`${orderOption}` is not an order direction; use `asc` or `desc`", orderOptionExpr) + } + asc = 'asc' == orderOption + if (orderOptionExpr instanceof MethodCallExpression) { + List optionArgs = ((TupleExpression) orderOptionExpr.arguments).expressions + String nullsOption = 1 == optionArgs.size() ? optionArgs[0].text : null + if (nullsOption !in NULLS_OPTION_LIST) { + error('`asc`/`desc` takes `nullsfirst` or `nullslast`', orderOptionExpr.arguments) + } + nullsLast = 'nullslast' == nullsOption + } + } + query.orderBy << new SqlOrderSpec(translateExpr(target), asc, nullsLast) + } + } + + private void translateLimit(Expression offsetAndSizeExpr, SqlQuery query) { + List expressions = offsetAndSizeExpr instanceof TupleExpression + ? offsetAndSizeExpr.expressions + : [offsetAndSizeExpr] + if (1 == expressions.size()) { + query.fetch = new SqlParam(expressions[0]) + } else { + query.offset = new SqlParam(expressions[0]) + query.fetch = new SqlParam(expressions[1]) + } + } + + private void translateSelect(GinqExpression ginqExpression, SqlQuery query) { + SelectExpression selectExpression = ginqExpression.selectExpression + Boolean distinct = ginqExpression.getNodeMetaData(GinqAstBuilder.GINQ_SELECT_DISTINCT) + query.distinct = Boolean.TRUE == distinct + + for (Expression projection : ((TupleExpression) selectExpression.projectionExpr).expressions) { + String alias = null + Expression expr = projection + if (projection instanceof CastExpression) { + alias = projection.type.text + expr = projection.expression + } + if (expr instanceof VariableExpression && expr.text in tableAliases) { + if (alias != null) { + error("whole-row projection `${expr.text}` cannot be aliased", projection) + } + query.projections << new SqlProjection(new SqlStar(expr.text)) + } else { + if (alias == null) { + alias = groupKeyProjectionAlias(expr) + } + query.projections << new SqlProjection(translateExpr(expr), alias) + } + } + } + + // a projected group key keeps its GINQ name as the column label, since the + // underlying expression's own label, e.g. `e.deptId` for `groupby e.deptId as dept`, + // may differ from the name the query author expects + private String groupKeyProjectionAlias(Expression expr) { + if (expr instanceof VariableExpression && groupKeysByName.containsKey(expr.text)) { + return expr.text + } + if (expr instanceof PropertyExpression && groupAlias != null + && expr.objectExpression instanceof VariableExpression + && groupAlias == expr.objectExpression.text + && expr.property instanceof ConstantExpression) { + return expr.propertyAsString + } + return null + } + + private SqlExpr translateExpr(Expression expr) { + expr = unwrapGrouping(expr) + if (expr instanceof GinqExpression) { + return new SqlScalarQuery(correlatedSubQuery(expr)) + } + if (expr instanceof AbstractGinqExpression) { + reject("`${expr.text}` cannot be used as an expression with the ${providerName} provider", expr) + return null + } + // NotExpression extends BooleanExpression; the negation has to be kept + if (expr instanceof NotExpression) return new SqlUnary('NOT', translateExpr(expr.expression)) + if (expr instanceof BooleanExpression) return translateExpr(expr.expression) + if (expr instanceof TernaryExpression) return translateTernary(expr) + if (expr instanceof BinaryExpression) return translateBinary(expr) + if (expr instanceof UnaryMinusExpression) return new SqlUnary('-', translateExpr(expr.expression)) + if (expr instanceof CastExpression) return translateGroovyCast((CastExpression) expr) + if (expr instanceof PropertyExpression) return translateProperty(expr) + if (expr instanceof MethodCallExpression) return translateMethodCall(expr) + if (expr instanceof ConstantExpression) return new SqlParam(expr) + if (expr instanceof VariableExpression) return translateVariable(expr) + reject("Expression `${expr.text}` cannot be translated to SQL by the ${providerName} provider", expr) + return null + } + + private SqlExpr translateTernary(TernaryExpression expr) { + if (expr instanceof ElvisOperatorExpression) { + // truthiness is not SQL null, so ?: is not COALESCE + reject("the Elvis operator cannot be translated to SQL by the ${providerName} provider; " + + 'Groovy truthiness is not SQL null. Use `coalesce(...)` or an explicit ternary with a `== null` check', expr) + return null + } + return new SqlCaseWhen( + translateExpr(expr.booleanExpression), + translateCaseBranch(expr.trueExpression), + translateCaseBranch(expr.falseExpression)) + } + + // CASE branch values that are compile-time constants are inlined as literals + // (never runtime values, so parameter safety is preserved) since databases + // cannot infer a type for `THEN ? ELSE ?` + private SqlExpr translateCaseBranch(Expression expr) { + if (expr instanceof ConstantExpression) { + return new SqlLiteral(expr.value) + } + return translateExpr(expr) + } + + private SqlExpr translateBinary(BinaryExpression expr) { + String op = expr.operation.text + Expression left = expr.leftExpression + Expression right = expr.rightExpression + switch (op) { + case 'in': + case '!in': + left = unwrapGrouping(left) + right = unwrapGrouping(right) + if (right instanceof GinqExpression) { + SqlExpr lhs = translateExpr(left) + if (lhs == null) { + return null + } + return new SqlInQuery(lhs, correlatedSubQuery((GinqExpression) right), '!in' == op) + } + if (right instanceof RangeExpression) { + return translateRangeMember(left, (RangeExpression) right, '!in' == op, expr) + } + if (!(right instanceof ListExpression)) { + reject("only list literals, constant ranges and subqueries are supported on the right-hand side of `in` by the ${providerName} provider", right) + return null + } + List elements = ((ListExpression) right).expressions + if (elements.isEmpty()) { + // `x in []` is false and `x !in []` is true, including when x is null + return new SqlBinary('=', new SqlLiteral(1), new SqlLiteral('!in' == op ? 1 : 0)) + } + return translateInList(left, elements, '!in' == op) + case '==': + case '!=': + boolean negated = '!=' == op + if (isNullLiteral(right)) return new SqlIsNull(translateExpr(left), negated) + if (isNullLiteral(left)) return new SqlIsNull(translateExpr(right), negated) + // Groovy == is null-safe. SQL = yields UNKNOWN when either side is null, + // including a bound parameter that happens to be null. + return new SqlBinary(negated ? 'IS DISTINCT FROM' : 'IS NOT DISTINCT FROM', + translateExpr(left), translateExpr(right)) + case '+': + return translatePlus(left, right, expr) + case '<': + case '<=': + case '>': + case '>=': + case '-': + case '*': + case '/': + return new SqlBinary(op, translateExpr(left), translateExpr(right)) + case '&&': + return new SqlBinary('AND', translateExpr(left), translateExpr(right)) + case '||': + return new SqlBinary('OR', translateExpr(left), translateExpr(right)) + case '%': + return emitFunction('MOD', [translateExpr(left), translateExpr(right)], expr) + default: + reject("Operator `${op}` cannot be translated to SQL by the ${providerName} provider", expr) + return null + } + } + + // `x in [null, 1]` is true for a null x. SQL `IN` is unknown when the list + // contains null, and `NOT IN` is unknown for every row, so null members + // become IS NULL / IS NOT NULL and the remaining values stay in the list. + private SqlExpr translateInList(Expression left, List elements, boolean negated) { + List values = [] + boolean includesNull = false + for (Expression element : elements) { + if (isNullLiteral(element)) { + includesNull = true + } else { + values.add(translateExpr(element)) + } + } + SqlExpr member = translateExpr(left) + if (values.isEmpty()) { + return new SqlIsNull(member, negated) + } + SqlIn inList = new SqlIn(member, values, negated) + if (!includesNull) { + if (!negated) return inList + // Groovy `null !in [1, 2]` is true. SQL NOT IN is UNKNOWN for a null member. + return new SqlBinary('OR', new SqlIsNull(member, false), inList) + } + return new SqlBinary(negated ? 'AND' : 'OR', new SqlIsNull(member, negated), inList) + } + + private static boolean isNullLiteral(Expression expr) { + return expr instanceof ConstantExpression && null == expr.value + } + + private SqlExpr translatePlus(Expression left, Expression right, Expression reported) { + OperandKind leftKind = operandKind(left) + OperandKind rightKind = operandKind(right) + if (plusIsText(leftKind, rightKind)) { + return new SqlBinary('||', translateExpr(left), translateExpr(right)) + } + if (plusIsNumber(leftKind, rightKind)) { + return new SqlBinary('+', translateExpr(left), translateExpr(right)) + } + reject('Operator `+` is not translated when it could be numeric addition or string concatenation. ' + + 'A number beside a column is addition (`e.salary + 1`); text on the left, or a string literal beside a column, is concatenation (`e.name + \'!\'`). ' + + 'A captured variable is pushed down only when its declared type is numeric or text, for example `e.name + (suffix as String)`. ' + + 'Two columns are not pushed down; use `concat` or a numeric cast', reported) + return null + } + + // Groovy concatenates when the left operand is text (`'!' + x`, `'!' + 1`). + // `column + '!'` is the other form this backend already promised; a number + // beside a string literal is not concatenation in Groovy, so it is rejected. + private static boolean plusIsText(OperandKind left, OperandKind right) { + if (left == OperandKind.TEXT) return true + return right == OperandKind.TEXT && left == OperandKind.COLUMN + } + + private static boolean plusIsNumber(OperandKind left, OperandKind right) { + if (left == OperandKind.TEXT || right == OperandKind.TEXT) return false + if (left == OperandKind.OTHER || right == OperandKind.OTHER) return false + if (left == OperandKind.COLUMN && right == OperandKind.COLUMN) return false + return left == OperandKind.NUMBER || right == OperandKind.NUMBER + } + + private SqlExpr translateProperty(PropertyExpression expr) { + if (!(expr.property instanceof ConstantExpression)) { + reject("Expression `${expr.text}` cannot be translated to SQL by the ${providerName} provider", expr) + return null + } + String property = expr.propertyAsString + if (!simpleIdentifier(property)) { + error("column `${property}` must be a simple identifier", expr) + return null + } + Expression object = expr.objectExpression + if (object instanceof VariableExpression) { + String name = object.text + if (name == aggregateLambdaParam) { + if (name in tableAliases) return new SqlColumn(name, property) + if (1 == tableAliases.size()) return new SqlColumn(tableAliases[0], property) + error("cannot resolve `${expr.text}`: name the aggregate lambda parameter after a table alias for multi-table queries", expr) + return null + } + if (name in tableAliases) { + return new SqlColumn(name, property) + } + if (name == groupAlias) { + SqlExpr keyExpr = groupKeysByName[property] + if (keyExpr == null) { + error("`${expr.text}` is not in the `groupby` clause", expr) + } + return keyExpr + } + if (isKnownAlias(name)) { // an outer-scope alias, i.e. a correlated reference + return new SqlColumn(name, property) + } + } + error("Unknown alias in `${expr.text}`; known aliases: ${knownAliases()}", expr) + return null + } + + private SqlExpr translateVariable(VariableExpression expr) { + String name = expr.text + if (isKnownAlias(name) || name == groupAlias) { + reject("whole-row reference `${name}` is only supported as a top-level `select` projection", expr) + return null + } + if ('_rn' == name) { + reject("`_rn` is a collection-provider row number and has no equivalent in the ${providerName} provider", expr) + return null + } + SqlExpr keyExpr = groupKeysByName[name] + if (keyExpr != null) { // an `as` alias of a groupby key, e.g. `groupby e.deptId as dept ... select dept` + return keyExpr + } + return new SqlParam(expr) // a captured variable becomes a bound parameter + } + + private SqlExpr translateMethodCall(MethodCallExpression call) { + String method = call.methodAsString + List args = ((TupleExpression) call.arguments).expressions + if ('over' == method) { + reject("window functions are deferred and are not translated by the ${providerName} provider", call) + return null + } + if ('exists' == method && args.empty && call.objectExpression instanceof GinqExpression) { + return new SqlExists(correlatedSubQuery((GinqExpression) call.objectExpression)) + } + if (groupAlias != null && !call.implicitThis + && call.objectExpression instanceof VariableExpression && groupAlias == call.objectExpression.text) { + return translateAggregate(call, args, true) + } + if (call.implicitThis && AGGREGATE_FUNCTION_MAP.containsKey(method)) { + return translateAggregate(call, args, false) + } + if (method != null && !call.implicitThis && TEXT_INPUT_METHODS.contains(method)) { + OperandKind receiver = operandKind(call.objectExpression) + if (receiver != OperandKind.TEXT && receiver != OperandKind.COLUMN) { + reject("`${method}()` is translated to SQL only when the receiver is a column or a value known to be text. " + + 'The type of a captured variable is not known at compile time', call) + return null + } + } + SqlFunctionMapping mapping = method == null ? null : SqlFunctionRegistry.standard().find(method, functionKind(call)) + if (mapping != null) { + return mapping.translate(call, args, calls) + } + reject("Method `${method}` cannot be translated to SQL by the ${providerName} provider", call) + return null + } + + // Math.max is a static call. An implicit-this max/min is the aggregate, handled above. + // A table alias named Math is not the class. + private SqlFunctionMapping.Kind functionKind(MethodCallExpression call) { + if (!call.implicitThis && isMathReceiver(call.objectExpression)) { + return SqlFunctionMapping.Kind.MATH + } + if (call.implicitThis) { + return SqlFunctionMapping.Kind.FREE + } + return SqlFunctionMapping.Kind.RECEIVER + } + + private SqlExpr translateLike(MethodCallExpression call, List argList, boolean matchBefore, boolean matchAfter) { + if (1 != argList.size()) { + reject("`${call.methodAsString}` expects a single argument", call) + return null + } + SqlExpr receiver = translateExpr(call.objectExpression) + Expression valueExpr = requireParamValue(argList[0], call.methodAsString) + // wildcards in the runtime value are escaped so it always matches literally + Expression patternExpr = callX(classX(SQL_GINQ_RUNTIME_TYPE), 'likePattern', + new ArgumentListExpression(valueExpr, constX(matchBefore), constX(matchAfter))) + return new SqlLike(receiver, new SqlParam(patternExpr)) + } + + private SqlExpr translateSubstring(MethodCallExpression call, List argList) { + if (argList.size() !in [1, 2]) { + reject('`substring` expects one or two arguments (a 0-based begin index, and an optional exclusive end index)', call) + return null + } + SqlExpr receiver = translateExpr(call.objectExpression) + List functionArgs = [receiver, shiftedIndex(argList[0])] + if (2 == argList.size()) { + functionArgs << substringLength(argList[0], argList[1]) + } + return emitFunction('SUBSTRING', functionArgs, call) + } + + // Groovy's 0-based begin index becomes SQL's 1-based FROM position. + // Literals and captured variables stay a single bound parameter; a column + // index is shifted in SQL so it can still be pushed down. + private SqlExpr shiftedIndex(Expression beginExpr) { + SqlExpr translated = translateExpr(beginExpr) + if (translated instanceof SqlParam) { + return new SqlParam(plusX(((SqlParam) translated).valueExpr, constX(1))) + } + return new SqlBinary('+', translated, new SqlLiteral(1)) + } + + private SqlExpr substringLength(Expression beginExpr, Expression endExpr) { + SqlExpr begin = translateExpr(beginExpr) + SqlExpr end = translateExpr(endExpr) + if (begin instanceof SqlParam && end instanceof SqlParam) { + return new SqlParam(minusX(((SqlParam) end).valueExpr, ((SqlParam) begin).valueExpr)) + } + return new SqlBinary('-', end, begin) + } + + private SqlExpr translateRangeMember(Expression left, RangeExpression range, boolean negated, Expression reported) { + Expression fromExpr = range.from + Expression toExpr = range.to + if (!(fromExpr instanceof ConstantExpression) || !(toExpr instanceof ConstantExpression)) { + reject('`in` against a range is translated only when both bounds are compile-time constants, ' + + 'because a descending Groovy range still contains every value between its endpoints. ' + + 'Write `x >= low && x <= high` when the order is known', reported) + return null + } + Object fromVal = ((ConstantExpression) fromExpr).value + Object toVal = ((ConstantExpression) toExpr).value + if (!(fromVal instanceof Comparable) || !(toVal instanceof Comparable)) { + reject('`in` against a range requires comparable constant bounds', reported) + return null + } + int cmp + try { + cmp = (fromVal <=> toVal) + } catch (RuntimeException ignored) { + reject('`in` against a range requires bounds that can be compared with each other', reported) + return null + } + boolean ascending = cmp <= 0 + SqlExpr value = translateExpr(left) + SqlExpr low = new SqlParam(ascending ? fromExpr : toExpr) + SqlExpr high = new SqlParam(ascending ? toExpr : fromExpr) + String lowOp = '>=' + String highOp = '<=' + if (!range.inclusive) { + // the exclusive end is the original `to`, which may be the lower bound of a descending range + if (ascending) { + highOp = '<' + } else { + lowOp = '>' + } + } + if (!negated) { + return new SqlBinary('AND', + new SqlBinary(lowOp, value, low), + new SqlBinary(highOp, value, high)) + } + // Groovy `null !in 1..3` is true. NOT (comparisons) stays UNKNOWN for null. + return new SqlBinary('OR', + new SqlIsNull(value, false), + new SqlBinary('OR', + new SqlBinary(invertCompare(lowOp), value, low), + new SqlBinary(invertCompare(highOp), value, high))) + } + + private static String invertCompare(String op) { + switch (op) { + case '>=': return '<' + case '>': return '<=' + case '<=': return '>' + case '<': return '>=' + default: throw new IllegalArgumentException(op) + } + } + + private Expression requireParamValue(Expression expr, String method) { + SqlExpr translated = translateExpr(expr) + if (!(translated instanceof SqlParam)) { + reject("the arguments of `${method}` must be literals or captured variables", expr) + return null + } + return ((SqlParam) translated).valueExpr + } + + // java.lang.Math.max/min are binary. A table alias named Math is not the class. + private boolean isMathReceiver(Expression object) { + if (object instanceof ClassExpression) { + String name = ((ClassExpression) object).type.name + return 'java.lang.Math' == name || 'Math' == name + } + String text = object.text + if ('java.lang.Math' == text) return true + return 'Math' == text && !(text in tableAliases) + } + + private SqlExpr translateAggregate(MethodCallExpression call, List args, boolean lambdaStyle) { + String method = call.methodAsString + String functionName = AGGREGATE_FUNCTION_MAP[method] + if (functionName == null) { + reject("`${method}` is not a supported aggregate function (supported: ${AGGREGATE_FUNCTION_MAP.keySet()})", call) + return null + } + if ('count' == method && args.empty) { + return new SqlCountStar() + } + if (1 != args.size()) { + reject("aggregate function `${method}` expects a single argument", call) + return null + } + Expression arg = args[0] + if (!lambdaStyle) { + return translatePlainAggregate(call, method, functionName, arg) + } + return translateLambdaAggregate(call, method, functionName, arg) + } + + private SqlExpr translatePlainAggregate(MethodCallExpression call, String method, String functionName, Expression arg) { + MethodCallExpression distinct = distinctCall(arg) + if (distinct != null) { + Expression inner = countDistinctArgument(call, method, distinct) + if (inner == null) return null + return emitFunction(functionName, [translateExpr(inner)], true, call) + } + return finishAggregate(method, emitFunction(functionName, [translateExpr(arg)], call), call) + } + + private SqlExpr translateLambdaAggregate(MethodCallExpression call, String method, String functionName, Expression arg) { + boolean countDistinct = false + ClosureExpression closure + MethodCallExpression wrapped = distinctCall(arg) + if (wrapped != null) { + Expression inner = countDistinctArgument(call, method, wrapped) + if (inner == null) return null + if (!(inner instanceof ClosureExpression)) { + reject("aggregate function `count` expects a lambda argument, e.g. `${groupAlias}.count(distinct(e -> e.salary))`", inner) + return null + } + closure = (ClosureExpression) inner + countDistinct = true + } else if (!(arg instanceof ClosureExpression)) { + reject("aggregate function `${method}` expects a lambda argument, e.g. `${groupAlias}.${method}(e -> e.salary)`", arg) + return null + } else { + closure = (ClosureExpression) arg + } + String param = closure.parameters ? closure.parameters[0].name : 'it' + Expression body = extractSingleExpression(closure) + if (body == null) return null + if (!countDistinct) { + MethodCallExpression bodyDistinct = distinctCall(body) + if (bodyDistinct != null) { + body = countDistinctArgument(call, method, bodyDistinct) + if (body == null) return null + countDistinct = true + } + } + String previousParam = aggregateLambdaParam + aggregateLambdaParam = param + try { + return finishAggregate(method, emitFunction(functionName, [translateExpr(body)], countDistinct, call), call) + } finally { + aggregateLambdaParam = previousParam + } + } + + // count(distinct(expr)) and g.count(distinct(e -> expr)); other aggregates stay plain + private Expression countDistinctArgument(MethodCallExpression aggregate, String method, MethodCallExpression distinct) { + if ('count' != method) { + reject('distinct aggregates are supported only for `count`', aggregate) + return null + } + List inner = ((TupleExpression) distinct.arguments).expressions + if (1 != inner.size()) { + reject('`count(distinct(...))` expects a single expression', distinct) + return null + } + return inner[0] + } + + private static MethodCallExpression distinctCall(Expression expr) { + if (!(expr instanceof MethodCallExpression)) return null + MethodCallExpression call = (MethodCallExpression) expr + if (call.implicitThis && 'distinct' == call.methodAsString) return call + return null + } + + // Groovy sum treats null as zero, so an all-null group is 0 rather than SQL null + private SqlExpr finishAggregate(String method, SqlExpr call, ASTNode node) { + if ('sum' == method) { + return emitFunction('COALESCE', [call, new SqlLiteral(0)], node) + } + return call + } + + private Expression extractSingleExpression(ClosureExpression closure) { + Statement code = closure.code + if (code instanceof BlockStatement && 1 == code.statements.size()) { + code = code.statements[0] + } + if (code instanceof ExpressionStatement) { + return code.expression + } + if (code instanceof ReturnStatement) { + return code.expression + } + reject('aggregate lambdas must consist of a single expression', closure) + return null + } + + private String knownAliases() { + List known = new ArrayList<>(tableAliases) + if (groupAlias) known << groupAlias + return known.toString() + } + + /** + * Plans {@code expression} for mixed mode. A fully translatable query is + * returned as {@link MixedPlan#fullQuery}. Otherwise the plan splits at the + * first clause that does not translate: {@code from}, then each join, then + * {@code where}, then {@code orderby} and {@code limit} when the query has + * no {@code groupby}. {@code groupby} stays in memory whenever anything + * from {@code groupby} onward cannot be translated, so group results keep + * collection-provider semantics. Set operations are not split. + */ + @PackageScope + MixedPlan planMixed(AbstractGinqExpression expression) { + int before = errorCount() + recoverUntranslatable = true + try { + SqlQueryNode full = translate(expression) + if (errorCount() != before) { + return null + } + if (full != null) { + if (!capabilities.supportsFullOuterJoin()) { + full = MixedSourceLayout.layoutComplete(full) + } + return MixedPlan.complete(full) + } + return null + } catch (Untranslatable untranslatable) { + if (errorCount() != before) { + return null + } + if (expression instanceof SetOperationExpression) { + error('mixed mode cannot split a set operation (`union`/`unionall`/`intersect`/`minus`); ' + + untranslatable.message, untranslatable.node ?: expression) + return null + } + if (!(expression instanceof GinqExpression)) { + error(untranslatable.message, untranslatable.node ?: expression) + return null + } + GinqToSqlTranslator splitter = new GinqToSqlTranslator(sourceUnit, providerName, capabilities) + splitter.recoverUntranslatable = true + return splitter.planSplit((GinqExpression) expression) + } finally { + recoverUntranslatable = false + } + } + + private MixedPlan planSplit(GinqExpression ginq) { + int before = errorCount() + SqlQuery query = new SqlQuery() + FromExpression fromExpression = ginq.fromExpression + SqlTableSource from + try { + from = tableSource(fromExpression) + } catch (Untranslatable untranslatable) { + error('mixed mode requires the `from` source to translate to SQL (a string table name or a fully translatable subquery). ' + + untranslatable.message, untranslatable.node ?: fromExpression) + return null + } + if (aborted(before) || from == null) { + return null + } + query.from = from + tableAliases << fromExpression.aliasExpr.text + + int pushedJoins = 0 + List joins = ginq.joinExpressionList + for (int i = 0; i < joins.size(); i++) { + int aliasSnapshot = tableAliases.size() + try { + SqlJoin join = translateJoin(joins[i]) + if (aborted(before) || join == null) { + trimAliases(aliasSnapshot) + return null + } + query.joins << join + pushedJoins++ + } catch (Untranslatable ignored) { + trimAliases(aliasSnapshot) + break + } + } + if (aborted(before)) { + return null + } + + boolean wherePushed = false + if (pushedJoins == joins.size()) { + if (ginq.whereExpression == null) { + wherePushed = true + } else { + try { + SqlExpr where = translateExpr(ginq.whereExpression.filterExpr) + if (aborted(before)) { + return null + } + query.where = where + wherePushed = true + } catch (Untranslatable ignored) { + query.where = null + } + } + } + if (aborted(before)) { + return null + } + + // orderby/limit apply to source rows only when there is no groupby. + // A groupby that cannot stay in SQL (because this query did not translate + // fully) is evaluated in memory, and so are the orderby/limit that follow it. + boolean orderPushed = false + boolean limitPushed = false + if (wherePushed && ginq.groupExpression == null) { + if (ginq.orderExpression == null) { + orderPushed = true + } else { + int orderSnapshot = query.orderBy.size() + try { + translateOrders(ginq.orderExpression.ordersExpr, query) + if (aborted(before)) { + return null + } + orderPushed = true + } catch (Untranslatable ignored) { + while (query.orderBy.size() > orderSnapshot) { + query.orderBy.remove(query.orderBy.size() - 1) + } + } + } + if (orderPushed) { + if (ginq.limitExpression == null) { + limitPushed = true + } else { + try { + translateLimit(ginq.limitExpression.offsetAndSizeExpr, query) + if (aborted(before)) { + return null + } + limitPushed = true + } catch (Untranslatable ignored) { + query.offset = null + query.fetch = null + } + } + } + } + if (aborted(before)) { + return null + } + + List aliases = [fromExpression.aliasExpr.text] + for (int i = 0; i < pushedJoins; i++) { + aliases << joins[i].aliasExpr.text + } + for (String alias : aliases) { + query.projections << new SqlProjection(new SqlStar(alias)) + } + + List labelSources = [query.from] + for (SqlJoin join : query.joins) { + labelSources << join.table + } + boolean emulateFull = !capabilities.supportsFullOuterJoin() && query.joins.any { SqlJoin join -> + join.type == SqlJoin.Type.FULL + } + if (emulateFull && !query.orderBy.every { SqlOrderSpec spec -> spec.expr instanceof SqlColumn }) { + query.orderBy.clear() + query.offset = null + query.fetch = null + orderPushed = false + limitPushed = false + } + SqlQueryNode laidOut = aliases.size() > 1 ? MixedSourceLayout.layout(query, aliases, emulateFull) : query + + List columnCountQueries = [] + if (aliases.size() > 1) { + for (SqlTableSource source : labelSources) { + columnCountQueries << countQuery(source) + } + } + + GinqExpression tail = new GinqExpression() + tail.fromExpression = fromExpression + tail.putNodeMetaData(GinqAstBuilder.ROOT_GINQ_EXPRESSION, tail) + if (Boolean.TRUE == ginq.getNodeMetaData(GinqAstBuilder.GINQ_SELECT_DISTINCT)) { + tail.putNodeMetaData(GinqAstBuilder.GINQ_SELECT_DISTINCT, Boolean.TRUE) + } + for (int i = 0; i < joins.size(); i++) { + JoinExpression original = joins[i] + if (i < pushedJoins) { + // The SQL join already aligned these lists, including nulls for + // unmatched outer-join sides. A collection join would drop those + // nulls or throw from mixedOrdinal, so the tail pairs by index. + JoinExpression zipped = new JoinExpression('join', original.aliasExpr, original.dataSourceExpr) + zipped.putNodeMetaData(INDEX_ALIGNED_JOIN, Boolean.TRUE) + tail.addJoinExpression(zipped) + } else { + tail.addJoinExpression(original) + } + } + if (!wherePushed && ginq.whereExpression != null) { + tail.whereExpression = ginq.whereExpression + } + if (ginq.groupExpression != null) { + tail.groupExpression = ginq.groupExpression + } + if (!orderPushed && ginq.orderExpression != null) { + tail.orderExpression = ginq.orderExpression + } + if (!limitPushed && ginq.limitExpression != null) { + tail.limitExpression = ginq.limitExpression + } + tail.selectExpression = ginq.selectExpression + return MixedPlan.split(laidOut, columnCountQueries, tail, pushedJoins) + } + + private static SqlQuery countQuery(SqlTableSource source) { + SqlQuery query = new SqlQuery() + query.projections << new SqlProjection(new SqlStar()) + if (source instanceof SqlTableRef) { + query.from = new SqlTableRef(source.tableName, source.alias) + } else if (source instanceof SqlDerivedTable) { + query.from = new SqlDerivedTable(source.query, source.alias) + } else { + return null + } + query.where = new SqlBinary('=', new SqlLiteral(1), new SqlLiteral(0)) + return query + } + + private boolean aborted(int before) { + return errorCount() != before + } + + private int errorCount() { + return sourceUnit.errorCollector.errorCount + } + + private void trimAliases(int size) { + while (tableAliases.size() > size) { + tableAliases.remove(tableAliases.size() - 1) + } + } + + /** + * Reports a construct that has no SQL translation. Mixed-mode planning + * catches {@link Untranslatable}; strict mode records a compile error. + */ + private void reject(String message, ASTNode node) { + reject(message, node, true) + } + + /** + * @param hintMixedMode append how to enable in-memory evaluation. Omitted + * while planning mixed mode, and for failures mixed mode cannot repair. + */ + private void reject(String message, ASTNode node, boolean hintMixedMode) { + if (recoverUntranslatable) { + throw new Untranslatable(message, node) + } + error(hintMixedMode ? message + MIXED_HINT : message, node) + } + + @PackageScope + static String invalidTableNameMessage(String tableName) { + return "table name `${tableName}` must be a simple identifier or a schema-qualified name such as `hr.employees`. " + + 'A quoting `table()` helper is not supported yet' + } + + @PackageScope + static boolean plainTableName(String name) { + if (!name) return false + for (String part : name.split('\\.', -1)) { + if (!simpleIdentifier(part)) return false + } + return true + } + + // Parentheses are a one-element tuple. Leaving them wrapped makes + // `(e.salary + 1) in (subquery)` fail to see the subquery. + private static Expression unwrapGrouping(Expression expr) { + while (expr instanceof TupleExpression && ((TupleExpression) expr).expressions.size() == 1) { + expr = ((TupleExpression) expr).expressions[0] + } + return expr + } + + private static boolean simpleIdentifier(String part) { + if (!part) return false + for (int i = 0; i < part.length(); i++) { + char ch = part.charAt(i) + // ASCII letter, digit or underscore. Char literals are Strings under static compilation. + boolean letter = (ch >= 65 && ch <= 90) || (ch >= 97 && ch <= 122) || ch == 95 + boolean digit = ch >= 48 && ch <= 57 + if (!(letter || (i > 0 && digit))) return false + } + return true + } + + private void error(String message, ASTNode node) { + collectSyntaxError(new GinqSyntaxError(message, node.lineNumber, node.columnNumber)) + } + + private static enum QueryContext { + TOP_LEVEL, INNER_OPERAND, FINAL_OPERAND + } + + /** + * Marks a pushed join whose two sides are already aligned by + * {@code SqlGinqRuntime.zipAliases}, one entry per output row. + */ + @PackageScope + static final String INDEX_ALIGNED_JOIN = 'org.apache.groovy.ginq.provider.sql.IndexAlignedJoin' + + private static final ClassNode SQL_GINQ_RUNTIME_TYPE = ClassHelper.makeCached(SqlGinqRuntime) + private static final List ORDER_OPTION_LIST = ['asc', 'desc'] + private static final List NULLS_OPTION_LIST = ['nullsfirst', 'nullslast'] + private static final Map AGGREGATE_FUNCTION_MAP = [ + count: 'COUNT', + sum : 'SUM', + avg : 'AVG', + min : 'MIN', + max : 'MAX', + ] + private static final String MIXED_HINT = + '. Rewrite it in supported SQL, or set `mixedMode: true` to evaluate that clause in memory.' + + private static final Set TEXT_INPUT_METHODS = Set.of( + 'toUpperCase', 'toLowerCase', 'trim', 'substring', 'replace', 'concat', + 'length', 'size', 'isEmpty', 'contains', 'startsWith', 'endsWith', 'indexOf') + private static final Set TEXT_RESULT_METHODS = Set.of( + 'toUpperCase', 'toLowerCase', 'trim', 'substring', 'replace', 'concat') + + private SqlExpr emitFunction(String name, List args, ASTNode node) { + return emitFunction(name, args, false, node) + } + + private SqlExpr emitFunction(String name, List args, boolean distinct, ASTNode node) { + if (!capabilities.supportsFunction(name)) { + reject("`${groovyName(node, name)}` maps to ${name}, which is not supported by the ${capabilities.dialectName()} dialect. " + + 'Rewrite the query without it, or use a dialect that provides it', node) + return null + } + return new SqlFunction(name, args, distinct) + } + + private static String groovyName(ASTNode node, String sqlName) { + if (node instanceof MethodCallExpression) { + String method = ((MethodCallExpression) node).methodAsString + if (method != null) return method + '()' + } + return sqlName + } + + private SqlExpr translateGroovyCast(CastExpression expr) { + OperandKind kind = typeKind(expr.type) + if (kind != OperandKind.TEXT && kind != OperandKind.NUMBER) { + reject('a cast is translated only for a numeric or text type, for example `(suffix as String)` or `(bonus as int)`. ' + + "For an explicit SQL type use `cast(expr, 'VARCHAR')`", expr) + return null + } + SqlExpr inner = translateExpr(expr.expression) + if (inner == null) return null + if (inner instanceof SqlParam) { + return new SqlParam(castX(expr.type, ((SqlParam) inner).valueExpr)) + } + String sqlType = kind == OperandKind.TEXT ? 'VARCHAR' : sqlNumericType(expr.type) + return new SqlCast(inner, sqlType) + } + + private static String sqlNumericType(ClassNode type) { + String name = simpleName(type) + if ('long' == name || 'Long' == name) return 'BIGINT' + if ('double' == name || 'float' == name || 'Double' == name || 'Float' == name) return 'DOUBLE' + if ('BigDecimal' == name || 'BigInteger' == name) return 'DECIMAL' + return 'INTEGER' + } + + private OperandKind operandKind(Expression expr) { + if (expr == null) return OperandKind.OTHER + if (expr instanceof ConstantExpression) return constantKind((ConstantExpression) expr) + if (expr instanceof CastExpression) { + OperandKind castKind = typeKind(((CastExpression) expr).type) + if (castKind != OperandKind.OTHER) return castKind + return operandKind(((CastExpression) expr).expression) + } + if (expr instanceof UnaryMinusExpression) { + return operandKind(((UnaryMinusExpression) expr).expression) == OperandKind.NUMBER + ? OperandKind.NUMBER : OperandKind.OTHER + } + if (expr instanceof NotExpression) return operandKind(((NotExpression) expr).expression) + if (expr instanceof BooleanExpression) return operandKind(((BooleanExpression) expr).expression) + if (expr instanceof BinaryExpression) return binaryKind((BinaryExpression) expr) + if (expr instanceof VariableExpression) return typeKind(variableType((VariableExpression) expr)) + if (expr instanceof PropertyExpression) return OperandKind.COLUMN + if (expr instanceof MethodCallExpression) return methodKind((MethodCallExpression) expr) + return OperandKind.OTHER + } + + private static OperandKind constantKind(ConstantExpression expr) { + Object value = expr.value + if (value instanceof CharSequence || value instanceof Character) return OperandKind.TEXT + if (value instanceof Number) return OperandKind.NUMBER + return OperandKind.OTHER + } + + private OperandKind binaryKind(BinaryExpression expr) { + OperandKind left = operandKind(expr.leftExpression) + OperandKind right = operandKind(expr.rightExpression) + String op = expr.operation.text + if ('+' == op) { + if (plusIsText(left, right)) return OperandKind.TEXT + if (plusIsNumber(left, right)) return OperandKind.NUMBER + return OperandKind.OTHER + } + if (op in ['-', '*', '/', '%']) { + if (left == OperandKind.TEXT || right == OperandKind.TEXT) return OperandKind.OTHER + if (left == OperandKind.NUMBER || right == OperandKind.NUMBER || left == OperandKind.COLUMN || right == OperandKind.COLUMN) { + return OperandKind.NUMBER + } + } + return OperandKind.OTHER + } + + private OperandKind methodKind(MethodCallExpression call) { + String method = call.methodAsString + if (method == null) return OperandKind.OTHER + if ('count' == method || 'sum' == method || 'avg' == method) return OperandKind.NUMBER + if (!call.implicitThis && isMathReceiver(call.objectExpression) && ('max' == method || 'min' == method)) { + return OperandKind.NUMBER + } + if (TEXT_RESULT_METHODS.contains(method)) { + OperandKind receiver = operandKind(call.objectExpression) + if (receiver == OperandKind.TEXT || receiver == OperandKind.COLUMN) return OperandKind.TEXT + return OperandKind.OTHER + } + if ('length' == method || 'size' == method || 'indexOf' == method) { + OperandKind receiver = operandKind(call.objectExpression) + if (receiver == OperandKind.TEXT || receiver == OperandKind.COLUMN) return OperandKind.NUMBER + return OperandKind.OTHER + } + if ('abs' == method || 'floor' == method || 'ceil' == method || 'round' == method) return OperandKind.NUMBER + return OperandKind.OTHER + } + + private static OperandKind typeKind(ClassNode type) { + if (type == null || ClassHelper.isDynamicTyped(type) || ClassHelper.isObjectType(type)) return OperandKind.OTHER + if (isTextType(type)) return OperandKind.TEXT + if (isNumericType(type)) return OperandKind.NUMBER + return OperandKind.OTHER + } + + private static boolean isTextType(ClassNode type) { + if (type == null) return false + if (ClassHelper.isPrimitiveChar(type)) return true + String name = simpleName(type) + return 'String' == name || 'GString' == name || 'Character' == name + } + + private static boolean isNumericType(ClassNode type) { + if (type == null) return false + if (ClassHelper.isNumberType(type)) return true + if (type.isResolved() && type.isDerivedFrom(ClassHelper.Number_TYPE)) return true + // A cast written in source may still be an unresolved ClassNode when the + // query is translated, so the simple name has to count too. + String name = simpleName(type) + return name in ['byte', 'Byte', 'short', 'Short', 'int', 'Integer', 'long', 'Long', + 'float', 'Float', 'double', 'Double', 'BigDecimal', 'BigInteger', 'Number'] + } + + private static String simpleName(ClassNode type) { + String name = type.name + int dot = name.lastIndexOf('.') + return dot < 0 ? name : name.substring(dot + 1) + } + + private static ClassNode variableType(VariableExpression expr) { + Variable accessed = expr.accessedVariable + if (accessed != null) { + OperandKind accessedKind = typeKind(accessed.type) + if (accessedKind != OperandKind.OTHER) return accessed.type + } + if (typeKind(expr.originType) != OperandKind.OTHER) return expr.originType + return expr.type + } + + private static enum OperandKind { + TEXT, NUMBER, COLUMN, OTHER + } + + @CompileStatic + private class CallSite implements SqlFunctionSite { + @Override + SqlExpr expr(Expression expression) { + return translateExpr(expression) + } + + @Override + void fail(String message, ASTNode node) { + reject(message, node) + } + + @Override + SqlExpr like(MethodCallExpression call, List args, boolean matchBefore, boolean matchAfter) { + return translateLike(call, args, matchBefore, matchAfter) + } + + @Override + SqlExpr substring(MethodCallExpression call, List args) { + return translateSubstring(call, args) + } + + @Override + SqlExpr function(String ansiName, List args, ASTNode node) { + return emitFunction(ansiName, args, node) + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedPlan.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedPlan.groovy new file mode 100644 index 00000000000..0a7dff7fad6 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedPlan.groovy @@ -0,0 +1,61 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope +import org.apache.groovy.ginq.dsl.expression.GinqExpression +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.lang.annotation.Incubating + +/** + * Result of planning a query for mixed-mode execution. + *

+ * When {@link #fullQuery} is set, the whole query translates to SQL. + * Otherwise {@link #prefix} is the translatable clause prefix (star + * projections) and {@link #tail} is the remainder, executed in memory. + */ +@PackageScope +@Incubating +@CompileStatic +class MixedPlan { + final SqlQueryNode fullQuery + final SqlQueryNode prefix + final List columnCountQueries + final GinqExpression tail + final int pushedJoins + + private MixedPlan(SqlQueryNode fullQuery, SqlQueryNode prefix, List columnCountQueries, + GinqExpression tail, int pushedJoins) { + this.fullQuery = fullQuery + this.prefix = prefix + this.columnCountQueries = columnCountQueries + this.tail = tail + this.pushedJoins = pushedJoins + } + + static MixedPlan complete(SqlQueryNode fullQuery) { + return new MixedPlan(fullQuery, null, Collections.emptyList(), null, 0) + } + + static MixedPlan split(SqlQueryNode prefix, List columnCountQueries, GinqExpression tail, int pushedJoins) { + return new MixedPlan(null, prefix, columnCountQueries, tail, pushedJoins) + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedSourceLayout.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedSourceLayout.groovy new file mode 100644 index 00000000000..fe8bd60bd2c --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedSourceLayout.groovy @@ -0,0 +1,734 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope + +import java.util.LinkedHashMap +import java.util.LinkedHashSet +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCaseWhen +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlDerivedTable +import org.apache.groovy.ginq.provider.sql.ir.SqlExists +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlIn +import org.apache.groovy.ginq.provider.sql.ir.SqlInQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlIsNull +import org.apache.groovy.ginq.provider.sql.ir.SqlJoin +import org.apache.groovy.ginq.provider.sql.ir.SqlLike +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlOrderSpec +import org.apache.groovy.ginq.provider.sql.ir.SqlProjection +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.ir.SqlScalarQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlSetQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlStar +import org.apache.groovy.ginq.provider.sql.ir.SqlTableRef +import org.apache.groovy.ginq.provider.sql.ir.SqlTableSource +import org.apache.groovy.ginq.provider.sql.ir.SqlUnary +import org.codehaus.groovy.GroovyBugError + +/** + * Puts a presence column on each mixed-mode source and, when the dialect has + * no {@code FULL OUTER JOIN}, nests each full join as its own union. The + * union is a derived table, and the next join reads that table. A later + * outer join sees the whole left subjoin as absent only when every presence + * column inside it is null. + */ +@PackageScope +@CompileStatic +class MixedSourceLayout { + static final String PRESENCE = '__ginq_present' + /** + * Planner reference to the synthetic presence marker. It is not a user + * column, so renaming the marker does not rewrite a real {@code __ginq_present}. + */ + static final String MARKER = '__ginq_marker' + private static final String SRC = '__ginq_src' + + private final List aliasNames + private final boolean userProjections + private final LayoutContext context + private final Map> usedColumns = new LinkedHashMap<>() + private final Map starProbesByAlias = new LinkedHashMap<>() + private List originals = [] + + private MixedSourceLayout(List aliasNames, boolean userProjections, LayoutContext context) { + this.aliasNames = aliasNames + this.userProjections = userProjections + this.context = context + } + + /** + * Wraps every source with a presence column. When {@code emulateFull} is + * set, each full join becomes + * {@code (left LEFT JOIN right) UNION ALL (left RIGHT JOIN right WHERE left is absent)} + * and that union is the left input of the following join. + */ + static SqlQueryNode layout(SqlQuery query, List aliasNames, boolean emulateFull) { + return new MixedSourceLayout(aliasNames, false, new LayoutContext()).apply(query, emulateFull) + } + + /** + * Rewrites a fully translated query so a dialect without {@code FULL OUTER JOIN} + * still executes it. Nested queries are rewritten too, including a full join + * that lives only inside {@code EXISTS}, {@code IN} or a scalar subquery. + * The outermost select list stays the user's projections; presence columns + * exist only inside the emulated unions. + */ + static SqlQueryNode layoutComplete(SqlQueryNode node) { + LayoutContext context = new LayoutContext() + SqlQueryNode laid = layOut(node, context) + attachProbes(laid, context.probes) + return laid + } + + private static SqlQueryNode layOut(SqlQueryNode node, LayoutContext context) { + if (node instanceof SqlSetQuery) { + SqlSetQuery set = (SqlSetQuery) node + SqlQueryNode left = layOut(set.left, context) + SqlQuery right = (SqlQuery) layOut(set.right, context) + if (left === set.left && right === set.right) { + return set + } + SqlSetQuery copy = new SqlSetQuery(left, set.op, right) + copy.orderBy.addAll(set.orderBy) + copy.offset = set.offset + copy.fetch = set.fetch + return copy + } + SqlQuery query = (SqlQuery) node + relayQuery(query, context) + if (!query.joins.any { SqlJoin join -> join.type == SqlJoin.Type.FULL }) { + return query + } + List names = [query.from.alias] + for (SqlJoin join : query.joins) { + names.add(join.table.alias) + } + return new MixedSourceLayout(names, true, context).completeNest(query) + } + + private SqlQueryNode apply(SqlQuery query, boolean emulateFull) { + query.from = wrap(query.from) + List wrapped = [] + for (SqlJoin join : query.joins) { + wrapped.add(new SqlJoin(join.type, wrap(join.table), join.on)) + } + query.joins.clear() + query.joins.addAll(wrapped) + if (!emulateFull) { + return query + } + return nest(query) + } + + private SqlQueryNode completeNest(SqlQuery query) { + originals = [query.from] + for (SqlJoin join : query.joins) { + originals.add(join.table) + } + registerStars(query) + collectUsed(query) + return apply(query, true) + } + + private static void relayQuery(SqlQuery query, LayoutContext context) { + if (query.from instanceof SqlDerivedTable) { + SqlDerivedTable derived = (SqlDerivedTable) query.from + SqlQueryNode inner = layOut(derived.query, context) + if (inner !== derived.query) { + query.from = new SqlDerivedTable(inner, derived.alias) + } + } + List joins = [] + boolean joinsChanged = false + for (SqlJoin join : query.joins) { + SqlExpr on = relayExpr(join.on, context) + SqlTableSource table = join.table + if (table instanceof SqlDerivedTable) { + SqlDerivedTable derived = (SqlDerivedTable) table + SqlQueryNode inner = layOut(derived.query, context) + if (inner !== derived.query) { + table = new SqlDerivedTable(inner, derived.alias) + } + } + if (on !== join.on || table !== join.table) { + joins.add(new SqlJoin(join.type, table, on)) + joinsChanged = true + } else { + joins.add(join) + } + } + if (joinsChanged) { + query.joins.clear() + query.joins.addAll(joins) + } + for (int i = 0; i < query.projections.size(); i++) { + SqlProjection projection = query.projections[i] + SqlExpr expr = relayExpr(projection.expr, context) + if (expr !== projection.expr) { + query.projections.set(i, new SqlProjection(expr, projection.alias)) + } + } + query.where = relayExpr(query.where, context) + for (int i = 0; i < query.groupBy.size(); i++) { + query.groupBy.set(i, relayExpr(query.groupBy[i], context)) + } + query.having = relayExpr(query.having, context) + for (int i = 0; i < query.orderBy.size(); i++) { + SqlOrderSpec spec = query.orderBy[i] + SqlExpr expr = relayExpr(spec.expr, context) + if (expr !== spec.expr) { + query.orderBy.set(i, new SqlOrderSpec(expr, spec.asc, spec.nullsLast)) + } + } + } + + private static SqlExpr relayExpr(SqlExpr expr, LayoutContext context) { + if (expr == null) { + return null + } + if (expr instanceof SqlBinary) { + SqlExpr left = relayExpr(expr.left, context) + SqlExpr right = relayExpr(expr.right, context) + return left === expr.left && right === expr.right ? expr : new SqlBinary(expr.op, left, right) + } + if (expr instanceof SqlUnary) { + SqlExpr operand = relayExpr(expr.operand, context) + return operand === expr.operand ? expr : new SqlUnary(expr.op, operand) + } + if (expr instanceof SqlIsNull) { + SqlExpr inner = relayExpr(expr.expr, context) + return inner === expr.expr ? expr : new SqlIsNull(inner, expr.negated) + } + if (expr instanceof SqlIn) { + SqlExpr inner = relayExpr(expr.expr, context) + List values = relayList(expr.values, context) + return inner === expr.expr && values === expr.values ? expr : new SqlIn(inner, values, expr.negated) + } + if (expr instanceof SqlLike) { + SqlExpr value = relayExpr(expr.expr, context) + SqlExpr pattern = relayExpr(expr.pattern, context) + return value === expr.expr && pattern === expr.pattern ? expr : new SqlLike(value, pattern) + } + if (expr instanceof SqlFunction) { + List args = relayList(expr.args, context) + return args === expr.args ? expr : new SqlFunction(expr.name, args, expr.distinct) + } + if (expr instanceof SqlCast) { + SqlExpr inner = relayExpr(expr.expr, context) + return inner === expr.expr ? expr : new SqlCast(inner, expr.sqlType) + } + if (expr instanceof SqlCaseWhen) { + SqlExpr condition = relayExpr(expr.condition, context) + SqlExpr thenExpr = relayExpr(expr.thenExpr, context) + SqlExpr elseExpr = relayExpr(expr.elseExpr, context) + return condition === expr.condition && thenExpr === expr.thenExpr && elseExpr === expr.elseExpr + ? expr : new SqlCaseWhen(condition, thenExpr, elseExpr) + } + if (expr instanceof SqlScalarQuery) { + SqlQuery laid = (SqlQuery) layOut(expr.query, context) + return laid === expr.query ? expr : new SqlScalarQuery(laid) + } + if (expr instanceof SqlExists) { + SqlQuery laid = (SqlQuery) layOut(expr.query, context) + return laid === expr.query ? expr : new SqlExists(laid) + } + if (expr instanceof SqlInQuery) { + SqlExpr inner = relayExpr(expr.expr, context) + SqlQuery laid = (SqlQuery) layOut(expr.query, context) + return inner === expr.expr && laid === expr.query ? expr : new SqlInQuery(inner, laid, expr.negated) + } + return expr + } + + private static List relayList(List exprs, LayoutContext context) { + List copy = null + for (int i = 0; i < exprs.size(); i++) { + SqlExpr relayed = relayExpr(exprs[i], context) + if (copy == null && relayed !== exprs[i]) { + copy = new ArrayList<>(exprs.subList(0, i)) + } + if (copy != null) { + copy.add(relayed) + } + } + return copy == null ? exprs : copy + } + + private static void attachProbes(SqlQueryNode node, List probes) { + if (probes.isEmpty()) { + return + } + List copy = new ArrayList<>(probes) + if (node instanceof SqlQuery) { + ((SqlQuery) node).starProbes = copy + } else if (node instanceof SqlSetQuery) { + ((SqlSetQuery) node).starProbes = copy + } + } + + private void registerStars(SqlQuery query) { + for (SqlProjection projection : query.projections) { + if (!(projection.expr instanceof SqlStar)) { + continue + } + String alias = ((SqlStar) projection.expr).tableAlias + if (alias == null || !aliasNames.contains(alias) || starProbesByAlias.containsKey(alias)) { + continue + } + int index = aliasNames.indexOf(alias) + int id = context.probes.size() + context.probes.add(countQuery(originals[index])) + starProbesByAlias.put(alias, id) + } + } + + private static SqlQuery countQuery(SqlTableSource source) { + SqlQuery query = new SqlQuery() + query.projections.add(new SqlProjection(new SqlStar())) + if (source instanceof SqlTableRef) { + query.from = new SqlTableRef(source.tableName, source.alias) + } else if (source instanceof SqlDerivedTable) { + query.from = new SqlDerivedTable(source.query, source.alias) + } else { + throw new GroovyBugError('unknown mixed-mode source ' + source.getClass().name) + } + query.where = new SqlBinary('=', new SqlLiteral(1), new SqlLiteral(0)) + return query + } + + private void collectUsed(SqlQuery query) { + collectQuery(query) + } + + private void collectQuery(SqlQuery query) { + if (query == null) { + return + } + for (SqlProjection projection : query.projections) { + collectExpr(projection.expr) + } + collectExpr(query.where) + for (SqlExpr key : query.groupBy) { + collectExpr(key) + } + collectExpr(query.having) + for (SqlOrderSpec spec : query.orderBy) { + collectExpr(spec.expr) + } + for (SqlJoin join : query.joins) { + collectExpr(join.on) + } + } + + private void collectExpr(SqlExpr expr) { + if (expr == null) { + return + } + if (expr instanceof SqlColumn) { + SqlColumn column = (SqlColumn) expr + if (column.tableAlias != null && aliasNames.contains(column.tableAlias)) { + LinkedHashSet columns = usedColumns.get(column.tableAlias) + if (columns == null) { + columns = new LinkedHashSet<>() + usedColumns.put(column.tableAlias, columns) + } + columns.add(column.column) + } + return + } + if (expr instanceof SqlBinary) { + collectExpr(expr.left) + collectExpr(expr.right) + } else if (expr instanceof SqlUnary) { + collectExpr(expr.operand) + } else if (expr instanceof SqlIsNull) { + collectExpr(expr.expr) + } else if (expr instanceof SqlIn) { + collectExpr(expr.expr) + for (SqlExpr value : expr.values) { + collectExpr(value) + } + } else if (expr instanceof SqlLike) { + collectExpr(expr.expr) + collectExpr(expr.pattern) + } else if (expr instanceof SqlFunction) { + for (SqlExpr arg : expr.args) { + collectExpr(arg) + } + } else if (expr instanceof SqlCast) { + collectExpr(expr.expr) + } else if (expr instanceof SqlCaseWhen) { + collectExpr(expr.condition) + collectExpr(expr.thenExpr) + collectExpr(expr.elseExpr) + } else if (expr instanceof SqlScalarQuery) { + collectQuery(((SqlScalarQuery) expr).query) + } else if (expr instanceof SqlExists) { + collectQuery(((SqlExists) expr).query) + } else if (expr instanceof SqlInQuery) { + SqlInQuery inQuery = (SqlInQuery) expr + collectExpr(inQuery.expr) + collectQuery(inQuery.query) + } + } + + private SqlQueryNode nest(SqlQuery query) { + Rel rel = new Rel() + rel.from = query.from + rel.direct.add(aliasNames[0]) + rel.output.add(0) + for (int j = 0; j < query.joins.size(); j++) { + SqlJoin join = query.joins[j] + int index = j + 1 + if (join.type == SqlJoin.Type.FULL) { + rel = nestFull(rel, join, index) + } else { + appendJoin(rel, join, index) + } + } + return userProjections ? finishComplete(rel, query) : finish(rel, query) + } + + private void appendJoin(Rel rel, SqlJoin join, int index) { + rel.joins.add(new SqlJoin(join.type, join.table, rewriteExpr(join.on, rel, aliasNames[index]))) + rel.direct.add(aliasNames[index]) + rel.output.add(index) + } + + private Rel nestFull(Rel rel, SqlJoin join, int index) { + List projections = project(rel) + if (userProjections) { + projections.addAll(directColumns(index, aliasNames[index])) + } else { + projections.add(new SqlProjection(new SqlStar(aliasNames[index]))) + } + SqlExpr on = rewriteExpr(join.on, rel, aliasNames[index]) + SqlQuery left = materialize(rel, SqlJoin.Type.LEFT, join.table, on, projections, null) + SqlQuery right = materialize(rel, SqlJoin.Type.RIGHT, join.table, on, projections, absence(rel)) + SqlSetQuery union = new SqlSetQuery(left, SqlSetQuery.SetOp.UNION_ALL, right) + int first = rel.output[0] + String container = '__ginqf' + first + '_' + (index + 1) + Rel next = new Rel() + next.from = new SqlDerivedTable(union, container) + next.container = container + next.output.addAll(rel.output) + next.output.add(index) + return next + } + + private SqlQuery materialize(Rel rel, SqlJoin.Type type, SqlTableSource right, SqlExpr on, + List projections, SqlExpr where) { + SqlQuery query = new SqlQuery() + query.from = rel.from + query.joins.addAll(rel.joins) + query.joins.add(new SqlJoin(type, right, on)) + query.projections.addAll(projections) + query.where = where + return query + } + + private List project(Rel rel) { + if (userProjections) { + List projections = [] + for (int index : rel.output) { + projections.addAll(passedColumns(rel, index)) + } + return projections + } + List projections = [] + if (rel.container != null) { + projections.add(new SqlProjection(new SqlStar(rel.container))) + } + for (String alias : rel.direct) { + projections.add(new SqlProjection(new SqlStar(alias))) + } + return projections + } + + private List directColumns(int index, String alias) { + List projections = [] + projections.add(new SqlProjection(new SqlColumn(alias, MARKER), presenceOut(index))) + Integer probe = starProbesByAlias.get(alias) + if (probe != null) { + projections.add(new SqlProjection(new SqlColumn(alias, '__ginqsrc_' + probe))) + return projections + } + LinkedHashSet columns = usedColumns.get(alias) + if (columns != null) { + for (String column : columns) { + projections.add(new SqlProjection(new SqlColumn(alias, column), columnOut(index, column))) + } + } + return projections + } + + private List passedColumns(Rel rel, int index) { + String alias = aliasNames[index] + if (rel.direct.contains(alias)) { + return directColumns(index, alias) + } + List projections = [] + projections.add(new SqlProjection(new SqlColumn(rel.container, presenceOut(index)), presenceOut(index))) + Integer probe = starProbesByAlias.get(alias) + if (probe != null) { + projections.add(new SqlProjection(new SqlColumn(rel.container, '__ginqpass_' + probe))) + return projections + } + LinkedHashSet columns = usedColumns.get(alias) + if (columns != null) { + for (String column : columns) { + projections.add(new SqlProjection(new SqlColumn(rel.container, columnOut(index, column)), columnOut(index, column))) + } + } + return projections + } + + private static String presenceOut(int index) { + return '__ginq_p' + index + } + + private static String columnOut(int index, String column) { + return '__ginq_' + index + '_' + column + } + + private SqlExpr absence(Rel rel) { + SqlExpr acc = null + for (int index : rel.output) { + SqlExpr column + if (rel.direct.contains(aliasNames[index])) { + column = new SqlColumn(aliasNames[index], MARKER) + } else { + column = new SqlColumn(rel.container, userProjections ? presenceOut(index) : '__ginqabs_' + index) + } + SqlExpr pred = new SqlIsNull(column, false) + acc = acc == null ? pred : new SqlBinary('AND', acc, pred) + } + return acc + } + + private SqlQueryNode finish(Rel rel, SqlQuery original) { + SqlExpr where = rewriteExpr(original.where, rel) + List orders = [] + for (SqlOrderSpec spec : original.orderBy) { + orders.add(rewriteOrder(spec, rel)) + } + if (rel.joins.isEmpty() && rel.container != null) { + SqlQuery wrapper = new SqlQuery() + wrapper.from = rel.from + wrapper.projections.add(new SqlProjection(new SqlStar(rel.container))) + wrapper.where = where + wrapper.orderBy.addAll(orders) + wrapper.offset = original.offset + wrapper.fetch = original.fetch + return wrapper + } + SqlQuery query = new SqlQuery() + query.from = rel.from + query.joins.addAll(rel.joins) + query.projections.addAll(project(rel)) + query.where = where + query.orderBy.addAll(orders) + query.offset = original.offset + query.fetch = original.fetch + return query + } + + private SqlQuery finishComplete(Rel rel, SqlQuery original) { + SqlQuery query = new SqlQuery() + query.distinct = original.distinct + query.from = rel.from + query.joins.addAll(rel.joins) + for (SqlProjection projection : original.projections) { + String alias = projection.alias + if ((alias == null || alias.isEmpty()) && projection.expr instanceof SqlColumn) { + alias = ((SqlColumn) projection.expr).column + } + query.projections.add(new SqlProjection(rewriteExpr(projection.expr, rel), alias)) + } + query.where = rewriteExpr(original.where, rel) + for (SqlExpr key : original.groupBy) { + query.groupBy.add(rewriteExpr(key, rel)) + } + query.having = rewriteExpr(original.having, rel) + for (SqlOrderSpec spec : original.orderBy) { + query.orderBy.add(new SqlOrderSpec(rewriteExpr(spec.expr, rel), spec.asc, spec.nullsLast)) + } + query.offset = original.offset + query.fetch = original.fetch + return query + } + + private SqlOrderSpec rewriteOrder(SqlOrderSpec spec, Rel rel) { + if (!(spec.expr instanceof SqlColumn)) { + throw new GroovyBugError('emulated full join order key is not a column') + } + SqlColumn column = (SqlColumn) spec.expr + if (rel.direct.contains(column.tableAlias)) { + return spec + } + int index = aliasNames.indexOf(column.tableAlias) + String qualifier = rel.container != null ? rel.container : column.tableAlias + return new SqlOrderSpec(new SqlColumn(qualifier, '__ginqord_' + index + '_' + column.column), spec.asc, spec.nullsLast) + } + + private SqlExpr rewriteExpr(SqlExpr expr, Rel rel, String alsoDirect = null) { + if (expr == null || rel.container == null) { + return expr + } + if (expr instanceof SqlColumn) { + SqlColumn column = (SqlColumn) expr + if (column.column != null && (column.column.startsWith('__ginqsrc_') + || column.column.startsWith('__ginqpass_') + || column.column.startsWith('__ginqstar_') + || column.column.startsWith('__ginqcol_') + || (column.tableAlias != null && column.tableAlias.startsWith('__ginq')))) { + return column + } + if (column.tableAlias == null || column.tableAlias == alsoDirect + || rel.direct.contains(column.tableAlias) || column.tableAlias == rel.container) { + return column + } + int index = aliasNames.indexOf(column.tableAlias) + if (index < 0) { + return column + } + Integer probe = starProbesByAlias.get(column.tableAlias) + if (userProjections && probe != null) { + return new SqlColumn(rel.container, '__ginqcol_' + probe + '_' + column.column) + } + String exposed = userProjections ? columnOut(index, column.column) : '__ginqref_' + index + '_' + column.column + return new SqlColumn(rel.container, exposed) + } + if (expr instanceof SqlStar) { + String alias = ((SqlStar) expr).tableAlias + Integer probe = alias == null ? null : starProbesByAlias.get(alias) + if (!userProjections || probe == null || rel.direct.contains(alias)) { + return expr + } + return new SqlColumn(rel.container, '__ginqstar_' + probe + '_' + alias) + } + if (expr instanceof SqlBinary) { + return new SqlBinary(expr.op, rewriteExpr(expr.left, rel, alsoDirect), rewriteExpr(expr.right, rel, alsoDirect)) + } + if (expr instanceof SqlUnary) { + return new SqlUnary(expr.op, rewriteExpr(expr.operand, rel, alsoDirect)) + } + if (expr instanceof SqlIsNull) { + return new SqlIsNull(rewriteExpr(expr.expr, rel, alsoDirect), expr.negated) + } + if (expr instanceof SqlIn) { + List values = [] + for (SqlExpr value : expr.values) { + values.add(rewriteExpr(value, rel, alsoDirect)) + } + return new SqlIn(rewriteExpr(expr.expr, rel, alsoDirect), values, expr.negated) + } + if (expr instanceof SqlLike) { + return new SqlLike(rewriteExpr(expr.expr, rel, alsoDirect), rewriteExpr(expr.pattern, rel, alsoDirect)) + } + if (expr instanceof SqlFunction) { + List args = [] + for (SqlExpr arg : expr.args) { + args.add(rewriteExpr(arg, rel, alsoDirect)) + } + return new SqlFunction(expr.name, args, expr.distinct) + } + if (expr instanceof SqlCast) { + return new SqlCast(rewriteExpr(expr.expr, rel, alsoDirect), expr.sqlType) + } + if (expr instanceof SqlCaseWhen) { + return new SqlCaseWhen(rewriteExpr(expr.condition, rel, alsoDirect), rewriteExpr(expr.thenExpr, rel, alsoDirect), rewriteExpr(expr.elseExpr, rel, alsoDirect)) + } + if (expr instanceof SqlScalarQuery) { + return new SqlScalarQuery(rewriteQuery(expr.query, rel, alsoDirect)) + } + if (expr instanceof SqlExists) { + return new SqlExists(rewriteQuery(expr.query, rel, alsoDirect)) + } + if (expr instanceof SqlInQuery) { + return new SqlInQuery(rewriteExpr(expr.expr, rel, alsoDirect), rewriteQuery(expr.query, rel, alsoDirect), expr.negated) + } + return expr + } + + private SqlQuery rewriteQuery(SqlQuery query, Rel rel, String alsoDirect = null) { + SqlQuery copy = new SqlQuery() + copy.distinct = query.distinct + for (SqlProjection projection : query.projections) { + copy.projections.add(new SqlProjection(rewriteExpr(projection.expr, rel, alsoDirect), projection.alias)) + } + copy.from = query.from + for (SqlJoin join : query.joins) { + copy.joins.add(new SqlJoin(join.type, join.table, rewriteExpr(join.on, rel, alsoDirect))) + } + copy.where = rewriteExpr(query.where, rel, alsoDirect) + for (SqlExpr key : query.groupBy) { + copy.groupBy.add(rewriteExpr(key, rel, alsoDirect)) + } + copy.having = rewriteExpr(query.having, rel, alsoDirect) + for (SqlOrderSpec spec : query.orderBy) { + copy.orderBy.add(new SqlOrderSpec(rewriteExpr(spec.expr, rel, alsoDirect), spec.asc, spec.nullsLast)) + } + copy.offset = query.offset + copy.fetch = query.fetch + return copy + } + + private SqlTableSource wrap(SqlTableSource source) { + SqlQuery inner = new SqlQuery() + inner.from = realias(source, SRC) + inner.projections.add(new SqlProjection(new SqlStar(SRC))) + // Complete-path SQL is executed as rendered, so the wrap must not + // introduce 1 AS "__ginq_present" beside a user column of that name. + // The split path still emits PRESENCE and lets prepareMixedSql rename + // only the AS definition (and MARKER) when the user label collides. + inner.projections.add(new SqlProjection(new SqlLiteral(1), userProjections ? MARKER : PRESENCE)) + return new SqlDerivedTable(inner, source.alias) + } + + private static SqlTableSource realias(SqlTableSource source, String alias) { + if (source instanceof SqlTableRef) { + return new SqlTableRef(source.tableName, alias) + } + if (source instanceof SqlDerivedTable) { + return new SqlDerivedTable(source.query, alias) + } + throw new GroovyBugError('unknown mixed-mode source ' + source.getClass().name) + } + + private static final class Rel { + SqlTableSource from + final List joins = [] + final List direct = [] + final List output = [] + String container + } + + private static final class LayoutContext { + final List probes = [] + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedTailWalker.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedTailWalker.groovy new file mode 100644 index 00000000000..fb57f06cf9c --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/MixedTailWalker.groovy @@ -0,0 +1,72 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope +import org.apache.groovy.ginq.dsl.expression.JoinExpression +import org.apache.groovy.ginq.provider.collection.GinqAstWalker +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.apache.groovy.ginq.provider.sql.runtime.SqlGinqRuntime +import org.codehaus.groovy.GroovyBugError +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.ClassNode +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.ast.expr.MethodCallExpression +import org.codehaus.groovy.control.SourceUnit + +import static org.codehaus.groovy.ast.tools.GeneralUtils.args +import static org.codehaus.groovy.ast.tools.GeneralUtils.callX +import static org.codehaus.groovy.ast.tools.GeneralUtils.classX + +/** + * Runs the in-memory tail of a mixed-mode query. A join that the database + * already aligned is paired by index, so a null alias stays null. Every + * other clause is the collection provider's. + */ +@CompileStatic +@PackageScope +class MixedTailWalker extends GinqAstWalker { + + MixedTailWalker(SourceUnit sourceUnit) { + super(sourceUnit) + } + + @Override + MethodCallExpression visitJoinExpression(JoinExpression joinExpression) { + if (!Boolean.TRUE.equals(joinExpression.getNodeMetaData(GinqToSqlTranslator.INDEX_ALIGNED_JOIN))) { + return super.visitJoinExpression(joinExpression) + } + Expression receiver = (Expression) joinExpression.getNodeMetaData(METHOD_CALL_RECEIVER) + if (receiver == null) { + throw new GroovyBugError('index-aligned join has no receiver') + } + MethodCallExpression right = callX(classX(QUERYABLE_TYPE), 'from', args(joinExpression.dataSourceExpr)) + MethodCallExpression zip = callX(classX(SQL_GINQ_RUNTIME_TYPE), 'indexZip', args(receiver, right)) + zip.setSourcePosition(joinExpression) + return zip + } + + /** + * Same metadata key {@code GinqAstWalker} stores the current receiver under. + */ + private static final String METHOD_CALL_RECEIVER = '__METHOD_CALL_RECEIVER' + private static final ClassNode QUERYABLE_TYPE = ClassHelper.makeCached(Queryable) + private static final ClassNode SQL_GINQ_RUNTIME_TYPE = ClassHelper.makeCached(SqlGinqRuntime) +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/NativeSqlGinqProvider.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/NativeSqlGinqProvider.java new file mode 100644 index 00000000000..a7d46f3c063 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/NativeSqlGinqProvider.java @@ -0,0 +1,73 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql; + +import org.apache.groovy.ginq.provider.GinqProvider; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.List; + +/** + * Registers the dependency-free {@code native-sql} GINQ provider. + * + * @since 7.0.0 + */ +@Incubating +public class NativeSqlGinqProvider implements GinqProvider { + /** + * Opt-in switch for mixed-mode execution. Absent or {@code false} keeps + * strict mode: an untranslatable construct is a compile error. + * {@code true} pushes the translatable clause prefix to the database and + * finishes the rest in memory. + */ + public static final String CONF_MIXED_MODE = "mixedMode"; + + /** + * Names a built-in native dialect ({@code ansi}, {@code h2}, {@code postgres}, + * {@code mysql}, {@code mariadb}, {@code sqlite}). Absent means ANSI. + * Other databases use the {@code jooq-sql} provider. + */ + public static final String CONF_DIALECT = "dialect"; + + @Override + public String getName() { + return "native-sql"; + } + + @Override + public String getAstWalkerClassName() { + return "org.apache.groovy.ginq.provider.sql.GinqSqlWalker"; + } + + @Override + public List getAdditionalOptionNames() { + return List.of(CONF_MIXED_MODE, CONF_DIALECT); + } + + /** + * {@code native-sql} needs {@code groovy-sql} and nothing from jOOQ. + */ + @Override + public String unavailableReason(ClassLoader loader) { + if (GinqProvider.canLoad(loader, "groovy.sql.Sql")) { + return null; + } + return "the native-sql provider requires org.apache.groovy:groovy-sql on the compile classpath"; + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlCapabilities.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlCapabilities.java new file mode 100644 index 00000000000..2e05730d417 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlCapabilities.java @@ -0,0 +1,79 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql; + +import org.apache.groovy.lang.annotation.Incubating; + +/** + * The dialect facts the translator needs while it is still deciding which + * clauses can become SQL. Rendering stays on the dialect; this only answers + * whether a function may be pushed down. + * + * @since 7.0.0 + */ +@Incubating +public final class SqlCapabilities { + private final String dialectName; + + private SqlCapabilities(String dialectName) { + this.dialectName = dialectName; + } + + /** + * Capabilities for the configured dialect name. A null or empty name is ANSI. + * + * @param dialectName the {@code dialect} option, a jOOQ {@code SQLDialect} name, or {@code null} + * @return the capabilities + */ + public static SqlCapabilities of(String dialectName) { + return new SqlCapabilities(FunctionSupport.canonical(dialectName)); + } + + /** + * Whether an ANSI function may be emitted for this dialect. + * + * @param ansiName the function name + * @return {@code false} when the dialect cannot render it + */ + public boolean supportsFunction(String ansiName) { + return FunctionSupport.supports(dialectName, ansiName); + } + + /** + * Whether the dialect can spell {@code FULL OUTER JOIN}. H2, MySQL and + * MariaDB cannot. An omitted dialect is ANSI, and ANSI does not either: + * the engine is unknown, and the nested union is valid both where + * {@code FULL OUTER JOIN} exists and where it does not. PostgreSQL, + * SQLite and other named dialects keep the native join. + * + * @return {@code false} when full joins must be emulated + */ + public boolean supportsFullOuterJoin() { + return !"h2".equals(dialectName) && !"mysql".equals(dialectName) && !"ansi".equals(dialectName); + } + + /** + * The dialect family, for diagnostics. + * + * @return the canonical dialect name + */ + public String dialectName() { + return dialectName; + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionMapping.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionMapping.groovy new file mode 100644 index 00000000000..1b0b492a36b --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionMapping.groovy @@ -0,0 +1,357 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import groovy.transform.PackageScope +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlCastTypes +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.ast.expr.MethodCallExpression + +/** + * One Groovy method or function and the SQL it becomes. + *

+ * A function whose SQL is {@code NAME(receiver, args...)} or + * {@code NAME(args...)} is a {@link #receiver}, {@link #freeFunction} or + * {@link #math} entry. Adding one does not require a change to the + * translator. Shapes that are not a plain call ({@code cast}, + * {@code indexOf}, {@code concat}, {@code isEmpty}, {@code substring}, + * {@code contains}) are still registry entries; a further shape is a new + * shape constant and a branch in {@link #translate}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +final class SqlFunctionMapping { + /** + * Where the Groovy call sits. + */ + enum Kind { + /** A method on a value, e.g. {@code e.name.toUpperCase()}. */ + RECEIVER, + /** An implicit-this call, e.g. {@code coalesce(a, b)}. */ + FREE, + /** A static call on {@code java.lang.Math}, e.g. {@code Math.max(a, b)}. */ + MATH + } + + private enum Shape { + SQL_FUNCTION, CONCAT, IS_EMPTY, SUBSTRING, LIKE, INDEX_OF, CAST + } + + final String groovyName + final Kind kind + /** ANSI function name for {@link Shape#SQL_FUNCTION}, otherwise {@code null}. */ + final String sqlName + + private final Shape shape + private final int minArgs + private final int maxArgs + private final String arityMessage + private final boolean matchBefore + private final boolean matchAfter + + private SqlFunctionMapping(String groovyName, Kind kind, Shape shape, String sqlName, + int minArgs, int maxArgs, String arityMessage, + boolean matchBefore, boolean matchAfter) { + this.groovyName = groovyName + this.kind = kind + this.shape = shape + this.sqlName = sqlName + this.minArgs = minArgs + this.maxArgs = maxArgs + this.arityMessage = arityMessage + this.matchBefore = matchBefore + this.matchAfter = matchAfter + } + + /** + * A receiver method with no arguments, e.g. {@code toUpperCase} to {@code UPPER}. + * + * @param groovyName the Groovy method name + * @param sqlName the ANSI function name + * @return the mapping + */ + static SqlFunctionMapping receiver(String groovyName, String sqlName) { + return receiver(groovyName, sqlName, 0, 0, null) + } + + /** + * A receiver method with a fixed number of arguments, e.g. {@code replace}. + * + * @param groovyName the Groovy method name + * @param sqlName the ANSI function name + * @param arguments how many arguments the method takes + * @return the mapping + */ + static SqlFunctionMapping receiver(String groovyName, String sqlName, int arguments) { + return receiver(groovyName, sqlName, arguments, arguments, null) + } + + /** + * A receiver method with an argument range, e.g. {@code round} with 0 or 1. + * + * @param groovyName the Groovy method name + * @param sqlName the ANSI function name + * @param minArgs minimum argument count + * @param maxArgs maximum argument count + * @return the mapping + */ + static SqlFunctionMapping receiver(String groovyName, String sqlName, int minArgs, int maxArgs) { + return receiver(groovyName, sqlName, minArgs, maxArgs, null) + } + + /** + * An implicit-this function, e.g. {@code coalesce}. + * + * @param groovyName the Groovy function name + * @param sqlName the ANSI function name + * @param minArgs minimum argument count + * @param maxArgs maximum argument count + * @return the mapping + */ + static SqlFunctionMapping freeFunction(String groovyName, String sqlName, int minArgs, int maxArgs) { + return freeFunction(groovyName, sqlName, minArgs, maxArgs, null) + } + + /** + * A two-argument {@code java.lang.Math} method, e.g. {@code max} to {@code GREATEST}. + * + * @param groovyName the method name without the {@code Math.} receiver + * @param sqlName the ANSI function name + * @return the mapping + */ + static SqlFunctionMapping math(String groovyName, String sqlName) { + return math(groovyName, sqlName, null) + } + + @PackageScope + static SqlFunctionMapping receiver(String groovyName, String sqlName, int minArgs, int maxArgs, String arityMessage) { + checkMethod(groovyName) + checkSql(sqlName) + checkRange(minArgs, maxArgs) + return new SqlFunctionMapping(groovyName, Kind.RECEIVER, Shape.SQL_FUNCTION, sqlName, + minArgs, maxArgs, arityMessage, false, false) + } + + @PackageScope + static SqlFunctionMapping freeFunction(String groovyName, String sqlName, int minArgs, int maxArgs, String arityMessage) { + checkMethod(groovyName) + checkSql(sqlName) + checkRange(minArgs, maxArgs) + return new SqlFunctionMapping(groovyName, Kind.FREE, Shape.SQL_FUNCTION, sqlName, + minArgs, maxArgs, arityMessage, false, false) + } + + @PackageScope + static SqlFunctionMapping math(String groovyName, String sqlName, String arityMessage) { + checkMethod(groovyName) + checkSql(sqlName) + return new SqlFunctionMapping(groovyName, Kind.MATH, Shape.SQL_FUNCTION, sqlName, + 2, 2, arityMessage, false, false) + } + + @PackageScope + static SqlFunctionMapping concat() { + return new SqlFunctionMapping('concat', Kind.RECEIVER, Shape.CONCAT, null, 1, 1, null, false, false) + } + + @PackageScope + static SqlFunctionMapping isEmpty() { + return new SqlFunctionMapping('isEmpty', Kind.RECEIVER, Shape.IS_EMPTY, null, 0, 0, null, false, false) + } + + @PackageScope + static SqlFunctionMapping substring() { + return new SqlFunctionMapping('substring', Kind.RECEIVER, Shape.SUBSTRING, null, 1, 2, null, false, false) + } + + @PackageScope + static SqlFunctionMapping like(String groovyName, boolean matchBefore, boolean matchAfter) { + checkMethod(groovyName) + return new SqlFunctionMapping(groovyName, Kind.RECEIVER, Shape.LIKE, null, 1, 1, null, matchBefore, matchAfter) + } + + @PackageScope + static SqlFunctionMapping indexOf() { + return new SqlFunctionMapping('indexOf', Kind.RECEIVER, Shape.INDEX_OF, null, 1, 1, null, false, false) + } + + @PackageScope + static SqlFunctionMapping cast() { + return new SqlFunctionMapping('cast', Kind.FREE, Shape.CAST, null, 2, 2, null, false, false) + } + + /** + * Translates the call. A wrong arity or an illegal {@code cast} type + * is reported through {@code site} and yields {@code null}. + * + * @param call the Groovy call + * @param args its arguments + * @param site translator operations + * @return the SQL IR, or {@code null} when the call was rejected + */ + SqlExpr translate(MethodCallExpression call, List args, SqlFunctionSite site) { + switch (shape) { + case Shape.LIKE: + return site.like(call, args, matchBefore, matchAfter) + case Shape.SUBSTRING: + return site.substring(call, args) + case Shape.CONCAT: + return concat(call, args, site) + case Shape.IS_EMPTY: + return isEmpty(call, args, site) + case Shape.INDEX_OF: + return indexOf(call, args, site) + case Shape.CAST: + return cast(call, args, site) + default: + return sqlFunction(call, args, site) + } + } + + private SqlExpr sqlFunction(MethodCallExpression call, List args, SqlFunctionSite site) { + if (args.size() < minArgs || args.size() > maxArgs) { + site.fail(wrongArity(), call) + return null + } + List sqlArgs = new ArrayList() + if (kind == Kind.RECEIVER) { + sqlArgs.add(site.expr(call.objectExpression)) + } + for (Expression arg : args) { + sqlArgs.add(site.expr(arg)) + } + return site.function(sqlName, sqlArgs, call) + } + + private SqlExpr concat(MethodCallExpression call, List args, SqlFunctionSite site) { + if (args.size() != 1) { + site.fail('`concat` expects one argument', call) + return null + } + return new SqlBinary('||', site.expr(call.objectExpression), site.expr(args.get(0))) + } + + private SqlExpr isEmpty(MethodCallExpression call, List args, SqlFunctionSite site) { + if (args) { + site.fail('`isEmpty` takes no arguments', call) + return null + } + SqlExpr length = site.function('CHAR_LENGTH', [site.expr(call.objectExpression)], call) + if (length == null) return null + return new SqlBinary('=', length, new SqlLiteral(0)) + } + + // POSITION/LOCATE/INSTR are 1-based and return 0 when absent. Subtracting 1 + // matches Groovy indexOf: the first character is 0, and absence is -1. + private SqlExpr indexOf(MethodCallExpression call, List args, SqlFunctionSite site) { + if (args.size() != 1) { + site.fail('`indexOf` expects one argument, the text to search for. A from-index has no portable SQL form', call) + return null + } + SqlExpr needle = site.expr(args.get(0)) + SqlExpr haystack = site.expr(call.objectExpression) + SqlExpr position = site.function('POSITION', [needle, haystack], call) + if (position == null) return null + return new SqlBinary('-', position, new SqlLiteral(1)) + } + + private SqlExpr cast(MethodCallExpression call, List args, SqlFunctionSite site) { + if (args.size() != 2) { + site.fail("`cast` expects an expression and a SQL type name, e.g. `cast(e.qty, 'DECIMAL')`", call) + return null + } + Expression typeExpr = args.get(1) + if (!(typeExpr instanceof ConstantExpression) || !(((ConstantExpression) typeExpr).value instanceof String)) { + site.fail("`cast` requires a string literal SQL type, e.g. 'DECIMAL' or 'VARCHAR(20)'. A variable type name is not translated", call) + return null + } + String raw = (String) ((ConstantExpression) typeExpr).value + String canonical = SqlCastTypes.canonical(raw) + if (canonical == null) { + site.fail("`cast` type `${raw}` is not a supported SQL type", call) + return null + } + return new SqlCast(site.expr(args.get(0)), canonical) + } + + private String wrongArity() { + if (arityMessage != null) return arityMessage + if (minArgs == 0 && maxArgs == 0) { + return "`${groovyName}()` is translated only with no arguments; extra arguments have no faithful SQL equivalent" + } + if (minArgs == maxArgs) { + return "`${groovyName}` expects ${minArgs == 1 ? 'one argument' : minArgs + ' arguments'}" + } + if (maxArgs == Integer.MAX_VALUE) { + return "`${groovyName}` expects at least ${minArgs} arguments" + } + return "`${groovyName}` expects ${minArgs} to ${maxArgs} arguments" + } + + private static void checkMethod(String name) { + if (!identifier(name, true)) { + throw new IllegalArgumentException("Groovy method name `${name}` is not an identifier") + } + } + + private static void checkSql(String name) { + if (!identifier(name, false)) { + throw new IllegalArgumentException("SQL function name `${name}` must be an uppercase identifier") + } + } + + private static void checkRange(int minArgs, int maxArgs) { + if (minArgs < 0 || maxArgs < minArgs) { + throw new IllegalArgumentException("argument range ${minArgs}..${maxArgs} is not valid") + } + } + + private static boolean identifier(String name, boolean groovyName) { + if (!name) return false + for (int i = 0; i < name.length(); i++) { + char ch = name.charAt(i) + // char literals are Strings under static compilation + boolean upper = ch >= 65 && ch <= 90 + boolean lower = ch >= 97 && ch <= 122 + boolean digit = ch >= 48 && ch <= 57 + boolean underscore = ch == 95 + if (i == 0) { + if (groovyName) { + if (!(upper || lower || underscore)) return false + } else if (!upper) { + return false + } + } else if (groovyName) { + if (!(upper || lower || digit || underscore)) return false + } else if (!(upper || digit || underscore)) { + return false + } + } + return true + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistry.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistry.groovy new file mode 100644 index 00000000000..b758b820350 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistry.groovy @@ -0,0 +1,145 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Maps Groovy method and function names onto SQL function shapes. + *

+ * {@link #standard()} is the sealed set the translator uses. A new uniform + * function is one {@link #register} line here (or on a {@link #copy()} for a + * caller that is not the built-in set). Unknown names are not registered, so + * the translator keeps rejecting them. Aggregates ({@code count}, {@code sum}, + * {@code avg}, {@code min}, {@code max}, including {@code count(distinct)}) + * stay on the aggregate path: {@code min} and {@code max} there are aggregates, + * while {@code Math.min} and {@code Math.max} are the entries in this registry. + *

+ * Not registered, because the SQL function is not faithful to Groovy: + * {@code padLeft} and {@code padRight} ({@code LPAD} and {@code RPAD} truncate + * when the value is already longer; Groovy does not), and {@code Math.signum} + * ({@code SIGN}'s numeric type differs by dialect). + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +final class SqlFunctionRegistry { + private final Map mappings = new LinkedHashMap() + private boolean sealed + + private SqlFunctionRegistry() { + } + + /** + * The built-in scalar mappings. The instance is sealed. + * + * @return the standard registry + */ + static SqlFunctionRegistry standard() { + return STANDARD + } + + /** + * A mutable copy. Registering on the copy does not change {@link #standard()}. + * + * @return an unsealed copy of these mappings + */ + SqlFunctionRegistry copy() { + SqlFunctionRegistry copy = new SqlFunctionRegistry() + copy.mappings.putAll(mappings) + return copy + } + + /** + * Adds a mapping. The built-in registry refuses further registration. + * Registering the same Groovy name and {@link SqlFunctionMapping.Kind} twice + * is an error, so a built-in is not silently replaced. + * + * @param mapping the mapping to add + */ + void register(SqlFunctionMapping mapping) { + if (sealed) { + throw new IllegalStateException('the built-in SQL function registry is sealed; copy() it to add a function') + } + if (mapping == null) { + throw new IllegalArgumentException('mapping is required') + } + String key = key(mapping.kind, mapping.groovyName) + if (mappings.containsKey(key)) { + throw new IllegalArgumentException("SQL function `${mapping.groovyName}` is already registered for ${mapping.kind}") + } + mappings.put(key, mapping) + } + + /** + * Looks up a mapping. + * + * @param groovyName the method or function name, without a receiver + * @param kind where the call sits + * @return the mapping, or {@code null} when nothing is registered + */ + SqlFunctionMapping find(String groovyName, SqlFunctionMapping.Kind kind) { + if (groovyName == null || kind == null) return null + return mappings.get(key(kind, groovyName)) + } + + private void seal() { + sealed = true + } + + private static String key(SqlFunctionMapping.Kind kind, String groovyName) { + return kind.name() + ':' + groovyName + } + + private static final SqlFunctionRegistry STANDARD = builtin() + + private static SqlFunctionRegistry builtin() { + SqlFunctionRegistry registry = new SqlFunctionRegistry() + registry.register(SqlFunctionMapping.receiver('toUpperCase', 'UPPER')) + registry.register(SqlFunctionMapping.receiver('toLowerCase', 'LOWER')) + registry.register(SqlFunctionMapping.receiver('trim', 'TRIM')) + registry.register(SqlFunctionMapping.receiver('length', 'CHAR_LENGTH')) + registry.register(SqlFunctionMapping.receiver('size', 'CHAR_LENGTH')) + registry.register(SqlFunctionMapping.receiver('abs', 'ABS')) + registry.register(SqlFunctionMapping.receiver('floor', 'FLOOR')) + registry.register(SqlFunctionMapping.receiver('ceil', 'CEILING')) + registry.register(SqlFunctionMapping.receiver('round', 'ROUND', 0, 1, + '`round` expects no arguments, or one scale argument')) + registry.register(SqlFunctionMapping.receiver('replace', 'REPLACE', 2, 2, + '`replace` expects two arguments, the search text and its replacement')) + registry.register(SqlFunctionMapping.concat()) + registry.register(SqlFunctionMapping.isEmpty()) + registry.register(SqlFunctionMapping.substring()) + registry.register(SqlFunctionMapping.like('contains', true, true)) + registry.register(SqlFunctionMapping.like('startsWith', false, true)) + registry.register(SqlFunctionMapping.like('endsWith', true, false)) + registry.register(SqlFunctionMapping.freeFunction('coalesce', 'COALESCE', 2, Integer.MAX_VALUE, + '`coalesce` expects at least two arguments')) + registry.register(SqlFunctionMapping.math('max', 'GREATEST', + '`Math.max` and `Math.min` expect two arguments')) + registry.register(SqlFunctionMapping.math('min', 'LEAST', + '`Math.max` and `Math.min` expect two arguments')) + registry.register(SqlFunctionMapping.cast()) + registry.register(SqlFunctionMapping.indexOf()) + registry.seal() + return registry + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionSite.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionSite.groovy new file mode 100644 index 00000000000..c20b5cc00f3 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionSite.groovy @@ -0,0 +1,87 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.ast.ASTNode +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.ast.expr.MethodCallExpression + +/** + * Operations a {@link SqlFunctionMapping} needs from the query translator. + * Shapes that are not a plain SQL function call — {@code LIKE}, and + * {@code SUBSTRING} with Groovy's 0-based indexes — are translated here + * so the mapping stays a registry entry. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +interface SqlFunctionSite { + /** + * Translates a sub-expression. + * + * @param expression the GINQ expression + * @return its SQL IR, or {@code null} when translation recorded an error + */ + SqlExpr expr(Expression expression) + + /** + * Records a compile-time rejection. In mixed mode this raises + * {@link Untranslatable} so the clause can run in memory. + * + * @param message the diagnostic, without the mixed-mode hint + * @param node the AST node to highlight + */ + void fail(String message, ASTNode node) + + /** + * Translates {@code contains}, {@code startsWith} or {@code endsWith}. + * + * @param call the method call + * @param args the arguments + * @param matchBefore whether the pattern may match before the text + * @param matchAfter whether the pattern may match after the text + * @return the {@code LIKE} expression, or {@code null} when rejected + */ + SqlExpr like(MethodCallExpression call, List args, boolean matchBefore, boolean matchAfter) + + /** + * Translates {@code substring}, shifting Groovy's 0-based indexes. + * + * @param call the method call + * @param args the arguments + * @return the {@code SUBSTRING} expression, or {@code null} when rejected + */ + SqlExpr substring(MethodCallExpression call, List args) + + /** + * A plain SQL function. The site checks that the active dialect can + * render {@code ansiName} and rejects the call when it cannot, so mixed + * mode can keep the clause in memory. + * + * @param ansiName the ANSI function name + * @param args the already translated arguments, receiver first when there is one + * @param node the call to highlight + * @return the function, or {@code null} when the dialect cannot render it + */ + SqlExpr function(String ansiName, List args, ASTNode node) +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/Untranslatable.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/Untranslatable.java new file mode 100644 index 00000000000..76f522aa08a --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/Untranslatable.java @@ -0,0 +1,41 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql; + +import org.apache.groovy.lang.annotation.Incubating; +import org.codehaus.groovy.ast.ASTNode; + +/** + * Signals that a GINQ construct has no SQL translation. In strict mode this + * becomes a compile error; in mixed mode the planner catches it and moves the + * enclosing clause to in-memory execution. + */ +@Incubating +final class Untranslatable extends RuntimeException { + private final ASTNode node; + + Untranslatable(String message, ASTNode node) { + super(message); + this.node = node; + } + + ASTNode getNode() { + return node; + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlBinary.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlBinary.groovy new file mode 100644 index 00000000000..08e760b0166 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlBinary.groovy @@ -0,0 +1,42 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a binary operation with a SQL operator, e.g. + * {@code =}, {@code <>}, {@code AND}, {@code OR}, {@code +}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlBinary extends SqlExpr { + final String op + final SqlExpr left + final SqlExpr right + + SqlBinary(String op, SqlExpr left, SqlExpr right) { + this.op = op + this.left = left + this.right = right + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCaseWhen.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCaseWhen.groovy new file mode 100644 index 00000000000..7a6e9b636cb --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCaseWhen.groovy @@ -0,0 +1,42 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a searched {@code CASE WHEN ... THEN ... ELSE ... END} expression, + * the translation of a ternary expression. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlCaseWhen extends SqlExpr { + final SqlExpr condition + final SqlExpr thenExpr + final SqlExpr elseExpr + + SqlCaseWhen(SqlExpr condition, SqlExpr thenExpr, SqlExpr elseExpr) { + this.condition = condition + this.thenExpr = thenExpr + this.elseExpr = elseExpr + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCast.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCast.groovy new file mode 100644 index 00000000000..4f571b88053 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCast.groovy @@ -0,0 +1,45 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents {@code CAST(expr AS sqlType)}. {@code sqlType} is a canonical + * type from {@link SqlCastTypes}, never a bound parameter or an arbitrary + * fragment of SQL. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlCast extends SqlExpr { + final SqlExpr expr + final String sqlType + + SqlCast(SqlExpr expr, String sqlType) { + String canonical = SqlCastTypes.canonical(sqlType) + if (canonical == null) { + throw new IllegalArgumentException('Unsupported SQL cast type: ' + sqlType) + } + this.expr = expr + this.sqlType = canonical + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCastTypes.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCastTypes.groovy new file mode 100644 index 00000000000..293a6cc2aec --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCastTypes.groovy @@ -0,0 +1,125 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +import java.util.Locale + +/** + * Whitelist of SQL types accepted by {@code cast(expr, 'TYPE')}. + * The canonical form is safe to splice into SQL text: letters, digits, + * spaces, parentheses and one comma, with no quotes or other punctuation. + *

+ * A length applies to character and binary types ({@code VARCHAR(20)}). + * A precision, and an optional scale, apply to {@code DECIMAL} and + * {@code NUMERIC} ({@code DECIMAL(10,2)}). Other parameterized forms, + * including {@code INT(11)} and {@code TIMESTAMP(6)}, are rejected. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +final class SqlCastTypes { + static final int MAX_LENGTH = 1_000_000 + static final int MAX_PRECISION = 1000 + + private static final Set BARE = names( + 'BOOLEAN', 'TINYINT', 'SMALLINT', 'INTEGER', 'INT', 'BIGINT', + 'REAL', 'FLOAT', 'DOUBLE', 'DOUBLE PRECISION', + 'DECIMAL', 'NUMERIC', + 'CHAR', 'CHARACTER', 'VARCHAR', 'CHARACTER VARYING', + 'DATE', 'TIME', 'TIMESTAMP', + 'CLOB', 'BLOB', 'BINARY', 'VARBINARY') + private static final Set LENGTH = names( + 'CHAR', 'CHARACTER', 'VARCHAR', 'CHARACTER VARYING', 'BINARY', 'VARBINARY') + private static final Set PRECISION = names('DECIMAL', 'NUMERIC') + + private SqlCastTypes() { + } + + /** + * Returns the canonical spelling of {@code raw}, or {@code null} when + * it is not in the whitelist. + * + * @param raw the type text from the query, still in its source spelling + * @return canonical SQL type text, or {@code null} + */ + static String canonical(String raw) { + if (raw == null) return null + String compact = raw.trim().replaceAll('\\s+', ' ').toUpperCase(Locale.ROOT) + if (!compact) return null + if (BARE.contains(compact)) return compact + + int open = compact.indexOf('(') + if (open <= 0 || !compact.endsWith(')')) return null + String name = compact.substring(0, open).trim() + String inner = compact.substring(open + 1, compact.length() - 1).trim() + if (!name || inner.isEmpty() || inner.indexOf('(') >= 0 || inner.indexOf(')') >= 0) return null + + List parts = new ArrayList() + for (String part : inner.split(',', -1)) { + String piece = part.trim() + if (!digits(piece)) return null + parts.add(piece) + } + if (parts.size() == 1 && LENGTH.contains(name)) { + int length = bounded(parts.get(0), 1, MAX_LENGTH) + if (length < 0) return null + return name + '(' + length + ')' + } + if (PRECISION.contains(name) && (parts.size() == 1 || parts.size() == 2)) { + int precision = bounded(parts.get(0), 1, MAX_PRECISION) + if (precision < 0) return null + if (parts.size() == 1) return name + '(' + precision + ')' + int scale = bounded(parts.get(1), 0, precision) + if (scale < 0) return null + return name + '(' + precision + ',' + scale + ')' + } + return null + } + + private static Set names(String... values) { + Set set = new LinkedHashSet() + Collections.addAll(set, values) + return Collections.unmodifiableSet(set) + } + + private static boolean digits(String piece) { + if (!piece) return false + for (int i = 0; i < piece.length(); i++) { + char ch = piece.charAt(i) + // char literals are Strings under static compilation + if (ch < 48 || ch > 57) return false + } + return true + } + + private static int bounded(String digits, int min, int max) { + long value + try { + value = Long.parseLong(digits) + } catch (NumberFormatException ignored) { + return -1 + } + if (value < min || value > max) return -1 + return (int) value + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlColumn.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlColumn.groovy new file mode 100644 index 00000000000..81d08c802f4 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlColumn.groovy @@ -0,0 +1,39 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a column reference, optionally qualified by a table alias. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlColumn extends SqlExpr { + final String tableAlias + final String column + + SqlColumn(String tableAlias, String column) { + this.tableAlias = tableAlias + this.column = column + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCountStar.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCountStar.groovy new file mode 100644 index 00000000000..3e37b316332 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlCountStar.groovy @@ -0,0 +1,32 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents {@code COUNT(*)}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlCountStar extends SqlExpr { +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlDerivedTable.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlDerivedTable.groovy new file mode 100644 index 00000000000..5c2a25b00ca --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlDerivedTable.groovy @@ -0,0 +1,40 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an aliased derived table, i.e. a parenthesized subquery + * in a {@code FROM} or join clause. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlDerivedTable implements SqlTableSource { + final SqlQueryNode query + final String alias + + SqlDerivedTable(SqlQueryNode query, String alias) { + this.query = query + this.alias = alias + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlExists.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlExists.groovy new file mode 100644 index 00000000000..65ba552149d --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlExists.groovy @@ -0,0 +1,37 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an {@code EXISTS (subquery)} test. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlExists extends SqlExpr { + final SqlQuery query + + SqlExists(SqlQuery query) { + this.query = query + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlExpr.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlExpr.groovy new file mode 100644 index 00000000000..ca5eca80fbd --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlExpr.groovy @@ -0,0 +1,33 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a SQL expression, i.e. anything usable in a select list, + * predicate, grouping key or ordering key. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +abstract class SqlExpr { +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlFunction.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlFunction.groovy new file mode 100644 index 00000000000..01ad1cc62de --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlFunction.groovy @@ -0,0 +1,48 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a function call by its ANSI name, e.g. {@code UPPER} or an + * aggregate such as {@code SUM}. Dialects may map the name when rendering. + * When {@code distinct} is set, the call is an aggregate + * {@code COUNT(DISTINCT ...)}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlFunction extends SqlExpr { + final String name + final List args + final boolean distinct + + SqlFunction(String name, List args) { + this(name, args, false) + } + + SqlFunction(String name, List args, boolean distinct) { + this.name = name + this.args = args + this.distinct = distinct + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlIn.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlIn.groovy new file mode 100644 index 00000000000..61ecd665b03 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlIn.groovy @@ -0,0 +1,41 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an {@code IN} or {@code NOT IN} test against a fixed-size value list. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlIn extends SqlExpr { + final SqlExpr expr + final List values + final boolean negated + + SqlIn(SqlExpr expr, List values, boolean negated = false) { + this.expr = expr + this.values = values + this.negated = negated + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlInQuery.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlInQuery.groovy new file mode 100644 index 00000000000..1838bd43ba7 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlInQuery.groovy @@ -0,0 +1,41 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an {@code IN} or {@code NOT IN} test against a subquery. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlInQuery extends SqlExpr { + final SqlExpr expr + final SqlQuery query + final boolean negated + + SqlInQuery(SqlExpr expr, SqlQuery query, boolean negated) { + this.expr = expr + this.query = query + this.negated = negated + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlIsNull.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlIsNull.groovy new file mode 100644 index 00000000000..65fc937250b --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlIsNull.groovy @@ -0,0 +1,39 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an {@code IS NULL} or {@code IS NOT NULL} test. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlIsNull extends SqlExpr { + final SqlExpr expr + final boolean negated + + SqlIsNull(SqlExpr expr, boolean negated) { + this.expr = expr + this.negated = negated + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlJoin.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlJoin.groovy new file mode 100644 index 00000000000..0b9fb55a9e4 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlJoin.groovy @@ -0,0 +1,56 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a SQL join clause. The {@code on} condition is {@code null} + * for cross joins only. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlJoin { + final Type type + final SqlTableSource table + final SqlExpr on + + SqlJoin(Type type, SqlTableSource table, SqlExpr on) { + this.type = type + this.table = table + this.on = on + } + + enum Type { + INNER('INNER JOIN'), + LEFT('LEFT JOIN'), + RIGHT('RIGHT JOIN'), + FULL('FULL OUTER JOIN'), + CROSS('CROSS JOIN') + + final String sqlText + + Type(String sqlText) { + this.sqlText = sqlText + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlLike.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlLike.groovy new file mode 100644 index 00000000000..a6428c57e09 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlLike.groovy @@ -0,0 +1,40 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a {@code LIKE} test. The pattern is always rendered with + * {@code ESCAPE '!'}; pattern values are escaped accordingly at runtime. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlLike extends SqlExpr { + final SqlExpr expr + final SqlExpr pattern + + SqlLike(SqlExpr expr, SqlExpr pattern) { + this.expr = expr + this.pattern = pattern + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlLiteral.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlLiteral.groovy new file mode 100644 index 00000000000..04c96f979db --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlLiteral.groovy @@ -0,0 +1,40 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an inline SQL literal. Only ever constructed from compile-time + * constants appearing in the query source, never from runtime values, so + * parameter safety is preserved. Used where databases require a typed value + * for inference, e.g. {@code CASE} branches. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlLiteral extends SqlExpr { + final Object value + + SqlLiteral(Object value) { + this.value = value + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlOrderSpec.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlOrderSpec.groovy new file mode 100644 index 00000000000..53da2c66302 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlOrderSpec.groovy @@ -0,0 +1,42 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an {@code ORDER BY} item. Null ordering is always rendered + * explicitly since the GINQ default (nulls last) differs from some databases. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlOrderSpec { + final SqlExpr expr + final boolean asc + final boolean nullsLast + + SqlOrderSpec(SqlExpr expr, boolean asc, boolean nullsLast) { + this.expr = expr + this.asc = asc + this.nullsLast = nullsLast + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlOrdinal.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlOrdinal.groovy new file mode 100644 index 00000000000..2e75abb50a7 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlOrdinal.groovy @@ -0,0 +1,39 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a 1-based select-list ordinal, used for {@code ORDER BY} on a + * set operation result. Rendered inline (not as a parameter) since it is a + * structural position computed at compile time. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlOrdinal extends SqlExpr { + final int position + + SqlOrdinal(int position) { + this.position = position + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlParam.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlParam.groovy new file mode 100644 index 00000000000..8aacc0884be --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlParam.groovy @@ -0,0 +1,41 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.ast.expr.Expression + +/** + * Represents a bound parameter. Every literal and captured variable of the + * GINQ query becomes a {@code SqlParam} holding the original Groovy expression; + * the renderer emits a positional {@code ?} placeholder and collects the + * expressions in emission order, so SQL text never contains user values. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlParam extends SqlExpr { + final Expression valueExpr + + SqlParam(Expression valueExpr) { + this.valueExpr = valueExpr + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlProjection.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlProjection.groovy new file mode 100644 index 00000000000..b96d06b6f11 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlProjection.groovy @@ -0,0 +1,39 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a select-list item with an optional column alias. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlProjection { + final SqlExpr expr + final String alias + + SqlProjection(SqlExpr expr, String alias = null) { + this.expr = expr + this.alias = alias + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlQuery.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlQuery.groovy new file mode 100644 index 00000000000..66bc90293ae --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlQuery.groovy @@ -0,0 +1,50 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a single SQL {@code SELECT} query. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlQuery implements SqlQueryNode { + boolean distinct + final List projections = [] + SqlTableSource from + final List joins = [] + SqlExpr where + final List groupBy = [] + SqlExpr having + final List orderBy = [] + SqlExpr offset + SqlExpr fetch + + /** + * Probes that name the columns of a whole-row projection hidden inside + * an emulated full join. Empty when the query has no such projection. + * The ids match {@code __ginqsrc_}, {@code __ginqpass_}, {@code __ginqstar_} + * and {@code __ginqcol_} in the rendered SQL. + */ + List starProbes +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlQueryNode.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlQueryNode.java new file mode 100644 index 00000000000..bddfe955904 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlQueryNode.java @@ -0,0 +1,31 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir; + +import org.apache.groovy.lang.annotation.Incubating; + +/** + * Marks a renderable top-level query: either a simple {@link SqlQuery} + * or a {@link SqlSetQuery} combining queries with a set operation. + * + * @since 7.0.0 + */ +@Incubating +public interface SqlQueryNode { +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlScalarQuery.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlScalarQuery.groovy new file mode 100644 index 00000000000..17f7d14fda0 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlScalarQuery.groovy @@ -0,0 +1,37 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a parenthesized scalar subquery used as an expression. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlScalarQuery extends SqlExpr { + final SqlQuery query + + SqlScalarQuery(SqlQuery query) { + this.query = query + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlSetQuery.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlSetQuery.groovy new file mode 100644 index 00000000000..67408cd8a3a --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlSetQuery.groovy @@ -0,0 +1,57 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents two queries combined with a SQL set operation. + * The left side may itself be a {@code SqlSetQuery}, mirroring the + * left-nested chaining of GINQ set operations. Ordering and limiting + * apply to the combined result and reference select-list ordinals. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlSetQuery implements SqlQueryNode { + final SqlQueryNode left + final SetOp op + final SqlQuery right + final List orderBy = [] + SqlExpr offset + SqlExpr fetch + + /** + * See {@link SqlQuery#starProbes}. Set on the outermost node when a + * nested operand projects a whole row. + */ + List starProbes + + SqlSetQuery(SqlQueryNode left, SetOp op, SqlQuery right) { + this.left = left + this.op = op + this.right = right + } + + enum SetOp { + UNION, UNION_ALL, INTERSECT, MINUS + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlStar.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlStar.groovy new file mode 100644 index 00000000000..b3b8fbeba67 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlStar.groovy @@ -0,0 +1,37 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents {@code *} or {@code alias.*} in a select list. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlStar extends SqlExpr { + final String tableAlias + + SqlStar(String tableAlias = null) { + this.tableAlias = tableAlias + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlTableRef.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlTableRef.groovy new file mode 100644 index 00000000000..0ca05c99ecd --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlTableRef.groovy @@ -0,0 +1,39 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents an aliased table reference. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlTableRef implements SqlTableSource { + final String tableName + final String alias + + SqlTableRef(String tableName, String alias) { + this.tableName = tableName + this.alias = alias + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlTableSource.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlTableSource.java new file mode 100644 index 00000000000..1c7b4dd500f --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlTableSource.java @@ -0,0 +1,37 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir; + +import org.apache.groovy.lang.annotation.Incubating; + +/** + * Marks an aliased source of rows in a {@code FROM} or join clause: + * either a {@link SqlTableRef} or a {@link SqlDerivedTable}. + * + * @since 7.0.0 + */ +@Incubating +public interface SqlTableSource { + /** + * Returns the source alias. + * + * @return the alias + */ + String getAlias(); +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlUnary.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlUnary.groovy new file mode 100644 index 00000000000..1a342e090fe --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlUnary.groovy @@ -0,0 +1,39 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating + +/** + * Represents a prefix unary operation, e.g. {@code NOT} or {@code -}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlUnary extends SqlExpr { + final String op + final SqlExpr operand + + SqlUnary(String op, SqlExpr operand) { + this.op = op + this.operand = operand + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/package-info.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/package-info.java new file mode 100644 index 00000000000..6be43404172 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/package-info.java @@ -0,0 +1,24 @@ +/* + * 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 + * + * http://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. + */ + +/** + * Intermediate representation for SQL queries derived from GINQ queries: a provider-neutral + * model consumed by renderers. Compile-time only; never present in generated code. + */ +package org.apache.groovy.ginq.provider.sql.ir; diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqRenderer.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqRenderer.groovy new file mode 100644 index 00000000000..df99bd483f6 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqRenderer.groovy @@ -0,0 +1,484 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.jooq + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.sql.FunctionSupport +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCaseWhen +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlCountStar +import org.apache.groovy.ginq.provider.sql.ir.SqlDerivedTable +import org.apache.groovy.ginq.provider.sql.ir.SqlExists +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlIn +import org.apache.groovy.ginq.provider.sql.ir.SqlInQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlIsNull +import org.apache.groovy.ginq.provider.sql.ir.SqlJoin +import org.apache.groovy.ginq.provider.sql.ir.SqlLike +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlOrderSpec +import org.apache.groovy.ginq.provider.sql.ir.SqlOrdinal +import org.apache.groovy.ginq.provider.sql.ir.SqlParam +import org.apache.groovy.ginq.provider.sql.ir.SqlProjection +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.ir.SqlScalarQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlSetQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlStar +import org.apache.groovy.ginq.provider.sql.ir.SqlTableRef +import org.apache.groovy.ginq.provider.sql.ir.SqlTableSource +import org.apache.groovy.ginq.provider.sql.ir.SqlUnary +import org.apache.groovy.ginq.provider.sql.render.RenderedSql +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.GroovyBugError +import org.codehaus.groovy.ast.expr.Expression +import org.jooq.Condition +import org.jooq.DSLContext +import org.jooq.DataType +import org.jooq.Field +import org.jooq.JoinType +import org.jooq.Name +import org.jooq.Param +import org.jooq.SQLDialect +import org.jooq.Select +import org.jooq.SelectFieldOrAsterisk +import org.jooq.SelectQuery +import org.jooq.SortField +import org.jooq.Table +import org.jooq.conf.RenderQuotedNames +import org.jooq.conf.Settings +import org.jooq.impl.DSL +import org.jooq.impl.SQLDataType + +import java.util.regex.Matcher + +/** + * Renders the SQL IR through jOOQ at compile time: the IR is mapped onto + * jOOQ's query model and rendered for the requested {@link SQLDialect} with + * named parameters, which are then converted back to positional {@code ?} + * placeholders so execution is identical to the native provider. + *

+ * The imperative {@link SelectQuery} model API is used with static compilation + * throughout: jOOQ query objects implement {@link Iterable}, so dynamic + * dispatch could select Groovy GDK extension methods, e.g. {@code groupBy}, + * over jOOQ's own. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class JooqRenderer { + private final SQLDialect dialect + private final List paramExpressions = [] + + private JooqRenderer(SQLDialect dialect) { + this.dialect = dialect + } + + static RenderedSql render(SqlQueryNode queryNode, String dialectName) { + return new JooqRenderer(resolveDialect(dialectName)).doRender(queryNode) + } + + /** + * Identifier quote jOOQ uses for {@code __ginq} names in this dialect. + * MySQL and MariaDB use a backtick; the other dialects use a double quote. + */ + static char identifierQuote(String dialectName) { + SQLDialect resolved = resolveDialect(dialectName) + SQLDialect family = resolved.family() + if (SQLDialect.MYSQL == family || SQLDialect.MARIADB == family) { + return '`' as char + } + return '"' as char + } + + private static SQLDialect resolveDialect(String dialectName) { + if (!dialectName) return SQLDialect.DEFAULT + try { + return SQLDialect.valueOf(dialectName.toUpperCase(Locale.ROOT)) + } catch (IllegalArgumentException ignore) { + throw new IllegalArgumentException("Unknown dialect: ${dialectName}. " + + "(supported dialects: ${SQLDialect.values()*.name()})") + } + } + + private RenderedSql doRender(SqlQueryNode queryNode) { + // EXPLICIT_DEFAULT_UNQUOTED leaves ordinary names unquoted (H2 folds them) + // and still quotes names built with DSL.quotedName, which the mixed-mode + // presence column needs. + DSLContext ctx = DSL.using(dialect, new Settings().withRenderQuotedNames(RenderQuotedNames.EXPLICIT_DEFAULT_UNQUOTED)) + Select select = buildQueryNode(ctx, queryNode) + return positionalize(ctx.renderNamedParams(select)) + } + + /** + * Converts jOOQ's named parameter placeholders back to positional {@code ?} + * placeholders, collecting the parameter expressions in placeholder order. + */ + private RenderedSql positionalize(String namedSql) { + List ordered = [] + StringBuilder sb = new StringBuilder() + Matcher m = namedSql =~ /:gqp(\d+)/ + int last = 0 + while (m.find()) { + sb.append(namedSql, last, m.start()).append('?') + ordered << paramExpressions[m.group(1) as int] + last = m.end() + } + sb.append(namedSql, last, namedSql.length()) + return new RenderedSql(sb.toString(), ordered) + } + + private Select buildQueryNode(DSLContext ctx, SqlQueryNode queryNode) { + if (!(queryNode instanceof SqlSetQuery)) { + return buildQuery(ctx, (SqlQuery) queryNode) + } + SqlSetQuery setQuery = (SqlSetQuery) queryNode + Select left = buildQueryNode(ctx, setQuery.left) + Select right = buildQuery(ctx, setQuery.right) + Select combined + switch (setQuery.op) { + case SqlSetQuery.SetOp.UNION: combined = left.union(right); break + case SqlSetQuery.SetOp.UNION_ALL: combined = left.unionAll(right); break + case SqlSetQuery.SetOp.INTERSECT: combined = left.intersect(right); break + case SqlSetQuery.SetOp.MINUS: combined = left.except(right); break + default: throw new GroovyBugError("Unknown set operation: ${setQuery.op}") + } + if (setQuery.orderBy || setQuery.offset != null || setQuery.fetch != null) { + // jOOQ's set operations return the combining query, which accepts the + // trailing ORDER BY/LIMIT of the whole result via the model API + if (!(combined instanceof SelectQuery)) { + throw new GroovyBugError("jOOQ set operation result is not a SelectQuery: ${combined.getClass().name}") + } + SelectQuery combinedQuery = (SelectQuery) combined + for (SqlOrderSpec spec : setQuery.orderBy) { + combinedQuery.addOrderBy(buildSortField(ctx, spec)) + } + if (setQuery.offset != null) combinedQuery.addOffset(limitParam((SqlParam) setQuery.offset)) + if (setQuery.fetch != null) combinedQuery.addLimit(limitParam((SqlParam) setQuery.fetch)) + } + return combined + } + + private SelectQuery buildQuery(DSLContext ctx, SqlQuery query) { + SelectQuery selectQuery = ctx.selectQuery() + for (SqlProjection projection : query.projections) { + selectQuery.addSelect(buildProjection(ctx, projection)) + } + if (query.distinct) selectQuery.setDistinct(true) + selectQuery.addFrom(buildTableSource(ctx, query.from)) + for (SqlJoin join : query.joins) { + Table table = buildTableSource(ctx, join.table) + switch (join.type) { + case SqlJoin.Type.INNER: selectQuery.addJoin(table, JoinType.JOIN, buildCondition(ctx, join.on)); break + case SqlJoin.Type.LEFT: selectQuery.addJoin(table, JoinType.LEFT_OUTER_JOIN, buildCondition(ctx, join.on)); break + case SqlJoin.Type.RIGHT: selectQuery.addJoin(table, JoinType.RIGHT_OUTER_JOIN, buildCondition(ctx, join.on)); break + case SqlJoin.Type.FULL: selectQuery.addJoin(table, JoinType.FULL_OUTER_JOIN, buildCondition(ctx, join.on)); break + case SqlJoin.Type.CROSS: selectQuery.addJoin(table, JoinType.CROSS_JOIN); break + default: throw new GroovyBugError("Unknown join type: ${join.type}") + } + } + if (query.where != null) selectQuery.addConditions(buildCondition(ctx, query.where)) + for (SqlExpr keyExpr : query.groupBy) { + selectQuery.addGroupBy(buildField(ctx, keyExpr)) + } + if (query.having != null) selectQuery.addHaving(buildCondition(ctx, query.having)) + for (SqlOrderSpec spec : query.orderBy) { + selectQuery.addOrderBy(buildSortField(ctx, spec)) + } + if (query.offset != null) selectQuery.addOffset(limitParam((SqlParam) query.offset)) + if (query.fetch != null) selectQuery.addLimit(limitParam((SqlParam) query.fetch)) + return selectQuery + } + + private SelectFieldOrAsterisk buildProjection(DSLContext ctx, SqlProjection projection) { + if (projection.expr instanceof SqlStar) { + SqlStar star = (SqlStar) projection.expr + return star.tableAlias ? DSL.table(sqlName(star.tableAlias)).asterisk() : DSL.asterisk() + } + Field field = buildField(ctx, projection.expr) + return projection.alias ? field.as(sqlName(projection.alias)) : field + } + + private Table buildTableSource(DSLContext ctx, SqlTableSource tableSource) { + if (tableSource instanceof SqlTableRef) { + String[] parts = tableSource.tableName.split('\\.', -1) + return DSL.table(sqlName(parts)).as(sqlName(tableSource.alias)) + } + if (tableSource instanceof SqlDerivedTable) { + Select nested = tableSource.query instanceof SqlQuery + ? buildQuery(ctx, (SqlQuery) tableSource.query) + : buildQueryNode(ctx, tableSource.query) + return nested.asTable(sqlName(tableSource.alias)) + } + throw new GroovyBugError("Unknown table source: ${tableSource?.getClass()?.name}") + } + + private SortField buildSortField(DSLContext ctx, SqlOrderSpec spec) { + Field field = buildField(ctx, spec.expr) + SortField sortField = spec.asc ? field.asc() : field.desc() + return spec.nullsLast ? sortField.nullsLast() : sortField.nullsFirst() + } + + private Condition buildCondition(DSLContext ctx, SqlExpr expr) { + if (expr instanceof SqlBinary) { + switch (expr.op) { + case 'AND': return buildCondition(ctx, expr.left).and(buildCondition(ctx, expr.right)) + case 'OR': return buildCondition(ctx, expr.left).or(buildCondition(ctx, expr.right)) + case '=': return buildField(ctx, expr.left).eq(buildField(ctx, expr.right)) + case '<>': return buildField(ctx, expr.left).ne(buildField(ctx, expr.right)) + case 'IS NOT DISTINCT FROM': return buildField(ctx, expr.left).isNotDistinctFrom(buildField(ctx, expr.right)) + case 'IS DISTINCT FROM': return buildField(ctx, expr.left).isDistinctFrom(buildField(ctx, expr.right)) + case '<': return buildField(ctx, expr.left).lt(buildField(ctx, expr.right)) + case '<=': return buildField(ctx, expr.left).le(buildField(ctx, expr.right)) + case '>': return buildField(ctx, expr.left).gt(buildField(ctx, expr.right)) + case '>=': return buildField(ctx, expr.left).ge(buildField(ctx, expr.right)) + } + } + if (expr instanceof SqlIsNull) { + Field field = buildField(ctx, expr.expr) + return expr.negated ? field.isNotNull() : field.isNull() + } + if (expr instanceof SqlIn) { + Field field = buildField(ctx, expr.expr) + List values = expr.values.collect { SqlExpr e -> buildField(ctx, e) } + return expr.negated ? field.notIn(values) : field.in(values) + } + if (expr instanceof SqlInQuery) { + Field field = buildField(ctx, expr.expr) + Select subQuery = buildQuery(ctx, expr.query) + return expr.negated ? field.notIn(subQuery) : field.in(subQuery) + } + if (expr instanceof SqlLike) { + return buildField(ctx, expr.expr).like(buildField(ctx, expr.pattern)).escape('!' as char) + } + if (expr instanceof SqlExists) { + return DSL.exists(buildQuery(ctx, expr.query)) + } + if (expr instanceof SqlUnary && 'NOT' == expr.op) { + return DSL.not(buildCondition(ctx, expr.operand)) + } + return DSL.condition(buildField(ctx, expr)) + } + + private Field buildField(DSLContext ctx, SqlExpr expr) { + if (expr instanceof SqlColumn) { + return expr.tableAlias ? DSL.field(sqlName(expr.tableAlias, expr.column)) : DSL.field(sqlName(expr.column)) + } + if (expr instanceof SqlParam) { + return registerParam((SqlParam) expr) + } + if (expr instanceof SqlLiteral) { + if (expr.value != null && expr.value.toString().contains(':gqp')) { + throw new IllegalArgumentException("literals containing ':gqp' are not supported by the jooq-sql provider") + } + return DSL.inline(expr.value) + } + if (expr instanceof SqlOrdinal) { + return DSL.inline(expr.position) + } + if (expr instanceof SqlCountStar) { + return DSL.count() + } + if (expr instanceof SqlCast) { + return DSL.cast(buildField(ctx, expr.expr), castDataType(expr.sqlType)) + } + if (expr instanceof SqlFunction) { + return buildFunction(ctx, (SqlFunction) expr) + } + if (expr instanceof SqlCaseWhen) { + return DSL.when(buildCondition(ctx, expr.condition), buildField(ctx, expr.thenExpr)) + .otherwise(buildField(ctx, expr.elseExpr)) + } + if (expr instanceof SqlScalarQuery) { + return DSL.field(buildQuery(ctx, expr.query)) + } + if (expr instanceof SqlBinary) { + switch (expr.op) { + case '+': return buildField(ctx, expr.left).add(buildField(ctx, expr.right)) + case '-': return buildField(ctx, expr.left).sub(buildField(ctx, expr.right)) + case '*': return buildField(ctx, expr.left).mul(buildField(ctx, expr.right)) + case '/': return DSL.cast(buildField(ctx, expr.left), SQLDataType.DOUBLE) + .div(DSL.cast(buildField(ctx, expr.right), SQLDataType.DOUBLE)) + case '||': return DSL.concat(buildField(ctx, expr.left), buildField(ctx, expr.right)) + default: return DSL.field(buildCondition(ctx, expr)) + } + } + if (expr instanceof SqlUnary) { + if ('-' == expr.op) return buildField(ctx, expr.operand).neg() + return DSL.field(buildCondition(ctx, expr)) + } + // condition-shaped expressions used as values + if (expr instanceof SqlIsNull || expr instanceof SqlIn || expr instanceof SqlInQuery + || expr instanceof SqlLike || expr instanceof SqlExists) { + return DSL.field(buildCondition(ctx, expr)) + } + throw new GroovyBugError("Unknown SQL expression: ${expr?.getClass()?.name}") + } + + private Field buildFunction(DSLContext ctx, SqlFunction function) { + if (!FunctionSupport.supports(dialect.name(), function.name)) { + throw new IllegalArgumentException(function.name + + " is not supported by the " + FunctionSupport.canonical(dialect.name()) + + " dialect. Rewrite the query without it, or use a dialect that provides it") + } + List fields = function.args.collect { SqlExpr e -> buildField(ctx, e) } + switch (function.name) { + case 'UPPER': return DSL.upper(fields[0]) + case 'LOWER': return DSL.lower(fields[0]) + case 'TRIM': return DSL.trim(fields[0]) + case 'CHAR_LENGTH': return DSL.charLength(fields[0]) + case 'ABS': return DSL.abs(fields[0]) + case 'FLOOR': return DSL.floor(fields[0]) + case 'CEILING': return DSL.ceil(fields[0]) + case 'ROUND': return fields.size() > 1 ? DSL.round(fields[0], fields[1]) : DSL.round(fields[0]) + case 'MOD': return fields[0].mod(fields[1]) + case 'REPLACE': return DSL.replace(fields[0], fields[1], fields[2]) + case 'SUBSTRING': return fields.size() > 2 + ? DSL.substring(fields[0], fields[1], fields[2]) + : DSL.substring(fields[0], fields[1]) + case 'POSITION': return searchPosition(fields) + case 'COALESCE': return coalesce(fields) + case 'COUNT': return function.distinct ? DSL.countDistinct(fields[0]) : DSL.count(fields[0]) + case 'GREATEST': return extreme(true, fields) + case 'LEAST': return extreme(false, fields) + case 'SUM': return DSL.sum(fields[0]) + case 'AVG': return DSL.avg(fields[0]) + case 'MIN': return DSL.min(fields[0]) + case 'MAX': return DSL.max(fields[0]) + default: return DSL.function(function.name, Object, fields as Field[]) + } + } + + private static DataType castDataType(String sqlType) { + String name = sqlType + Integer length = null + Integer precision = null + Integer scale = null + int open = sqlType.indexOf('(') + if (open >= 0) { + name = sqlType.substring(0, open) + String inner = sqlType.substring(open + 1, sqlType.length() - 1) + String[] parts = inner.split(',') + if (parts.length == 1) { + int n = Integer.parseInt(parts[0]) + if ('DECIMAL' == name || 'NUMERIC' == name) { + precision = Integer.valueOf(n) + } else { + length = Integer.valueOf(n) + } + } else { + precision = Integer.valueOf(Integer.parseInt(parts[0])) + scale = Integer.valueOf(Integer.parseInt(parts[1])) + } + } + DataType type + switch (name) { + case 'BOOLEAN': type = SQLDataType.BOOLEAN; break + case 'TINYINT': type = SQLDataType.TINYINT; break + case 'SMALLINT': type = SQLDataType.SMALLINT; break + case 'INTEGER': + case 'INT': type = SQLDataType.INTEGER; break + case 'BIGINT': type = SQLDataType.BIGINT; break + case 'REAL': type = SQLDataType.REAL; break + case 'FLOAT': type = SQLDataType.FLOAT; break + case 'DOUBLE': + case 'DOUBLE PRECISION': type = SQLDataType.DOUBLE; break + case 'DECIMAL': type = SQLDataType.DECIMAL; break + case 'NUMERIC': type = SQLDataType.NUMERIC; break + case 'CHAR': + case 'CHARACTER': type = SQLDataType.CHAR; break + case 'VARCHAR': + case 'CHARACTER VARYING': type = SQLDataType.VARCHAR; break + case 'DATE': type = SQLDataType.DATE; break + case 'TIME': type = SQLDataType.TIME; break + case 'TIMESTAMP': type = SQLDataType.TIMESTAMP; break + case 'CLOB': type = SQLDataType.CLOB; break + case 'BLOB': type = SQLDataType.BLOB; break + case 'BINARY': type = SQLDataType.BINARY; break + case 'VARBINARY': type = SQLDataType.VARBINARY; break + default: throw new GroovyBugError("Unsupported SQL cast type: ${sqlType}") + } + if (length != null) return type.length(length.intValue()) + if (precision != null && scale != null) return type.precision(precision.intValue(), scale.intValue()) + if (precision != null) return type.precision(precision.intValue()) + return type + } + + private Field coalesce(List fields) { + if (2 == fields.size()) return DSL.coalesce(fields[0], fields[1]) + return DSL.coalesce(fields[0], tail(fields)) + } + + // POSITION(needle IN haystack), MySQL LOCATE(needle, haystack), SQLite INSTR(haystack, needle) + private Field searchPosition(List fields) { + Field needle = fields[0] + Field haystack = fields[1] + SQLDialect family = dialect.family() + if (SQLDialect.MYSQL == family) { + return DSL.function('locate', Object, [needle, haystack] as Field[]) + } + if (SQLDialect.SQLITE == family) { + return DSL.function('instr', Object, [haystack, needle] as Field[]) + } + return DSL.position(haystack, needle) + } + + // GREATEST/LEAST, or SQLite's scalar max/min + private Field extreme(boolean greatest, List fields) { + if (SQLDialect.SQLITE == dialect.family()) { + return DSL.function(greatest ? 'max' : 'min', Object, fields as Field[]) + } + return greatest ? DSL.greatest(fields[0], tail(fields)) : DSL.least(fields[0], tail(fields)) + } + + private static Field[] tail(List fields) { + Field[] rest = new Field[fields.size() - 1] + for (int i = 1; i < fields.size(); i++) { + rest[i - 1] = fields.get(i) + } + return rest + } + + private static Name sqlName(String... parts) { + Name acc = null + for (String part : parts) { + Name next = part != null && part.startsWith('__ginq') ? DSL.quotedName(part) : DSL.name(part) + acc = acc == null ? next : acc.append(next) + } + return acc + } + + private Param registerParam(SqlParam param) { + int index = paramExpressions.size() + paramExpressions << param.valueExpr + return DSL.param('gqp' + index, Object) + } + + // limit/offset parameters carry a placeholder value: jOOQ eagerly folds a + // null/zero-valued limit into a `where false` optimization + private Param limitParam(SqlParam param) { + int index = paramExpressions.size() + paramExpressions << param.valueExpr + return DSL.param('gqp' + index, 1) + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlGinqProvider.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlGinqProvider.java new file mode 100644 index 00000000000..34cb67cae97 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlGinqProvider.java @@ -0,0 +1,77 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.jooq; + +import org.apache.groovy.ginq.provider.GinqProvider; +import org.apache.groovy.ginq.provider.sql.NativeSqlGinqProvider; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.List; + +/** + * Registers the {@code jooq-sql} GINQ provider. This class deliberately + * references no jOOQ types so it loads even when jOOQ is absent. + * {@link #unavailableReason(ClassLoader)} probes the compile classpath, and + * selection fails with a message naming {@code org.jooq:jooq} when jOOQ + * cannot be loaded. + * + * @since 7.0.0 + */ +@Incubating +public class JooqSqlGinqProvider implements GinqProvider { + /** + * The option naming the jOOQ {@code SQLDialect} to render for. + */ + public static final String CONF_DIALECT = "dialect"; + + /** + * Reported when {@code org.jooq.SQLDialect} cannot be loaded. + */ + static final String MISSING_JOOQ_MESSAGE = + "the jooq-sql provider requires org.jooq:jooq on the compile classpath"; + + @Override + public String getName() { + return "jooq-sql"; + } + + @Override + public String getAstWalkerClassName() { + return "org.apache.groovy.ginq.provider.sql.jooq.JooqSqlWalker"; + } + + @Override + public List getAdditionalOptionNames() { + return List.of(CONF_DIALECT, NativeSqlGinqProvider.CONF_MIXED_MODE); + } + + /** + * jOOQ is optional; {@code groovy-sql} is required to execute the rendered SQL. + */ + @Override + public String unavailableReason(ClassLoader loader) { + if (!GinqProvider.canLoad(loader, "org.jooq.SQLDialect")) { + return MISSING_JOOQ_MESSAGE; + } + if (!GinqProvider.canLoad(loader, "groovy.sql.Sql")) { + return "the jooq-sql provider requires org.apache.groovy:groovy-sql on the compile classpath"; + } + return null; + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlWalker.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlWalker.groovy new file mode 100644 index 00000000000..bb351fbf03b --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlWalker.groovy @@ -0,0 +1,80 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.jooq + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.dsl.expression.AbstractGinqExpression +import org.apache.groovy.ginq.provider.sql.GinqSqlWalker +import org.apache.groovy.ginq.provider.sql.SqlCapabilities +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.render.RenderedSql +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.control.SourceUnit +import org.jooq.SQLDialect + +/** + * The {@code jooq-sql} provider: identical to the native provider except the + * SQL is rendered by jOOQ for the {@code dialect} option's + * {@link SQLDialect}, giving dialect-aware SQL, function mapping and + * limit/offset rendering. jOOQ is required on the compile classpath only. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class JooqSqlWalker extends GinqSqlWalker { + + JooqSqlWalker(SourceUnit sourceUnit) { + super(sourceUnit) + } + + @Override + protected String getProviderName() { + return 'jooq-sql' + } + + @Override + protected void validateOptions(AbstractGinqExpression expression) { + // `dialect` is supported by this provider + validateMixedMode(expression) + } + + @Override + protected SqlCapabilities capabilities() { + return SqlCapabilities.of(effectiveDialectName()) + } + + @Override + protected char identifierQuoteChar() { + return JooqRenderer.identifierQuote(effectiveDialectName()) + } + + @Override + protected RenderedSql renderSql(SqlQueryNode queryNode, AbstractGinqExpression expression) { + String dialectName = effectiveDialectName() + try { + return JooqRenderer.render(queryNode, dialectName) + } catch (NoClassDefFoundError ignore) { + error(JooqSqlGinqProvider.MISSING_JOOQ_MESSAGE, expression) + } catch (IllegalArgumentException e) { + error(e.message, expression) + } + return null // unreachable: error() reports fatally + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/package-info.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/package-info.java new file mode 100644 index 00000000000..a9e037c28b8 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/package-info.java @@ -0,0 +1,26 @@ +/* + * 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 + * + * http://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. + */ + +/** + * The {@code jooq-sql} GINQ provider: uses jOOQ as a compile-time, + * dialect-aware SQL renderer over the shared SQL IR. jOOQ is only + * required on the compile classpath; execution and results are the + * same as for the {@code native-sql} provider. + */ +package org.apache.groovy.ginq.provider.sql.jooq; diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/package-info.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/package-info.java new file mode 100644 index 00000000000..5fae8a0d3db --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/package-info.java @@ -0,0 +1,27 @@ +/* + * 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 + * + * http://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. + */ + +/** + * SQL provider for GINQ (GEP-26): translates GINQ queries into SQL with bound + * parameters at compile time and executes them against a relational database at runtime. + * The native renderer defaults to ANSI and can target a small set of open-source dialects. + * Strict mode is the default; {@code mixedMode: true} pushes the translatable clause + * prefix and finishes the rest in memory. + */ +package org.apache.groovy.ginq.provider.sql; diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/AnsiDialect.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/AnsiDialect.java new file mode 100644 index 00000000000..31199279d37 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/AnsiDialect.java @@ -0,0 +1,30 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.render; + +import org.apache.groovy.lang.annotation.Incubating; + +/** + * The default dialect: plain ANSI SQL. + * + * @since 7.0.0 + */ +@Incubating +public class AnsiDialect implements Dialect { +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialect.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialect.java new file mode 100644 index 00000000000..8749358d6d4 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialect.java @@ -0,0 +1,309 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.render; + +import org.apache.groovy.ginq.provider.sql.FunctionSupport; +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr; +import org.apache.groovy.lang.annotation.Incubating; + +/** + * Abstracts the dialect-specific concerns of the native SQL renderer. + * The defaults produce ANSI SQL. + * + * @since 7.0.0 + */ +@Incubating +public interface Dialect { + /** + * Renders an identifier, e.g. a table name, table alias or column name. + * The default applies no quoting so identifiers follow the database's + * case-folding of unquoted DDL identifiers. + * + * @param identifier the identifier + * @return the rendered identifier + */ + default String identifier(String identifier) { + return identifier; + } + + /** + * Renders an identifier, quoting synthetic {@code __ginq} names so a + * presence column does not fold into a real column of the same spelling. + * + * @param identifier the identifier + * @return the rendered identifier + * @since 7.0.0 + */ + default String mixedIdentifier(String identifier) { + if (identifier != null && identifier.startsWith("__ginq")) { + char mark = identifierQuote(); + if (mark != 0) { + String quote = String.valueOf(mark); + return quote + identifier.replace(quote, quote + quote) + quote; + } + } + return identifier(identifier); + } + + /** + * Renders a simple or schema-qualified name. Each part is passed through + * {@link #identifier(String)}, so quoting matches other table and column + * references in this dialect. + * + * @param name a plain table name, possibly schema-qualified + * @return the rendered name + * @since 7.0.0 + */ + default String qualifiedName(String name) { + String[] parts = name.split("\\.", -1); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < parts.length; i++) { + if (i > 0) { + sb.append('.'); + } + sb.append(identifier(parts[i])); + } + return sb.toString(); + } + + /** + * Name used in diagnostics and in {@link #supportsFunction(String)}. + * Dialects that share an implementation override this so a message names + * the dialect the caller asked for. + * + * @return the dialect family name + * @since 7.0.0 + */ + default String name() { + return "ansi"; + } + + /** + * Whether {@code ansiName} can be rendered, including under a dialect + * spelling from {@link #functionName(String)}. The translator treats a + * {@code false} result as not translatable, so mixed mode leaves that + * clause in memory and strict mode rejects the query. The renderer + * refuses the same names, so the decision does not depend on which + * function is being mapped. + * + * @param ansiName the ANSI function name + * @return {@code false} when this dialect has no rendering of the function + * @since 7.0.0 + */ + default boolean supportsFunction(String ansiName) { + return FunctionSupport.supports(name(), ansiName); + } + + /** + * Quote character used when mixed mode names source columns explicitly. + * {@code 0} means identifiers are left unquoted, which is only safe for + * simple names. Quoting is independent of {@link #identifier(String)}: + * H2 leaves ordinary names unquoted so they follow case folding, and + * still quotes the names read back from JDBC metadata. + * + * @return the quote character, or {@code 0} + * @since 7.0.0 + */ + default char identifierQuote() { + return '"'; + } + + /** + * Maps an ANSI function name, e.g. {@code UPPER} or {@code SUM}, + * to its dialect-specific counterpart. {@code GREATEST} and {@code LEAST} + * are included; a dialect that spells those as scalar {@code MAX} and + * {@code MIN} overrides this method. Callers check + * {@link #supportsFunction(String)} first; this method is not the place + * that decides a function is unavailable. + * + * @param ansiName the ANSI function name + * @return the dialect-specific function name + */ + default String functionName(String ansiName) { + return ansiName; + } + + /** + * Renders null-safe equality, the SQL form of Groovy {@code ==} and + * {@code !=} when neither side is a null literal. The default is ANSI + * {@code IS NOT DISTINCT FROM} / {@code IS DISTINCT FROM}. Each operand + * is passed to {@link NullSafeRender#expr(SqlExpr)} once, in the order + * the text consumes it. + * + * @param negated {@code true} for Groovy {@code !=} + * @param left the left operand + * @param right the right operand + * @param out receives clause text and operands + * @since 7.0.0 + */ + default void renderNullSafeEqual(boolean negated, SqlExpr left, SqlExpr right, NullSafeRender out) { + out.expr(left); + out.text(negated ? " IS DISTINCT FROM " : " IS NOT DISTINCT FROM "); + out.expr(right); + } + + /** + * Receives the text and operands of a null-safe comparison. + * + * @since 7.0.0 + */ + interface NullSafeRender { + /** + * Appends literal SQL text that contains no placeholders. + * + * @param text the text to append + */ + void text(String text); + + /** + * Renders one operand, including its placeholders. + * + * @param expr the operand + */ + void expr(SqlExpr expr); + } + + /** + * How a 1-based character search is spelled. The translator subtracts + * one so the result matches Groovy {@code indexOf}: the first character + * is 0, and a search that finds nothing is -1, because these functions + * return 0 when the text is absent. + * + * @return the spelling + * @since 7.0.0 + */ + default SearchPosition searchPosition() { + return SearchPosition.POSITION_IN; + } + + /** + * Spelling of the search behind Groovy {@code indexOf}. + * + * @since 7.0.0 + */ + enum SearchPosition { + /** {@code POSITION(needle IN haystack)}. */ + POSITION_IN, + /** {@code LOCATE(needle, haystack)}. */ + LOCATE, + /** {@code INSTR(haystack, needle)}. */ + INSTR + } + + /** + * Whether {@code SUBSTRING} is rendered in the ANSI + * {@code SUBSTRING(x FROM start FOR length)} form. Dialects that only + * accept {@code SUBSTR(x, start, length)} return {@code false}. + * + * @return {@code true} for the ANSI form + * @since 7.0.0 + */ + default boolean substringFromFor() { + return true; + } + + /** + * Whether {@code MOD(x, y)} is available. Dialects that only have the + * {@code %} operator return {@code false}. + * + * @return {@code true} when {@code MOD} is a function + * @since 7.0.0 + */ + default boolean moduloFunction() { + return true; + } + + /** + * Whether {@code ORDER BY} accepts {@code NULLS FIRST}/{@code NULLS LAST}. + * When {@code false}, the renderer emulates the requested null order so + * results stay faithful to GINQ, which defaults to nulls last. + * + * @return {@code true} when the dialect has explicit null ordering + * @since 7.0.0 + */ + default boolean explicitNullOrdering() { + return true; + } + + /** + * SQL type name that forces real division, matching Groovy {@code /} + * rather than integer truncation. + * + * @return the type name + * @since 7.0.0 + */ + default String realTypeName() { + return "DOUBLE"; + } + + /** + * Returns the set operator subtracting one query result from another. + * + * @return the operator text, {@code EXCEPT} by default + */ + default String minusOperator() { + return "EXCEPT"; + } + + /** + * Appends the {@code OFFSET}/{@code FETCH} clause. The default is ANSI + * {@code OFFSET n ROWS FETCH NEXT m ROWS ONLY}, using {@code FETCH FIRST} + * when there is no offset. Implementations must pass each non-null + * expression to {@link LimitRender#expr(SqlExpr)} exactly once, in the + * order their text emits placeholders, so the parameter list stays aligned. + * + * @param offset the offset expression, or {@code null} + * @param fetch the row-count expression, or {@code null} + * @param out receives clause text and expressions + * @since 7.0.0 + */ + default void renderLimit(SqlExpr offset, SqlExpr fetch, LimitRender out) { + if (offset != null) { + out.text(" OFFSET "); + out.expr(offset); + out.text(" ROWS"); + } + if (fetch != null) { + out.text(offset != null ? " FETCH NEXT " : " FETCH FIRST "); + out.expr(fetch); + out.text(" ROWS ONLY"); + } + } + + /** + * Receives the text and expressions of a limit clause, in placeholder order. + * + * @since 7.0.0 + */ + interface LimitRender { + /** + * Appends literal SQL text that contains no placeholders. + * + * @param text the text to append + */ + void text(String text); + + /** + * Renders an offset or fetch expression, including its placeholder. + * + * @param expr the expression to render + */ + void expr(SqlExpr expr); + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialects.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialects.java new file mode 100644 index 00000000000..6e162857871 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialects.java @@ -0,0 +1,253 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.render; + +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.Locale; + +/** + * The native dialects that cover the high-variance points called out by + * GEP-26: limit/offset syntax, identifier quoting, and a few function names. + * Comprehensive dialect coverage stays with the jOOQ provider. + * + * @since 7.0.0 + */ +@Incubating +public final class Dialects { + /** + * Names accepted by {@link #resolve(String)}, for diagnostics. + */ + public static final String SUPPORTED = "ansi, h2, postgres, mysql, mariadb, sqlite"; + + /** + * Dialect family named by a JDBC URL, or {@code null} when the URL is + * not one of the built-in families. + * + * @param url a JDBC URL, possibly with leading space + * @return {@code h2}, {@code mysql}, {@code postgres}, {@code sqlite}, or {@code null} + */ + public static String fromJdbcUrl(String url) { + if (url == null) { + return null; + } + String trimmed = url.trim().toLowerCase(Locale.ROOT); + if (trimmed.startsWith("jdbc:h2:")) { + return "h2"; + } + if (trimmed.startsWith("jdbc:mysql:") || trimmed.startsWith("jdbc:mariadb:")) { + return "mysql"; + } + if (trimmed.startsWith("jdbc:postgresql:")) { + return "postgres"; + } + if (trimmed.startsWith("jdbc:sqlite:")) { + return "sqlite"; + } + return null; + } + + private Dialects() { + } + + /** + * Returns the dialect named {@code name}, or ANSI when {@code name} is + * null or empty. The match is case-insensitive. Unknown names return null. + * + * @param name the dialect name + * @return the dialect, or null when the name is not supported + */ + public static Dialect resolve(String name) { + if (name == null || name.isEmpty()) { + return new AnsiDialect(); + } + switch (name.toLowerCase(Locale.ROOT)) { + case "ansi": + case "default": + case "h2": + // H2 folds unquoted identifiers to upper case, so quoting a + // lowercase name would miss tables created without quotes. + // Its limit syntax, null ordering and function names are ANSI. + return new AnsiDialect(); + case "postgres": + case "postgresql": + return new PostgresDialect(); + case "mysql": + case "mariadb": + return new MySqlDialect(); + case "sqlite": + return new SqliteDialect(); + default: + return null; + } + } + + private static String quote(String identifier, char mark) { + String q = String.valueOf(mark); + return q + identifier.replace(q, q + q) + q; + } + + private static void limitOffset(SqlExpr offset, SqlExpr fetch, Dialect.LimitRender out) { + if (fetch == null && offset != null) { + // LIMIT is required before OFFSET. This is the largest unsigned + // BIGINT, the usual stand-in for "no limit". + out.text(" LIMIT 18446744073709551615"); + } else if (fetch != null) { + out.text(" LIMIT "); + out.expr(fetch); + } + if (offset != null) { + out.text(" OFFSET "); + out.expr(offset); + } + } + + private static final class PostgresDialect implements Dialect { + @Override + public String name() { + return "postgres"; + } + + @Override + public String identifier(String identifier) { + return quote(identifier, '"'); + } + + @Override + public String realTypeName() { + return "DOUBLE PRECISION"; + } + } + + private static final class MySqlDialect implements Dialect { + @Override + public String name() { + return "mysql"; + } + + @Override + public String identifier(String identifier) { + return quote(identifier, '`'); + } + + @Override + public char identifierQuote() { + return '`'; + } + + @Override + public void renderNullSafeEqual(boolean negated, SqlExpr left, SqlExpr right, NullSafeRender out) { + // <=> is null-safe and yields true or false, so NOT of it is not UNKNOWN. + if (negated) { + out.text("NOT ("); + out.expr(left); + out.text(" <=> "); + out.expr(right); + out.text(")"); + } else { + out.expr(left); + out.text(" <=> "); + out.expr(right); + } + } + + @Override + public boolean explicitNullOrdering() { + return false; + } + + @Override + public Dialect.SearchPosition searchPosition() { + return Dialect.SearchPosition.LOCATE; + } + + @Override + public void renderLimit(SqlExpr offset, SqlExpr fetch, LimitRender out) { + limitOffset(offset, fetch, out); + } + } + + private static final class SqliteDialect implements Dialect { + @Override + public String name() { + return "sqlite"; + } + + @Override + public String identifier(String identifier) { + return quote(identifier, '"'); + } + + @Override + public void renderNullSafeEqual(boolean negated, SqlExpr left, SqlExpr right, NullSafeRender out) { + // SQLite IS / IS NOT are null-safe. IS NOT DISTINCT FROM arrived later. + out.expr(left); + out.text(negated ? " IS NOT " : " IS "); + out.expr(right); + } + + @Override + public String realTypeName() { + return "REAL"; + } + + @Override + public String functionName(String ansiName) { + switch (ansiName) { + case "CHAR_LENGTH": + return "LENGTH"; + case "SUBSTRING": + return "SUBSTR"; + case "GREATEST": + // scalar max/min; GREATEST/LEAST arrived only in later SQLite + return "MAX"; + case "LEAST": + return "MIN"; + default: + return ansiName; + } + } + + @Override + public Dialect.SearchPosition searchPosition() { + return Dialect.SearchPosition.INSTR; + } + + @Override + public boolean substringFromFor() { + return false; + } + + @Override + public boolean moduloFunction() { + return false; + } + + @Override + public boolean explicitNullOrdering() { + return false; + } + + @Override + public void renderLimit(SqlExpr offset, SqlExpr fetch, LimitRender out) { + limitOffset(offset, fetch, out); + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/RenderedSql.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/RenderedSql.groovy new file mode 100644 index 00000000000..ac67a6c0bf5 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/RenderedSql.groovy @@ -0,0 +1,41 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.render + +import groovy.transform.CompileStatic +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.ast.expr.Expression + +/** + * Represents rendered SQL text plus the parameter value expressions + * in positional order, one per {@code ?} placeholder. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class RenderedSql { + final String sql + final List parameters + + RenderedSql(String sql, List parameters) { + this.sql = sql + this.parameters = parameters + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/SqlRenderer.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/SqlRenderer.groovy new file mode 100644 index 00000000000..ec3b48c14f3 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/SqlRenderer.groovy @@ -0,0 +1,398 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.render + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCaseWhen +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlCountStar +import org.apache.groovy.ginq.provider.sql.ir.SqlDerivedTable +import org.apache.groovy.ginq.provider.sql.ir.SqlExists +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlIn +import org.apache.groovy.ginq.provider.sql.ir.SqlInQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlIsNull +import org.apache.groovy.ginq.provider.sql.ir.SqlJoin +import org.apache.groovy.ginq.provider.sql.ir.SqlLike +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlOrderSpec +import org.apache.groovy.ginq.provider.sql.ir.SqlOrdinal +import org.apache.groovy.ginq.provider.sql.ir.SqlParam +import org.apache.groovy.ginq.provider.sql.ir.SqlProjection +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.ir.SqlScalarQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlSetQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlStar +import org.apache.groovy.ginq.provider.sql.ir.SqlTableRef +import org.apache.groovy.ginq.provider.sql.ir.SqlTableSource +import org.apache.groovy.ginq.provider.sql.ir.SqlUnary +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.GroovyBugError +import org.codehaus.groovy.ast.expr.Expression + +/** + * Renders the SQL IR to SQL text with positional {@code ?} placeholders, + * collecting the parameter value expressions in emission order so they are + * guaranteed to match the placeholders. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlRenderer { + private final Dialect dialect + + SqlRenderer(Dialect dialect) { + this.dialect = dialect + } + + RenderedSql render(SqlQueryNode queryNode) { + StringBuilder sb = new StringBuilder() + List parameters = [] + renderQueryNode(queryNode, sb, parameters) + return new RenderedSql(sb.toString(), parameters) + } + + private void renderQueryNode(SqlQueryNode queryNode, StringBuilder sb, List parameters) { + if (queryNode instanceof SqlSetQuery) { + // parenthesize a set-query left operand to preserve GINQ's left-to-right + // chaining, since INTERSECT binds tighter than UNION/EXCEPT in SQL + boolean parenthesizeLeft = queryNode.left instanceof SqlSetQuery + if (parenthesizeLeft) sb.append('(') + renderQueryNode(queryNode.left, sb, parameters) + if (parenthesizeLeft) sb.append(')') + sb.append(' ').append(setOperator(queryNode.op)).append(' ') + renderQuery(queryNode.right, sb, parameters) + renderOrderAndLimit(queryNode.orderBy, queryNode.offset, queryNode.fetch, sb, parameters) + } else { + renderQuery((SqlQuery) queryNode, sb, parameters) + } + } + + private String setOperator(SqlSetQuery.SetOp op) { + switch (op) { + case SqlSetQuery.SetOp.UNION: return 'UNION' + case SqlSetQuery.SetOp.UNION_ALL: return 'UNION ALL' + case SqlSetQuery.SetOp.INTERSECT: return 'INTERSECT' + case SqlSetQuery.SetOp.MINUS: return dialect.minusOperator() + default: throw new GroovyBugError("Unknown set operation: ${op}") + } + } + + private void renderQuery(SqlQuery query, StringBuilder sb, List parameters) { + sb.append('SELECT ') + if (query.distinct) sb.append('DISTINCT ') + query.projections.eachWithIndex { SqlProjection projection, int i -> + if (i > 0) sb.append(', ') + renderExpr(projection.expr, sb, parameters) + if (projection.alias) sb.append(' AS ').append(dialect.mixedIdentifier(projection.alias)) + } + + sb.append(' FROM ') + renderTableSource(query.from, sb, parameters) + + for (SqlJoin join : query.joins) { + sb.append(' ').append(join.type.sqlText).append(' ') + renderTableSource(join.table, sb, parameters) + if (join.on != null) { + sb.append(' ON ') + renderExpr(join.on, sb, parameters) + } + } + + if (query.where != null) { + sb.append(' WHERE ') + renderExpr(query.where, sb, parameters) + } + + if (query.groupBy) { + sb.append(' GROUP BY ') + query.groupBy.eachWithIndex { SqlExpr keyExpr, int i -> + if (i > 0) sb.append(', ') + renderExpr(keyExpr, sb, parameters) + } + } + + if (query.having != null) { + sb.append(' HAVING ') + renderExpr(query.having, sb, parameters) + } + + renderOrderAndLimit(query.orderBy, query.offset, query.fetch, sb, parameters) + } + + private void renderOrderAndLimit(List orderBy, SqlExpr offset, SqlExpr fetch, StringBuilder sb, List parameters) { + if (orderBy) { + sb.append(' ORDER BY ') + orderBy.eachWithIndex { SqlOrderSpec orderSpec, int i -> + if (i > 0) sb.append(', ') + renderOrderItem(orderSpec, sb, parameters) + } + } + + if (offset != null || fetch != null) { + dialect.renderLimit(offset, fetch, new Dialect.LimitRender() { + @Override + void text(String text) { + sb.append(text) + } + + @Override + void expr(SqlExpr expr) { + renderExpr(expr, sb, parameters) + } + }) + } + } + + private void renderExpr(SqlExpr expr, StringBuilder sb, List parameters) { + if (expr instanceof SqlColumn) { + if (expr.tableAlias) sb.append(dialect.mixedIdentifier(expr.tableAlias)).append('.') + sb.append(dialect.mixedIdentifier(expr.column)) + } else if (expr instanceof SqlParam) { + sb.append('?') + parameters.add(expr.valueExpr) + } else if (expr instanceof SqlLiteral) { + renderLiteral(expr.value, sb) + } else if (expr instanceof SqlBinary) { + if ('IS NOT DISTINCT FROM' == expr.op || 'IS DISTINCT FROM' == expr.op) { + dialect.renderNullSafeEqual('IS DISTINCT FROM' == expr.op, expr.left, expr.right, new Dialect.NullSafeRender() { + @Override + void text(String text) { + sb.append(text) + } + + @Override + void expr(SqlExpr child) { + renderOperand(child, 4, sb, parameters) + } + }) + return + } + if ('/' == expr.op) { + // Groovy divides in real arithmetic; SQL integer division would truncate + String realType = dialect.realTypeName() + sb.append('(CAST(') + renderExpr(expr.left, sb, parameters) + sb.append(' AS ').append(realType).append(') / CAST(') + renderExpr(expr.right, sb, parameters) + sb.append(' AS ').append(realType).append('))') + return + } + int prec = precedence(expr.op) + renderOperand(expr.left, prec, sb, parameters) + sb.append(' ').append(expr.op).append(' ') + // at equal precedence, the right operand of a non-associative operator needs parentheses + int rightPrec = expr.op in NON_ASSOCIATIVE_OPS ? prec + 1 : prec + renderOperand(expr.right, rightPrec, sb, parameters) + } else if (expr instanceof SqlUnary) { + sb.append(expr.op == 'NOT' ? 'NOT ' : expr.op) + renderOperand(expr.operand, PREC_UNARY, sb, parameters) + } else if (expr instanceof SqlIsNull) { + renderOperand(expr.expr, PREC_UNARY, sb, parameters) + sb.append(expr.negated ? ' IS NOT NULL' : ' IS NULL') + } else if (expr instanceof SqlIn) { + renderOperand(expr.expr, PREC_UNARY, sb, parameters) + sb.append(expr.negated ? ' NOT IN (' : ' IN (') + expr.values.eachWithIndex { SqlExpr valueExpr, int i -> + if (i > 0) sb.append(', ') + renderExpr(valueExpr, sb, parameters) + } + sb.append(')') + } else if (expr instanceof SqlExists) { + sb.append('EXISTS (') + renderQuery(expr.query, sb, parameters) + sb.append(')') + } else if (expr instanceof SqlInQuery) { + renderOperand(expr.expr, PREC_UNARY, sb, parameters) + sb.append(expr.negated ? ' NOT IN (' : ' IN (') + renderQuery(expr.query, sb, parameters) + sb.append(')') + } else if (expr instanceof SqlScalarQuery) { + sb.append('(') + renderQuery(expr.query, sb, parameters) + sb.append(')') + } else if (expr instanceof SqlLike) { + renderOperand(expr.expr, PREC_UNARY, sb, parameters) + sb.append(' LIKE ') + renderExpr(expr.pattern, sb, parameters) + // pattern values are escaped with '!' at runtime, see SqlGinqRuntime#likePattern + sb.append(" ESCAPE '!'") + } else if (expr instanceof SqlCaseWhen) { + sb.append('CASE WHEN ') + renderExpr(expr.condition, sb, parameters) + sb.append(' THEN ') + renderExpr(expr.thenExpr, sb, parameters) + sb.append(' ELSE ') + renderExpr(expr.elseExpr, sb, parameters) + sb.append(' END') + } else if (expr instanceof SqlOrdinal) { + sb.append(expr.position) + } else if (expr instanceof SqlCast) { + sb.append('CAST(') + renderExpr(expr.expr, sb, parameters) + sb.append(' AS ').append(expr.sqlType).append(')') + } else if (expr instanceof SqlFunction) { + if (!dialect.supportsFunction(expr.name)) { + throw new IllegalArgumentException(expr.name + + ' is not supported by the ' + dialect.name() + + ' dialect. Rewrite the query without it, or use a dialect that provides it') + } + if ('POSITION' == expr.name && expr.args.size() == 2) { + renderSearchPosition(expr.args[0], expr.args[1], sb, parameters) + return + } + if ('MOD' == expr.name && expr.args.size() == 2 && !dialect.moduloFunction()) { + renderOperand(expr.args[0], precedence('%'), sb, parameters) + sb.append(' % ') + renderOperand(expr.args[1], precedence('%') + 1, sb, parameters) + return + } + if ('SUBSTRING' == expr.name && expr.args.size() > 1 && dialect.substringFromFor()) { + // ANSI form: SUBSTRING(x FROM start [FOR length]) + sb.append(dialect.functionName(expr.name)).append('(') + renderExpr(expr.args[0], sb, parameters) + sb.append(' FROM ') + renderExpr(expr.args[1], sb, parameters) + if (expr.args.size() > 2) { + sb.append(' FOR ') + renderExpr(expr.args[2], sb, parameters) + } + sb.append(')') + return + } + sb.append(dialect.functionName(expr.name)).append('(') + if (expr.distinct) sb.append('DISTINCT ') + expr.args.eachWithIndex { SqlExpr argExpr, int i -> + if (i > 0) sb.append(', ') + renderExpr(argExpr, sb, parameters) + } + sb.append(')') + } else if (expr instanceof SqlCountStar) { + sb.append('COUNT(*)') + } else if (expr instanceof SqlStar) { + if (expr.tableAlias) sb.append(dialect.mixedIdentifier(expr.tableAlias)).append('.') + sb.append('*') + } else { + throw new GroovyBugError("Unknown SQL expression: ${expr?.getClass()?.name}") + } + } + + // needle is args[0] and haystack is args[1], the ANSI POSITION argument order + private void renderSearchPosition(SqlExpr needle, SqlExpr haystack, StringBuilder sb, List parameters) { + switch (dialect.searchPosition()) { + case Dialect.SearchPosition.LOCATE: + sb.append('LOCATE(') + renderExpr(needle, sb, parameters) + sb.append(', ') + renderExpr(haystack, sb, parameters) + sb.append(')') + return + case Dialect.SearchPosition.INSTR: + sb.append('INSTR(') + renderExpr(haystack, sb, parameters) + sb.append(', ') + renderExpr(needle, sb, parameters) + sb.append(')') + return + default: + sb.append('POSITION(') + renderExpr(needle, sb, parameters) + sb.append(' IN ') + renderExpr(haystack, sb, parameters) + sb.append(')') + } + } + + private void renderTableSource(SqlTableSource tableSource, StringBuilder sb, List parameters) { + if (tableSource instanceof SqlTableRef) { + renderQualifiedName(tableSource.tableName, sb) + } else if (tableSource instanceof SqlDerivedTable) { + sb.append('(') + if (tableSource.query instanceof SqlQuery) { + renderQuery((SqlQuery) tableSource.query, sb, parameters) + } else { + renderQueryNode(tableSource.query, sb, parameters) + } + sb.append(')') + } else { + throw new GroovyBugError("Unknown table source: ${tableSource?.getClass()?.name}") + } + sb.append(' ').append(dialect.mixedIdentifier(tableSource.alias)) + } + + private void renderOrderItem(SqlOrderSpec orderSpec, StringBuilder sb, List parameters) { + if (dialect.explicitNullOrdering()) { + renderExpr(orderSpec.expr, sb, parameters) + sb.append(orderSpec.asc ? ' ASC' : ' DESC') + sb.append(orderSpec.nullsLast ? ' NULLS LAST' : ' NULLS FIRST') + return + } + // (expr IS NULL) is 0 for values and 1 for nulls, so ASC puts nulls last + sb.append('(') + renderExpr(orderSpec.expr, sb, parameters) + sb.append(' IS NULL) ').append(orderSpec.nullsLast ? 'ASC' : 'DESC').append(', ') + renderExpr(orderSpec.expr, sb, parameters) + sb.append(orderSpec.asc ? ' ASC' : ' DESC') + } + + private void renderQualifiedName(String name, StringBuilder sb) { + sb.append(dialect.qualifiedName(name)) + } + + private static void renderLiteral(Object value, StringBuilder sb) { + if (value == null) { + sb.append('NULL') + } else if (value instanceof String || value instanceof Character) { + sb.append("'").append(value.toString().replace("'", "''")).append("'") + } else if (value instanceof Boolean) { + sb.append(value ? 'TRUE' : 'FALSE') + } else if (value instanceof Number) { + sb.append(value) + } else { + throw new GroovyBugError("Unsupported SQL literal: ${value.getClass().name}") + } + } + + private void renderOperand(SqlExpr operand, int parentPrecedence, StringBuilder sb, List parameters) { + boolean parenthesize = operand instanceof SqlBinary && precedence(operand.op) < parentPrecedence + if (parenthesize) sb.append('(') + renderExpr(operand, sb, parameters) + if (parenthesize) sb.append(')') + } + + private static int precedence(String op) { + switch (op) { + case 'OR': return 1 + case 'AND': return 2 + case '=': case '<>': case '<': case '<=': case '>': case '>=': + case 'IS NOT DISTINCT FROM': case 'IS DISTINCT FROM': return 4 + case '+': case '-': case '||': return 5 + case '*': case '/': case '%': return 6 + default: return PREC_UNARY + } + } + + private static final List NON_ASSOCIATIVE_OPS = ['-', '/'] + private static final int PREC_UNARY = 7 +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/package-info.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/package-info.java new file mode 100644 index 00000000000..74cadc0a726 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/package-info.java @@ -0,0 +1,24 @@ +/* + * 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 + * + * http://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. + */ + +/** + * Renders the SQL intermediate representation to SQL text with positional parameters, + * with dialect-specific concerns abstracted behind the {@code Dialect} SPI. + */ +package org.apache.groovy.ginq.provider.sql.render; diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/MixedSourceRow.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/MixedSourceRow.java new file mode 100644 index 00000000000..5d53446d8bf --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/MixedSourceRow.java @@ -0,0 +1,56 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.runtime; + +import groovy.sql.GroovyRowResult; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.Map; + +/** + * One source row rebuilt from a mixed-mode join. Column values live in the + * map under the names reported for that source. The output-row index is kept + * beside the map, so a real column cannot be overwritten by it and a column + * of any name stays readable. An unmatched outer-join side is null rather + * than one of these rows. + * + * @since 7.0.0 + */ +@Incubating +public final class MixedSourceRow extends GroovyRowResult { + private final int ordinal; + + /** + * @param columns column name to value, in select order + * @param ordinal the output-row index shared by every alias of this joined row + */ + public MixedSourceRow(Map columns, int ordinal) { + super(columns); + this.ordinal = ordinal; + } + + /** + * The join ordinal. Not a column, and not looked up by name. + * + * @return the output-row index + */ + public int mixedOrdinal() { + return ordinal; + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/SqlGinqRuntime.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/SqlGinqRuntime.java new file mode 100644 index 00000000000..bcd73b9738d --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/SqlGinqRuntime.java @@ -0,0 +1,1362 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.runtime; + +import groovy.lang.Tuple2; +import groovy.sql.GroovyRowResult; +import groovy.sql.Sql; +import org.apache.groovy.ginq.provider.collection.runtime.Queryable; +import org.apache.groovy.lang.annotation.Incubating; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static groovy.lang.Tuple.tuple; + +/** + * Executes the SQL generated by the native SQL provider. The generated code + * calls {@link #execute(Object, String, List)} with the compile-time constant + * SQL text and the runtime parameter values. + * + * @since 7.0.0 + */ +@Incubating +public final class SqlGinqRuntime { + /** + * Historical name of the mixed-mode join ordinal. The ordinal is no longer + * stored under this name: a real column could collide with it. Rows expose + * it through {@link #mixedOrdinal(Object)} instead. + */ + public static final String MIXED_KEY = "__ginq_mixed_key"; + + /** + * Runs the supplied SQL with the supplied bound parameters against the + * supplied data source and returns the rows as a {@code Queryable}. + *

+ * The data source may be a {@link Sql} instance or {@link Connection} + * (used as-is; the caller owns their lifecycle), or a {@link DataSource} + * (a connection is borrowed and released per query). + * + * @param dataSource the data source to query + * @param sqlText the SQL text with {@code ?} placeholders + * @param params the parameter values in placeholder order + * @return the resulting rows + * @throws SQLException if the query fails + */ + public static Queryable execute(Object dataSource, String sqlText, List params) throws SQLException { + if (dataSource instanceof Sql) { + return Queryable.from(((Sql) dataSource).rows(sqlText, params)); + } + if (dataSource instanceof DataSource) { + Sql sql = new Sql((DataSource) dataSource); + try { + return Queryable.from(sql.rows(sqlText, params)); + } finally { + sql.close(); + } + } + if (dataSource instanceof Connection) { + return Queryable.from(new Sql((Connection) dataSource).rows(sqlText, params)); + } + throw unsupported(dataSource); + } + + /** + * Expands whole-row placeholders left by full-join emulation, then runs + * the SQL. {@code __ginqsrc_}, {@code __ginqpass_}, {@code __ginqstar_} + * and {@code __ginqcol_} name columns discovered from {@code columnsByAlias}. + * + * @param dataSource the data source to query + * @param sqlText the SQL text with star placeholders + * @param params the parameter values in placeholder order + * @param columnsByAlias column labels for each whole-row probe, in id order + * @param identifierQuote the renderer's identifier quote, one character, or empty + * @return the resulting rows + * @throws SQLException if the query fails or a placeholder cannot be expanded + */ + public static Queryable expandAndExecute(Object dataSource, String sqlText, List params, + List> columnsByAlias, String identifierQuote) throws SQLException { + char quote = quoteChar(identifierQuote); + return execute(dataSource, expandStarTokens(sqlText, columnsByAlias, quote), params); + } + + /** + * Returns the number of columns the supplied query produces. + * The SQL text is a compile-time constant; values are bound as parameters. + * + * @param dataSource the data source to query + * @param sqlText the SQL text with {@code ?} placeholders + * @param params the parameter values in placeholder order + * @return the column count + * @throws SQLException if the query fails + */ + public static int columnCount(Object dataSource, String sqlText, List params) throws SQLException { + return columnLabels(dataSource, sqlText, params).size(); + } + + /** + * Column labels of one mixed-mode source, in ordinal order. The label is + * preferred over the base column name so a derived column {@code expr as label} + * is exposed as {@code label}. A blank name becomes {@code __ginq_cN}. + * Callers still have to reject duplicate labels; this method does not drop + * any of them. + * + * @param dataSource the data source to query + * @param sqlText the SQL text with {@code ?} placeholders + * @param params the parameter values in placeholder order + * @return the labels, one per column + * @throws SQLException if the query fails + */ + public static List columnLabels(Object dataSource, String sqlText, List params) throws SQLException { + return withConnection(dataSource, connection -> { + try (PreparedStatement statement = connection.prepareStatement(sqlText)) { + bind(statement, params); + try (ResultSet rs = statement.executeQuery()) { + ResultSetMetaData metaData = rs.getMetaData(); + List names = new ArrayList<>(); + int count = metaData.getColumnCount(); + for (int i = 1; i <= count; i++) { + String name = metaData.getColumnLabel(i); + if (name == null || name.isEmpty()) { + name = metaData.getColumnName(i); + } + if (name == null || name.isEmpty()) { + name = freshName(names, "__ginq_c" + (i - 1)); + } + names.add(name); + } + return names; + } + } + }); + } + + /** + * The output-row index stored on a {@link MixedSourceRow}. It is not a + * column. The mixed-mode tail does not pair rows with this value: an + * unmatched outer-join alias is null and has no ordinal, and the rows + * {@link #zipAliases} returns are already index-aligned. + * + * @param row a mixed-mode source row + * @return the output-row index + */ + public static int mixedOrdinal(Object row) { + if (row instanceof MixedSourceRow) { + return ((MixedSourceRow) row).mixedOrdinal(); + } + throw new IllegalArgumentException("mixed-mode join row has no ordinal: " + + (row == null ? "null" : row.getClass().getName())); + } + + /** + * Runs a mixed-mode prefix that projects {@code alias.*} for each alias + * and splits every output row into one entry per alias. + *

+ * Each source is wrapped so it carries a presence column the outer join + * can null out, then the stars are rewritten to explicitly named columns + * ({@code alias.col AS __ginqA_C}). Values are read by ordinal and stored + * under the source's own column labels, so a duplicate label in the joined + * projection cannot drop a column and the driver is not asked to invent + * labels for {@code alias.*}. Duplicate labels within one source are + * rejected. A null presence marker becomes a null entry, matching an + * unmatched outer-join side; a present row whose columns are all null + * stays a row. The lists have one entry per output row and are index-aligned. + * + * @param dataSource the data source to query + * @param sqlText the SQL text with {@code ?} placeholders, projecting {@code alias.*} + * @param params the parameter values in placeholder order + * @param columnsByAlias the column labels of each alias, in select-list order + * @param identifierQuote the dialect's identifier quote, one character, or empty to leave simple names unquoted + * @return one list of rows per alias + * @throws SQLException if the query fails, labels collide, or the column layout does not match + */ + public static List> zipAliases(Object dataSource, String sqlText, List params, + List> columnsByAlias, String identifierQuote) throws SQLException { + char quote = quoteChar(identifierQuote); + String presence = presenceName(columnsByAlias); + List> extended = withPresence(columnsByAlias, presence); + String rewritten = prepareMixedSql(sqlText, columnsByAlias, quote); + int aliasCount = extended.size(); + int columnTotal = 0; + for (List names : extended) { + columnTotal += names.size(); + } + List> byAlias = new ArrayList<>(aliasCount); + for (int i = 0; i < aliasCount; i++) { + byAlias.add(new ArrayList<>()); + } + int expected = columnTotal; + withConnection(dataSource, connection -> { + try (PreparedStatement statement = connection.prepareStatement(rewritten)) { + bind(statement, params); + try (ResultSet rs = statement.executeQuery()) { + ResultSetMetaData metaData = rs.getMetaData(); + if (metaData.getColumnCount() != expected) { + throw new SQLException("mixed-mode result has " + metaData.getColumnCount() + + " columns but the alias layout expected " + expected); + } + int rowIndex = 0; + while (rs.next()) { + int column = 1; + for (int alias = 0; alias < aliasCount; alias++) { + Map values = new LinkedHashMap<>(); + List names = extended.get(alias); + int dataCount = names.size() - 1; + for (int c = 0; c < dataCount; c++) { + values.put(names.get(c), rs.getObject(column)); + column++; + } + Object marker = rs.getObject(column); + boolean absent = marker == null || rs.wasNull(); + column++; + byAlias.get(alias).add(absent ? null : new MixedSourceRow(values, rowIndex)); + } + rowIndex++; + } + } + } + return null; + }); + return byAlias; + } + + /** + * Pairs two already index-aligned mixed-mode sources, including nulls. + * The SQL join produced one entry per output row on each side, so this + * does not apply a collection join and does not compare ordinals. + * + * @param left the rows so far, one per output row + * @param right the next alias, one per output row, null where that side was absent + * @return one tuple per output row, in the same order + */ + public static Queryable> indexZip(Queryable left, Queryable right) { + if (left == null || right == null) { + throw new IllegalArgumentException("mixed-mode join source is null"); + } + List leftRows = left.toList(); + List rightRows = right.toList(); + if (leftRows.size() != rightRows.size()) { + throw new IllegalStateException("mixed-mode join rows are not aligned (" + + leftRows.size() + " and " + rightRows.size() + ")"); + } + List> zipped = new ArrayList<>(leftRows.size()); + for (int i = 0; i < leftRows.size(); i++) { + zipped.add(tuple(leftRows.get(i), rightRows.get(i))); + } + return Queryable.from(zipped); + } + + /** + * Rewrites a mixed-mode prefix so each source column is named and a + * presence column is projected with it. Sources wrapped by the planner + * already carry that column; other prefixes are wrapped here. Full joins + * are nested in the planner, not by flattening this text. + * + * @param sql the rendered prefix + * @param columnsByAlias column labels for each alias, in select-list order, without the presence column + * @param quote the identifier quote, or {@code 0} for simple unquoted names + * @return the SQL to execute + * @throws SQLException when the prefix cannot be rewritten + */ + public static String prepareMixedSql(String sql, List> columnsByAlias, char quote) throws SQLException { + String presence = presenceName(columnsByAlias); + List> extended = withPresence(columnsByAlias, presence); + if (!prewrapped(sql)) { + return rewriteStarSelect(wrapPresenceSources(sql, columnsByAlias.size(), presence, quote), extended, quote); + } + String named = substitutePresence(sql, presence, quote); + named = expandAllSelectLists(named, extended, quote); + return replaceTokens(named, extended, quote); + } + + private static boolean prewrapped(String sql) { + // A user column named __ginq_present is not a wrap. Only the planner's + // source alias and full-join container mark SQL that is already wrapped. + return sql.contains("__ginq_src") || sql.contains("__ginqf"); + } + + private static String substitutePresence(String sql, String presence, char quote) { + String marker = quoteIdentifierUnchecked("__ginq_marker", quote); + String named = quoteIdentifierUnchecked(presence, quote); + sql = sql.replace(marker, named); + if (PRESENCE_BASE.equals(presence)) { + return sql; + } + // Rename only the marker we introduced (`1 AS "__ginq_present"`). + // A qualified user column `m."__ginq_present"` stays the user's column. + String definition = quoteIdentifierUnchecked(PRESENCE_BASE, quote); + return Pattern.compile("(?i)AS\\s+" + Pattern.quote(definition)) + .matcher(sql) + .replaceAll("AS " + Matcher.quoteReplacement(named)); + } + + private static String quoteIdentifierUnchecked(String name, char quote) { + if (quote == 0) { + return name; + } + String mark = String.valueOf(quote); + return mark + name.replace(mark, mark + mark) + mark; + } + + private static String expandAllSelectLists(String sql, List> extended, char quote) throws SQLException { + List ranges = starSelectRanges(sql); + for (int i = ranges.size() - 1; i >= 0; i--) { + int from = ranges.get(i)[0]; + int to = ranges.get(i)[1]; + String expanded = expandStarList(sql.substring(from, to).trim(), extended, quote); + if (expanded != null) { + sql = sql.substring(0, from) + ' ' + expanded + ' ' + sql.substring(to); + } + } + return sql; + } + + private static List starSelectRanges(String sql) throws SQLException { + List ranges = new ArrayList<>(); + int depth = 0; + Quote quote = Quote.NONE; + for (int i = 0; i < sql.length(); i++) { + char ch = sql.charAt(i); + if (quote != Quote.NONE) { + i = skipQuoted(sql, i, quote) - 1; + quote = Quote.NONE; + continue; + } + Quote opened = openingQuote(ch); + if (opened != Quote.NONE) { + quote = opened; + continue; + } + if (ch == '(') { + depth++; + } else if (ch == ')') { + depth = Math.max(0, depth - 1); + } else if (isBareKeywordAt(sql, i, "select")) { + int listAt = i + "select".length(); + int fromAt = fromAtDepth(sql, listAt, depth); + if (fromAt > listAt) { + ranges.add(new int[] {listAt, fromAt}); + } + } + } + return ranges; + } + + private static int fromAtDepth(String sql, int start, int baseDepth) throws SQLException { + int depth = baseDepth; + Quote quote = Quote.NONE; + for (int i = start; i < sql.length(); i++) { + char ch = sql.charAt(i); + if (quote != Quote.NONE) { + i = skipQuoted(sql, i, quote) - 1; + quote = Quote.NONE; + continue; + } + Quote opened = openingQuote(ch); + if (opened != Quote.NONE) { + quote = opened; + continue; + } + if (ch == '(') { + depth++; + } else if (ch == ')') { + depth--; + } else if (depth == baseDepth && isBareKeywordAt(sql, i, "from")) { + return i; + } + } + return -1; + } + + private static final Pattern STAR_ITEM = Pattern.compile( + "^(?:\"([^\"]+)\"|`([^`]+)`|([A-Za-z_][A-Za-z0-9_]*))\\.\\*$"); + private static final Pattern CONTAINER = Pattern.compile("__ginqf(\\d+)_(\\d+)"); + + private static String expandStarList(String selectList, List> extended, char quote) throws SQLException { + List items = new ArrayList<>(); + for (String item : splitTopLevel(selectList, ',')) { + String trimmed = item.trim(); + if (!STAR_ITEM.matcher(trimmed).matches()) { + return null; + } + items.add(trimmed); + } + if (items.isEmpty()) { + return null; + } + StringBuilder out = new StringBuilder(); + int next = 0; + boolean any = false; + for (String item : items) { + Matcher star = STAR_ITEM.matcher(item); + if (!star.matches()) { + return null; + } + String alias = star.group(1) != null ? star.group(1) : star.group(2) != null ? star.group(2) : star.group(3); + String qualifier = item.substring(0, item.length() - 2); + Matcher container = CONTAINER.matcher(alias); + if (container.matches()) { + int start = Integer.parseInt(container.group(1)); + int end = Integer.parseInt(container.group(2)); + if (start != next || end > extended.size()) { + throw new SQLException("mixed-mode select list does not match the alias layout"); + } + for (int aliasIndex = start; aliasIndex < end; aliasIndex++) { + any = appendContainerColumns(out, qualifier, aliasIndex, extended.get(aliasIndex), quote, any); + } + next = end; + } else { + if (next >= extended.size()) { + throw new SQLException("mixed-mode select list has more stars than aliases"); + } + any = appendAliasedColumns(out, qualifier, next, extended.get(next), quote, any); + next++; + } + } + return out.toString(); + } + + private static boolean appendAliasedColumns(StringBuilder out, String qualifier, int aliasIndex, + List names, char quote, boolean any) throws SQLException { + for (int c = 0; c < names.size(); c++) { + if (any) { + out.append(", "); + } + any = true; + out.append(qualifier).append('.').append(quoteIdentifier(names.get(c), quote)); + out.append(" AS ").append(quoteIdentifier("__ginq" + aliasIndex + "_" + c, quote)); + } + return any; + } + + private static boolean appendContainerColumns(StringBuilder out, String qualifier, int aliasIndex, + List names, char quote, boolean any) throws SQLException { + for (int c = 0; c < names.size(); c++) { + if (any) { + out.append(", "); + } + any = true; + out.append(qualifier).append('.').append(quoteIdentifier("__ginq" + aliasIndex + "_" + c, quote)); + } + return any; + } + + private static final Pattern MIXED_TOKEN = Pattern.compile( + "(?i)([\"`\\[]?)__ginq(ref|abs|ord)_(\\d+)(?:_([A-Za-z_][A-Za-z0-9_]*))?"); + + private static String replaceTokens(String sql, List> extended, char quote) throws SQLException { + Matcher matcher = MIXED_TOKEN.matcher(sql); + StringBuilder out = new StringBuilder(); + int last = 0; + while (matcher.find()) { + String open = matcher.group(1); + int end = matcher.end(); + char emit = quote; + if (open != null && !open.isEmpty()) { + char ch = open.charAt(0); + char close = ch == '[' ? ']' : ch; + if (end >= sql.length() || sql.charAt(end) != close) { + continue; + } + end++; + emit = ch; + } + int aliasIndex = Integer.parseInt(matcher.group(3)); + if (aliasIndex < 0 || aliasIndex >= extended.size()) { + throw new SQLException("mixed-mode column reference is outside the alias layout"); + } + List names = extended.get(aliasIndex); + int column; + if ("abs".equalsIgnoreCase(matcher.group(2))) { + column = names.size() - 1; + } else { + column = columnIndex(names, matcher.group(4)); + } + out.append(sql, last, matcher.start()); + String rewritten = "__ginq" + aliasIndex + "_" + column; + if (emit == '[') { + out.append(quoteBracket(rewritten)); + } else { + out.append(quoteIdentifier(rewritten, emit)); + } + last = end; + } + out.append(sql, last, sql.length()); + return out.toString(); + } + + private static String expandStarTokens(String sql, List> columnsByAlias, char quote) throws SQLException { + StringBuilder out = new StringBuilder(); + int i = 0; + while (i < sql.length()) { + int at = nextStarToken(sql, i); + if (at < 0) { + out.append(sql, i, sql.length()); + break; + } + StarToken token = readStarToken(sql, at); + if (token == null) { + out.append(sql, i, at + 6); + i = at + 6; + continue; + } + out.append(sql, i, token.qualifierStart); + out.append(expandStar(sql.substring(token.qualifierStart, token.qualifierEnd), token, columnsByAlias, quote)); + i = token.end; + } + return out.toString(); + } + + private static String expandStar(String qualifier, StarToken token, List> columnsByAlias, char quote) throws SQLException { + if (token.id < 0 || columnsByAlias == null || token.id >= columnsByAlias.size()) { + throw new SQLException("whole-row projection is outside the column layout"); + } + List names = columnsByAlias.get(token.id); + if (names == null || names.isEmpty()) { + throw new SQLException("whole-row source has no columns"); + } + if ("col".equals(token.kind)) { + String label = matchLabel(names, token.column); + return qualifier + "." + quoteIdentifier(starName(token.id, label), quote); + } + StringBuilder expanded = new StringBuilder(); + boolean any = false; + for (String label : names) { + if (any) { + expanded.append(", "); + } + any = true; + String synthetic = quoteIdentifier(starName(token.id, label), quote); + if ("src".equals(token.kind)) { + expanded.append(qualifier).append('.').append(quoteIdentifier(label, quote)); + expanded.append(" AS ").append(synthetic); + } else if ("pass".equals(token.kind)) { + expanded.append(qualifier).append('.').append(synthetic); + } else { + String visible = (token.alias == null || token.alias.isEmpty() ? "" : token.alias + "_") + label; + expanded.append(qualifier).append('.').append(synthetic); + expanded.append(" AS ").append(quoteIdentifier(visible, quote)); + } + } + if (!any) { + throw new SQLException("whole-row source has no columns"); + } + return expanded.toString(); + } + + private static String matchLabel(List names, String column) throws SQLException { + if (column == null) { + throw new SQLException("mixed-mode column reference is blank"); + } + for (String name : names) { + if (name.equalsIgnoreCase(column)) { + return name; + } + } + throw new SQLException("mixed-mode join refers to unknown column `" + column + "`"); + } + + private static String starName(int id, String label) { + // Disjoint from complete-path alias columns `__ginq__`, + // which case-fold onto the same spelling when a star probe reuses that index. + return "__ginqstarcol_" + id + "_" + label; + } + + private static String quoteBracket(String name) { + return "[" + name.replace("]", "]]") + "]"; + } + + private static int nextStarToken(String sql, int from) { + int best = -1; + for (String needle : new String[] {"__ginqsrc_", "__ginqpass_", "__ginqstar_", "__ginqcol_"}) { + int at = indexOfIgnoreCase(sql, needle, from); + if (at >= 0 && (best < 0 || at < best)) { + best = at; + } + } + return best; + } + + private static int indexOfIgnoreCase(String sql, String needle, int from) { + int limit = sql.length() - needle.length(); + for (int i = from; i <= limit; i++) { + if (sql.regionMatches(true, i, needle, 0, needle.length())) { + return i; + } + } + return -1; + } + + private static StarToken readStarToken(String sql, int at) { + int p = at + 6; + String kind = null; + if (sql.regionMatches(true, p, "src_", 0, 4)) { + kind = "src"; + } else if (sql.regionMatches(true, p, "pass_", 0, 5)) { + kind = "pass"; + } else if (sql.regionMatches(true, p, "star_", 0, 5)) { + kind = "star"; + } else if (sql.regionMatches(true, p, "col_", 0, 4)) { + kind = "col"; + } + if (kind == null) { + return null; + } + p += kind.length() + 1; + int idStart = p; + while (p < sql.length() && Character.isDigit(sql.charAt(p))) { + p++; + } + if (p == idStart) { + return null; + } + int id = Integer.parseInt(sql.substring(idStart, p)); + String column = null; + if (("col".equals(kind) || "star".equals(kind)) && p < sql.length() && sql.charAt(p) == '_') { + int nameStart = ++p; + while (p < sql.length() && isIdent(sql.charAt(p))) { + p++; + } + if (p == nameStart) { + return null; + } + column = sql.substring(nameStart, p); + } + int tokenStart = at; + char open = 0; + if (at > 0) { + char prev = sql.charAt(at - 1); + if (prev == '"' || prev == '`' || prev == '[') { + open = prev; + tokenStart = at - 1; + } + } + int end = p; + if (open != 0) { + char close = open == '[' ? ']' : open; + if (p >= sql.length() || sql.charAt(p) != close) { + return null; + } + end = p + 1; + } + int q = tokenStart - 1; + while (q >= 0 && Character.isWhitespace(sql.charAt(q))) { + q--; + } + if (q < 0 || sql.charAt(q) != '.') { + return null; + } + q--; + while (q >= 0 && Character.isWhitespace(sql.charAt(q))) { + q--; + } + if (q < 0) { + return null; + } + int qualifierEnd = q + 1; + int qualifierStart; + char mark = sql.charAt(q); + if (mark == '"' || mark == '`' || mark == ']') { + char opener = mark == ']' ? '[' : mark; + qualifierStart = sql.lastIndexOf(opener, q - 1); + if (qualifierStart < 0) { + return null; + } + } else { + qualifierStart = q; + while (qualifierStart > 0 && isIdent(sql.charAt(qualifierStart - 1))) { + qualifierStart--; + } + } + StarToken token = new StarToken(); + token.kind = kind; + token.id = id; + token.column = "col".equals(kind) ? column : null; + token.alias = "star".equals(kind) ? column : null; + token.end = end; + token.qualifierStart = qualifierStart; + token.qualifierEnd = qualifierEnd; + return token; + } + + private static final class StarToken { + String kind; + int id; + String column; + String alias; + int end; + int qualifierStart; + int qualifierEnd; + } + + private static int columnIndex(List names, String column) throws SQLException { + if (column == null) { + throw new SQLException("mixed-mode column reference is blank"); + } + for (int i = 0; i < names.size(); i++) { + if (names.get(i).equalsIgnoreCase(column)) { + return i; + } + } + throw new SQLException("mixed-mode join refers to unknown column `" + column + "`"); + } + + /** + * Replaces a mixed-mode {@code SELECT alias.*, ...} list with one named + * column per source label. The {@code FROM} clause, including its + * placeholders, is kept as rendered. + * + * @param sql the rendered prefix, projecting {@code alias.*} + * @param columnsByAlias column labels for each star, in select-list order + * @param quote the identifier quote, or {@code 0} for simple unquoted names + * @return the rewritten SQL + * @throws SQLException when a label is duplicated or the select list is not {@code alias.*} + */ + public static String rewriteStarSelect(String sql, List> columnsByAlias, char quote) throws SQLException { + int fromAt = indexOfTopLevelKeyword(sql, "from"); + int selectAt = indexOfTopLevelKeyword(sql, "select"); + if (selectAt < 0 || fromAt < 0 || selectAt > fromAt) { + throw new SQLException("mixed-mode SQL has no SELECT ... FROM shape"); + } + String selectList = sql.substring(selectAt + "select".length(), fromAt).trim(); + List aliases = new ArrayList<>(); + for (String item : splitTopLevel(selectList, ',')) { + String trimmed = item.trim(); + if (trimmed.length() < 3 || !trimmed.endsWith(".*")) { + throw new SQLException("mixed-mode prefix projection is not alias.* (" + trimmed + ")"); + } + aliases.add(trimmed.substring(0, trimmed.length() - 2).trim()); + } + if (aliases.size() != columnsByAlias.size()) { + throw new SQLException("mixed-mode SQL projects " + aliases.size() + + " aliases but " + columnsByAlias.size() + " column layouts were supplied"); + } + StringBuilder select = new StringBuilder("SELECT "); + boolean any = false; + for (int alias = 0; alias < aliases.size(); alias++) { + List names = columnsByAlias.get(alias); + requireDistinctLabels(names); + if (names.isEmpty()) { + throw new SQLException("mixed-mode source has no columns to reconstruct"); + } + for (int c = 0; c < names.size(); c++) { + if (any) { + select.append(", "); + } + any = true; + select.append(aliases.get(alias)).append('.').append(quoteIdentifier(names.get(c), quote)); + select.append(" AS ").append(quoteIdentifier("__ginq" + alias + "_" + c, quote)); + } + } + return select.append(' ').append(sql.substring(fromAt)).toString(); + } + + private static final String PRESENCE_BASE = "__ginq_present"; + private static final String SOURCE_ALIAS = "__ginq_src"; + private static final String[] JOIN_PHRASES = { + "full outer join", "left outer join", "right outer join", + "full join", "left join", "right join", "inner join", "cross join", "join" + }; + private static final String[] FROM_LIST_END = { + "where", "group", "having", "window", "order", "limit", "fetch", "offset", + "union", "except", "intersect", "minus" + }; + + private static String presenceName(List> columnsByAlias) { + List all = new ArrayList<>(); + for (List names : columnsByAlias) { + all.addAll(names); + } + return freshName(all, PRESENCE_BASE); + } + + private static List> withPresence(List> columnsByAlias, String presence) { + List> extended = new ArrayList<>(columnsByAlias.size()); + for (List names : columnsByAlias) { + List copy = new ArrayList<>(names.size() + 1); + copy.addAll(names); + copy.add(presence); + extended.add(copy); + } + return extended; + } + + /** + * Wraps every top-level source of {@code sql}'s {@code FROM} list so the + * source itself projects {@code 1 AS presence}. An outer join then nulls + * that column together with the rest of an unmatched side. + */ + private static String wrapPresenceSources(String sql, int sourceCount, String presence, char quote) throws SQLException { + int fromAt = indexOfTopLevelKeyword(sql, "from"); + if (fromAt < 0) { + throw new SQLException("mixed-mode SQL has no FROM clause to mark presence"); + } + int fromEnd = endOfFromList(sql, fromAt); + StringBuilder out = new StringBuilder(sql.length() + 64 * sourceCount); + out.append(sql, 0, fromAt); + int wrapped = writeWrappedFromList(sql, fromAt, fromEnd, presence, quote, out); + if (wrapped != sourceCount) { + throw new SQLException("mixed-mode FROM clause has " + wrapped + + " sources but " + sourceCount + " aliases were supplied"); + } + out.append(sql, fromEnd, sql.length()); + return out.toString(); + } + + private static int endOfFromList(String sql, int fromAt) throws SQLException { + int i = fromAt + "from".length(); + int depth = 0; + Quote quote = Quote.NONE; + while (i < sql.length()) { + char ch = sql.charAt(i); + if (quote != Quote.NONE) { + i = skipQuoted(sql, i, quote); + quote = Quote.NONE; + continue; + } + Quote opened = openingQuote(ch); + if (opened != Quote.NONE) { + quote = opened; + i++; + continue; + } + if (ch == '(') { + depth++; + i++; + continue; + } + if (ch == ')') { + if (depth == 0) { + return i; + } + depth--; + i++; + continue; + } + if (depth == 0 && clauseEndsFromList(sql, i)) { + return i; + } + i++; + } + return sql.length(); + } + + private static int writeWrappedFromList(String sql, int fromAt, int fromEnd, String presence, char quote, + StringBuilder out) throws SQLException { + int i = fromAt; + if (!isBareKeywordAt(sql, i, "from")) { + throw new SQLException("mixed-mode SQL has no FROM clause to mark presence"); + } + i += "from".length(); + out.append("FROM "); + SourceAndAlias first = readSource(sql, i, fromEnd); + out.append(wrapSource(first, presence, quote)); + i = first.end; + int count = 1; + while (true) { + i = skipWs(sql, i, fromEnd); + if (i >= fromEnd) { + return count; + } + int joinLength = matchJoinPhrase(sql, i); + if (joinLength < 0) { + throw new SQLException("mixed-mode FROM clause could not be wrapped near `" + + snippet(sql, i) + "`"); + } + out.append(' ').append(sql, i, i + joinLength).append(' '); + i += joinLength; + SourceAndAlias source = readSource(sql, i, fromEnd); + out.append(wrapSource(source, presence, quote)); + i = source.end; + i = skipWs(sql, i, fromEnd); + if (i < fromEnd && isBareKeywordAt(sql, i, "on")) { + int onAt = i; + i += "on".length(); + int onEnd = endOfOnClause(sql, i, fromEnd); + out.append(' ').append(sql, onAt, onEnd); + i = onEnd; + } + count++; + } + } + + private static int endOfOnClause(String sql, int start, int fromEnd) throws SQLException { + int i = start; + int depth = 0; + Quote quote = Quote.NONE; + while (i < fromEnd) { + char ch = sql.charAt(i); + if (quote != Quote.NONE) { + i = skipQuoted(sql, i, quote); + quote = Quote.NONE; + continue; + } + Quote opened = openingQuote(ch); + if (opened != Quote.NONE) { + quote = opened; + i++; + continue; + } + if (ch == '(') { + depth++; + i++; + continue; + } + if (ch == ')') { + if (depth == 0) { + return i; + } + depth--; + i++; + continue; + } + if (depth == 0 && matchJoinPhrase(sql, i) > 0) { + return i; + } + i++; + } + return fromEnd; + } + + private static String wrapSource(SourceAndAlias source, String presence, char quote) throws SQLException { + String inner = quoteIdentifier(SOURCE_ALIAS, quote); + String marker = quoteIdentifier(presence, quote); + return "(SELECT " + inner + ".*, 1 AS " + marker + " FROM " + source.text + " " + inner + ") " + source.alias; + } + + private static SourceAndAlias readSource(String sql, int start, int fromEnd) throws SQLException { + int i = skipWs(sql, start, fromEnd); + if (i >= fromEnd) { + throw new SQLException("mixed-mode FROM clause is missing a source"); + } + int sourceAt = i; + if (sql.charAt(i) == '(') { + i = skipGroup(sql, i); + } else { + i = readQualifiedName(sql, i, fromEnd); + } + if (i > fromEnd) { + throw new SQLException("mixed-mode FROM clause source runs past the clause"); + } + String text = sql.substring(sourceAt, i); + i = skipWs(sql, i, fromEnd); + if (i < fromEnd && isBareKeywordAt(sql, i, "as")) { + i = skipWs(sql, i + "as".length(), fromEnd); + } + int aliasAt = i; + i = readIdentifier(sql, i, fromEnd); + if (i == aliasAt) { + throw new SQLException("mixed-mode FROM clause source `" + text + "` has no alias"); + } + return new SourceAndAlias(text, sql.substring(aliasAt, i), i); + } + + private static int readQualifiedName(String sql, int start, int fromEnd) throws SQLException { + int i = readIdentifier(sql, start, fromEnd); + if (i == start) { + throw new SQLException("mixed-mode FROM clause has no table name near `" + snippet(sql, start) + "`"); + } + while (true) { + int after = skipWs(sql, i, fromEnd); + if (after >= fromEnd || sql.charAt(after) != '.') { + return i; + } + int next = skipWs(sql, after + 1, fromEnd); + int ident = readIdentifier(sql, next, fromEnd); + if (ident == next) { + throw new SQLException("mixed-mode FROM clause has a dangling qualifier near `" + snippet(sql, after) + "`"); + } + i = ident; + } + } + + private static int readIdentifier(String sql, int start, int fromEnd) throws SQLException { + if (start >= fromEnd) { + return start; + } + char ch = sql.charAt(start); + Quote quote = openingQuote(ch); + if (quote == Quote.DOUBLE || quote == Quote.BACK) { + return skipQuoted(sql, start + 1, quote); + } + int i = start; + while (i < fromEnd && isIdent(sql.charAt(i))) { + i++; + } + return i; + } + + private static int skipGroup(String sql, int openParen) throws SQLException { + int i = openParen + 1; + int depth = 1; + Quote quote = Quote.NONE; + while (i < sql.length()) { + char ch = sql.charAt(i); + if (quote != Quote.NONE) { + i = skipQuoted(sql, i, quote); + quote = Quote.NONE; + continue; + } + Quote opened = openingQuote(ch); + if (opened != Quote.NONE) { + quote = opened; + i++; + continue; + } + if (ch == '(') { + depth++; + } else if (ch == ')') { + depth--; + if (depth == 0) { + return i + 1; + } + } + i++; + } + throw new SQLException("mixed-mode SQL has an unclosed parenthesis"); + } + + private static int skipQuoted(String sql, int start, Quote quote) throws SQLException { + char mark = quote.mark; + for (int i = start; i < sql.length(); i++) { + if (sql.charAt(i) != mark) { + continue; + } + if (i + 1 < sql.length() && sql.charAt(i + 1) == mark) { + i++; + continue; + } + return i + 1; + } + throw new SQLException("mixed-mode SQL has an unclosed quoted literal"); + } + + private static int matchJoinPhrase(String sql, int start) { + for (String phrase : JOIN_PHRASES) { + int consumed = phraseLengthAt(sql, start, phrase); + if (consumed > 0) { + return consumed; + } + } + return -1; + } + + private static int phraseLengthAt(String sql, int start, String phrase) { + int i = start; + int word = 0; + int length = phrase.length(); + while (word < length) { + int end = phrase.indexOf(' ', word); + if (end < 0) { + end = length; + } + String token = phrase.substring(word, end); + if (i >= sql.length() || !isBareKeywordAt(sql, i, token)) { + return -1; + } + i += token.length(); + if (end == length) { + return i - start; + } + if (i >= sql.length() || !isWs(sql.charAt(i))) { + return -1; + } + while (i < sql.length() && isWs(sql.charAt(i))) { + i++; + } + word = end + 1; + } + return -1; + } + + private static boolean clauseEndsFromList(String sql, int i) { + for (String keyword : FROM_LIST_END) { + if (isBareKeywordAt(sql, i, keyword)) { + return true; + } + } + return false; + } + + private static boolean isBareKeywordAt(String sql, int i, String keyword) { + if (i > 0) { + char prev = sql.charAt(i - 1); + if (prev == '.' || isIdent(prev)) { + return false; + } + } + return isKeywordAt(sql, i, keyword); + } + + private static int skipWs(String sql, int i, int end) { + while (i < end && isWs(sql.charAt(i))) { + i++; + } + return i; + } + + private static boolean isWs(char ch) { + return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '\f'; + } + + private static Quote openingQuote(char ch) { + if (ch == '\'') { + return Quote.SINGLE; + } + if (ch == '"') { + return Quote.DOUBLE; + } + if (ch == '`') { + return Quote.BACK; + } + return Quote.NONE; + } + + private static String snippet(String sql, int i) { + int end = Math.min(sql.length(), i + 40); + return sql.substring(i, end).replace('\n', ' '); + } + + private enum Quote { + NONE('\0'), SINGLE('\''), DOUBLE('"'), BACK('`'); + + final char mark; + + Quote(char mark) { + this.mark = mark; + } + } + + private static final class SourceAndAlias { + final String text; + final String alias; + final int end; + + SourceAndAlias(String text, String alias, int end) { + this.text = text; + this.alias = alias; + this.end = end; + } + } + + private static void requireDistinctLabels(List names) throws SQLException { + Map seen = new LinkedHashMap<>(); + List duplicates = new ArrayList<>(); + for (String name : names) { + String folded = name.toLowerCase(Locale.ROOT); + String first = seen.put(folded, name); + if (first != null) { + duplicates.add(name); + } + } + if (!duplicates.isEmpty()) { + throw new SQLException("mixed mode cannot reconstruct a source row because JDBC returned duplicate column labels " + + duplicates + " within one alias. Drivers differ on labels, case folding and quoting, " + + "and a duplicate label would drop a value. Project that source with distinct column names."); + } + } + + static String quoteIdentifier(String name, char quote) throws SQLException { + if (name == null || name.isEmpty()) { + throw new SQLException("mixed-mode column name is blank"); + } + if (quote == 0) { + if (!simpleIdentifier(name)) { + throw new SQLException("mixed-mode column `" + name + "` needs quoting and this dialect does not quote identifiers"); + } + return name; + } + String mark = String.valueOf(quote); + return mark + name.replace(mark, mark + mark) + mark; + } + + private static boolean simpleIdentifier(String name) { + for (int i = 0; i < name.length(); i++) { + char ch = name.charAt(i); + boolean letter = (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || ch == '_'; + boolean digit = ch >= '0' && ch <= '9'; + if (i == 0 ? !letter : !(letter || digit)) { + return false; + } + } + return true; + } + + private static String freshName(List existing, String base) { + String candidate = base; + int n = 0; + while (containsIgnoreCase(existing, candidate)) { + candidate = base + "_" + (++n); + } + return candidate; + } + + private static boolean containsIgnoreCase(List names, String candidate) { + for (String name : names) { + if (name.equalsIgnoreCase(candidate)) { + return true; + } + } + return false; + } + + private static char quoteChar(String identifierQuote) throws SQLException { + if (identifierQuote == null || identifierQuote.isEmpty()) { + return 0; + } + if (identifierQuote.length() != 1) { + throw new SQLException("mixed-mode identifier quote must be one character"); + } + return identifierQuote.charAt(0); + } + + private static int indexOfTopLevelKeyword(String sql, String keyword) { + if (sql == null) { + return -1; + } + int depth = 0; + for (int i = 0; i < sql.length(); i++) { + char ch = sql.charAt(i); + if (ch == '(') { + depth++; + } else if (ch == ')') { + depth--; + } else if (depth == 0 && isKeywordAt(sql, i, keyword)) { + return i; + } + } + return -1; + } + + private static boolean isKeywordAt(String sql, int i, String keyword) { + int end = i + keyword.length(); + if (end > sql.length() || !sql.regionMatches(true, i, keyword, 0, keyword.length())) { + return false; + } + if (i > 0 && isIdent(sql.charAt(i - 1))) { + return false; + } + return end >= sql.length() || !isIdent(sql.charAt(end)); + } + + private static boolean isIdent(char ch) { + return (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_'; + } + + private static List splitTopLevel(String text, char separator) { + List parts = new ArrayList<>(); + int depth = 0; + int start = 0; + for (int i = 0; i < text.length(); i++) { + char ch = text.charAt(i); + if (ch == '(') { + depth++; + } else if (ch == ')') { + depth--; + } else if (ch == separator && depth == 0) { + parts.add(text.substring(start, i)); + start = i + 1; + } + } + parts.add(text.substring(start)); + return parts; + } + + private static void bind(PreparedStatement statement, List params) throws SQLException { + if (params == null) { + return; + } + for (int i = 0; i < params.size(); i++) { + statement.setObject(i + 1, params.get(i)); + } + } + + private static T withConnection(Object dataSource, SqlWork work) throws SQLException { + if (dataSource instanceof Sql) { + Sql sql = (Sql) dataSource; + Connection connection = sql.getConnection(); + if (connection != null) { + return work.run(connection); + } + DataSource nested = sql.getDataSource(); + if (nested == null) { + throw unsupported(dataSource); + } + try (Connection borrowed = nested.getConnection()) { + return work.run(borrowed); + } + } + if (dataSource instanceof DataSource) { + try (Connection borrowed = ((DataSource) dataSource).getConnection()) { + return work.run(borrowed); + } + } + if (dataSource instanceof Connection) { + return work.run((Connection) dataSource); + } + throw unsupported(dataSource); + } + + private static IllegalArgumentException unsupported(Object dataSource) { + return new IllegalArgumentException("Unsupported dataSource: expected a groovy.sql.Sql, javax.sql.DataSource or java.sql.Connection but got: " + + (dataSource == null ? "null" : dataSource.getClass().getName())); + } + + @FunctionalInterface + private interface SqlWork { + T run(Connection connection) throws SQLException; + } + + /** + * Builds a {@code LIKE} pattern from a runtime value, escaping the + * wildcard characters {@code %} and {@code _} (and the escape character + * itself) with {@code !}, matching the {@code ESCAPE '!'} clause the + * renderer emits. Used for {@code contains}/{@code startsWith}/{@code endsWith}. + * + * @param value the value to match literally; {@code null} stays {@code null} + * so the predicate is unknown instead of matching the text {@code "null"} + * @param matchBefore whether anything may precede the value + * @param matchAfter whether anything may follow the value + * @return the escaped pattern, or {@code null} when {@code value} is {@code null} + */ + public static String likePattern(Object value, boolean matchBefore, boolean matchAfter) { + if (value == null) { + return null; + } + String escaped = String.valueOf(value) + .replace("!", "!!") + .replace("%", "!%") + .replace("_", "!_"); + return (matchBefore ? "%" : "") + escaped + (matchAfter ? "%" : ""); + } + + private SqlGinqRuntime() { + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/package-info.java b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/package-info.java new file mode 100644 index 00000000000..06849d1bd89 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/runtime/package-info.java @@ -0,0 +1,24 @@ +/* + * 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 + * + * http://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. + */ + +/** + * Runtime support invoked by the generated code of the SQL provider to execute + * the rendered SQL against a data source. + */ +package org.apache.groovy.ginq.provider.sql.runtime; diff --git a/subprojects/groovy-ginq-sql/src/main/resources/META-INF/services/org.apache.groovy.ginq.provider.GinqProvider b/subprojects/groovy-ginq-sql/src/main/resources/META-INF/services/org.apache.groovy.ginq.provider.GinqProvider new file mode 100644 index 00000000000..ab1922abb2b --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/resources/META-INF/services/org.apache.groovy.ginq.provider.GinqProvider @@ -0,0 +1,16 @@ +# 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 +# +# http://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. +org.apache.groovy.ginq.provider.sql.NativeSqlGinqProvider +org.apache.groovy.ginq.provider.sql.jooq.JooqSqlGinqProvider diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlErrorTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlErrorTest.groovy new file mode 100644 index 00000000000..76e7e5db0dd --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlErrorTest.groovy @@ -0,0 +1,433 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.shouldFail + +/** + * Asserts the strict-mode compile-time errors of the native-sql provider. + */ +class GinqSqlErrorTest { + + @Test + void testMissingDataSource() { + def err = shouldFail '''\ + GQ(provider: 'native-sql') { + from e in 'employees' + select e.name + } + ''' + assert err.message.contains("the native-sql provider requires a `dataSource`") + } + + @Test + void testParallelNotSupported() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db, parallel: true) { + from e in 'employees' + select e.name + } + ''' + assert err.message.contains('`parallel` is not supported by the native-sql provider') + } + + @Test + void testNonLiteralTableReference() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from n in [1, 2, 3] + select n + } + ''' + assert err.message.contains('table references must be string literals') + } + + @Test + void testUnknownAliasInsideSubquery() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where (from d in 'departments' where d.id == z.deptId select d.id).exists() + select e.name + } + ''' + assert err.message.contains('Unknown alias in `z.deptId`') + } + + @Test + void testUntranslatableOperator() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name ==~ /A.*/ + select e.name + } + ''' + assert err.message.contains('Operator `==~` cannot be translated to SQL by the native-sql provider') + } + + @Test + void testUntranslatableExpression() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name == "prefix${'x'}" + select e.name + } + ''' + assert err.message.contains('cannot be translated to SQL by the native-sql provider') + } + + @Test + void testUntranslatableMethod() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.reverse() == 'ecilA' + select e.name + } + ''' + assert err.message.contains('Method `reverse` cannot be translated to SQL by the native-sql provider') + } + + @Test + void testCapturedCollectionInList() { + def err = shouldFail '''\ + def salaries = [3000, 4000] + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary in salaries + select e.name + } + ''' + assert err.message.contains('only list literals, constant ranges and subqueries are supported on the right-hand side of `in`') + assert err.message.contains('mixedMode: true') + } + + @Test + void testUnknownAlias() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where x.salary > 1000 + select e.name + } + ''' + assert err.message.contains('Unknown alias in `x.salary`') + } + + @Test + void testWindowFunctionNotSupported() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name, (rowNumber() over (orderby e.salary)) + } + ''' + assert err.message.contains('window functions are deferred and are not translated by the native-sql provider') + assert err.message.contains('mixedMode: true') + } + + @Test + void testOrderByInInnerSetOperationOperand() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from a in 'employees' + orderby a.name + select a.name + union + from b in 'employees' + select b.name + } + ''' + assert err.message.contains('`orderby` within set operation operands is only supported on the final operand') + } + + @Test + void testOrderByOnSetOperationResultMustMatchSelect() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from a in 'employees' + select a.name + union + from b in 'employees' + orderby b.salary + select b.name + } + ''' + assert err.message.contains('`orderby` on a set operation result must reference columns of the final `select` clause') + } + + @Test + void testElvisOperator() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name ?: 'unknown' + } + ''' + assert err.message.contains('the Elvis operator cannot be translated to SQL by the native-sql provider') + } + + @Test + void testLikeArgumentMustBeParameter() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + where e.name.contains(d.name) + select e.name + } + ''' + assert err.message.contains('the arguments of `contains` must be literals or captured variables') + } + + @Test + void testGroupKeyNotInGroupBy() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + groupby e.deptId into g + select g.name + } + ''' + assert err.message.contains('`g.name` is not in the `groupby` clause') + } + + @Test + void testShutdownNotSupported() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + shutdown immediate + } + ''' + assert err.message.contains('`shutdown` is not supported by the native-sql provider') + } + + @Test + void testUnknownJooqDialect() { + def err = shouldFail '''\ + GQ(provider: 'jooq-sql', dialect: 'NOPE', dataSource: db) { + from e in 'employees' + select e.name + } + ''' + assert err.message.contains('Unknown dialect: NOPE') + } + + @Test + void testSqliteRejectsFloorAndCeiling() { + def floor = shouldFail '''\ + GQ(provider: 'native-sql', dialect: 'sqlite', dataSource: db) { + from e in 'employees' + select e.salary.floor() + } + ''' + assert floor.message.contains('FLOOR') + assert floor.message.contains('sqlite') + assert floor.message.contains('floor()') + + def ceiling = shouldFail '''\ + GQ(provider: 'native-sql', dialect: 'sqlite', dataSource: db) { + from e in 'employees' + select e.salary.ceil() + } + ''' + assert ceiling.message.contains('CEILING') + assert ceiling.message.contains('sqlite') + assert ceiling.message.contains('ceil()') + } + + @Test + void testUnknownNativeDialect() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dialect: 'ORACLE', dataSource: db) { + from e in 'employees' + select e.name + } + ''' + assert err.message.contains('`ORACLE` is not a native SQL dialect') + assert err.message.contains('postgres') + assert err.message.contains("provider: 'jooq-sql'") + } + + @Test + void testUnsafeTableNameIsRejected() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees; delete from employees' + select e.name + } + ''' + assert err.message.contains('table name `employees; delete from employees` must be a simple identifier') + assert !err.message.contains('mixedMode') + } + + @Test + void testVariableRangeIsRejected() { + def err = shouldFail '''\ + def low = 1 + def high = 3 + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id in low..high + select e.id + } + ''' + assert err.message.contains('both bounds are compile-time constants') + assert err.message.contains('mixedMode: true') + } + + @Test + void testJooqProviderNamesItself() { + def err = shouldFail '''\ + GQ(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + select e.name.reverse() + } + ''' + assert err.message.contains('jooq-sql provider') + assert err.message.contains('mixedMode: true') + } + + @Test + void testAnnotationWithoutDataSource() { + def err = shouldFail '''\ + import groovy.ginq.transform.GQ + + class Repository { + @GQ(provider = 'native-sql') + def names() { + from e in 'employees' + select e.name + } + } + ''' + assert err.message.contains("the native-sql provider requires a `dataSource`") + } + + @Test + void testCoalesceNeedsTwoArguments() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select coalesce(e.name) + } + ''' + assert err.message.contains('`coalesce` expects at least two arguments') + } + + @Test + void testDistinctAggregateOnlyForCount() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select sum(distinct(e.salary)) + } + ''' + assert err.message.contains('distinct aggregates are supported only for `count`') + } + + @Test + void testCountDistinctExpectsOneExpression() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select count(distinct(e.salary, e.deptId)) + } + ''' + assert err.message.contains('`count(distinct(...))` expects a single expression') + } + + @Test + void testCastRejectsUnknownType() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select cast(e.id, 'JAVA_OBJECT') + } + ''' + assert err.message.contains('`cast` type `JAVA_OBJECT` is not a supported SQL type') + + def injected = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select cast(e.id, 'INTEGER); DROP TABLE employees') + } + ''' + assert injected.message.contains('is not a supported SQL type') + + def displayWidth = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select cast(e.id, 'INT(11)') + } + ''' + assert displayWidth.message.contains('`cast` type `INT(11)` is not a supported SQL type') + } + + @Test + void testCastRejectsNonLiteralType() { + def err = shouldFail '''\ + def typeName = 'INTEGER' + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select cast(e.id, typeName) + } + ''' + assert err.message.contains('`cast` requires a string literal SQL type') + } + + @Test + void testIndexOfRejectsFromIndex() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name.indexOf('A', 1) + } + ''' + assert err.message.contains('A from-index has no portable SQL form') + } + + @Test + void testMathMaxExpectsTwoArguments() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select Math.max(e.salary) + } + ''' + assert err.message.contains('`Math.max` and `Math.min` expect two arguments') + } + + @Test + void testAggregateLambdaParamForMultiTableQuery() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + groupby d.name into g + select g.name, g.sum(x -> x.salary) + } + ''' + assert err.message.contains('name the aggregate lambda parameter after a table alias') + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlIntegrationTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlIntegrationTest.groovy new file mode 100644 index 00000000000..d8f54fe9900 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlIntegrationTest.groovy @@ -0,0 +1,750 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.sql.Sql +import org.h2.jdbcx.JdbcDataSource +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +import java.sql.DriverManager + +/** + * Runs GINQ queries end-to-end against an in-memory H2 database + * via the native-sql provider. + */ +class GinqSqlIntegrationTest { + private String dbUrl + private Sql db + + @BeforeEach + void setUp() { + dbUrl = GinqSqlTestSupport.newDbUrl() + db = GinqSqlTestSupport.newPopulatedDb(dbUrl) + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void testSingleTableWhereWithCapturedVariable() { + def threshold = 2500 + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary > threshold && e.active == true + orderby e.name + select e.name, e.salary + } + assert [['Alice', 5000], ['Bob', 3000], ['Carol', 4000], ['Eve', 5000], ['Frank', 6000]] == + result.collect { [it.name, it.salary] } + } + + @Test + void testOrderByDescAndLimit() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.salary in desc, e.name + limit 1, 2 + select e.name + } + assert ['Alice', 'Eve'] == result.collect { it.name } + } + + @Test + void testDistinct() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.active == true + orderby e.salary + select distinct(e.salary) + } + assert [3000, 4000, 5000, 6000] == result.collect { it.salary } + } + + @Test + void testIsNull() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId == null + select e.name + } + assert ['Dave'] == result.collect { it.name } + } + + @Test + void testInAndNotIn() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary in [3000, 4000] + orderby e.name + select e.name + } + assert ['Bob', 'Carol'] == result.collect { it.name } + + result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary !in [3000, 4000] + orderby e.name + select e.name + } + assert ['Alice', 'Dave', 'Eve', 'Frank'] == result.collect { it.name } + } + + @Test + void testFunctionMapping() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.toUpperCase() == 'ALICE' + select e.name.toLowerCase() as lname + } + assert ['alice'] == result.collect { it.lname } + } + + @Test + void testInnerJoin() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + orderby e.name + select e.name, d.name as deptName + } + assert [['Alice', 'Dev'], ['Bob', 'Dev'], ['Carol', 'Sales'], ['Eve', 'Sales'], ['Frank', 'Support']] == + result.collect { [it.name, it.deptName] } + } + + @Test + void testLeftJoin() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + leftjoin d in 'departments' on e.deptId == d.id + orderby e.name + select e.name, d.name as deptName + } + assert [['Alice', 'Dev'], ['Bob', 'Dev'], ['Carol', 'Sales'], ['Dave', null], ['Eve', 'Sales'], ['Frank', 'Support']] == + result.collect { [it.name, it.deptName] } + } + + @Test + void testCrossJoin() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + crossjoin d in 'departments' + select e.name, d.name as deptName + } + assert 18 == result.size() + } + + @Test + void testGroupByWithAggregates() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId into g + orderby g.deptId + select g.deptId, g.count() as cnt, g.avg(e -> e.salary) as avgSalary, + g.min(e -> e.salary) as minSalary, g.max(e -> e.salary) as maxSalary + } + assert [[1, 2, 4000, 3000, 5000], [2, 2, 4500, 4000, 5000], [3, 1, 6000, 6000, 6000]] == + result.collect { [it.deptId, it.cnt, it.avgSalary, it.minSalary, it.maxSalary] } + } + + @Test + void testGroupByHaving() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId into g + having g.count() > 1 + orderby g.deptId + select g.deptId + } + assert [1, 2] == result.collect { it.deptId } + } + + @Test + void testJoinWithGroupBy() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + groupby d.name into g + orderby g.name + select g.name, g.sum(e -> e.salary) as total + } + assert [['Dev', 8000], ['Sales', 9000], ['Support', 6000]] == + result.collect { [it.name, it.total] } + } + + @Test + void testWholeTableAggregates() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select count() as cnt, max(e.salary) as maxSalary, min(e.salary) as minSalary + } + assert [[6, 6000, 2000]] == result.collect { [it.cnt, it.maxSalary, it.minSalary] } + } + + @Test + void testUnionAndUnionAll() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.salary + union + from b in 'employees' + where b.deptId == 2 + select b.salary + } + assert [3000, 4000, 5000] == result.collect { it.salary }.sort() + + result = GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.salary + unionall + from b in 'employees' + where b.deptId == 2 + select b.salary + } + assert [3000, 4000, 5000, 5000] == result.collect { it.salary }.sort() + } + + @Test + void testIntersectAndMinus() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.salary + intersect + from b in 'employees' + where b.deptId == 2 + select b.salary + } + assert [5000] == result.collect { it.salary } + + result = GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.salary + minus + from b in 'employees' + where b.deptId == 2 + select b.salary + } + assert [3000] == result.collect { it.salary } + } + + @Test + void testLikeMethods() { + def part = 'li' + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.contains(part) + select e.name + } + assert ['Alice'] == result.collect { it.name } + + result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.startsWith('Da') || e.name.endsWith('ve') + orderby e.name + select e.name + } + assert ['Dave', 'Eve'] == result.collect { it.name } + } + + @Test + void testLikeWildcardsAreEscaped() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.startsWith('A%') + select e.name + } + // '%' matches literally, so 'Alice' must not match 'A%...' + assert [] == result + } + + @Test + void testSubstring() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.substring(0, 3) == 'Ali' + select e.name.substring(1) as rest + } + assert ['lice'] == result.collect { it.rest } + } + + @Test + void testReplaceAndConcat() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name + '!' == 'Bob!' + select e.name.replace('B', 'R') + '?' as renamed + } + assert ['Rob?'] == result.collect { it.renamed } + } + + @Test + void testTernaryBecomesCaseWhen() { + // equal-length branch literals since some databases infer a + // CHAR(n) type for the CASE expression and pad the shorter value + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, (e.salary > 4000 ? 'high' : 'low!') as band + } + assert [['Alice', 'high'], ['Bob', 'low!'], ['Carol', 'low!'], ['Dave', 'low!'], ['Eve', 'high'], ['Frank', 'high']] == + result.collect { [it.name, it.band] } + } + + @Test + void testClassicGroupBy() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId + orderby e.deptId + select e.deptId, count() as cnt, sum(e.salary) as total + } + assert [[1, 2, 8000], [2, 2, 9000], [3, 1, 6000]] == + result.collect { [it.deptId, it.cnt, it.total] } + } + + @Test + void testClassicGroupByWithHavingAndJoin() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + groupby d.name + having count() > 1 + orderby d.name + select d.name, max(e.salary) as top + } + assert [['Dev', 5000], ['Sales', 5000]] == result.collect { [it.name, it.top] } + } + + @Test + void testClassicGroupByWithKeyAlias() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId as dept + orderby dept + select dept, count() as cnt + } + assert [[1, 2], [2, 2], [3, 1]] == result.collect { [it.dept, it.cnt] } + } + + @Test + void testSetOperationWithTrailingOrderByAndLimit() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.name, a.salary + union + from b in 'employees' + where b.deptId == 2 + orderby b.salary in desc, b.name + limit 1, 2 + select b.name, b.salary + } + // combined rows ordered by salary desc, name asc: Alice/5000, Eve/5000, Carol/4000, Bob/3000; offset 1, size 2 + def sqlRows = result.collect { [it.name, it.salary] } + assert [['Eve', 5000], ['Carol', 4000]] == sqlRows + + // the same clause text on the collection provider orders the last operand, then combines + def employees = [ + [name: 'Alice', salary: 5000, deptId: 1], + [name: 'Bob', salary: 3000, deptId: 1], + [name: 'Carol', salary: 4000, deptId: 2], + [name: 'Dave', salary: 2000, deptId: null], + [name: 'Eve', salary: 5000, deptId: 2], + [name: 'Frank', salary: 6000, deptId: 3] + ] + def collectionRows = GQ { + from a in employees + where a.deptId == 1 + select a.name, a.salary + union + from b in employees + where b.deptId == 2 + orderby b.salary in desc, b.name + limit 1, 2 + select b.name, b.salary + }.toList() + assert [['Alice', 5000], ['Bob', 3000], ['Carol', 4000]] == collectionRows + assert collectionRows != sqlRows + } + + @Test + void testDerivedTable() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from v in (from e in 'employees' where e.salary >= 4000 select e.name, e.salary) + where v.salary < 6000 + orderby v.name + select v.name + } + assert ['Alice', 'Carol', 'Eve'] == result.collect { it.name } + } + + @Test + void testDerivedTableInJoin() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join t in (from x in 'employees' where x.deptId != null groupby x.deptId select x.deptId, max(x.salary) as top) on e.deptId == t.deptId + where e.salary == t.top + orderby e.name + select e.name, e.salary + } + assert [['Alice', 5000], ['Eve', 5000], ['Frank', 6000]] == + result.collect { [it.name, it.salary] } + } + + @Test + void testCorrelatedExists() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where (from d in 'departments' where d.id == e.deptId select d.id).exists() + orderby e.name + select e.name + } + assert ['Alice', 'Bob', 'Carol', 'Eve', 'Frank'] == result.collect { it.name } + } + + @Test + void testInSubquery() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId in (from d in 'departments' where d.name != 'Support' select d.id) + orderby e.name + select e.name + } + assert ['Alice', 'Bob', 'Carol', 'Eve'] == result.collect { it.name } + } + + @Test + void testComputedInSubquery() { + // Parentheses close the where argument, so `in (subquery)` is outside it. + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def added = GQL(provider: 'native-sql', dataSource: captured) { + from e in 'employees' + where (e.salary + 1) in (from x in 'employees' where x.name == 'Alice' select x.salary + 1) + orderby e.name + select e.name + } + assert captured.sqlText.toUpperCase(Locale.ROOT).contains(' IN (') + assert ['Alice', 'Eve'] == added.collect { it.name } + + def parenthesized = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where (e.name) in (from x in 'employees' where x.salary > 4500 select x.name) + orderby e.name + select e.name + } + assert ['Alice', 'Eve', 'Frank'] == parenthesized.collect { it.name } + } + + @Test + void testNotInSubquery() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null && e.deptId !in (from d in 'departments' where d.name != 'Support' select d.id) + select e.name + } + assert ['Frank'] == result.collect { it.name } + } + + @Test + void testScalarSubquery() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary == (from x in 'employees' select max(x.salary)) + select e.name + } + assert ['Frank'] == result.collect { it.name } + } + + @Test + void testCorrelatedScalarSubqueryInSelect() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from d in 'departments' + orderby d.name + select d.name, (from e in 'employees' where e.deptId == d.id select count()) as headcount + } + assert [['Dev', 2], ['Sales', 2], ['Support', 1]] == result.collect { [it.name, it.headcount] } + } + + @Test + void testWholeRowProjection() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id == 1 + select e + } + assert 1 == result.size() + assert 'Alice' == result[0].name + assert 5000 == result[0].salary + } + + @Test + void testArithmeticInProjectionAndPredicate() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary * 2 > 9000 + orderby e.name + select e.name, e.salary + 500 as bumped + } + assert [['Alice', 5500], ['Eve', 5500], ['Frank', 6500]] == + result.collect { [it.name, it.bumped] } + } + + @Test + void testGQReturnsQueryable() { + def queryable = GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary >= 5000 + orderby e.name + select e.name + } + assert ['Alice', 'Eve', 'Frank'] == queryable.toList().collect { it.name } + } + + @Test + void testAutoDetectSqlProvider() { + def result = GQL(provider: 'sql', dataSource: db) { + from e in 'employees' + where e.id == 2 + select e.name + } + assert ['Bob'] == result.collect { it.name } + } + + @Test + void testExplicitAstWalker() { + def result = GQL(astWalker: 'org.apache.groovy.ginq.provider.sql.GinqSqlWalker', dataSource: db) { + from e in 'employees' + where e.id == 3 + select e.name + } + assert ['Carol'] == result.collect { it.name } + } + + @Test + void testDataSourceAsJdbcDataSource() { + def dataSource = new JdbcDataSource(URL: dbUrl, user: 'sa', password: '') + def result = GQL(provider: 'native-sql', dataSource: dataSource) { + from e in 'employees' + where e.id == 4 + select e.name + } + assert ['Dave'] == result.collect { it.name } + } + + @Test + void testDataSourceAsConnection() { + def connection = DriverManager.getConnection(dbUrl, 'sa', '') + try { + def result = GQL(provider: 'native-sql', dataSource: connection) { + from e in 'employees' + where e.id == 5 + select e.name + } + assert ['Eve'] == result.collect { it.name } + } finally { + connection.close() + } + } + + @Test + void testRealDivisionDoesNotTruncate() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id / 2 > 2 + orderby e.name + select e.name + } + assert ['Eve', 'Frank'] == result.collect { it.name } + } + + @Test + void testInListContainingNullMatchesNull() { + def onlyNull = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId in [null] + select e.name + } + assert ['Dave'] == onlyNull.collect { it.name } + + def withValue = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId in [1, null] + orderby e.name + select e.name + } + assert ['Alice', 'Bob', 'Dave'] == withValue.collect { it.name } + + def excluded = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId !in [1, null] + orderby e.name + select e.name + } + assert ['Carol', 'Eve', 'Frank'] == excluded.collect { it.name } + + def notNull = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId !in [null] + orderby e.name + select e.name + } + assert ['Alice', 'Bob', 'Carol', 'Eve', 'Frank'] == notNull.collect { it.name } + } + + @Test + void testEmptyInList() { + def none = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id in [] + select e.name + } + assert [] == none.toList() + def all = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id !in [] + select e.id + } + assert 6 == all.toList().size() + } + + @Test + void testContainsNullDoesNotMatchTheWordNull() { + def missing = null + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.contains(missing) || e.name == 'null' + select e.name + } + assert [] == result.toList() + } + + @Test + void testSumOfAllNullsIsZero() { + db.execute('insert into employees (id, name, salary, deptId, active) values (?, ?, ?, ?, ?)', + [7, 'Gina', null, 1, true]) + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name == 'Gina' + groupby e.name + select sum(e.salary) as total + } + assert 1 == result.toList().size() + assert result.toList()[0].total == 0 + } + + @Test + void testCoalesceMatchesNullTernary() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.id + select e.id, coalesce(e.deptId, 0) as dept, (e.deptId == null ? 0 : e.deptId) as viaTernary + } + assert [[1, 1, 1], [2, 1, 1], [3, 2, 2], [4, 0, 0], [5, 2, 2], [6, 3, 3]] == + result.collect { [it.id, it.dept, it.viaTernary] } + def onlyNullDept = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where coalesce(e.deptId, -1) == -1 + select e.name + } + assert ['Dave'] == onlyNullDept.collect { it.name } + } + + @Test + void testCountDistinct() { + db.execute('insert into employees (id, name, salary, deptId, active) values (?, ?, ?, ?, ?)', + [7, 'Grace', 5000, 1, true]) + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId + orderby e.deptId + select e.deptId, count() as cnt, count(distinct(e.salary)) as kinds + } + assert [[1, 3, 2], [2, 2, 2], [3, 1, 1]] == result.collect { [it.deptId, it.cnt, it.kinds] } + + def total = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select count(distinct(e.deptId)) as depts + } + assert 3 == total.toList()[0].depts + + def into = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId == 1 + groupby e.deptId into g + select g.count(distinct(e -> e.salary)) as viaCall, g.count(e -> distinct(e.salary)) as viaBody + } + assert [[2, 2]] == into.collect { [it.viaCall, it.viaBody] } + } + + @Test + void testMathMaxAndMinMatchComparison() { + def floor = 4500 + def cap = 5500 + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.id + select Math.max(e.salary, floor) as hi, (e.salary > floor ? e.salary : floor) as hiTernary, + Math.min(e.salary, cap) as lo, (e.salary < cap ? e.salary : cap) as loTernary + } + assert [[5000, 5000, 5000, 5000], + [4500, 4500, 3000, 3000], + [4500, 4500, 4000, 4000], + [4500, 4500, 2000, 2000], + [5000, 5000, 5000, 5000], + [6000, 6000, 5500, 5500]] == + result.collect { [it.hi, it.hiTernary, it.lo, it.loTernary] } + } + + @Test + void testCastThenDivideAndIndexOf() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id == 1 || e.id == 5 + orderby e.id + select e.id, cast(e.id, 'DECIMAL') / 2 as half, cast(e.salary, 'VARCHAR') as salaryText, + e.name.indexOf('l') as atL, e.name.indexOf('z') as missing + } + def rows = result.collect { [it.id, (it.half as BigDecimal), it.salaryText, it.atL, it.missing] } + assert [[1, 0.5G, '5000', 1, -1], [5, 2.5G, '5000', -1, -1]] == rows + } + + @Test + void testFunctionAndRangePushDown() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary in 5000..3000 && e.name.toLowerCase().concat('!') == 'alice!' + select e.name, e.salary.abs() as absSalary, e.salary.floor() as floorSalary, + e.salary.ceil() as ceilSalary, e.name.length() as nameLength + } + assert [['Alice', 5000, 5000, 5000, 5]] == + result.collect { [it.name, it.absSalary, it.floorSalary, it.ceilSalary, it.nameLength] } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedModeTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedModeTest.groovy new file mode 100644 index 00000000000..9288f8cac66 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedModeTest.groovy @@ -0,0 +1,330 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.sql.Sql +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.shouldFail + +/** + * Mixed-mode execution: the translatable clause prefix is pushed to H2 and + * the rest runs through the collection provider. Strict mode stays the default. + */ +class GinqSqlMixedModeTest { + private Sql realDb + private GinqSqlTranslationTest.CapturingSql db + + @BeforeEach + void setUp() { + realDb = GinqSqlTestSupport.newPopulatedDb() + db = new GinqSqlTranslationTest.CapturingSql(realDb) + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(realDb) + } + + @Test + void testFullyTranslatableQueryStaysSql() { + def threshold = 2500 + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > threshold + orderby e.name + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.salary > ? ORDER BY e.name ASC NULLS LAST' == db.sqlText + assert [2500] == db.params + assert ['Alice', 'Bob', 'Carol', 'Eve', 'Frank'] == result.collect { it.name } + } + + @Test + void testSelectFallsBackAfterPushedFilterOrderAndLimit() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > 2000 + orderby e.salary in desc, e.name + limit 2 + select e.name.reverse() + } + assert 'SELECT e.* FROM employees e WHERE e.salary > ? ' + + 'ORDER BY e.salary DESC NULLS LAST, e.name ASC NULLS LAST FETCH FIRST ? ROWS ONLY' == db.sqlText + assert [2000, 2] == db.params + assert ['knarF', 'ecilA'] == result.toList() + } + + @Test + void testWhereClauseIsNotSplitMidPredicate() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > 5000 && e.name.reverse() == 'knarF' + select e.name + } + assert 'SELECT e.* FROM employees e' == db.sqlText + assert [] == db.params + assert ['Frank'] == result.toList() + } + + @Test + void testCapturedValueStaysBoundWhenPrefixIsPushed() { + def name = "Alice' OR '1'='1" + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.name == name + select e.name.reverse() + } + assert 'SELECT e.* FROM employees e WHERE e.name IS NOT DISTINCT FROM ?' == db.sqlText + assert ["Alice' OR '1'='1"] == db.params + assert [] == result.toList() + } + + @Test + void testGroupByRunsInMemoryWhenSelectDoesNotTranslate() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.name.reverse() != '' + groupby e.deptId into g + orderby g.deptId + select g.deptId, g.count() + } + assert 'SELECT e.* FROM employees e' == db.sqlText + def rows = result.toList().collect { [it[0], it[1]] } + // collection-provider orderby, which puts nulls last + assert [[1, 2], [2, 2], [3, 1], [null, 1]] == rows + } + + @Test + void testInMemoryCollectionJoin() { + def bonuses = [[deptId: 1, label: 'dev'], [deptId: 3, label: 'sup']] + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + join b in bonuses on e.deptId == b.deptId + orderby e.name + select e.name, b.label + } + assert 'SELECT e.* FROM employees e' == db.sqlText + assert [['Alice', 'dev'], ['Bob', 'dev'], ['Frank', 'sup']] == result.toList() + } + + @Test + void testPushedLeftJoinKeepsUnmatchedRows() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + leftjoin d in 'departments' on e.deptId == d.id + orderby e.name + select e.name, d?.name?.reverse() + } + assert [['Alice', 'veD'], ['Bob', 'veD'], ['Carol', 'selaS'], ['Dave', null], ['Eve', 'selaS'], ['Frank', 'troppuS']] == + result.toList() + } + + @Test + void testWindowFunctionInMemory() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.deptId == 1 + orderby e.name + select e.name, (rowNumber() over(orderby e.name)) + } + assert 'SELECT e.* FROM employees e WHERE e.deptId IS NOT DISTINCT FROM ? ORDER BY e.name ASC NULLS LAST' == db.sqlText + assert [1] == db.params + assert [['Alice', 0], ['Bob', 1]] == result.toList() + } + + @Test + void testCorrelatedSubqueryInTheInMemoryTail() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.name.reverse().endsWith('A') && (from d in 'departments' where d.id == e.deptId select d.id).exists() + select e.name + } + assert ['SELECT e.* FROM employees e', 'SELECT * FROM departments'] == db.sqlTexts + assert [[], []] == db.paramLists + assert ['Alice'] == result.toList() + } + + @Test + void testUntranslatableJoinSubqueryRunsInMemory() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + join v in (from d in 'departments' where d.name.reverse() == 'veD' select d.id, d.name as label) on e.deptId == v.id + orderby e.name + select e.name, v.label + } + assert ['SELECT e.* FROM employees e', 'SELECT * FROM departments'] == db.sqlTexts + assert [[], []] == db.paramLists + assert [['Alice', 'Dev'], ['Bob', 'Dev']] == result.toList() + } + + @Test + void testJooqProviderUsesTheSameSplit() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > 5000 + select e.name.reverse() + } + assert ['knarF'] == result.toList() + } + + @Test + void testJooqPushedJoin() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', mixedMode: true, dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + where e.name == 'Alice' + select e.name.reverse(), d.name + } + assert [['ecilA', 'Dev']] == result.toList() + } + + @Test + void testStrictModeStillRejectsUntranslatableMethod() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name.reverse() + } + ''' + assert err.message.contains('Method `reverse` cannot be translated to SQL by the native-sql provider') + } + + @Test + void testExplicitStrictModeRejectsUntranslatableMethod() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', mixedMode: false, dataSource: db) { + from e in 'employees' + select e.name.reverse() + } + ''' + assert err.message.contains('Method `reverse` cannot be translated to SQL by the native-sql provider') + } + + @Test + void testMixedModeMustBeBoolean() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', mixedMode: 'yes', dataSource: db) { + from e in 'employees' + select e.name + } + ''' + assert err.message.contains('`mixedMode` must be `true` or `false`') + } + + @Test + void testMixedModeFromMustBeSql() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', mixedMode: true, dataSource: db) { + from n in [1, 2, 3] + select n + } + ''' + assert err.message.contains('mixed mode requires the `from` source to translate to SQL') + assert err.message.contains('string literals') + } + + @Test + void testMixedModeNestedTableNameIsValidated() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.name.reverse() == 'x' && (from d in 'departments; delete from departments' where d.id == e.deptId select d.id).exists() + select e.name + } + ''' + assert err.message.contains('table name `departments; delete from departments` must be a simple identifier') + assert !err.message.contains('SELECT * FROM departments;') + } + + @Test + void testMixedModeDeferredJoinTableNameIsValidated() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + join d in 'departments; delete from departments' on e.deptId == d.id + select e.name.reverse() + } + ''' + assert err.message.contains('table name `departments; delete from departments` must be a simple identifier') + assert !err.message.contains('SELECT * FROM departments;') + } + + @Test + void testMixedModeDoesNotSplitSetOperations() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', mixedMode: true, dataSource: db) { + from a in 'employees' + select a.name.reverse() + union + from b in 'employees' + select b.name + } + ''' + assert err.message.contains('mixed mode cannot split a set operation') + assert err.message.contains('Method `reverse` cannot be translated to SQL') + } + + @Test + void testHavingKeepsGroupingInMemory() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > 2000 + groupby e.deptId into g + having g.count() > 1 && 'x'.reverse() == 'x' + select g.deptId, g.count() + } + assert 'SELECT e.* FROM employees e WHERE e.salary > ?' == db.sqlText + assert [2000] == db.params + assert [[1, 2], [2, 2]] as Set == result.toList().collect { [it[0], it[1]] } as Set + } + + @Test + void testSecondJoinStaysInMemory() { + def bonuses = [[deptId: 1, label: 'dev'], [deptId: 3, label: 'sup']] + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + join b in bonuses on e.deptId == b.deptId + where e.salary > 4000 + orderby e.name + select e.name as employee, d.name as dept, b.label + } + // the pushed join is executed through the zip path, not Sql.rows + assert [] == db.sqlTexts + assert [['Alice', 'Dev', 'dev'], ['Frank', 'Support', 'sup']] == + result.collect { [it.employee, it.dept, it.label] } + } + + @Test + void testUntranslatableOrderKeepsLimitInMemory() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > 0 + orderby e.name.reverse() + limit 1 + select e.name + } + assert 'SELECT e.* FROM employees e WHERE e.salary > ?' == db.sqlText + assert [0] == db.params + assert ['Bob'] == result.toList() + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedOuterJoinTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedOuterJoinTest.groovy new file mode 100644 index 00000000000..c319fab52ec --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedOuterJoinTest.groovy @@ -0,0 +1,768 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.sql.Sql +import org.junit.jupiter.api.AfterEach + +import java.sql.SQLException + +import static groovy.test.GroovyAssert.shouldFail + +import java.util.Locale +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +/** + * Mixed-mode outer joins must expose an unmatched alias as null, the same + * way the collection provider does, including when later clauses stay in memory. + */ +class GinqSqlMixedOuterJoinTest { + private Sql db + + @BeforeEach + void setUp() { + db = GinqSqlTestSupport.newPopulatedDb() + db.execute("insert into departments (id, name) values (9, 'Empty')") + db.execute("insert into departments (id, name) values (10, 'Vacant')") + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void testLeftJoinUnmatchedAliasIsNull() { + def employees = db.rows('select * from employees') + def departments = db.rows('select * from departments') + def memory = GQL { + from e in employees + leftjoin d in departments on e.deptId == d.id + orderby e.name, (d == null ? 'missing' : d.name) + select e.name, (d == null ? 'missing' : d.name), d == null, d != null + }.toList() + def sql = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + leftjoin d in 'departments' on e.deptId == d.id + orderby e.name, (d == null ? 'missing' : d.name) + select e.name, (d == null ? 'missing' : d.name), d == null, d != null + }.toList() + assert memory == sql + assert ['Dave', 'missing', true, false] in sql + assert sql.findAll { it[2] } == [['Dave', 'missing', true, false]] + assert sql.findAll { !it[2] }.every { it[3] && it[1] != 'missing' } + } + + @Test + void testRightJoinUnmatchedAliasIsNull() { + def employees = db.rows('select * from employees') + def departments = db.rows('select * from departments') + def memory = GQL { + from e in employees + rightjoin d in departments on e.deptId == d.id + orderby (e == null ? 'missing' : e.name), d.name + select (e == null ? 'missing' : e.name), d.name, e == null, e != null + }.toList() + def sql = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + rightjoin d in 'departments' on e.deptId == d.id + orderby (e == null ? 'missing' : e.name), d.name + select (e == null ? 'missing' : e.name), d.name, e == null, e != null + }.toList() + assert memory == sql + assert ['missing', 'Empty', true, false] in sql + assert ['missing', 'Vacant', true, false] in sql + assert sql.findAll { it[2] }.collect { it[1] }.sort() == ['Empty', 'Vacant'] + assert !sql.any { it[0] == 'Dave' } + } + + @Test + void testFullJoinUnmatchedAliasIsNullOnEitherSide() { + def employees = db.rows('select * from employees') + def departments = db.rows('select * from departments') + def excluded = -1 + def memory = GQL { + from e in employees + fulljoin d in departments on e.deptId == d.id && d.id != excluded + orderby (e == null ? 'missing' : e.name), (d == null ? 'missing' : d.name) + select (e == null ? 'missing' : e.name), (d == null ? 'missing' : d.name), e == null, d == null + }.toList() + def sql = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id && d.id != excluded + orderby (e == null ? 'missing' : e.name), (d == null ? 'missing' : d.name) + select (e == null ? 'missing' : e.name), (d == null ? 'missing' : d.name), e == null, d == null + }.toList() + assert memory == sql + assert ['Dave', 'missing', false, true] in sql + assert ['missing', 'Empty', true, false] in sql + assert ['missing', 'Vacant', true, false] in sql + assert !sql.any { it[2] && it[3] } + } + + @Test + void testHashOuterJoinsUseTheSameNullAlias() { + def employees = db.rows('select * from employees') + def departments = db.rows('select * from departments') + def memory = GQL { + from e in employees + lefthashjoin d in departments on e.deptId == d.id + orderby e.name + select e.name, (d == null ? 'missing' : d?.name), d == null + }.toList() + def sql = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + lefthashjoin d in 'departments' on e.deptId == d.id + orderby e.name + select e.name, (d == null ? 'missing' : d?.name), d == null + }.toList() + assert memory == sql + assert ['Dave', 'missing', true] in sql + + def right = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + righthashjoin d in 'departments' on e.deptId == d.id + select (e == null ? 'missing' : e.name), d.name, e == null, e != null + }.toList() + assert right.findAll { it[2] }.collect { it[1] }.sort() == ['Empty', 'Vacant'] + assert right.findAll { it[2] }.every { it[0] == 'missing' && !it[3] } + } + + @Test + void testInnerAndCrossJoinsDoNotInventNullAliases() { + def inner = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + orderby e.name, d.name + select e.name, (d == null), (d != null) + }.toList() + assert inner.every { !it[1] && it[2] } + assert !inner.any { it[0] == 'Dave' } + assert 5 == inner.size() + + def crossed = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + crossjoin d in 'departments' + select e == null, d == null + }.toList() + assert 6 * 5 == crossed.size() + assert crossed.every { !it[0] && !it[1] } + } + + @Test + void testAllNullColumnsStayAPresentRow() { + db.execute('create table anchors (id integer)') + db.execute('insert into anchors (id) values (1)') + db.execute('create table blanks (id integer, note varchar(20))') + db.execute('insert into blanks (id, note) values (null, null)') + + def present = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from a in 'anchors' + join b in 'blanks' on a.id == 1 + select b == null, b != null, b.id, b.note + }.toList() + assert [[false, true, null, null]] == present + + def absent = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from a in 'anchors' + leftjoin b in 'blanks' on a.id == b.id + select b == null, b != null, (b == null ? 'missing' : b.note) + }.toList() + assert [[true, false, 'missing']] == absent + } + + @Test + void testPresenceNameDoesNotHideARealColumn() { + db.execute('create table marks (__ginq_present integer, name varchar(20))') + db.execute("insert into marks (__ginq_present, name) values (7, 'kept')") + db.execute('create table anchors (id integer)') + db.execute('insert into anchors (id) values (1)') + + def present = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from a in 'anchors' + join m in 'marks' on a.id == 1 + select m == null, m.__ginq_present, m.name + }.toList() + assert [[false, 7, 'kept']] == present + + def absent = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from a in 'anchors' + leftjoin m in 'marks' on 1 == 0 + select m == null, (m == null ? 'missing' : m.name) + }.toList() + assert [[true, 'missing']] == absent + } + + @Test + void testUserPresenceColumnIsNotRewrittenToTheMarker() { + db.execute('create table people (id integer, name varchar(20))') + db.execute("insert into people (id, name) values (1, 'Alice'), (7, 'Gina'), (8, 'Hugo')") + db.execute('create table marks ("__ginq_present" integer, name varchar(20))') + db.execute('insert into marks ("__ginq_present", name) values (7, \'seven\'), (8, \'eight\')') + def rows = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'people' + leftjoin m in 'marks' on e.id == m.__ginq_present + select e.name, (m == null ? 'missing' : m.name) + }.toList() + assert ['Gina', 'seven'] in rows.collect { [it[0], it[1]] } + assert ['Hugo', 'eight'] in rows.collect { [it[0], it[1]] } + assert ['Alice', 'missing'] in rows.collect { [it[0], it[1]] } + assert !rows.any { it[0] == 'Alice' && it[1] != 'missing' } + } + + @Test + void testCompleteFullJoinKeepsAUserPresenceColumn() { + db.execute('create table people (id integer, name varchar(20))') + db.execute("insert into people (id, name) values (1, 'Alice'), (7, 'Gina'), (8, 'Hugo')") + db.execute('create table marks ("__ginq_present" integer, name varchar(20))') + db.execute('insert into marks ("__ginq_present", name) values (7, \'seven\'), (8, \'eight\')') + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'people' + fulljoin m in 'marks' on e.id == m.__ginq_present + select e.name as en, m.name as mn, m.__ginq_present as mp + }.toList() + assertNoNativeFullJoin(captured.sqlText) + assert captured.sqlText.contains('1 AS "__ginq_marker"') + assert !captured.sqlText.contains('1 AS "__ginq_present"') + assert [['Alice', null, null], ['Gina', 'seven', 7], ['Hugo', 'eight', 8]] as Set == + rows.collect { [it.en, it.mn, it.mp] } as Set + assert 3 == rows.size() + } + + @Test + void testSeveralUnmatchedAliasesStayIndexAligned() { + db.execute('create table anchors (id integer, name varchar(20))') + db.execute("insert into anchors (id, name) values (1, 'one'), (2, 'two')") + + def rows = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from a in 'anchors' + leftjoin b in 'departments' on 1 == 0 + leftjoin c in 'departments' on 1 == 0 + orderby a.name + select a.name, b == null, c == null, (b == null ? 'no-b' : b.name), (c == null ? 'no-c' : c.name) + }.toList() + assert [['one', true, true, 'no-b', 'no-c'], ['two', true, true, 'no-b', 'no-c']] == rows + } + + @Test + void testInMemoryTailSeesNullAlias() { + def labels = [[dept: 'Dev', tag: 'code'], [dept: 'none', tag: 'gap']] + def rows = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + leftjoin d in 'departments' on e.deptId == d.id + innerjoin t in labels on (d == null ? 'none' : d.name) == t.dept + where e.name == 'Alice' || e.name == 'Dave' + orderby e.name + select e.name, (d == null ? 'missing' : d.name), t.tag, d == null, d != null + }.toList() + assert [['Alice', 'Dev', 'code', false, true], ['Dave', 'missing', 'gap', true, false]] == rows + } + + @Test + void testGroupByAndOrderByOnANullAlias() { + def rows = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + rightjoin d in 'departments' on e.deptId == d.id + groupby (e == null ? 'missing' : e.name) into g + orderby g.key + select g.key, g.count() + }.toList() + def missing = rows.find { it[0] == 'missing' } + assert missing != null + assert 2 == missing[1] + assert rows.any { it[0] == 'Alice' && it[1] == 1 } + } + + @Test + void testCompleteFullJoinIncludesBothUnmatchedSides() { + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e.name as en, d.name as dn + }.toList() + def upper = captured.sqlText.toUpperCase(Locale.ROOT) + assert !upper.contains('FULL OUTER JOIN') + assert !upper.contains('FULL JOIN') + assert upper.contains('UNION ALL') + assert rows.any { it.en == 'Dave' && it.dn == null } + assert rows.any { it.en == null && it.dn == 'Empty' } + assert rows.any { it.en == null && it.dn == 'Vacant' } + assert rows.any { it.en == 'Alice' && it.dn == 'Dev' } + assert 8 == rows.size() + } + + @Test + void testCompleteFullJoinChainOrderAndLimit() { + db.execute('create table aa (id integer)') + db.execute('create table bb (id integer)') + db.execute('create table cc (id integer)') + db.execute('insert into aa (id) values (1), (2)') + db.execute('insert into bb (id) values (1), (3)') + db.execute('insert into cc (id) values (3), (4)') + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def limited = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + fulljoin c in 'cc' on b.id == c.id + orderby a.id, b.id, c.id + limit 3 + select a.id as aId, b.id as bId, c.id as cId + }.toList() + def upper = captured.sqlText.toUpperCase(Locale.ROOT) + assert !upper.contains('FULL OUTER JOIN') + assert !upper.contains('FULL JOIN') + assert upper.contains('UNION ALL') + assert upper.contains('ORDER BY') + assert upper.contains('FETCH') + assert !upper.contains('ORDER BY A.ID') + assert captured.sqlText.indexOf('UNION ALL') < upper.indexOf('ORDER BY') + assert [[1, 1, null], [2, null, null], [null, 3, 3]] == limited.collect { [it.aId, it.bId, it.cId] } + + def all = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + fulljoin c in 'cc' on b.id == c.id + select a.id as aId, b.id as bId, c.id as cId + }.toList() + assert 4 == all.size() + assert all.any { it.aId == null && it.bId == null && it.cId == 4 } + } + + @Test + void testCompleteFullJoinWhereStaysInSql() { + def floor = 4000 + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + where e.salary > floor + select e.name as en, d.name as dn + }.toList() + assert captured.sqlText.toUpperCase(Locale.ROOT).contains('UNION ALL') + assert !captured.sqlText.toUpperCase(Locale.ROOT).contains('FULL JOIN') + assert !captured.sqlText.toUpperCase(Locale.ROOT).contains('FULL OUTER JOIN') + assert [4000] == captured.params + assert ['Alice', 'Eve', 'Frank'] as Set == rows.collect { it.en } as Set + assert rows.every { it.dn != null } + assert 3 == rows.size() + } + + @Test + void testCompleteFullJoinCorrelatedExistsProjectsTheOuterColumn() { + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + where (from x in 'employees' where x.name == e.name && x.salary > 4500 select x.id).exists() + select e.id as eid, d.name as dn + }.toList() + assertNoNativeFullJoin(captured.sqlText) + assert [4500] == captured.params + assert [[1, 'Dev'], [5, 'Sales'], [6, 'Support']] as Set == rows.collect { [it.eid, it.dn] } as Set + assert 3 == rows.size() + } + + @Test + void testCompleteFullJoinInSubqueryProjectsTheOuterColumn() { + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + where e.name in (from x in 'employees' where x.salary > 4500 select x.name) + select e.id as eid, d.name as dn + }.toList() + assertNoNativeFullJoin(captured.sqlText) + assert [4500] == captured.params + assert [[1, 'Dev'], [5, 'Sales'], [6, 'Support']] as Set == rows.collect { [it.eid, it.dn] } as Set + assert 3 == rows.size() + } + + @Test + void testCompleteFullJoinScalarSubqueryProjectsTheOuterColumn() { + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e.name as en, (from x in 'departments' where x.id == e.id select x.name) as xn + }.toList() + assertNoNativeFullJoin(captured.sqlText) + def named = rows.findAll { it.en != null }.collectEntries { [it.en, it.xn] } + assert ['Alice': 'Dev', 'Bob': 'Sales', 'Carol': 'Support', 'Dave': null, 'Eve': null, 'Frank': null] == named + assert 2 == rows.count { it.en == null && it.xn == null } + assert 8 == rows.size() + } + + @Test + void testCompleteFullJoinSubqueryGroupAndOrderProjectTheOuterColumn() { + def ordered = new GinqSqlTranslationTest.CapturingSql(db) + def byOrder = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: ordered) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + where (from x in 'employees' where x.id == e.id orderby e.salary select x.id).exists() + select e.id as eid, d.name as dn + }.toList() + assertNoNativeFullJoin(ordered.sqlText) + assert [[1, 'Dev'], [2, 'Dev'], [3, 'Sales'], [4, null], [5, 'Sales'], [6, 'Support']] as Set == + byOrder.collect { [it.eid, it.dn] } as Set + assert 6 == byOrder.size() + + def grouped = new GinqSqlTranslationTest.CapturingSql(db) + def byGroup = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: grouped) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + where (from x in 'employees' where x.salary > 4500 groupby x.name, e.name having count() > 0 select x.name).exists() + select e.id as eid, d.name as dn + }.toList() + assertNoNativeFullJoin(grouped.sqlText) + assert [[1, 'Dev'], [2, 'Dev'], [3, 'Sales'], [4, null], [5, 'Sales'], [6, 'Support'], [null, 'Empty'], [null, 'Vacant']] as Set == + byGroup.collect { [it.eid, it.dn] } as Set + assert 8 == byGroup.size() + } + + private static void assertNoNativeFullJoin(String sql) { + def upper = sql.toUpperCase(Locale.ROOT) + assert upper.contains('UNION ALL') + assert !upper.contains('FULL JOIN') + assert !upper.contains('FULL OUTER JOIN') + } + + @Test + void testGStringJdbcUrlSelectsTheDialect() { + def bucket = 'ginqmem' + def h2 = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', mixedMode: true, dataSource: keep(h2, "jdbc:h2:mem:${bucket}")) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e.name as en, d.name as dn + }.toList() + assertNoNativeFullJoin(h2.sqlText) + assert rows.any { it.en == 'Alice' && it.dn == 'Dev' } + assert rows.any { it.en == 'Dave' && it.dn == null } + + def host = 'db.example' + def postgres = new GinqSqlTranslationTest.CapturingSql(db) + shouldFail(SQLException) { + GQL(provider: 'native-sql', mixedMode: true, dataSource: keep(postgres, "jdbc:postgresql://${host}/db")) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e.name as en, d.name as dn + }.toList() + } + assert postgres.sqlText.toUpperCase(Locale.ROOT).contains('FULL OUTER JOIN') + } + + @Test + void testOmittedDialectFullJoinRunsOnH2() { + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e.name as en, d.name as dn + }.toList() + assertNoNativeFullJoin(captured.sqlText) + assert rows.any { it.en == 'Dave' && it.dn == null } + assert rows.any { it.en == null && it.dn == 'Empty' } + assert rows.any { it.en == 'Alice' && it.dn == 'Dev' } + assert 8 == rows.size() + } + + @Test + void testPlanSplitFullJoinSqlHasNoNativeFullJoin() { + // The split prefix is executed through JDBC directly. H2 rejects + // FULL JOIN, so a successful bag means the prefix was the nested union. + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select (e == null ? 'missing' : e.name), (d == null ? null : d.name) + }.toList() + assert rows.any { it[0] == 'missing' && it[1] == 'Empty' } + assert rows.any { it[0] == 'Dave' && it[1] == null } + assert rows.any { it[0] == 'Alice' && it[1] == 'Dev' } + } + + @Test + void testCompleteFullJoinWholeRowSelect() { + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: captured) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e, d + }.toList() + assertNoNativeFullJoin(captured.sqlText) + assert rows.every { !it.keySet().any { String key -> key.toLowerCase(Locale.ROOT).contains('present') } } + assert rows.every { it.values().size() == 7 } + def alice = rows.find { cell(it, 'e_NAME') == 'Alice' } + assert cell(alice, 'd_NAME') == 'Dev' + assert cell(alice, 'e_SALARY') == 5000 + def dave = rows.find { cell(it, 'e_NAME') == 'Dave' } + assert cell(dave, 'e_SALARY') == 2000 + assert cell(dave, 'd_NAME') == null + def empty = rows.find { cell(it, 'd_NAME') == 'Empty' } + assert cell(empty, 'e_NAME') == null + assert 8 == rows.size() + + def namedCapture = new GinqSqlTranslationTest.CapturingSql(db) + def named = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: namedCapture) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + select e.name, d + }.toList() + def triples = named.collect { it.values().toList() } + assert triples.any { it[0] == 'Dave' && it[1] == null } + assert triples.any { it[0] == null && it[2] == 'Empty' } + assert triples.any { it[0] == 'Alice' && it[2] == 'Dev' } + assert triples.every { it.size() == 3 } + def namedAlice = named.find { cell(it, 'name') == 'Alice' } + assert cell(namedAlice, 'd_NAME') == 'Dev' + def namedDave = named.find { cell(it, 'name') == 'Dave' } + assert cell(namedDave, 'd_NAME') == null + assert 8 == named.size() + def lower = namedCapture.sqlText.toLowerCase(Locale.ROOT) + assert lower.contains('__ginq_0_name') + assert lower.contains('__ginqstarcol_0_name') + } + + private static Object cell(row, String key) { + def found = row.keySet().find { String name -> name.equalsIgnoreCase(key) } + return found == null ? null : row[found] + } + + static Sql keep(Sql db, String url) { + return db + } + + @Test + void testStrictFullJoinChainRunsOnH2() { + db.execute('create table aa (id integer)') + db.execute('create table bb (id integer)') + db.execute('create table cc (id integer)') + db.execute('insert into aa (id) values (1), (2)') + db.execute('insert into bb (id) values (1), (3)') + db.execute('insert into cc (id) values (3), (4)') + def captured = new GinqSqlTranslationTest.CapturingSql(db) + def full = GQL(provider: 'native-sql', dialect: 'h2', dataSource: captured) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + fulljoin c in 'cc' on b.id == c.id + select a.id as aId, b.id as bId, c.id as cId + }.toList() + assertNoNativeFullJoin(captured.sqlText) + assert [[1, 1, null], [2, null, null], [null, 3, 3], [null, null, 4]] as Set == + full.collect { [it.aId, it.bId, it.cId] } as Set + assert 4 == full.size() + + def rightCaptured = new GinqSqlTranslationTest.CapturingSql(db) + def right = GQL(provider: 'native-sql', dialect: 'h2', dataSource: rightCaptured) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + rightjoin c in 'cc' on b.id == c.id + select a.id as aId, b.id as bId, c.id as cId + }.toList() + assertNoNativeFullJoin(rightCaptured.sqlText) + assert [[null, 3, 3], [null, null, 4]] as Set == right.collect { [it.aId, it.bId, it.cId] } as Set + assert 2 == right.size() + } + + @Test + void testFullJoinOnlyInsideSubqueryRunsOnH2() { + db.execute('create table nums (id integer)') + db.execute('create table aa (id integer)') + db.execute('create table bb (id integer)') + db.execute('insert into nums (id) values (1), (2), (3)') + db.execute('insert into aa (id) values (1), (2)') + db.execute('insert into bb (id) values (1), (3)') + def mixedExists = new GinqSqlTranslationTest.CapturingSql(db) + def existsRows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: mixedExists) { + from n in 'nums' + where (from a in 'aa' fulljoin b in 'bb' on a.id == b.id where a.id == n.id select a.id).exists() + select n.id as id + }.toList() + assertNoNativeFullJoin(mixedExists.sqlText) + assert [1, 2] as Set == existsRows.collect { it.id } as Set + + def mixedIn = new GinqSqlTranslationTest.CapturingSql(db) + def inRows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: mixedIn) { + from n in 'nums' + where n.id in (from a in 'aa' fulljoin b in 'bb' on a.id == b.id select a.id) + select n.id as id + }.toList() + assertNoNativeFullJoin(mixedIn.sqlText) + assert [1, 2] as Set == inRows.collect { it.id } as Set + + def mixedScalar = new GinqSqlTranslationTest.CapturingSql(db) + def scalarRows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: mixedScalar) { + from n in 'nums' + select n.id as id, (from a in 'aa' fulljoin b in 'bb' on a.id == b.id where a.id == n.id select b.id) as bid + }.toList() + assertNoNativeFullJoin(mixedScalar.sqlText) + assert [[1, 1], [2, null], [3, null]] as Set == scalarRows.collect { [it.id, it.bid] } as Set + + def strictExists = new GinqSqlTranslationTest.CapturingSql(db) + def strictRows = GQL(provider: 'native-sql', dialect: 'h2', dataSource: strictExists) { + from n in 'nums' + where (from a in 'aa' fulljoin b in 'bb' on a.id == b.id where a.id == n.id select a.id).exists() + select n.id as id + }.toList() + assertNoNativeFullJoin(strictExists.sqlText) + assert [1, 2] as Set == strictRows.collect { it.id } as Set + + def strictIn = new GinqSqlTranslationTest.CapturingSql(db) + GQL(provider: 'native-sql', dialect: 'h2', dataSource: strictIn) { + from n in 'nums' + where n.id in (from a in 'aa' fulljoin b in 'bb' on a.id == b.id select a.id) + select n.id as id + } + assertNoNativeFullJoin(strictIn.sqlText) + + def strictScalar = new GinqSqlTranslationTest.CapturingSql(db) + def strictScalarRows = GQL(provider: 'native-sql', dialect: 'h2', dataSource: strictScalar) { + from n in 'nums' + select n.id as id, (from a in 'aa' fulljoin b in 'bb' on a.id == b.id where a.id == n.id select b.id) as bid + }.toList() + assertNoNativeFullJoin(strictScalar.sqlText) + assert [[1, 1], [2, null], [3, null]] as Set == strictScalarRows.collect { [it.id, it.bid] } as Set + } + + @Test + void testNestedFullJoinMatchesTheCollectionProvider() { + db.execute('create table aa (id integer)') + db.execute('create table bb (id integer)') + db.execute('create table cc (id integer)') + db.execute('insert into aa (id) values (1), (2)') + db.execute('insert into bb (id) values (1), (3)') + db.execute('insert into cc (id) values (3), (4)') + // A full-joined with B, then with C: one row for each of (1,1), (2), (3,3) and (4). + def expectFull = [ + [false, 1, false, 1, true, null], + [false, 2, true, null, true, null], + [true, null, false, 3, false, 3], + [true, null, true, null, false, 4], + ] + def sqlFull = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + fulljoin c in 'cc' on b.id == c.id + select (a == null), (a?.id) as aId, (b == null), (b?.id) as bId, (c == null), (c?.id) as cId + }.toList() + assert bag(expectFull) == bag(sqlFull) + assert sqlFull.count { it[4] == false && it[5] == 4 } == 1 + assert sqlFull.count { it[2] == false && it[3] == 3 && it[5] == 3 } == 1 + + def expectRight = [ + [true, null, false, 3, false, 3], + [true, null, true, null, false, 4], + ] + def sqlRight = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + rightjoin c in 'cc' on b.id == c.id + select (a == null), (a?.id) as aId, (b == null), (b?.id) as bId, (c == null), (c?.id) as cId + }.toList() + assert bag(expectRight) == bag(sqlRight) + + def sqlHash = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from a in 'aa' + fullhashjoin b in 'bb' on a.id == b.id + righthashjoin c in 'cc' on b.id == c.id + select (a == null), (a?.id) as aId, (b == null), (b?.id) as bId, (c == null), (c?.id) as cId + }.toList() + assert bag(expectRight) == bag(sqlHash) + + def jooq = GQL(provider: 'jooq-sql', dialect: 'H2', mixedMode: true, dataSource: db) { + from a in 'aa' + fulljoin b in 'bb' on a.id == b.id + fulljoin c in 'cc' on b.id == c.id + select (a == null), (a?.id) as aId, (b == null), (b?.id) as bId, (c == null), (c?.id) as cId + }.toList() + assert bag(expectFull) == bag(jooq) + } + + @Test + void testFullJoinPushesTranslatableOrderAndLimit() { + def employees = db.rows('select * from employees') + def departments = db.rows('select * from departments') + def joined = GQL { + from e in employees + fulljoin d in departments on e.deptId == d.id + select (e == null ? null : e.name), (d == null ? null : d.name), (e == null), (d == null) + }.toList() + def memory = joined.sort { a, b -> + int byName = compareNullsLast(a[0], b[0]) + byName != 0 ? byName : compareNullsLast(a[1], b[1]) + }.take(4) + def sql = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + orderby e.name, d.name + limit 4 + select (e == null ? null : e.name), (d == null ? null : d.name), (e == null), (d == null) + }.toList() + assert memory == sql + assert 4 == sql.size() + assert ['Alice', 'Dev', false, false] == sql[0] + assert sql.every { it[2] == false } + } + + @Test + void testPushedWhereOnAFullJoinRepeatsBranchParameters() { + def floor = 4000 + def rows = GQL(provider: 'native-sql', dialect: 'h2', mixedMode: true, dataSource: db) { + from e in 'employees' + fulljoin d in 'departments' on e.deptId == d.id + where e.salary > floor + orderby e.name + select (e == null ? 'missing' : e.name), d == null + }.toList() + assert ['Alice', 'Eve', 'Frank'] == rows.collect { it[0] } + assert rows.every { it[1] == false } + } + + private static int compareNullsLast(Object left, Object right) { + if (left == null && right == null) { + return 0 + } + if (left == null) { + return 1 + } + if (right == null) { + return -1 + } + return left.toString() <=> right.toString() + } + + private static List bag(List rows) { + rows.collect { row -> (0.. ? ORDER BY e.name ASC NULLS LAST' == db.sqlText + assert [1, 3] == db.params + assert ['Dave'] == result.collect { it.name } + } + + @Test + void testNotInListIncludesNull() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId !in [1, 2] + orderby e.name + select e.name + } + assert db.sqlText.contains('e.deptId IS NULL OR e.deptId NOT IN (?, ?)') + assert ['Dave', 'Frank'] == result.collect { it.name } + } + + @Test + void testComparisonDoesNotTreatNullAsLessThanAValue() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId < 1 + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId < ?' == db.sqlText + assert [] == result.toList() + } + + @Test + void testCapturedStringPlusIsNotArithmetic() { + def err = shouldFail '''\ + def suffix = '!' + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name + suffix + } + ''' + assert err.message.contains('Operator `+`') + assert err.message.contains('mixedMode: true') + + def suffix = '!' + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.name == 'Bob' + select e.name + suffix + } + assert 'SELECT e.* FROM employees e WHERE e.name IS NOT DISTINCT FROM ?' == db.sqlText + assert ['Bob'] == db.params + assert ['Bob!'] == result.toList() + } + + @Test + void testStringCastAndNumericAnchorStillPushDown() { + def suffix = '!' + def bonus = 500 + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name == 'Bob' + select e.name + (suffix as String) as decorated, e.salary + (bonus as int) as bumped + } + assert db.sqlText.contains('e.name || ?') + assert db.sqlText.contains('e.salary + ?') + assert !db.sqlText.contains('e.name +') + assert [['Bob!', 3500]] == result.collect { [it.decorated, it.bumped] } + } + + @Test + void testTwoColumnsAreNotPushedForPlus() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.salary + e.deptId + } + ''' + assert err.message.contains('Operator `+`') + assert err.message.contains('Two columns') + } + + @Test + void testCapturedTextMethodIsNotPushed() { + def err = shouldFail '''\ + def suffix = '!' + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select suffix.length() + } + ''' + assert err.message.contains('`length()`') + assert err.message.contains('captured variable') + + def suffix = '!' + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.name == 'Alice' + select suffix.length() + } + assert [1] == result.toList() + } + + @Test + void testSqliteFloorStaysOutOfPushedSql() { + def recorded = new RecordingSql(realDb) + def rows = GQL(provider: 'native-sql', dialect: 'sqlite', mixedMode: true, dataSource: recorded) { + from e in 'employees' + where e.salary > 1000 + select e.salary.floor() + } + assert [] == rows.toList() + assert 1 == recorded.sqlTexts.size() + assert !recorded.sqlTexts[0].contains('FLOOR') + assert recorded.sqlTexts[0].contains('WHERE') + assert recorded.sqlTexts[0].contains('salary') + + def length = new RecordingSql(realDb) + GQL(provider: 'native-sql', dialect: 'sqlite', dataSource: length) { + from e in 'employees' + select e.name.length() + } + assert length.sqlTexts[0].contains('LENGTH(') + assert !length.sqlTexts[0].contains('CHAR_LENGTH') + assert !length.sqlTexts[0].contains('FLOOR') + } + + @Test + void testJooqSqliteUsesTheSameFunctionSupport() { + def recorded = new RecordingSql(realDb) + GQL(provider: 'jooq-sql', dialect: 'SQLITE', mixedMode: true, dataSource: recorded) { + from e in 'employees' + where e.salary > 1000 + select e.salary.ceil() + } + assert 1 == recorded.sqlTexts.size() + assert !recorded.sqlTexts[0].toUpperCase(Locale.ROOT).contains('CEIL') + assert recorded.sqlTexts[0].toLowerCase(Locale.ROOT).contains('where') + } + + @Test + void testFunctionSupportIsShared() { + assert !FunctionSupport.supports('sqlite', 'FLOOR') + assert !FunctionSupport.supports('SQLITE', 'CEILING') + assert FunctionSupport.supports('sqlite', 'CHAR_LENGTH') + assert FunctionSupport.supports('sqlite', 'UPPER') + assert FunctionSupport.supports('h2', 'FLOOR') + assert FunctionSupport.supports('postgres', 'CEILING') + assert !Dialects.resolve('sqlite').supportsFunction('FLOOR') + assert Dialects.resolve('sqlite').supportsFunction('UPPER') + assert Dialects.resolve('h2').supportsFunction('CEILING') + assert 'sqlite' == SqlCapabilities.of('SQLITE').dialectName() + } + + private static class RecordingSql extends Sql { + final List sqlTexts = [] + + RecordingSql(Sql parent) { + super(parent) + } + + @Override + List rows(String sql, List params) { + sqlTexts << sql + return [] + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlTestSupport.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlTestSupport.groovy new file mode 100644 index 00000000000..fdbe72f3b65 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlTestSupport.groovy @@ -0,0 +1,64 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.sql.Sql + +import java.sql.SQLException +import java.util.concurrent.atomic.AtomicInteger + +/** + * Creates uniquely-named in-memory H2 databases populated with the + * employees/departments test schema. + */ +class GinqSqlTestSupport { + private static final AtomicInteger COUNTER = new AtomicInteger() + + static String newDbUrl() { + // keep the database alive between connections; closeDb shuts it down + "jdbc:h2:mem:ginqSqlTest${COUNTER.getAndIncrement()};DB_CLOSE_DELAY=-1" + } + + static Sql newPopulatedDb(String url = newDbUrl()) { + def db = Sql.newInstance(url, 'sa', '', 'org.h2.Driver') + db.execute 'create table employees (id integer, name varchar(50), salary integer, deptId integer, active boolean)' + db.execute 'create table departments (id integer, name varchar(50))' + [[1, 'Dev'], [2, 'Sales'], [3, 'Support']].each { + db.execute('insert into departments (id, name) values (?, ?)', it) + } + [[1, 'Alice', 5000, 1, true], + [2, 'Bob', 3000, 1, true], + [3, 'Carol', 4000, 2, true], + [4, 'Dave', 2000, null, false], + [5, 'Eve', 5000, 2, true], + [6, 'Frank', 6000, 3, true]].each { + db.execute('insert into employees (id, name, salary, deptId, active) values (?, ?, ?, ?, ?)', it) + } + return db + } + + static void closeDb(Sql db) { + try { + db.execute 'SHUTDOWN' + } catch (SQLException ignore) { + // H2 reports the connection as closed once SHUTDOWN completes + } + db.close() + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlTranslationTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlTranslationTest.groovy new file mode 100644 index 00000000000..1fe70afc275 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlTranslationTest.groovy @@ -0,0 +1,432 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.sql.GroovyRowResult +import groovy.sql.Sql +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +import java.sql.SQLException + +/** + * Asserts the SQL text and bound parameters the native-sql provider generates, + * by capturing what reaches {@link Sql#rows(String, List)}. Queries still + * execute against a real H2 database, so the SQL is also validated. + */ +class GinqSqlTranslationTest { + private Sql realDb + private CapturingSql db + + @BeforeEach + void setUp() { + realDb = GinqSqlTestSupport.newPopulatedDb() + db = new CapturingSql(realDb) + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(realDb) + } + + @Test + void testBoundParameters() { + def threshold = 2500 + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary > threshold && e.active == true + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.salary > ? AND e.active IS NOT DISTINCT FROM ?' == db.sqlText + assert [2500, true] == db.params + } + + @Test + void testJoinWithAlias() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + where e.salary >= 3000 + select e.name, d.name as deptName + } + assert 'SELECT e.name, d.name AS deptName FROM employees e ' + + 'INNER JOIN departments d ON e.deptId IS NOT DISTINCT FROM d.id WHERE e.salary >= ?' == db.sqlText + assert [3000] == db.params + } + + @Test + void testNullChecksInListAndFunctions() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId == null || e.salary in [3000, 4000] || e.name.toUpperCase() == 'EVE' + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId IS NULL ' + + 'OR e.salary IN (?, ?) OR UPPER(e.name) IS NOT DISTINCT FROM ?' == db.sqlText + assert [3000, 4000, 'EVE'] == db.params + } + + @Test + void testGroupByAggregates() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId into g + select g.deptId, g.count() as cnt, g.avg(e -> e.salary) as avgSalary + } + assert 'SELECT e.deptId AS deptId, COUNT(*) AS cnt, AVG(e.salary) AS avgSalary FROM employees e ' + + 'WHERE e.deptId IS NOT NULL GROUP BY e.deptId' == db.sqlText + assert [] == db.params + } + + @Test + void testHaving() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + groupby e.deptId into g + having g.count() > 1 + select g.deptId + } + assert 'SELECT e.deptId AS deptId FROM employees e GROUP BY e.deptId HAVING COUNT(*) > ?' == db.sqlText + assert [1] == db.params + } + + @Test + void testOrderByAndLimit() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.salary in desc, e.name + limit 1, 2 + select e.name + } + assert 'SELECT e.name FROM employees e ORDER BY e.salary DESC NULLS LAST, e.name ASC NULLS LAST ' + + 'OFFSET ? ROWS FETCH NEXT ? ROWS ONLY' == db.sqlText + assert [1, 2] == db.params + } + + @Test + void testDistinct() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select distinct(e.salary) + } + assert 'SELECT DISTINCT e.salary FROM employees e' == db.sqlText + } + + @Test + void testLikeMethods() { + def part = 'li' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.contains(part) || e.name.startsWith('Bo') || e.name.endsWith('ve') + select e.name + } + assert "SELECT e.name FROM employees e WHERE e.name LIKE ? ESCAPE '!' " + + "OR e.name LIKE ? ESCAPE '!' OR e.name LIKE ? ESCAPE '!'" == db.sqlText + assert ['%li%', 'Bo%', '%ve'] == db.params + } + + @Test + void testSubstringReplaceAndConcat() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.substring(0, 3) == 'Ali' + select e.name.replace('A', 'X') + '!' as decorated + } + assert "SELECT REPLACE(e.name, ?, ?) || ? AS decorated FROM employees e " + + 'WHERE SUBSTRING(e.name FROM ? FOR ?) IS NOT DISTINCT FROM ?' == db.sqlText + assert ['A', 'X', '!', 1, 3, 'Ali'] == db.params + } + + @Test + void testTernaryBecomesCaseWhen() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name, (e.salary > 4000 ? 'high' : 'low') as band + } + assert "SELECT e.name, CASE WHEN e.salary > ? THEN 'high' ELSE 'low' END AS band FROM employees e" == db.sqlText + assert [4000] == db.params + } + + @Test + void testClassicGroupBy() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + groupby e.deptId + having count() > 1 + select e.deptId, count() as cnt, sum(e.salary) as total + } + assert 'SELECT e.deptId, COUNT(*) AS cnt, COALESCE(SUM(e.salary), 0) AS total FROM employees e ' + + 'GROUP BY e.deptId HAVING COUNT(*) > ?' == db.sqlText + assert [1] == db.params + } + + @Test + void testSetOperationWithTrailingOrderByAndLimit() { + GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.name, a.salary + union + from b in 'employees' + where b.deptId == 2 + orderby b.salary in desc, b.name + limit 1, 2 + select b.name, b.salary + } + assert 'SELECT a.name, a.salary FROM employees a WHERE a.deptId IS NOT DISTINCT FROM ? ' + + 'UNION SELECT b.name, b.salary FROM employees b WHERE b.deptId IS NOT DISTINCT FROM ? ' + + 'ORDER BY 2 DESC NULLS LAST, 1 ASC NULLS LAST OFFSET ? ROWS FETCH NEXT ? ROWS ONLY' == db.sqlText + assert [1, 2, 1, 2] == db.params + } + + @Test + void testDerivedTable() { + GQL(provider: 'native-sql', dataSource: db) { + from v in (from e in 'employees' where e.salary >= 4000 select e.name, e.salary) + where v.salary < 6000 + select v.name + } + assert 'SELECT v.name FROM (SELECT e.name, e.salary FROM employees e WHERE e.salary >= ?) v ' + + 'WHERE v.salary < ?' == db.sqlText + assert [4000, 6000] == db.params + } + + @Test + void testCorrelatedExists() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where (from d in 'departments' where d.id == e.deptId select d.id).exists() + select e.name + } + assert 'SELECT e.name FROM employees e ' + + 'WHERE EXISTS (SELECT d.id FROM departments d WHERE d.id IS NOT DISTINCT FROM e.deptId)' == db.sqlText + assert [] == db.params + } + + @Test + void testInSubquery() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId in (from d in 'departments' where d.name != 'Support' select d.id) + select e.name + } + assert 'SELECT e.name FROM employees e ' + + 'WHERE e.deptId IN (SELECT d.id FROM departments d WHERE d.name IS DISTINCT FROM ?)' == db.sqlText + assert ['Support'] == db.params + } + + @Test + void testScalarSubquery() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary == (from x in 'employees' select max(x.salary)) + select e.name + } + assert 'SELECT e.name FROM employees e ' + + 'WHERE e.salary IS NOT DISTINCT FROM (SELECT MAX(x.salary) FROM employees x)' == db.sqlText + assert [] == db.params + } + + @Test + void testSetOperation() { + GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.salary + union + from b in 'employees' + where b.deptId == 2 + select b.salary + } + assert 'SELECT a.salary FROM employees a WHERE a.deptId IS NOT DISTINCT FROM ? ' + + 'UNION SELECT b.salary FROM employees b WHERE b.deptId IS NOT DISTINCT FROM ?' == db.sqlText + assert [1, 2] == db.params + } + + @Test + void testFunctionsAndConstantRange() { + def low = 1 + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary in 3000..5000 && e.name.concat('!') == 'Alice!' + select e.name.length(), e.salary.abs(), e.salary.round(0), e.name.substring(low, 3) + } + assert 'SELECT CHAR_LENGTH(e.name), ABS(e.salary), ROUND(e.salary, ?), ' + + 'SUBSTRING(e.name FROM ? FOR ?) FROM employees e ' + + 'WHERE e.salary >= ? AND e.salary <= ? AND e.name || ? IS NOT DISTINCT FROM ?' == db.sqlText + assert [0, low + 1, 3 - low, 3000, 5000, '!', 'Alice!'] == db.params + + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.name.isEmpty() || !(e.name.isEmpty()) + select e.name + } + assert 'SELECT e.name FROM employees e WHERE CHAR_LENGTH(e.name) = 0 OR NOT (CHAR_LENGTH(e.name) = 0)' == db.sqlText + } + + @Test + void testInListContainingNull() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId in [null] + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId IS NULL' == db.sqlText + assert [] == db.params + + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId in [null, 1] || e.salary !in [null, 2000] + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId IS NULL OR e.deptId IN (?) ' + + 'OR e.salary IS NOT NULL AND e.salary NOT IN (?)' == db.sqlText + assert [1, 2000] == db.params + + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId !in [null] + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId IS NOT NULL' == db.sqlText + } + + @Test + void testEmptyInAndNullLikePattern() { + def missing = null + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id in [] || e.name.contains(missing) + select e.name + } + assert 'SELECT e.name FROM employees e WHERE 1 = 0 OR e.name LIKE ? ESCAPE \'!\'' == db.sqlText + assert [null] == db.params + } + + @Test + void testDescendingAndExclusiveRanges() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id in 3..1 || e.id in 4..<6 + select e.id + } + assert 'SELECT e.id FROM employees e WHERE e.id >= ? AND e.id <= ? OR e.id >= ? AND e.id < ?' == db.sqlText + assert [1, 3, 4, 6] == db.params + } + + @Test + void testCoalesce() { + def fallback = 'n/a' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where coalesce(e.deptId, 0) == 0 + select coalesce(e.name, fallback, 'x') as display + } + assert 'SELECT COALESCE(e.name, ?, ?) AS display FROM employees e WHERE COALESCE(e.deptId, ?) IS NOT DISTINCT FROM ?' == db.sqlText + assert ['n/a', 'x', 0, 0] == db.params + } + + @Test + void testCountDistinct() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + groupby e.deptId into g + having count(distinct(e.salary)) > 1 + select g.deptId, count(distinct(e.salary)) as kinds, g.count(distinct(e -> e.name)) as names + } + assert 'SELECT e.deptId AS deptId, COUNT(DISTINCT e.salary) AS kinds, COUNT(DISTINCT e.name) AS names FROM employees e ' + + 'GROUP BY e.deptId HAVING COUNT(DISTINCT e.salary) > ?' == db.sqlText + assert [1] == db.params + } + + @Test + void testCountDistinctLambdaBody() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + groupby e.deptId into g + select g.count(e -> distinct(e.salary)) as kinds + } + assert 'SELECT COUNT(DISTINCT e.salary) AS kinds FROM employees e GROUP BY e.deptId' == db.sqlText + } + + @Test + void testMathMaxAndMin() { + def floor = 4500 + def cap = 5500 + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select Math.max(e.salary, floor) as hi, Math.min(e.salary, cap) as lo + } + assert 'SELECT GREATEST(e.salary, ?) AS hi, LEAST(e.salary, ?) AS lo FROM employees e' == db.sqlText + assert [4500, 5500] == db.params + } + + @Test + void testCastKeepsAliasAndRendersCast() { + def needle = 'li' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id == 1 + select e.name as label, cast(e.id, 'DECIMAL') / 2 as half, e.name.indexOf(needle) as at + } + assert 'SELECT e.name AS label, (CAST(CAST(e.id AS DECIMAL) AS DOUBLE) / CAST(? AS DOUBLE)) AS half, ' + + 'POSITION(? IN e.name) - 1 AS at FROM employees e WHERE e.id IS NOT DISTINCT FROM ?' == db.sqlText + assert [2, 'li', 1] == db.params + + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select cast(e.salary, 'decimal(10, 2)') as money, cast(e.id, 'double precision') as realId + } + assert 'SELECT CAST(e.salary AS DECIMAL(10,2)) AS money, CAST(e.id AS DOUBLE PRECISION) AS realId FROM employees e' == db.sqlText + } + + @Test + void testNativeH2DialectKeepsAnsiLimit() { + GQL(provider: 'native-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + limit 1, 2 + select e.name + } + assert 'SELECT e.name FROM employees e ORDER BY e.name ASC NULLS LAST OFFSET ? ROWS FETCH NEXT ? ROWS ONLY' == db.sqlText + assert [1, 2] == db.params + } + + static class CapturingSql extends Sql { + String sqlText + List params + final List sqlTexts = [] + final List paramLists = [] + + CapturingSql(Sql parent) { + super(parent) + } + + @Override + List rows(String sql, List params) throws SQLException { + this.sqlText = sql + this.params = new ArrayList(params) + sqlTexts << sql + paramLists << new ArrayList(params) + return super.rows(sql, params) + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlAutoProviderTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlAutoProviderTest.groovy new file mode 100644 index 00000000000..b68dac6682b --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlAutoProviderTest.groovy @@ -0,0 +1,193 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import org.apache.groovy.ginq.GinqGroovyMethods +import org.apache.groovy.ginq.provider.GinqProvider +import org.apache.groovy.ginq.provider.collection.GinqAstWalker +import org.apache.groovy.ginq.provider.sql.jooq.JooqSqlGinqProvider +import org.codehaus.groovy.ast.expr.MapExpression +import org.codehaus.groovy.control.SourceUnit +import org.codehaus.groovy.control.messages.SyntaxErrorMessage +import org.junit.jupiter.api.Test + +import java.lang.reflect.InvocationTargetException +import java.lang.reflect.Method + +/** + * Providers report whether their dependencies can be loaded. + * {@code provider: 'sql'} uses the first candidate that can; + * an explicit name fails with that provider's message when it cannot. + */ +class SqlAutoProviderTest { + + private static final String NATIVE_WALKER = 'org.apache.groovy.ginq.provider.sql.GinqSqlWalker' + private static final String JOOQ_WALKER = 'org.apache.groovy.ginq.provider.sql.jooq.JooqSqlWalker' + + @Test + void testProvidersAreAvailableOnTheTestClasspath() { + ClassLoader loader = GinqGroovyMethods.class.classLoader + assert new NativeSqlGinqProvider().unavailableReason(loader) == null + assert new JooqSqlGinqProvider().unavailableReason(loader) == null + } + + @Test + void testJooqProviderReportsMissingJooq() { + String reason = new JooqSqlGinqProvider().unavailableReason(hidingLoader('org.jooq.')) + assert reason.contains('org.jooq:jooq') + assert reason.contains('compile classpath') + assert new NativeSqlGinqProvider().unavailableReason(hidingLoader('org.jooq.')) == null + } + + @Test + void testSqlProvidersReportMissingGroovySql() { + ClassLoader loader = hidingLoader('groovy.sql.') + assert new NativeSqlGinqProvider().unavailableReason(loader).contains('groovy-sql') + assert new JooqSqlGinqProvider().unavailableReason(loader).contains('groovy-sql') + } + + @Test + void testSqlProviderFallsBackWhenJooqClassesAreAbsent() { + Selection selection = select(hidingLoader('org.jooq.'), 'sql') + assert selection.error == null + assert NATIVE_WALKER == selection.walker + } + + @Test + void testExplicitNativeProviderStaysSelectedWhenJooqClassesAreAbsent() { + Selection selection = select(hidingLoader('org.jooq.'), 'native-sql') + assert selection.error == null + assert NATIVE_WALKER == selection.walker + } + + @Test + void testExplicitJooqProviderFailsWhenJooqClassesAreAbsent() { + Selection selection = select(hidingLoader('org.jooq.'), 'jooq-sql') + assert selection.walker == null + assert selection.error != null + assert selection.error.contains('org.jooq:jooq') + assert selection.error.contains('compile classpath') + } + + @Test + void testExplicitNativeProviderFailsWhenGroovySqlIsAbsent() { + Selection selection = select(hidingLoader('groovy.sql.'), 'native-sql') + assert selection.walker == null + assert selection.error != null + assert selection.error.contains('groovy-sql') + assert !selection.error.contains('org.jooq:jooq') + } + + @Test + void testSqlProviderFailsWhenNoBackendCanLoad() { + Selection selection = select(hidingLoader('org.jooq.', 'groovy.sql.'), 'sql') + assert selection.walker == null + assert selection.error != null + assert selection.error.contains('No usable GINQ SQL provider') + assert selection.error.contains('org.jooq:jooq') + assert selection.error.contains('groovy-sql') + } + + @Test + void testSqlProviderPrefersJooqWhenPresent() { + Selection selection = select(GinqGroovyMethods.class.classLoader, 'sql') + assert selection.error == null + assert JOOQ_WALKER == selection.walker + } + + private static Selection select(ClassLoader loader, String provider) { + Class methods = loader.loadClass(GinqGroovyMethods.name) + Method resolve = methods.getDeclaredMethod('resolveAstWalkerClassName', SourceUnit, Map, MapExpression) + resolve.accessible = true + SourceUnit source = SourceUnit.create('auto-sql', '') + Selection selection = new Selection() + try { + selection.walker = (String) resolve.invoke(null, source, Collections.singletonMap('provider', provider), new MapExpression()) + } catch (InvocationTargetException e) { + // collectErrors reports a fatal error, which aborts compilation + if (!source.errorCollector.hasErrors()) { + throw e.cause ?: e + } + } + if (source.errorCollector.hasErrors()) { + selection.error = ((SyntaxErrorMessage) source.errorCollector.errors[0]).cause.originalMessage + } + return selection + } + + private static ClassLoader hidingLoader(String... hiddenPrefixes) { + List urls = [ + GinqGroovyMethods, + GinqProvider, + GinqAstWalker, + NativeSqlGinqProvider, + JooqSqlGinqProvider, + GinqSqlWalker, + ].collect { Class type -> type.protectionDomain.codeSource.location } + return new HidingLoader(urls.unique().toArray(new URL[0]), hiddenPrefixes) + } + + private static class Selection { + String walker + String error + } + + /** + * Defines the GINQ classes itself and refuses the supplied prefixes, + * so provider selection runs as it would on a classpath missing those dependencies. + */ + private static class HidingLoader extends URLClassLoader { + private final String[] hiddenPrefixes + + HidingLoader(URL[] urls, String[] hiddenPrefixes) { + super(urls, GinqGroovyMethods.class.classLoader) + this.hiddenPrefixes = hiddenPrefixes + } + + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + for (String prefix : hiddenPrefixes) { + if (name.startsWith(prefix)) { + throw new ClassNotFoundException(name) + } + } + synchronized (getClassLoadingLock(name)) { + Class loaded = findLoadedClass(name) + if (loaded != null) { + if (resolve) { + resolveClass(loaded) + } + return loaded + } + if (name.startsWith('org.apache.groovy.ginq.') || name.startsWith('groovy.ginq.')) { + try { + Class found = findClass(name) + if (resolve) { + resolveClass(found) + } + return found + } catch (ClassNotFoundException ignored) { + // fall through to the parent for classes outside these jars + } + } + return super.loadClass(name, resolve) + } + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistryTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistryTest.groovy new file mode 100644 index 00000000000..4bb6aa9dc6f --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistryTest.groovy @@ -0,0 +1,172 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlCastTypes +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlParam +import org.codehaus.groovy.ast.ASTNode +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.ast.expr.MethodCallExpression +import org.codehaus.groovy.ast.expr.PropertyExpression +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.shouldFail +import static org.codehaus.groovy.ast.tools.GeneralUtils.args +import static org.codehaus.groovy.ast.tools.GeneralUtils.callX +import static org.codehaus.groovy.ast.tools.GeneralUtils.constX +import static org.codehaus.groovy.ast.tools.GeneralUtils.propX +import static org.codehaus.groovy.ast.tools.GeneralUtils.varX + +/** + * The built-in registry is sealed. A copy accepts a new function without + * changing the mappings the translator uses. + */ +class SqlFunctionRegistryTest { + + @Test + void testBuiltinNames() { + def registry = SqlFunctionRegistry.standard() + assert 'UPPER' == registry.find('toUpperCase', SqlFunctionMapping.Kind.RECEIVER).sqlName + assert 'COALESCE' == registry.find('coalesce', SqlFunctionMapping.Kind.FREE).sqlName + assert 'GREATEST' == registry.find('max', SqlFunctionMapping.Kind.MATH).sqlName + assert 'LEAST' == registry.find('min', SqlFunctionMapping.Kind.MATH).sqlName + assert registry.find('cast', SqlFunctionMapping.Kind.FREE) != null + assert registry.find('indexOf', SqlFunctionMapping.Kind.RECEIVER) != null + assert registry.find('padLeft', SqlFunctionMapping.Kind.RECEIVER) == null + assert registry.find('signum', SqlFunctionMapping.Kind.RECEIVER) == null + assert registry.find('max', SqlFunctionMapping.Kind.RECEIVER) == null + } + + @Test + void testRegisterOnACopyLeavesTheBuiltinSealed() { + def extra = SqlFunctionRegistry.standard().copy() + extra.register(SqlFunctionMapping.receiver('signum', 'SIGN')) + assert 'SIGN' == extra.find('signum', SqlFunctionMapping.Kind.RECEIVER).sqlName + assert 'UPPER' == extra.find('toUpperCase', SqlFunctionMapping.Kind.RECEIVER).sqlName + assert SqlFunctionRegistry.standard().find('signum', SqlFunctionMapping.Kind.RECEIVER) == null + + def duplicate = shouldFail(IllegalArgumentException) { + extra.register(SqlFunctionMapping.receiver('signum', 'SIGN')) + } + assert duplicate.message.contains('already registered') + + def sealed = shouldFail(IllegalStateException) { + SqlFunctionRegistry.standard().register(SqlFunctionMapping.receiver('signum', 'SIGN')) + } + assert sealed.message.contains('sealed') + + def injected = shouldFail(IllegalArgumentException) { + extra.register(SqlFunctionMapping.receiver('evil', 'UPPER; DROP')) + } + assert injected.message.contains('uppercase identifier') + } + + @Test + void testRegisteredFunctionTranslatesToItsSqlName() { + def extra = SqlFunctionRegistry.standard().copy() + extra.register(SqlFunctionMapping.receiver('signum', 'SIGN')) + def call = callX(propX(varX('e'), 'salary'), 'signum') + def expr = extra.find('signum', SqlFunctionMapping.Kind.RECEIVER).translate(call, [], recordingSite()) + assert expr instanceof SqlFunction + assert 'SIGN' == expr.name + assert 1 == expr.args.size() + assert expr.args[0] instanceof SqlColumn + } + + @Test + void testCastAndIndexOfShapes() { + def site = recordingSite() + def castCall = callX(varX('this'), 'cast', args(propX(varX('e'), 'id'), constX(' decimal(10, 2) '))) + def castExpr = SqlFunctionRegistry.standard().find('cast', SqlFunctionMapping.Kind.FREE) + .translate(castCall, [propX(varX('e'), 'id'), constX(' decimal(10, 2) ')], site) + assert castExpr instanceof SqlCast + assert 'DECIMAL(10,2)' == castExpr.sqlType + + def indexCall = callX(propX(varX('e'), 'name'), 'indexOf', args(constX('li'))) + def indexExpr = SqlFunctionRegistry.standard().find('indexOf', SqlFunctionMapping.Kind.RECEIVER) + .translate(indexCall, [constX('li')], site) + assert indexExpr instanceof SqlBinary + assert '-' == indexExpr.op + assert indexExpr.left instanceof SqlFunction + assert 'POSITION' == indexExpr.left.name + } + + @Test + void testCastTypeWhitelist() { + assert 'DECIMAL' == SqlCastTypes.canonical('decimal') + assert 'DECIMAL(10,2)' == SqlCastTypes.canonical(' decimal(10, 2) ') + assert 'DOUBLE PRECISION' == SqlCastTypes.canonical('double precision') + assert 'VARCHAR(8)' == SqlCastTypes.canonical('varchar(08)') + assert 'CHARACTER VARYING(20)' == SqlCastTypes.canonical('character varying(20)') + assert null == SqlCastTypes.canonical('JAVA_OBJECT') + assert null == SqlCastTypes.canonical('VARCHAR(10); drop table e') + assert null == SqlCastTypes.canonical('INT(11)') + assert null == SqlCastTypes.canonical('DECIMAL(2,10)') + assert null == SqlCastTypes.canonical('VARCHAR(0)') + assert null == SqlCastTypes.canonical('TIMESTAMP(6)') + assert null == SqlCastTypes.canonical(null) + assert null == SqlCastTypes.canonical(' ') + + def rejected = shouldFail(IllegalArgumentException) { + new SqlCast(new SqlColumn('e', 'id'), 'INTEGER); DROP TABLE employees') + } + assert rejected.message.contains('Unsupported SQL cast type') + } + + private static SqlFunctionSite recordingSite() { + return new SqlFunctionSite() { + @Override + SqlExpr expr(Expression expression) { + if (expression instanceof PropertyExpression) { + return new SqlColumn(expression.objectExpression.text, expression.propertyAsString) + } + if (expression instanceof ConstantExpression) { + return new SqlParam(expression) + } + throw new AssertionError(expression.text) + } + + @Override + void fail(String message, ASTNode node) { + throw new IllegalArgumentException(message) + } + + @Override + SqlExpr like(MethodCallExpression call, List args, boolean matchBefore, boolean matchAfter) { + return null + } + + @Override + SqlExpr substring(MethodCallExpression call, List args) { + return null + } + + @Override + SqlExpr function(String ansiName, List args, ASTNode node) { + return new SqlFunction(ansiName, args) + } + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlRendererTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlRendererTest.groovy new file mode 100644 index 00000000000..d8905a38574 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlRendererTest.groovy @@ -0,0 +1,405 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCaseWhen +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlCountStar +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlIn +import org.apache.groovy.ginq.provider.sql.ir.SqlIsNull +import org.apache.groovy.ginq.provider.sql.ir.SqlJoin +import org.apache.groovy.ginq.provider.sql.ir.SqlLike +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlOrderSpec +import org.apache.groovy.ginq.provider.sql.ir.SqlOrdinal +import org.apache.groovy.ginq.provider.sql.ir.SqlParam +import org.apache.groovy.ginq.provider.sql.ir.SqlProjection +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlQueryNode +import org.apache.groovy.ginq.provider.sql.ir.SqlSetQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlStar +import org.apache.groovy.ginq.provider.sql.ir.SqlTableRef +import org.apache.groovy.ginq.provider.sql.ir.SqlUnary +import org.apache.groovy.ginq.provider.sql.ir.SqlExpr +import org.apache.groovy.ginq.provider.sql.render.AnsiDialect +import org.apache.groovy.ginq.provider.sql.render.Dialect +import org.apache.groovy.ginq.provider.sql.render.Dialects +import org.apache.groovy.ginq.provider.sql.render.RenderedSql +import org.apache.groovy.ginq.provider.sql.render.SqlRenderer +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.shouldFail + +@CompileStatic +class SqlRendererTest { + + @Test + void testSingleTable() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.where = new SqlBinary('>', col('e', 'salary'), param(1000)) + query.projections << new SqlProjection(col('e', 'name')) + + def rendered = render(query) + assert 'SELECT e.name FROM employees e WHERE e.salary > ?' == rendered.sql + assert [1000] == values(rendered) + } + + @Test + void testDistinctOrderByOffsetFetch() { + def query = new SqlQuery() + query.distinct = true + query.from = new SqlTableRef('employees', 'e') + query.where = new SqlBinary('>', col('e', 'salary'), param(1000)) + query.orderBy << new SqlOrderSpec(col('e', 'salary'), false, true) + query.orderBy << new SqlOrderSpec(col('e', 'name'), true, false) + query.offset = param(2) + query.fetch = param(5) + query.projections << new SqlProjection(col('e', 'name')) + + def rendered = render(query) + assert 'SELECT DISTINCT e.name FROM employees e WHERE e.salary > ? ' + + 'ORDER BY e.salary DESC NULLS LAST, e.name ASC NULLS FIRST ' + + 'OFFSET ? ROWS FETCH NEXT ? ROWS ONLY' == rendered.sql + assert [1000, 2, 5] == values(rendered) + } + + @Test + void testFetchWithoutOffset() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.fetch = param(3) + query.projections << new SqlProjection(new SqlStar('e')) + + assert 'SELECT e.* FROM employees e FETCH FIRST ? ROWS ONLY' == render(query).sql + } + + @Test + void testJoins() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.joins << new SqlJoin(SqlJoin.Type.INNER, new SqlTableRef('departments', 'd'), + new SqlBinary('=', col('e', 'deptId'), col('d', 'id'))) + query.joins << new SqlJoin(SqlJoin.Type.LEFT, new SqlTableRef('locations', 'l'), + new SqlBinary('=', col('d', 'locId'), col('l', 'id'))) + query.joins << new SqlJoin(SqlJoin.Type.CROSS, new SqlTableRef('grades', 'g'), null) + query.projections << new SqlProjection(col('e', 'name')) + + assert 'SELECT e.name FROM employees e ' + + 'INNER JOIN departments d ON e.deptId = d.id ' + + 'LEFT JOIN locations l ON d.locId = l.id ' + + 'CROSS JOIN grades g' == render(query).sql + } + + @Test + void testGroupByHavingAggregates() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.groupBy << col('e', 'deptId') + query.having = new SqlBinary('>', new SqlCountStar(), param(1)) + query.projections << new SqlProjection(col('e', 'deptId')) + query.projections << new SqlProjection(new SqlCountStar(), 'cnt') + query.projections << new SqlProjection(new SqlFunction('AVG', [col('e', 'salary')]), 'avgSalary') + + def rendered = render(query) + assert 'SELECT e.deptId, COUNT(*) AS cnt, AVG(e.salary) AS avgSalary FROM employees e ' + + 'GROUP BY e.deptId HAVING COUNT(*) > ?' == rendered.sql + assert [1] == values(rendered) + } + + @Test + void testSetOperationsChainingAndMinus() { + def a = simpleQuery('a') + def b = simpleQuery('b') + def c = simpleQuery('c') + def setQuery = new SqlSetQuery(new SqlSetQuery(a, SqlSetQuery.SetOp.UNION, b), SqlSetQuery.SetOp.MINUS, c) + + assert '(SELECT a.id FROM a a UNION SELECT b.id FROM b b) EXCEPT SELECT c.id FROM c c' == render(setQuery).sql + } + + @Test + void testUnionAllAndIntersect() { + def setQuery = new SqlSetQuery(simpleQuery('a'), SqlSetQuery.SetOp.UNION_ALL, simpleQuery('b')) + assert 'SELECT a.id FROM a a UNION ALL SELECT b.id FROM b b' == render(setQuery).sql + + setQuery = new SqlSetQuery(simpleQuery('a'), SqlSetQuery.SetOp.INTERSECT, simpleQuery('b')) + assert 'SELECT a.id FROM a a INTERSECT SELECT b.id FROM b b' == render(setQuery).sql + } + + @Test + void testPrecedenceParentheses() { + def query = new SqlQuery() + query.from = new SqlTableRef('t', 't') + def aOrB = new SqlBinary('OR', new SqlBinary('=', col('t', 'a'), param(1)), new SqlBinary('=', col('t', 'b'), param(2))) + query.where = new SqlBinary('AND', aOrB, new SqlBinary('=', col('t', 'c'), param(3))) + query.projections << new SqlProjection(col('t', 'a')) + + assert 'SELECT t.a FROM t t WHERE (t.a = ? OR t.b = ?) AND t.c = ?' == render(query).sql + } + + @Test + void testNonAssociativeRightOperand() { + def query = new SqlQuery() + query.from = new SqlTableRef('t', 't') + def bMinusC = new SqlBinary('-', col('t', 'b'), col('t', 'c')) + query.projections << new SqlProjection(new SqlBinary('-', col('t', 'a'), bMinusC)) + + assert 'SELECT t.a - (t.b - t.c) FROM t t' == render(query).sql + } + + @Test + void testIsNullInNotAndFunctions() { + def query = new SqlQuery() + query.from = new SqlTableRef('t', 't') + def isNull = new SqlIsNull(col('t', 'a'), false) + def isNotNull = new SqlIsNull(col('t', 'b'), true) + def inList = new SqlIn(col('t', 'c'), [param(1), param(2)], false) + def notInList = new SqlIn(col('t', 'd'), [param(3)], true) + def notExpr = new SqlUnary('NOT', new SqlBinary('=', new SqlFunction('UPPER', [col('t', 'e')]), param('X'))) + query.where = new SqlBinary('AND', + new SqlBinary('AND', + new SqlBinary('AND', + new SqlBinary('AND', isNull, isNotNull), inList), notInList), notExpr) + query.projections << new SqlProjection(col('t', 'a')) + + def rendered = render(query) + assert 'SELECT t.a FROM t t WHERE t.a IS NULL AND t.b IS NOT NULL ' + + 'AND t.c IN (?, ?) AND t.d NOT IN (?) AND NOT (UPPER(t.e) = ?)' == rendered.sql + assert [1, 2, 3, 'X'] == values(rendered) + } + + @Test + void testParameterOrderingAcrossClauses() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.joins << new SqlJoin(SqlJoin.Type.INNER, new SqlTableRef('departments', 'd'), + new SqlBinary('AND', + new SqlBinary('=', col('e', 'deptId'), col('d', 'id')), + new SqlBinary('>', col('d', 'budget'), param(100)))) + query.where = new SqlBinary('>', col('e', 'salary'), param(200)) + query.groupBy << col('d', 'name') + query.having = new SqlBinary('>', new SqlCountStar(), param(300)) + query.orderBy << new SqlOrderSpec(new SqlCountStar(), true, true) + query.offset = param(400) + query.fetch = param(500) + query.projections << new SqlProjection(new SqlBinary('+', col('d', 'name'), param(50))) + + assert [50, 100, 200, 300, 400, 500] == values(render(query)) + } + + @Test + void testLikeAndCaseWhen() { + def query = new SqlQuery() + query.from = new SqlTableRef('t', 't') + query.where = new SqlLike(col('t', 'name'), param('%x%')) + query.projections << new SqlProjection( + new SqlCaseWhen(new SqlBinary('>', col('t', 'salary'), param(1000)), param('high'), param('low')), 'band') + + def rendered = render(query) + assert "SELECT CASE WHEN t.salary > ? THEN ? ELSE ? END AS band FROM t t " + + "WHERE t.name LIKE ? ESCAPE '!'" == rendered.sql + assert [1000, 'high', 'low', '%x%'] == values(rendered) + } + + @Test + void testSubstringRendersFromFor() { + def query = new SqlQuery() + query.from = new SqlTableRef('t', 't') + query.projections << new SqlProjection(new SqlFunction('SUBSTRING', [col('t', 'name'), param(1), param(3)])) + + assert 'SELECT SUBSTRING(t.name FROM ? FOR ?) FROM t t' == render(query).sql + } + + @Test + void testSetQueryWithOrdinalOrderByAndLimit() { + def setQuery = new SqlSetQuery(simpleQuery('a'), SqlSetQuery.SetOp.UNION, simpleQuery('b')) + setQuery.orderBy << new SqlOrderSpec(new SqlOrdinal(1), false, true) + setQuery.offset = param(1) + setQuery.fetch = param(2) + + def rendered = render(setQuery) + assert 'SELECT a.id FROM a a UNION SELECT b.id FROM b b ' + + 'ORDER BY 1 DESC NULLS LAST OFFSET ? ROWS FETCH NEXT ? ROWS ONLY' == rendered.sql + assert [1, 2] == values(rendered) + } + + @Test + void testDialectChoosesLimitPlaceholderOrder() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.offset = param(2) + query.fetch = param(5) + query.projections << new SqlProjection(col('e', 'name')) + + def rendered = new SqlRenderer(new LimitThenOffsetDialect()).render(query) + assert 'SELECT e.name FROM employees e LIMIT ? OFFSET ?' == rendered.sql + assert [5, 2] == values(rendered) + } + + @Test + void testNativeDialectsQuoteLimitAndFunctions() { + def query = new SqlQuery() + query.from = new SqlTableRef('hr.employees', 'e') + query.where = new SqlFunction('MOD', [col('e', 'salary'), param(2)]) + query.orderBy << new SqlOrderSpec(col('e', 'name'), true, true) + query.offset = param(1) + query.fetch = param(2) + query.projections << new SqlProjection(new SqlFunction('CHAR_LENGTH', [col('e', 'name')])) + query.projections << new SqlProjection(new SqlFunction('SUBSTRING', [col('e', 'name'), param(1), param(3)])) + + def mysql = new SqlRenderer(Dialects.resolve('mysql')).render(query) + assert 'SELECT CHAR_LENGTH(`e`.`name`), SUBSTRING(`e`.`name` FROM ? FOR ?) FROM `hr`.`employees` `e` ' + + 'WHERE MOD(`e`.`salary`, ?) ORDER BY (`e`.`name` IS NULL) ASC, `e`.`name` ASC ' + + 'LIMIT ? OFFSET ?' == mysql.sql + assert [1, 3, 2, 2, 1] == values(mysql) + + def sqlite = new SqlRenderer(Dialects.resolve('SQLITE')).render(query) + assert 'SELECT LENGTH("e"."name"), SUBSTR("e"."name", ?, ?) FROM "hr"."employees" "e" ' + + 'WHERE "e"."salary" % ? ORDER BY ("e"."name" IS NULL) ASC, "e"."name" ASC ' + + 'LIMIT ? OFFSET ?' == sqlite.sql + assert [1, 3, 2, 2, 1] == values(sqlite) + + def postgres = new SqlRenderer(Dialects.resolve('PostgreSQL')).render(query) + assert postgres.sql.contains('FROM "hr"."employees" "e"') + assert postgres.sql.contains('OFFSET ? ROWS FETCH NEXT ? ROWS ONLY') + assert postgres.sql.contains('CHAR_LENGTH("e"."name")') + assert [1, 3, 2, 1, 2] == values(postgres) + + assert Dialects.resolve('nope') == null + assert Dialects.resolve('h2') instanceof AnsiDialect + } + + @Test + void testCountDistinctAndGreatestLeast() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.projections << new SqlProjection(new SqlFunction('COUNT', [col('e', 'deptId')], true)) + query.projections << new SqlProjection(new SqlFunction('GREATEST', [col('e', 'salary'), param(1)])) + query.projections << new SqlProjection(new SqlFunction('LEAST', [col('e', 'salary'), param(2)])) + + def rendered = render(query) + assert 'SELECT COUNT(DISTINCT e.deptId), GREATEST(e.salary, ?), LEAST(e.salary, ?) FROM employees e' == rendered.sql + assert [1, 2] == values(rendered) + + def sqlite = new SqlRenderer(Dialects.resolve('sqlite')).render(query) + assert 'SELECT COUNT(DISTINCT "e"."deptId"), MAX("e"."salary", ?), MIN("e"."salary", ?) FROM "employees" "e"' == sqlite.sql + assert !sqlite.sql.contains('GREATEST') + assert !sqlite.sql.contains('LEAST') + + def mysql = new SqlRenderer(Dialects.resolve('mysql')).render(query) + assert mysql.sql.contains('COUNT(DISTINCT `e`.`deptId`)') + assert mysql.sql.contains('GREATEST(`e`.`salary`, ?)') + assert mysql.sql.contains('LEAST(`e`.`salary`, ?)') + } + + @Test + void testSqliteRejectsFloorAndCeiling() { + def floor = shouldFail(IllegalArgumentException) { + new SqlRenderer(Dialects.resolve('sqlite')).render(functionQuery('FLOOR')) + } + assert floor.message.contains('FLOOR') + assert floor.message.contains('sqlite') + assert !floor.message.contains('SELECT') + + def ceiling = shouldFail(IllegalArgumentException) { + new SqlRenderer(Dialects.resolve('sqlite')).render(functionQuery('CEILING')) + } + assert ceiling.message.contains('CEILING') + assert ceiling.message.contains('sqlite') + + def ansi = new SqlRenderer(Dialects.resolve('ansi')).render(functionQuery('FLOOR')) + assert ansi.sql.contains('FLOOR(') + def h2 = new SqlRenderer(Dialects.resolve('h2')).render(functionQuery('CEILING')) + assert h2.sql.contains('CEILING(') + } + + @Test + void testCastAndSearchPosition() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.projections << new SqlProjection(new SqlCast(col('e', 'id'), 'DECIMAL(10,2)')) + query.projections << new SqlProjection(new SqlBinary('-', + new SqlFunction('POSITION', [param('li'), col('e', 'name')]), + new SqlLiteral(1))) + + def rendered = render(query) + assert 'SELECT CAST(e.id AS DECIMAL(10,2)), POSITION(? IN e.name) - 1 FROM employees e' == rendered.sql + assert ['li'] == values(rendered) + + def mysql = new SqlRenderer(Dialects.resolve('mysql')).render(query) + assert mysql.sql.contains('CAST(`e`.`id` AS DECIMAL(10,2))') + assert mysql.sql.contains('LOCATE(?, `e`.`name`) - 1') + assert !mysql.sql.contains('POSITION') + + def sqlite = new SqlRenderer(Dialects.resolve('sqlite')).render(query) + assert sqlite.sql.contains('CAST("e"."id" AS DECIMAL(10,2))') + assert sqlite.sql.contains('INSTR("e"."name", ?) - 1') + assert !sqlite.sql.contains('POSITION') + assert !sqlite.sql.contains('LOCATE') + } + + private static SqlQuery functionQuery(String name) { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.projections << new SqlProjection(new SqlFunction(name, [col('e', 'salary')])) + return query + } + + private static SqlQuery simpleQuery(String table) { + def query = new SqlQuery() + query.from = new SqlTableRef(table, table) + query.projections << new SqlProjection(col(table, 'id')) + return query + } + + private static SqlColumn col(String alias, String column) { + new SqlColumn(alias, column) + } + + private static SqlParam param(Object value) { + new SqlParam(new ConstantExpression(value)) + } + + private static RenderedSql render(SqlQueryNode queryNode) { + new SqlRenderer(new AnsiDialect()).render(queryNode) + } + + private static List values(RenderedSql renderedSql) { + renderedSql.parameters.collect { ((ConstantExpression) it).value } + } + + private static class LimitThenOffsetDialect implements Dialect { + @Override + void renderLimit(SqlExpr offset, SqlExpr fetch, Dialect.LimitRender out) { + if (fetch != null) { + out.text(' LIMIT ') + out.expr(fetch) + } + if (offset != null) { + out.text(' OFFSET ') + out.expr(offset) + } + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlIntegrationTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlIntegrationTest.groovy new file mode 100644 index 00000000000..0eed1d361e8 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlIntegrationTest.groovy @@ -0,0 +1,218 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.jooq + +import groovy.sql.Sql +import org.apache.groovy.ginq.provider.sql.GinqSqlTestSupport +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +/** + * Runs GINQ queries end-to-end against an in-memory H2 database + * via the jooq-sql provider with the H2 dialect. + */ +class JooqSqlIntegrationTest { + private Sql db + + @BeforeEach + void setUp() { + db = GinqSqlTestSupport.newPopulatedDb() + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void testSingleTableWhereWithCapturedVariable() { + def threshold = 2500 + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.salary > threshold && e.active == true + orderby e.name + select e.name, e.salary + } + assert [['Alice', 5000], ['Bob', 3000], ['Carol', 4000], ['Eve', 5000], ['Frank', 6000]] == + result.collect { [it.name, it.salary] } + } + + @Test + void testJoinOrderByAndLimit() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + orderby e.salary in desc, e.name + limit 1, 2 + select e.name, d.name as deptName + } + assert [['Alice', 'Dev'], ['Eve', 'Sales']] == result.collect { [it.name, it.deptName] } + } + + @Test + void testGroupByIntoWithHaving() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId into g + having g.count() > 1 + orderby g.deptId + select g.deptId, g.count() as cnt, g.avg(e -> e.salary) as avgSalary + } + assert [[1, 2, 4000], [2, 2, 4500]] == result.collect { [it.deptId, it.cnt, it.avgSalary] } + } + + @Test + void testSetOperationWithTrailingOrderByAndLimit() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.name, a.salary + union + from b in 'employees' + where b.deptId == 2 + orderby b.salary in desc, b.name + limit 1, 2 + select b.name, b.salary + } + assert [['Eve', 5000], ['Carol', 4000]] == result.collect { [it.name, it.salary] } + } + + @Test + void testCorrelatedExistsAndLike() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where (from d in 'departments' where d.id == e.deptId select d.id).exists() + && e.name.contains('a') + orderby e.name + select e.name + } + assert ['Carol', 'Frank'] == result.collect { it.name } + } + + @Test + void testScalarSubqueryAndCaseWhen() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.salary == (from x in 'employees' select max(x.salary)) + select e.name, (e.salary > 4000 ? 'high' : 'low!') as band + } + assert [['Frank', 'high']] == result.collect { [it.name, it.band] } + } + + @Test + void testRealDivisionMatchesNative() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.id / 2 > 2 + orderby e.name + select e.name + } + assert ['Eve', 'Frank'] == result.collect { it.name } + } + + @Test + void testRoundAndFloorMatchNative() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.salary.round(0) == 5000 && e.salary.floor() == e.salary + orderby e.name + select e.name + } + assert ['Alice', 'Eve'] == result.collect { it.name } + } + + @Test + void testCoalesceCountDistinctAndExtremes() { + db.execute('insert into employees (id, name, salary, deptId, active) values (?, ?, ?, ?, ?)', + [7, 'Grace', 5000, 1, true]) + def floor = 4500 + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.deptId != null + groupby e.deptId + orderby e.deptId + select e.deptId, count(distinct(e.salary)) as kinds + } + assert [[1, 2], [2, 2], [3, 1]] == result.collect { [it.deptId, it.kinds] } + + def rows = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.id == 4 || e.id == 6 + orderby e.id + select e.id, coalesce(e.deptId, 0) as dept, (e.deptId == null ? 0 : e.deptId) as viaTernary, + Math.max(e.salary, floor) as hi, Math.min(e.salary, floor) as lo + } + assert [[4, 0, 0, 4500, 2000], [6, 3, 3, 6000, 4500]] == + rows.collect { [it.id, it.dept, it.viaTernary, it.hi, it.lo] } + } + + @Test + void testCastThenDivideAndIndexOf() { + def result = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.id == 1 || e.id == 5 + orderby e.id + select e.id, cast(e.id, 'DECIMAL') / 2 as half, cast(e.salary, 'VARCHAR') as salaryText, + e.name.indexOf('l') as atL, e.name.indexOf('z') as missing + } + def rows = result.collect { [it.id, (it.half as BigDecimal), it.salaryText, it.atL, it.missing] } + assert [[1, 0.5G, '5000', 1, -1], [5, 2.5G, '5000', -1, -1]] == rows + } + + @Test + void testDefaultDialect() { + def result = GQL(provider: 'jooq-sql', dataSource: db) { + from e in 'employees' + where e.id == 2 + select e.name + } + assert ['Bob'] == result.collect { it.name } + } + + @Test + void testAutoDetectPrefersJooq() { + // with jOOQ on the classpath, provider 'sql' resolves to jooq-sql + def result = GQL(provider: 'sql', dataSource: db) { + from e in 'employees' + where e.id == 3 + select e.name + } + assert ['Carol'] == result.collect { it.name } + } + + @Test + void testInListContainingNullMatchesNull() { + def onlyNull = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.deptId in [null] + select e.name + } + assert ['Dave'] == onlyNull.collect { it.name } + + def excluded = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.deptId !in [1, null] + orderby e.name + select e.name + } + assert ['Carol', 'Eve', 'Frank'] == excluded.collect { it.name } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlTranslationTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlTranslationTest.groovy new file mode 100644 index 00000000000..a8e04167515 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqSqlTranslationTest.groovy @@ -0,0 +1,187 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider.sql.jooq + +import groovy.sql.Sql +import org.apache.groovy.ginq.provider.sql.GinqSqlTestSupport +import org.apache.groovy.ginq.provider.sql.GinqSqlTranslationTest.CapturingSql +import org.apache.groovy.ginq.provider.sql.ir.SqlBinary +import org.apache.groovy.ginq.provider.sql.ir.SqlCast +import org.apache.groovy.ginq.provider.sql.ir.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlFunction +import org.apache.groovy.ginq.provider.sql.ir.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlParam +import org.apache.groovy.ginq.provider.sql.ir.SqlProjection +import org.apache.groovy.ginq.provider.sql.ir.SqlQuery +import org.apache.groovy.ginq.provider.sql.ir.SqlTableRef +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +/** + * Asserts the dialect-specific SQL the jooq-sql provider generates, e.g. + * H2's alias rendering without {@code AS} and lowercase keywords. + */ +class JooqSqlTranslationTest { + private Sql realDb + private CapturingSql db + + @BeforeEach + void setUp() { + realDb = GinqSqlTestSupport.newPopulatedDb() + db = new CapturingSql(realDb) + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(realDb) + } + + @Test + void testH2Rendering() { + def threshold = 2500 + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.salary > threshold + orderby e.name + limit 1, 2 + select e.name + } + assert 'select e.name from employees e where e.salary > ? ' + + 'order by e.name asc nulls last offset ? rows fetch next ? rows only' == db.sqlText + assert [2500, 1, 2] == db.params + } + + @Test + void testSetOperationWithTrailingOrderByAndLimit() { + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.name, a.salary + union + from b in 'employees' + where b.deptId == 2 + orderby b.salary in desc, b.name + limit 1, 2 + select b.name, b.salary + } + assert 'select a.name, a.salary from employees a where a.deptId is not distinct from ? ' + + 'union select b.name, b.salary from employees b where b.deptId is not distinct from ? ' + + 'order by 2 desc nulls last, 1 asc nulls last offset ? rows fetch next ? rows only' == db.sqlText + assert [1, 2, 1, 2] == db.params + } + + @Test + void testGroupByAggregatesAndLike() { + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.deptId != null && e.name.contains('a') + groupby e.deptId into g + having g.count() > 1 + select g.deptId, g.count() as cnt + } + assert "select e.deptId deptId, count(*) cnt from employees e " + + "where (e.deptId is not null and e.name like ? escape '!') " + + 'group by e.deptId having count(*) > ?' == db.sqlText + assert ['%a%', 1] == db.params + } + + @Test + void testCoalesceCountDistinctAndExtremes() { + def floor = 4500 + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where coalesce(e.deptId, 0) > 0 + select coalesce(e.name, 'x') as display, Math.max(e.salary, floor) as hi, Math.min(e.salary, floor) as lo + } + assert 'select coalesce(e.name, ?) display, greatest(e.salary, ?) hi, least(e.salary, ?) lo ' + + 'from employees e where coalesce(e.deptId, ?) > ?' == db.sqlText + assert ['x', 4500, 4500, 0, 0] == db.params + + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + groupby e.deptId + select e.deptId, count(distinct(e.salary)) as kinds + } + assert 'select e.deptId, count(distinct e.salary) kinds from employees e group by e.deptId' == db.sqlText + } + + @Test + void testCastAndIndexOf() { + def needle = 'li' + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + where e.id == 1 + select e.name as label, cast(e.id, 'DECIMAL') / 2 as half, e.name.indexOf(needle) as at + } + assert 'select e.name label, (cast(cast(e.id as decimal) as double) / cast(? as double)) half, ' + + '(position(? in e.name) - 1) at from employees e where e.id is not distinct from ?' == db.sqlText + assert [2, 'li', 1] == db.params + } + + @Test + void testCastAndPositionDialectSpellings() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.projections << new SqlProjection(new SqlCast(new SqlColumn('e', 'id'), 'DECIMAL')) + query.projections << new SqlProjection(new SqlBinary('-', + new SqlFunction('POSITION', [new SqlParam(new ConstantExpression('a')), new SqlColumn('e', 'name')]), + new SqlLiteral(1))) + + def h2 = JooqRenderer.render(query, 'H2').sql.toLowerCase() + assert h2.contains('cast(e.id as decimal)') + assert h2.contains('position(') + assert h2.contains('in e.name') + + def mysql = JooqRenderer.render(query, 'MYSQL').sql.toLowerCase() + assert mysql.contains('locate(') + assert !mysql.contains('position(') + + def sqlite = JooqRenderer.render(query, 'SQLITE').sql.toLowerCase() + assert sqlite.contains('instr(') + assert !sqlite.contains('position(') + assert !sqlite.contains('locate(') + } + + @Test + void testSqliteRendersScalarMaxMin() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.projections << new SqlProjection(new SqlFunction('GREATEST', [new SqlColumn('e', 'salary'), new SqlParam(new ConstantExpression(1))])) + query.projections << new SqlProjection(new SqlFunction('LEAST', [new SqlColumn('e', 'salary'), new SqlParam(new ConstantExpression(2))])) + query.projections << new SqlProjection(new SqlFunction('COUNT', [new SqlColumn('e', 'deptId')], true)) + def sql = JooqRenderer.render(query, 'SQLITE').sql.toLowerCase() + assert sql.contains('max(') + assert sql.contains('min(') + assert sql.contains('count(distinct') + assert !sql.contains('greatest') + assert !sql.contains('least') + } + + @Test + void testSchemaQualifiedTableIsTwoIdentifiers() { + def query = new SqlQuery() + query.from = new SqlTableRef('hr.employees', 'e') + query.projections << new SqlProjection(new SqlColumn('e', 'id')) + def sql = JooqRenderer.render(query, 'H2').sql.toLowerCase() + assert sql.contains('from hr.employees e') + assert !sql.contains('"hr.employees"') + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/transform/GQ.java b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/transform/GQ.java index 5b48291ba9c..53455141e52 100644 --- a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/transform/GQ.java +++ b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/transform/GQ.java @@ -19,6 +19,7 @@ package groovy.ginq.transform; import org.apache.groovy.ginq.dsl.GinqAstVisitor; +import org.apache.groovy.ginq.provider.GinqProvider; import org.apache.groovy.ginq.provider.collection.runtime.Queryable; import org.apache.groovy.lang.annotation.Incubating; import org.codehaus.groovy.transform.GroovyASTTransformationClass; @@ -63,4 +64,18 @@ */ @Incubating String astWalker() default "org.apache.groovy.ginq.provider.collection.GinqAstWalker"; + + /** + * Specify the GINQ provider by name, e.g. {@code collection} (the default) or a + * provider registered via the {@link GinqProvider} + * SPI such as {@code native-sql}. + *

+ * Note that database-backed providers also require a {@code dataSource}, which + * cannot be supplied via an annotation; use the macro form instead, e.g. + * {@code GQ(provider: 'native-sql', dataSource: db) {...}}. + * + * @since 7.0.0 + */ + @Incubating + String provider() default "collection"; } diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqGroovyMethods.groovy b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqGroovyMethods.groovy index a83f50b9fcf..0e7e82d503b 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqGroovyMethods.groovy +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqGroovyMethods.groovy @@ -24,6 +24,7 @@ import org.apache.groovy.ginq.dsl.GinqAstOptimizer import org.apache.groovy.ginq.dsl.GinqAstVisitor import org.apache.groovy.ginq.dsl.expression.AbstractGinqExpression import org.apache.groovy.ginq.dsl.expression.GinqExpression +import org.apache.groovy.ginq.provider.GinqProvider import org.apache.groovy.ginq.provider.collection.GinqAstWalker import org.codehaus.groovy.ast.ASTNode import org.codehaus.groovy.ast.expr.ClosureExpression @@ -111,27 +112,109 @@ class GinqGroovyMethods { GinqAstBuilder ginqAstBuilder = new GinqAstBuilder(sourceUnit) AbstractGinqExpression ginqExpression = ginqAstBuilder.buildAST(code) Map configuration = createConfiguration(sourceUnit, ginqConfigurationMapExpression) + String astWalkerClassName = resolveAstWalkerClassName(sourceUnit, configuration, ginqConfigurationMapExpression) - if (ginqExpression instanceof GinqExpression && TRUE_STR == configuration.get(CONF_OPTIMIZE, TRUE_STR)) { + // the optimizer rewrites queries assuming collection semantics, so only run it for the default provider + if (DEFAULT_AST_WALKER_CLASS_NAME == astWalkerClassName + && ginqExpression instanceof GinqExpression && TRUE_STR == configuration.get(CONF_OPTIMIZE, TRUE_STR)) { GinqAstOptimizer ginqAstOptimizer = new GinqAstOptimizer() ginqAstOptimizer.visitGinqExpression(ginqExpression) } - Class clazz = GinqGroovyMethods.class.classLoader.loadClass(configuration.get(CONF_AST_WALKER, DEFAULT_AST_WALKER_CLASS_NAME)) + Class clazz = GinqGroovyMethods.class.classLoader.loadClass(astWalkerClassName) GinqAstVisitor ginqAstWalker = (GinqAstVisitor) clazz.getDeclaredConstructor(SourceUnit.class).newInstance(sourceUnit) ginqAstWalker.setConfiguration(configuration) + ginqAstWalker.setConfigurationExpressions(createConfigurationExpressions(ginqConfigurationMapExpression)) return (Expression) ginqAstWalker.visit(ginqExpression) } + private static String resolveAstWalkerClassName(SourceUnit sourceUnit, Map configuration, MapExpression ginqConfigurationMapExpression) { + String provider = configuration.get(CONF_PROVIDER) + if (!provider || CONF_PROVIDER_COLLECTION == provider) { + return configuration.get(CONF_AST_WALKER, DEFAULT_AST_WALKER_CLASS_NAME) + } + + // `@GQ` always supplies the default astWalker, so only a non-default value conflicts + String astWalker = configuration.get(CONF_AST_WALKER) + if (astWalker && DEFAULT_AST_WALKER_CLASS_NAME != astWalker) { + collectErrors("Options `${CONF_PROVIDER}` and `${CONF_AST_WALKER}` are mutually exclusive", ginqConfigurationMapExpression, sourceUnit) + } + + ClassLoader loader = GinqGroovyMethods.class.classLoader + Map providers = [:] + for (GinqProvider ginqProvider : ServiceLoader.load(GinqProvider, loader)) { + providers.put(ginqProvider.name, ginqProvider) + } + + String astWalkerClassName = null + boolean unavailable = false + if (CONF_PROVIDER_AUTO_SQL == provider) { + // Each candidate decides whether its own dependencies load. + // jooq-sql is registered even when the optional jOOQ classes are absent. + List reasons = [] + for (String name : PREFERRED_SQL_PROVIDERS) { + GinqProvider candidate = providers.get(name) + if (candidate == null) { + continue + } + String reason = candidate.unavailableReason(loader) + if (reason == null) { + astWalkerClassName = candidate.astWalkerClassName + break + } + reasons.add(reason) + } + if (!astWalkerClassName && reasons) { + unavailable = true + collectErrors("No usable GINQ SQL provider. ${reasons.join('; ')}", ginqConfigurationMapExpression, sourceUnit) + } + } else { + GinqProvider selected = providers.get(provider) + if (selected != null) { + String reason = selected.unavailableReason(loader) + if (reason == null) { + astWalkerClassName = selected.astWalkerClassName + } else { + unavailable = true + collectErrors(reason, ginqConfigurationMapExpression, sourceUnit) + } + } + } + if (!astWalkerClassName && !unavailable) { + List knownProviders = [CONF_PROVIDER_COLLECTION] + providers.keySet().sort() + collectErrors("Unknown GINQ provider: ${provider}. (known providers: ${knownProviders}) " + + 'Is the provider module, e.g. groovy-ginq-sql, on the compile classpath?', ginqConfigurationMapExpression, sourceUnit) + } + return astWalkerClassName + } + + private static Map createConfigurationExpressions(MapExpression ginqConfigurationMapExpression) { + Map configurationExpressions = [:] + if (!ginqConfigurationMapExpression) return configurationExpressions + + for (MapEntryExpression mapEntryExpression : ginqConfigurationMapExpression.getMapEntryExpressions()) { + configurationExpressions.put(mapEntryExpression.keyExpression.text, mapEntryExpression.valueExpression) + } + return configurationExpressions + } + private static Map createConfiguration(SourceUnit sourceUnit, MapExpression ginqConfigurationMapExpression) { Map configuration = [:] if (!ginqConfigurationMapExpression) return configuration + List providerOptionNames = null // discovered lazily, only when an unknown key is seen for (MapEntryExpression mapEntryExpression : ginqConfigurationMapExpression.getMapEntryExpressions()) { def conf = mapEntryExpression.keyExpression.text if (conf !in CONF_LIST) { - collectErrors("Invalid option: ${conf}. (supported options: ${CONF_LIST})", mapEntryExpression.keyExpression, sourceUnit) + if (providerOptionNames == null) { + providerOptionNames = ServiceLoader.load(GinqProvider, GinqGroovyMethods.class.classLoader) + .collectMany { GinqProvider p -> p.additionalOptionNames } + } + if (conf !in providerOptionNames) { + collectErrors("Invalid option: ${conf}. (supported options: ${CONF_LIST + providerOptionNames.sort()})", + mapEntryExpression.keyExpression, sourceUnit) + } } configuration.put(conf, mapEntryExpression.valueExpression.text) } @@ -151,13 +234,32 @@ class GinqGroovyMethods { private GinqGroovyMethods() {} /** Supported GINQ configuration keys. */ - public static final List CONF_LIST = [CONF_PARALLEL, CONF_AST_WALKER, CONF_OPTIMIZE] + public static final List CONF_LIST = [CONF_PARALLEL, CONF_AST_WALKER, CONF_OPTIMIZE, CONF_PROVIDER, CONF_DATA_SOURCE] /** Configuration key enabling parallel execution. */ public static final String CONF_PARALLEL = 'parallel' + /** + * Configuration key selecting the GINQ provider by name, e.g. {@code collection} (the default) + * or a provider registered via the {@link GinqProvider} SPI such as {@code native-sql}. + * + * @since 7.0.0 + */ + public static final String CONF_PROVIDER = 'provider' + /** + * Configuration key supplying the data source for database-backed providers. + * Its value is an arbitrary expression evaluated at runtime, available to + * providers via {@link GinqAstVisitor#setConfigurationExpressions(Map)}. + * + * @since 7.0.0 + */ + public static final String CONF_DATA_SOURCE = 'dataSource' // The 'astWalker' key selects a custom GinqAstVisitor provider; that SPI is still // incubating (see GinqAstVisitor / @GQ.astWalker) and may change in a future release. private static final String CONF_AST_WALKER = 'astWalker' private static final String CONF_OPTIMIZE = 'optimize' + private static final String CONF_PROVIDER_COLLECTION = 'collection' + private static final String CONF_PROVIDER_AUTO_SQL = 'sql' + // First candidate whose dependencies load wins. jOOQ is preferred; native-sql is the fallback. + private static final List PREFERRED_SQL_PROVIDERS = ['jooq-sql', 'native-sql'] private static final String DEFAULT_AST_WALKER_CLASS_NAME = GinqAstWalker.class.name private static final String TRUE_STR = 'true' } diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstBuilder.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstBuilder.java index 606e1d05cda..40e0ee1d481 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstBuilder.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstBuilder.java @@ -49,6 +49,7 @@ import org.codehaus.groovy.ast.stmt.ExpressionStatement; import org.codehaus.groovy.ast.stmt.Statement; import org.codehaus.groovy.control.SourceUnit; +import org.codehaus.groovy.syntax.Token; import org.codehaus.groovy.syntax.Types; import java.util.ArrayDeque; @@ -311,6 +312,22 @@ public void visitMethodCallExpression(MethodCallExpression call) { return; } + // `(expr) in (subquery)` is parsed as a method call `where(expr).in(subquery)` + // in some Groovy shapes. Keep the binary-expression repair below as the + // path the parser actually produces; this covers the method-call shape. + if (KW_IN.equals(methodName) || "!in".equals(methodName)) { + if (latestGinqExpression != null && latestGinqExpressionClause instanceof FilterExpression) { + FilterExpression filter = (FilterExpression) latestGinqExpressionClause; + int opType = "!in".equals(methodName) ? Types.COMPARE_NOT_IN : Types.KEYWORD_IN; + filter.setFilterExpr(new BinaryExpression( + filter.getFilterExpr(), + new Token(opType, methodName, -1, -1), + latestGinqExpression)); + latestGinqExpression = null; + } + return; + } + if (KW_EXISTS.equals(methodName)) { if (null != latestGinqExpression) { ArgumentListExpression argumentListExpression = (ArgumentListExpression) call.getArguments(); @@ -465,6 +482,24 @@ public void visitBinaryExpression(BinaryExpression expression) { latestGinqExpression = null; } } + // `where (e.salary + 1) in (subquery)` is parsed as + // `where(e.salary + 1) in (subquery)`, so the filter would keep + // only the addition. Fold that outer `in` back into the filter. + AbstractGinqExpression clause = ginqExpressionStack.isEmpty() || ginqExpressionStack.peek() == null + ? null + : ginqExpressionStack.peek().getNodeMetaData(__LATEST_GINQ_EXPRESSION_CLAUSE); + if ((Types.KEYWORD_IN == opType || Types.COMPARE_NOT_IN == opType) + && expression.getLeftExpression() instanceof MethodCallExpression + && clause instanceof FilterExpression) { + String leftName = ((MethodCallExpression) expression.getLeftExpression()).getMethodAsString(); + if (KW_WHERE.equals(leftName) || KW_ON.equals(leftName) || KW_HAVING.equals(leftName)) { + FilterExpression filter = (FilterExpression) clause; + filter.setFilterExpr(new BinaryExpression( + filter.getFilterExpr(), + expression.getOperation(), + expression.getRightExpression())); + } + } } } diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstVisitor.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstVisitor.java index a33ab30c8df..06782c137ef 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstVisitor.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/dsl/GinqAstVisitor.java @@ -32,6 +32,7 @@ import org.apache.groovy.ginq.dsl.expression.ShutdownExpression; import org.apache.groovy.ginq.dsl.expression.WhereExpression; import org.apache.groovy.lang.annotation.Incubating; +import org.codehaus.groovy.ast.expr.Expression; import java.util.Collections; import java.util.Map; @@ -149,4 +150,21 @@ default void setConfiguration(Map configuration) {} * @return the current configuration */ default Map getConfiguration() { return Collections.emptyMap(); } + /** + * Updates the visitor configuration with the raw option value expressions. + * Unlike {@link #setConfiguration(Map)}, which receives option values as text, + * this method supplies each option's value as the original expression, allowing + * providers to splice runtime values, e.g. a {@code dataSource}, into generated code. + * + * @param configurationExpressions the raw option value expressions keyed by option name + * @since 7.0.0 + */ + default void setConfigurationExpressions(Map configurationExpressions) {} + /** + * Returns the raw option value expressions. + * + * @return the current raw option value expressions keyed by option name + * @since 7.0.0 + */ + default Map getConfigurationExpressions() { return Collections.emptyMap(); } } diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqProvider.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqProvider.java new file mode 100644 index 00000000000..aa35d11ad47 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqProvider.java @@ -0,0 +1,108 @@ +/* + * 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 + * + * http://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. + */ +package org.apache.groovy.ginq.provider; + +import org.apache.groovy.ginq.dsl.GinqAstVisitor; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.Collections; +import java.util.List; +import java.util.ServiceLoader; + +/** + * Represents a named GINQ provider, i.e. an execution back-end for GINQ queries, + * discovered via {@link ServiceLoader}. A provider maps a short name, + * usable as the {@code provider} option of {@code GQ}/{@code GQL}/{@code @GQ}, + * to the {@link GinqAstVisitor} implementation that + * transforms GINQ queries for that back-end. + *

+ * The {@code collection} provider is built in; provider modules, e.g. {@code groovy-ginq-sql}, + * register additional implementations via + * {@code META-INF/services/org.apache.groovy.ginq.provider.GinqProvider}. + * + * @since 7.0.0 + */ +@Incubating +public interface GinqProvider { + /** + * Returns the provider name, e.g. {@code native-sql}. + * + * @return the provider name + */ + String getName(); + + /** + * Returns the fully qualified name of the provider's + * {@link GinqAstVisitor} implementation. + * + * @return the AST walker class name + */ + String getAstWalkerClassName(); + + /** + * Returns the names of provider-specific configuration options, e.g. + * {@code dialect}, accepted in addition to the standard GINQ options. + * Registering an option here only relaxes validation; interpreting it + * is up to the provider's AST walker. + * + * @return the additional option names, empty by default + */ + default List getAdditionalOptionNames() { + return Collections.emptyList(); + } + + /** + * Checks whether this provider's dependencies can be loaded from {@code loader}. + * Providers with optional dependencies, such as jOOQ, probe with + * {@link #canLoad(ClassLoader, String)} and return a message naming the + * missing artifact. The default implementation has no extra dependencies + * and returns {@code null}. + *

+ * {@code provider: 'sql'} skips a provider that reports a missing dependency + * and tries the next candidate. An explicit provider name that reports one + * is rejected with that message, before its AST walker is loaded. + * + * @param loader the class loader that will load the provider implementation + * @return {@code null} when the provider can be selected, otherwise the reason it cannot + * @since 7.0.0 + */ + default String unavailableReason(ClassLoader loader) { + return null; + } + + /** + * Returns whether {@code className} can be loaded from {@code loader} + * without initializing it. A missing class or a linkage error means the + * dependency is not usable. Provider implementations use this from + * {@link #unavailableReason(ClassLoader)}. + * + * @param loader the class loader to probe; {@code null} is the bootstrap loader + * @param className the binary name of a class from the dependency + * @return {@code true} when the class can be loaded + * @since 7.0.0 + */ + static boolean canLoad(ClassLoader loader, String className) { + try { + Class.forName(className, false, loader); + return true; + } catch (ClassNotFoundException | LinkageError ignored) { + return false; + } + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImpl.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImpl.java index c5e63e591c3..5739fcb1b05 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImpl.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImpl.java @@ -170,12 +170,16 @@ public Long denseRank() { } long result = 1L; - T latest = null; + // The window list is ordered, so a new preceding key differs from the + // adjacent row. The sentinel must not go through the key extractor: + // `orderby e.prop` would dereference a null row. + T previous = null; for (T t : list) { - if (comparator.compare(currentRecord.getV1(), t) > 0 && comparator.compare(latest, t) != 0) { + if (comparator.compare(currentRecord.getV1(), t) > 0 + && (null == previous || comparator.compare(previous, t) != 0)) { result++; } - latest = t; + previous = t; } return result; } @@ -265,37 +269,73 @@ static > RowBound getValidRowBound(WindowDefi ValueBound valueBound = windowDefinition.range(); U lower = valueBound.getLower(); U upper = valueBound.getUpper(); - if (value instanceof Number && (lower instanceof Number || null == lower) && (upper instanceof Number || null == upper)) { - final List> orderList = windowDefinition.orderBy(); - if (orderList.size() == 1) { - Order order = orderList.get(0); - - if (listWithIndex.isEmpty()) { + boolean numericBounds = (lower instanceof Number || null == lower) && (upper instanceof Number || null == upper); + final List> orderList = windowDefinition.orderBy(); + if (numericBounds && null != orderList && 1 == orderList.size() && (value instanceof Number || null == value)) { + if (listWithIndex.isEmpty()) { + return null; + } + Order order = orderList.get(0); + List keys = listWithIndex.stream() + .map(e -> order.getKeyExtractor().apply(e.getV1())) + .collect(Collectors.toList()); + int keyCount = keys.size(); + int[] span = numericSpan(keys, order.isNullsLast()); + int numericStart = span[0]; + int numericEnd = span[1]; + boolean hasNumeric = numericStart <= numericEnd; + boolean hasNull = order.isNullsLast() ? numericEnd < keyCount - 1 : numericStart > 0; + + if (null == value) { + // A null plus an offset is null. The offset bounds therefore + // address the null peer group; an unbounded bound addresses + // the corresponding edge of the partition. + RowBound bound = nullKeyRange(lower, upper, keyCount, numericStart, numericEnd, order.isNullsLast()); + if (null == bound) { return null; } - int flag = order.isAsc() ? 1 : -1; - BigDecimal firstElement = toBigDecimal((Number) order.getKeyExtractor().apply(listWithIndex.get(0).getV1())); - BigDecimal lastElement = toBigDecimal((Number) order.getKeyExtractor().apply(listWithIndex.get(size - 1).getV1())); - - BigDecimal lowerValue = null == lower ? MIN_VALUE : toBigDecimal(plus((Number) value, (Number) lower)); - BigDecimal upperValue = null == upper ? MAX_VALUE : toBigDecimal(plus((Number) value, (Number) upper)); - if ((flag * lowerValue.compareTo(firstElement) < 0 && flag * upperValue.compareTo(firstElement) < 0) - || (flag * lowerValue.compareTo(lastElement) > 0 && flag * upperValue.compareTo(lastElement) > 0)) { + firstIndex = bound.getLower(); + lastIndex = bound.getUpper(); + } else if (!hasNull) { + long[] indexes = numericRangeIndexes(order.isAsc(), (Number) value, (Number) lower, (Number) upper, keys); + if (null == indexes) { return null; } - - List list = - listWithIndex.stream() - .map(e -> order.getKeyExtractor().apply(e.getV1())) - .collect(Collectors.toList()); - if (order.isAsc()) { - firstIndex = getIndexByValue(lowerValue, true, list); - lastIndex = getIndexByValue(upperValue, false, list); + firstIndex = indexes[0]; + lastIndex = indexes[1]; + } else if (!hasNumeric) { + if (null == lower && null == upper) { + firstIndex = 0; + lastIndex = keyCount - 1L; } else { - final List reversedList = new ReversedList<>(list); - lastIndex = size - 1 - getIndexByValue(lowerValue, true, reversedList); - firstIndex = size - 1 - getIndexByValue(upperValue, false, reversedList); + return null; + } + } else { + List numericKeys = keys.subList(numericStart, numericEnd + 1); + long[] indexes = numericRangeIndexes(order.isAsc(), (Number) value, (Number) lower, (Number) upper, numericKeys); + if (null == indexes) { + return null; } + int numericSize = numericKeys.size(); + if ((indexes[0] < 0 && indexes[1] < 0) || (indexes[0] >= numericSize && indexes[1] >= numericSize)) { + return null; + } + // Null keys are not inside a finite numeric interval. Include + // them only when an unbounded side already reaches the numeric + // edge they sit against, so the frame stays one contiguous slice. + long absFirst = numericStart + Math.max(indexes[0], 0L); + long absLast = numericStart + Math.min(indexes[1], numericSize - 1L); + if (null == lower && absFirst == numericStart) { + absFirst = 0; + } + if (null == upper && absLast == numericEnd) { + absLast = keyCount - 1L; + } + if (absFirst > absLast) { + return null; + } + firstIndex = absFirst; + lastIndex = absLast; } } } @@ -306,6 +346,98 @@ static > RowBound getValidRowBound(WindowDefi return new RowBound(Math.max(firstIndex, 0L), Math.min(lastIndex, size - 1L)); } + /** + * Finds the contiguous numeric keys. Null keys are grouped at one end by the + * window order ({@code NULLS LAST} by default, {@code NULLS FIRST} otherwise). + * + * @param keys ordered window keys + * @param nullsLast whether null keys sort after non-null keys + * @param the order value type + * @return {@code [numericStart, numericEnd]}; the end is before the start when every key is null + */ + private static int[] numericSpan(List keys, boolean nullsLast) { + int size = keys.size(); + int numericStart; + int numericEnd; + if (nullsLast) { + numericEnd = size - 1; + while (numericEnd >= 0 && null == keys.get(numericEnd)) { + numericEnd--; + } + numericStart = 0; + } else { + numericStart = 0; + while (numericStart < size && null == keys.get(numericStart)) { + numericStart++; + } + numericEnd = size - 1; + } + return new int[] {numericStart, numericEnd}; + } + + /** + * Resolves a numeric {@code range} frame against keys that are all non-null numbers. + * A null offset is an unbounded bound. Returns {@code null} when the interval misses + * every key. The indexes follow {@code keys} and may lie outside {@code [0, size)}. + * + * @param asc whether the keys are ascending + * @param value the current order value + * @param lower the lower offset, or {@code null} for unbounded preceding + * @param upper the upper offset, or {@code null} for unbounded following + * @param keys non-null numeric keys in window order + * @param the order value type + * @return the relative {@code [first, last]} indexes, or {@code null} when the frame is empty + */ + private static > long[] numericRangeIndexes(boolean asc, Number value, Number lower, Number upper, List keys) { + int size = keys.size(); + int flag = asc ? 1 : -1; + BigDecimal firstElement = toBigDecimal((Number) keys.get(0)); + BigDecimal lastElement = toBigDecimal((Number) keys.get(size - 1)); + BigDecimal lowerValue = null == lower ? MIN_VALUE : toBigDecimal(plus(value, lower)); + BigDecimal upperValue = null == upper ? MAX_VALUE : toBigDecimal(plus(value, upper)); + if ((flag * lowerValue.compareTo(firstElement) < 0 && flag * upperValue.compareTo(firstElement) < 0) + || (flag * lowerValue.compareTo(lastElement) > 0 && flag * upperValue.compareTo(lastElement) > 0)) { + return null; + } + long firstIndex; + long lastIndex; + if (asc) { + firstIndex = getIndexByValue(lowerValue, true, keys); + lastIndex = getIndexByValue(upperValue, false, keys); + } else { + List reversedList = new ReversedList<>(keys); + lastIndex = size - 1L - getIndexByValue(lowerValue, true, reversedList); + firstIndex = size - 1L - getIndexByValue(upperValue, false, reversedList); + } + return new long[] {firstIndex, lastIndex}; + } + + /** + * Range frame for a null current key. Offset bounds select the null peer group. + * Unbounded bounds select the edges of the partition. + * + * @param lower the lower offset, or {@code null} when unbounded + * @param upper the upper offset, or {@code null} when unbounded + * @param size the partition size + * @param numericStart index of the first numeric key + * @param numericEnd index of the last numeric key + * @param nullsLast whether null keys sort last + * @return the frame, or {@code null} when it is empty + */ + private static RowBound nullKeyRange(Object lower, Object upper, int size, int numericStart, int numericEnd, boolean nullsLast) { + long peerStart = nullsLast ? numericEnd + 1L : 0L; + long peerEnd = nullsLast ? size - 1L : numericStart - 1L; + if (peerStart > peerEnd) { + return null; + } + long start = null == lower ? 0L : peerStart; + long end = null == upper ? size - 1L : peerEnd; + if (start > end) { + return null; + } + return new RowBound(start, end); + } + private static > long getIndexByValue(BigDecimal value, boolean isLower, List list) { int tmpIndex = binarySearch(list, value, Comparator.comparing(u -> toBigDecimal((Number) u))); int valueIndex; diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/package-info.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/package-info.java new file mode 100644 index 00000000000..e71b282c483 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/package-info.java @@ -0,0 +1,24 @@ +/* + * 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 + * + * http://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. + */ + +/** + * GINQ providers, i.e. execution back-ends for GINQ queries, and the SPI + * through which provider modules register themselves. + */ +package org.apache.groovy.ginq.provider; diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/transform/GinqASTTransformation.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/transform/GinqASTTransformation.java index b8680cafc28..6b8030bda53 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/transform/GinqASTTransformation.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/transform/GinqASTTransformation.java @@ -129,11 +129,23 @@ private static Object getDefaultOptionValue(String optionName) { } } + private static boolean hasOptionMember(String optionName) { + try { + GQ_CLASS_NODE.getTypeClass().getMethod(optionName); + return true; + } catch (NoSuchMethodException e) { + // some options, e.g. `dataSource`, hold runtime values and have no annotation counterpart + return false; + } + } + private static final String VALUE = "value"; private static final ClassNode GQ_CLASS_NODE = make(GQ.class); private static final ClassNode DEFAULT_RESULT_TYPE = ClassHelper.makeWithoutCaching((Class) getDefaultOptionValue(VALUE)); - private static final Map DEFAULT_OPTION_MAP = unmodifiableMap(CONF_LIST.stream().collect(Collectors.toMap( - c -> c, - c -> constX(getDefaultOptionValue(c)) + private static final Map DEFAULT_OPTION_MAP = unmodifiableMap(CONF_LIST.stream() + .filter(GinqASTTransformation::hasOptionMember) + .collect(Collectors.toMap( + c -> c, + c -> constX(getDefaultOptionValue(c)) ))); } diff --git a/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc b/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc index f364a0fee75..d81b9217d8b 100644 --- a/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc +++ b/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc @@ -586,6 +586,9 @@ include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_setop_minus,in Each side of a set operation is a complete `from...select` expression and can include `where`, `groupby`, `orderby`, `limit`, and any other clauses. +An `orderby` or `limit` on the final operand orders and slices that operand before the +sides are combined. The combined rows are not reordered. +The SQL providers order that combined result instead; see <>. NOTE: The set operation keyword must appear on its own line. Set operations are also available as methods on any `Queryable` result: @@ -1166,8 +1169,8 @@ include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_async_await,in === Customize GINQ NOTE: *INCUBATING*: the custom code-generator (provider) extension point described here -- the -`astWalker` option and the `GinqAstVisitor` SPI it selects -- is still incubating and may change -in a future release, even though the rest of GINQ is stable. +`provider` and `astWalker` options, the `GinqProvider` registry and the `GinqAstVisitor` SPI -- +is still incubating and may change in a future release, even though the rest of GINQ is stable. For advanced users, you could customize GINQ behaviour by specifying your own target code generator. For example, we could specify the qualified class name `org.apache.groovy.ginq.provider.collection.GinqAstWalker` as the target code generator to generate GINQ method calls for querying collections, @@ -1177,6 +1180,258 @@ which is the default behaviour of GINQ: include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_customize_01,indent=0] ---- +Alternatively, a code generator can be selected by short name through the `provider` option. +The name is resolved through the `org.apache.groovy.ginq.provider.GinqProvider` SPI, so provider +modules on the compile classpath register themselves automatically. The built-in provider is +`collection`, the default, which executes queries in memory. + +=== Executing GINQ against a database + +NOTE: *INCUBATING*: the SQL backend described here is provided by the optional `groovy-ginq-sql` +module (GEP-26) and is still incubating. + +With the `groovy-ginq-sql` module on the classpath, the same query syntax can be executed against +a relational database by selecting the `native-sql` provider and supplying a `dataSource`, which +may be a `groovy.sql.Sql`, a `javax.sql.DataSource` or a `java.sql.Connection`. Table references +are string literals naming the tables: +[source, groovy] +---- +def threshold = 2500 +def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + where e.salary > threshold + select e.name, d.name as deptName +} +---- + +Rather than loading rows into memory, the query is translated at compile time into ANSI SQL, e.g. +`SELECT e.name, d.name AS deptName FROM employees e INNER JOIN departments d ON e.deptId = d.id +WHERE e.salary > ?`, and filtering, joining and aggregating are pushed down to the database. +The result rows are `groovy.sql.GroovyRowResult` instances. + +Aggregate and expression values keep the types the database returns, so they can differ +from an in-memory query. The collection provider returns `BigDecimal` for `avg` (and for +`sum` and the other numeric aggregates). H2 returns `AVG` as a `Double`. In mixed mode the +in-memory tail sees those database types on the columns the pushed prefix projected. + +Every literal and captured variable in the query becomes a positional bound parameter, so the SQL +text never contains user-supplied values and SQL injection is structurally impossible. + +The SQL backend operates in strict mode by default: an expression either translates cleanly to SQL, +or the query is rejected at compile time with an error explaining the untranslatable construct. +Opt in to mixed mode with `mixedMode: true` (the same option on `native-sql` and `jooq-sql`) when +a query also needs something SQL cannot express, such as an arbitrary Groovy method, a window +function, or a join to an in-memory collection: +[source, groovy] +---- +def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + where e.salary > threshold + select e.name.reverse() +} +---- + +Mixed mode splits the query at the first clause that does not translate (`from`, each `join`, +`where`, then `orderby` and `limit`). The translatable prefix is executed on the database and +comes back as `GroovyRowResult` rows; the remaining clauses run in memory through the collection +provider. A single-table prefix is one row per result. A join prefix is planned as `alias.*` +for each alias, then each source is probed and the prefix is re-run with those columns named +explicitly (`alias.col AS __ginqN_M`) and read back by ordinal. The in-memory tail still sees +`e.name` and `d.name`, including when both sources have a column called `name`. Duplicate labels +within one source are rejected rather than dropping a value: JDBC drivers differ on labels, +duplicates, case folding and quoting, and a label map is not treated as a faithful copy of the +table. A real column called `__ginq_mixed_key` stays readable; mixed mode does not store join +alignment under a column name. An unmatched side of a pushed outer join is null, as it is for +the collection provider. Each joined source is wrapped so the source itself carries a presence +column, for example `(SELECT t.*, 1 AS "__ginq_present" FROM departments t) d`. The outer join +makes that column null when the side has no row, and the name is chosen so it does not collide +with a real column. A real column that is already named `__ginq_present` stays that column: +only the marker definition is renamed, so `on e.id == m.__ginq_present` still compares the +user's values. A row that exists but whose columns are all null therefore stays a non-null +row, while `d == null` is true when the join did not match. The in-memory tail pairs those +already aligned rows by index, so a null alias stays null for a later `where`, `select`, +`orderby`, `groupby` or join. PostgreSQL and SQLite spell a full join as +`FULL OUTER JOIN`. H2, MySQL and MariaDB have no such join. An omitted `dialect`, or +`dialect: 'ansi'`, does not spell it either: the engine is not known yet, and the +emulation below is valid both where `FULL OUTER JOIN` exists and where the engine +rejects it. A JDBC URL visible on the `dataSource` expression (`jdbc:h2:`, +`jdbc:mysql:`, `jdbc:mariadb:`, `jdbc:postgresql:`, `jdbc:sqlite:`), including the +constant prefix of a GString such as `"jdbc:h2:mem:${name}"` or +`"jdbc:postgresql://${host}/db"`, selects that dialect when `dialect` itself is +omitted, including for a strict query. Each full +join, in strict mode and in mixed mode, and inside `exists`, `in` or a scalar +subquery as well as at the top, is then a left join union the right-join rows for +which the whole left side is absent, and that union is a derived table the next +join reads. A query that stays entirely in SQL keeps the author's `select` list. A +whole-row projection such as `select e, d` stays one flat row. Each of its +columns is labeled with the source alias, for example `e_NAME` and `d_NAME`, +so a shared name cannot overwrite the other source. A named column beside a +star keeps that column's own name: `select e.name, d` exposes `name` and +`d_NAME`. The presence marker stays inside the union and is not a result column. +`orderby` and `limit` apply to the combined rows, by the names of those output +columns. A `where` clause is kept together: if any part of it cannot be translated, the whole +predicate runs in memory and only the preceding `from`/`join` clauses are pushed. +`groupby` and its `having` clause are not pushed when a later clause falls back to memory, so +grouped results keep collection-provider semantics. `orderby` and `limit` are pushed only when +they apply to the source rows (there is no `groupby`), the preceding `where` translated, and they +themselves translate. An `orderby` that stays in memory keeps the following `limit` in memory too, +so the limit is applied to the filtered rows rather than to an unordered prefix. Set operations +are not split; one that does not translate entirely is still a compile error. `mixedMode: false`, +or omitting the option, keeps the strict default. The `from` source itself must still be a string +table name or a subquery that translates to SQL. Strict-mode errors name the construct that failed +and say how to rewrite it or how to enable `mixedMode`. This split follows the same boundary as +LINQ's `AsEnumerable`: a translatable prefix runs in the database and the rest of the query +continues in memory. It is never the default. + +The main current restriction in strict mode is window functions. Aggregation is supported both in +the classic form, e.g. `groupby e.deptId` with `select e.deptId, count(), sum(e.salary)`, and the +`groupby ... into g` form, e.g. `g.count()`, `g.sum(e -> e.salary)`. +`count(distinct(e.deptId))` and `g.count(distinct(e -> e.deptId))` (or +`g.count(e -> distinct(e.deptId))`) translate to `COUNT(DISTINCT ...)`. Other aggregates do not +take `distinct`. + +Nested queries translate to SQL subqueries: a nested query as a data source becomes a derived +table, `(...).exists()` becomes `EXISTS (...)`, `in` against a nested query becomes `IN (subquery)`, +and a nested query in an expression position becomes a scalar subquery. Subqueries in expression +positions may be correlated, i.e. reference the aliases of enclosing queries; derived tables +cannot, matching standard SQL. + +A set of common methods and operators maps to SQL. Where the mapping cannot be decided safely +it is rejected at compile time, or left in memory when `mixedMode: true` is set. It is not +emitted as a guess. The exact SQL behaviour of a mapped function still depends on the database. + +.Groovy operations and the SQL they become +[cols="2,2,3"] +|=== +|Groovy |SQL |Constraints + +|`==` / `!=` and a null literal +|`IS NULL` / `IS NOT NULL` +|Same result as Groovy for that literal. + +|`==` / `!=` otherwise +|`IS NOT DISTINCT FROM` / `IS DISTINCT FROM` +|Null-safe, like Groovy `==`. A bound parameter that is null matches a null column (`deptId == wanted` selects null departments when `wanted` is null). MySQL and MariaDB spell equality as `<=>`; SQLite spells it `IS` / `IS NOT`. Numeric equality still follows the database when the types differ (`1` and `1.0`). + +|`<` `<=` `>` `>=` +|the same operator +|SQL three-valued logic, not Groovy's ordering. A null does not compare as less than every other value, so `deptId < 1` does not select a null `deptId`. + +|`in` / `!in` on a list +|`IN`, or `IS NULL OR NOT IN` when `!in` has no null member +|`null in [1, 2]` is false and `null !in [1, 2]` is true. A null member of the list is `IS NULL` (and `IS NOT NULL` for `!in`), matching Groovy. `in []` matches nothing and `!in []` matches every row. + +|`in` / `!in` on a constant range +|a pair of comparisons +|`1..3` and `3..1` are the same bounds, and an exclusive end uses `<` or `>`. `!in` is `value IS NULL OR value` outside the bounds, so a null value matches Groovy. A range whose bounds are not compile-time constants is rejected, because a descending Groovy range still contains the values between its endpoints; write `x >= low && x <= high` when the order is known. + +|`+` +|string concatenation, or numeric `+` +|Concatenation when the left operand is text, or a column stands beside a string literal (`e.name + '!'`, `'!' + e.name`). Addition when a number stands beside a column or both sides are numbers (`e.salary + 1`). A captured variable is pushed down only when its declared type is text or numeric, or it is cast, for example `e.name + (suffix as String)`. Two columns are not pushed down (`e.first.concat(e.last)`, or a numeric cast). Anything else is a compile error in strict mode and runs in memory in mixed mode. A number beside a string literal is rejected: Groovy does not concatenate that way. + +|`length()` / `size()` +|`CHAR_LENGTH` +|Character count, not bytes. Null stays null; Groovy would throw on a null receiver. The receiver must be a column or a value known to be text. A captured variable is not pushed down, because it might be a list or some other value whose `size()` is not a character length. + +|`toUpperCase` / `toLowerCase` / `trim` / `substring` / `replace` / `concat` / `isEmpty` +|`UPPER` / `LOWER` / `TRIM` / `SUBSTRING` / `REPLACE` / string concatenation / `CHAR_LENGTH(...) = 0` +|Same receiver rule as `length()`. `substring` uses Groovy's 0-based, exclusive indexes; a column index is shifted in SQL. `concat` is the explicit string form of `+`. + +|`contains` / `startsWith` / `endsWith` +|`LIKE ... ESCAPE '!'` +|`%`, `_` and `!` in the runtime value are escaped, so the value matches literally. `contains(null)` does not match the text `null`. The argument must be a literal or a captured variable. + +|`indexOf(text)` +|`POSITION(text IN value) - 1` +|Groovy's 0-based result, and `-1` when the text is absent. MySQL and MariaDB spell `LOCATE`; SQLite spells `INSTR`. A from-index is not translated. + +|`abs` / `floor` / `ceil` / `round` +|`ABS` / `FLOOR` / `CEILING` / `ROUND` +|Pushed only when the dialect can render the function. See the dialect note below. + +|`-` `*` `/` `%` +|`-` `*` real division `MOD` +|Numeric operators, not overloaded the way `+` is. `/` is `CAST(... AS DOUBLE)` so it does not truncate. SQLite spells `%` as the `%` operator. + +|`&&` / `\|\|` / `!` +|`AND` / `OR` / `NOT` +|SQL three-valued logic, not Groovy truthiness. `UNKNOWN` stays `UNKNOWN`. + +|ternary +|`CASE WHEN ... END` +|The condition uses SQL truth. The Elvis operator is rejected: Groovy truthiness is not SQL null. Use `coalesce(...)` or an explicit `== null` ternary. + +|`coalesce(a, b, ...)` +|`COALESCE` +|The first non-null argument. + +|`sum` +|`COALESCE(SUM(...), 0)` +|An all-null group is 0, matching the collection provider. Other aggregates can return SQL null. + +|`Math.max` / `Math.min` +|`GREATEST` / `LEAST` +|Two arguments. SQLite spells these as scalar `MAX` / `MIN`. Aggregate `min` and `max` are a different translation. + +|`cast(expr, 'TYPE')` +|`CAST(expr AS TYPE)` +|`TYPE` is a string literal from a fixed list, for example `INTEGER`, `DECIMAL`, `DECIMAL(10,2)`, `VARCHAR`, `VARCHAR(20)` or `DOUBLE PRECISION`. Any other type is rejected. `select expr as alias` is a column alias, not this cast. A Groovy cast used to fix the type of `+`, such as `(suffix as String)`, casts a captured value before it is bound and casts a column in SQL. +|=== + +SQL nulls propagate where Groovy would throw, for example `null.toUpperCase()` on a column. + +Table names are simple identifiers or `schema.table`. Anything else, including quotes and +spaces, is rejected. A quoting `table()` helper is not part of this backend yet. + +The native provider accepts a small `dialect` option for the points that vary among common +open-source databases: `ansi` (the default), `h2` (ANSI; H2 uppercases unquoted names, so they +are left unquoted), `postgres`, `mysql`, `mariadb`, and `sqlite`. MySQL, MariaDB and SQLite use +`LIMIT`/`OFFSET` and emulate `NULLS FIRST`/`NULLS LAST`, which they do not spell. SQLite spells +`LENGTH`, `SUBSTR`, `%` and `INSTR` instead of `CHAR_LENGTH`, `SUBSTRING`, `MOD` and `POSITION`, +and scalar `MAX`/`MIN` instead of `GREATEST`/`LEAST`. MySQL and MariaDB spell `LOCATE` instead of +`POSITION`. Whether a function can be pushed down is a dialect capability, shared by the +translator and the renderer, not a special case written beside one function. `FLOOR` and +`CEILING` are not in the SQLite set: `dialect: 'sqlite'` rejects `floor()` and `ceil()` in +strict mode, and with `mixedMode: true` the clause that uses them runs in memory while the +rest of the query can still be pushed. A function the dialect only spells differently, such as +`CHAR_LENGTH` as SQLite `LENGTH`, is still pushed. Other databases belong on `jooq-sql`, which +uses the same capability check. + +A trailing `orderby`/`limit` on the final operand of a set operation applies to the combined +result, matching SQL semantics; the order keys must match columns of the final `select` clause. +(Note that the collection provider instead applies such an `orderby` to the final operand before +combining.) `orderby`/`limit` within earlier operands are rejected. + +Because a `dataSource` is a runtime value, it cannot be supplied via the `@GQ` annotation; +use the `GQ`/`GQL` macro form for database-backed queries. + +==== The jooq-sql provider + +When `org.jooq:jooq` is also on the compile classpath, the `jooq-sql` provider becomes available. +It supports everything the `native-sql` provider supports but uses jOOQ as a compile-time, +dialect-aware SQL renderer: the `dialect` option names one of jOOQ's `SQLDialect` values and the +generated SQL uses that dialect's syntax and function spellings, e.g. HSQLDB's `limit ? offset ?` +in place of the ANSI `OFFSET ? ROWS FETCH NEXT ? ROWS ONLY`: +[source, groovy] +---- +def result = GQL(provider: 'jooq-sql', dialect: 'POSTGRES', dataSource: db) { + from e in 'employees' + where e.salary > threshold + orderby e.salary in desc + limit 10 + select e.name, e.salary +} +---- + +jOOQ is used at compile time only: execution and results are identical to the `native-sql` +provider (bound positional parameters, `GroovyRowResult` rows), and jOOQ does not need to be +on the runtime classpath. With no `dialect` option, jOOQ's `DEFAULT` dialect is used. +`mixedMode: true` is available here as well and uses the same split as `native-sql`; only the +pushed prefix is rendered by jOOQ. +Selecting `provider: 'sql'` auto-detects, preferring `jooq-sql` when jOOQ is on the compile +classpath and otherwise using `native-sql`. + === Optimize GINQ GINQ optimizer is enabled by default for better performance. It will transform the GINQ AST to achieve better execution plan. diff --git a/subprojects/groovy-ginq/src/spec/test/org/apache/groovy/ginq/GinqTest.groovy b/subprojects/groovy-ginq/src/spec/test/org/apache/groovy/ginq/GinqTest.groovy index aa6f36b7539..f3e3480b353 100644 --- a/subprojects/groovy-ginq/src/spec/test/org/apache/groovy/ginq/GinqTest.groovy +++ b/subprojects/groovy-ginq/src/spec/test/org/apache/groovy/ginq/GinqTest.groovy @@ -3768,6 +3768,16 @@ class GinqTest { ''' } + @Test + void "testGinq - customize GINQ target - 1"() { + assertGinqScript ''' + assert [0, 1, 2] == GQ(provider: 'collection') { + from n in [0, 1, 2] + select n + }.toList() + ''' + } + @Test void "testGinq - GINQ tips - 0"() { assertGinqScript ''' @@ -3907,6 +3917,32 @@ class GinqTest { ''' } + @Test + void "testGinq - set operation trailing orderby and limit orders the last operand"() { + assertGinqScript ''' + def employees = [ + [name: 'Alice', salary: 5000, deptId: 1], + [name: 'Bob', salary: 3000, deptId: 1], + [name: 'Carol', salary: 4000, deptId: 2], + [name: 'Dave', salary: 2000, deptId: null], + [name: 'Eve', salary: 5000, deptId: 2], + [name: 'Frank', salary: 6000, deptId: 3] + ] + // the final operand is ordered and sliced, then combined with the first operand + assert [['Alice', 5000], ['Bob', 3000], ['Carol', 4000]] == GQ { + from a in employees + where a.deptId == 1 + select a.name, a.salary + union + from b in employees + where b.deptId == 2 + orderby b.salary in desc, b.name + limit 1, 2 + select b.name, b.salary + }.toList() + ''' + } + @Test void "testGinq - chained set operations"() { assertGinqScript ''' @@ -6809,6 +6845,97 @@ class GinqTest { ''' } + @Test + void "testGinq - window - 92"() { + assertGinqScript ''' + def employees = [ + [name: 'a', salary: 100], + [name: 'b', salary: 300], + [name: 'c', salary: 100], + [name: 'd', salary: 200], + [name: 'e', salary: null] + ] + // denseRank without partitionby, ordered by a property of the row + assert [['a', 1], ['b', 3], ['c', 1], ['d', 2], ['e', 4]] == GQ { + from e in employees + select e.name, (denseRank() over(orderby e.salary)) + }.toList() + + assert [[1, 'a', 1], [1, 'b', 2], [2, 'c', 1]] == GQ { + from e in [[dept: 1, name: 'a', salary: 10], [dept: 1, name: 'b', salary: 20], [dept: 2, name: 'c', salary: 10]] + select e.dept, e.name, (denseRank() over(partitionby e.dept orderby e.salary)) + }.toList() + ''' + } + + @Test + void "testGinq - window - 93"() { + assertGinqScript ''' + // range frame with a null order key (nulls last by default) + assert [[1, 2, 3], [2, 3, 6], [null, 1, 0], [3, 2, 5]] == GQ { + from n in [1, 2, null, 3] + select n, + (count() over(orderby n range -1, 1)), + (sum(n) over(orderby n range -1, 1)) + }.toList() + + assert [[1, 1, 1], [null, 2, 0], [null, 2, 0]] == GQ { + from n in [1, null, null] + select n, + (count() over(orderby n range -1, 1)), + (sum(n) over(orderby n range -1, 1)) + }.toList() + + // unbounded range still covers the whole partition, including null keys + assert [[1, 3, 4], [null, 3, 4], [3, 3, 4]] == GQ { + from n in [1, null, 3] + select n, + (count() over(orderby n range null, null)), + (sum(n) over(orderby n range null, null)) + }.toList() + + // nulls first: an unbounded preceding bound includes the leading null peers + assert [[1, 2, 1], [null, 1, 0], [2, 3, 3]] == GQ { + from n in [1, null, 2] + select n, + (count() over(orderby n in asc(nullsfirst) range null, 0)), + (sum(n) over(orderby n in asc(nullsfirst) range null, 0)) + }.toList() + + // a finite range does not pull in null keys on either side + assert [[1, 2, 3], [null, 1, 0], [2, 2, 3]] == GQ { + from n in [1, null, 2] + select n, + (count() over(orderby n in asc(nullsfirst) range -1, 1)), + (sum(n) over(orderby n in asc(nullsfirst) range -1, 1)) + }.toList() + + // descending order uses the same value interval; nulls stay out of it + assert [[1, 1, 1], [null, 1, 0], [3, 1, 3]] == GQ { + from n in [1, null, 3] + select n, + (count() over(orderby n in desc range -1, 1)), + (sum(n) over(orderby n in desc range -1, 1)) + }.toList() + + // unbounded following includes a trailing null peer group + assert [[1, 3, 4], [3, 2, 3], [null, 1, 0]] == GQ { + from n in [1, 3, null] + select n, + (count() over(orderby n range 0, null)), + (sum(n) over(orderby n range 0, null)) + }.toList() + + // the null key may be a property, not the row itself + assert [[1, 2, 3], [null, 1, 0], [2, 2, 3]] == GQ { + from e in [[v: 1], [v: null], [v: 2]] + select e.v, + (count() over(orderby e.v range -1, 1)), + (sum(e.v) over(orderby e.v range -1, 1)) + }.toList() + ''' + } + @Test void "testGinq - window - 91"() { assertGinqScript ''' diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqErrorTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqErrorTest.groovy index 7b42a395914..af654cab509 100644 --- a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqErrorTest.groovy +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqErrorTest.groovy @@ -602,7 +602,31 @@ final class GinqErrorTest { } ''' - assert err.message.toString().contains('Invalid option: xxx. (supported options: [parallel, astWalker, optimize]) @ line 1, column 16.') + assert err.message.toString().contains('Invalid option: xxx. (supported options: [parallel, astWalker, optimize, provider, dataSource]) @ line 1, column 16.') + } + + @Test + void "testGinq - unknown provider - 1"() { + def err = shouldFail '''\ + GQ(provider:'unknown-provider') { + from n in [1, 2, 3] + select n + } + ''' + + assert err.message.toString().contains('Unknown GINQ provider: unknown-provider. (known providers: [collection])') + } + + @Test + void "testGinq - provider conflicts with astWalker - 1"() { + def err = shouldFail '''\ + GQ(provider:'sql', astWalker:'com.example.CustomAstWalker') { + from n in [1, 2, 3] + select n + } + ''' + + assert err.message.toString().contains('Options `provider` and `astWalker` are mutually exclusive') } @Test diff --git a/versions.properties b/versions.properties index b65f98012a4..422400594b9 100644 --- a/versions.properties +++ b/versions.properties @@ -32,6 +32,7 @@ commonsMath3=3.6.1 equinox=3.24.300 felix=8.0.0 flatLaf=3.8 +h2=2.5.252 ivy=2.6.0 jackson2=2.23.0 jackson3=3.3.0 @@ -45,6 +46,7 @@ jcipAnnotations=1.0 jline=4.5.0 jmh=1.37 jna=5.19.1 +jooq=3.19.36 # Don't change jqwik version jqwik=1.9.3 jruby=9.2.17.0