diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 45ca1cc12d3..9cf972447a1 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -79,9 +79,14 @@ + + + + + @@ -860,6 +865,11 @@ + + + + + @@ -1208,6 +1218,12 @@ + + + + + + @@ -3129,6 +3145,12 @@ + + + + + + @@ -3604,6 +3626,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/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java b/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java index 0e7fade4f1b..0b95c8c9602 100644 --- a/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java +++ b/src/main/java/org/codehaus/groovy/ast/tools/GenericsUtils.java @@ -368,6 +368,126 @@ public static ClassNode erasure(final ClassNode type) { return t.getPlainNodeReference(); } + /** + * Type arguments safe to store on {@code owner}. A class that declares no + * type parameters gets none. Each argument is a reference type. + *

+ * The declaration is read from the class, not from whether a use site has + * already been resolved. A primary class records its formals on itself. + * A use-site proxy reads the redirect target. An unresolved name has no + * declaration yet, so its arguments are left in place. A source use site + * is not rewritten; the generics check reports a type argument that is + * not well-formed. Callers that build a type, such as inference or + * substitution, use this method so the type they store is one a signature + * can carry. + * + * @param owner the parameterized type + * @param arguments the arguments about to be stored + * @return the arguments to store, or {@code null} when the class declares none + */ + public static GenericsType[] legalTypeArguments(final ClassNode owner, final GenericsType[] arguments) { + if (arguments == null) return null; + if (arguments.length > 0 && declaresNoTypeParameters(owner)) return null; + GenericsType[] legal = new GenericsType[arguments.length]; + boolean changed = false; + for (int i = 0; i < arguments.length; i += 1) { + legal[i] = asReferenceTypeArgument(arguments[i]); + changed |= legal[i] != arguments[i]; + } + return changed ? legal : arguments; + } + + /** + * Whether {@code type}'s declaration has no type parameters. + * {@link ClassNode#redirect()} is never null. A primary class is not + * resolved to a {@code Class}, and its formals are the ones the parser + * recorded. A loaded class whose formals were not copied onto the node + * answers from {@code Class.getTypeParameters()}. An unresolved use site + * answers {@code false} because the declaration is not this node; its + * own generics are the arguments. + */ + private static boolean declaresNoTypeParameters(final ClassNode type) { + if (type == null || type.isGenericsPlaceHolder()) return false; + ClassNode declared = type.redirect(); + if (declared.isArray()) return false; + if (declared.isPrimaryClassNode()) { + // A source class records its formals on the primary node. A synthetic + // carrier such as the closure-hint class has no module and uses the + // node only to hold the arguments being inferred, so a missing formal + // list is not a declaration of a raw type. + if (declared.getModule() == null) return false; + GenericsType[] formals = declared.getGenericsTypes(); + return formals == null || formals.length == 0; + } + if (declared != type) { + GenericsType[] formals = declared.getGenericsTypes(); + if (formals != null) return formals.length == 0; + if (declared.isResolved()) { + return declared.getTypeClass().getTypeParameters().length == 0; + } + return false; + } + if (declared.isResolved()) { + return declared.getTypeClass().getTypeParameters().length == 0; + } + return false; + } + + /** + * A type argument or wildcard bound is a reference type (JLS 4.5). + * A primitive is replaced by its wrapper. Nested arguments are corrected + * the same way. Placeholders are left as placeholders. + * + * @param type the type argument + * @return a type argument javac could write, or {@code type} when it already is one + */ + public static GenericsType asReferenceTypeArgument(final GenericsType type) { + if (type == null) return null; + ClassNode base = referenceType(type.getType()); + ClassNode[] upper = referenceTypes(type.getUpperBounds()); + ClassNode lower = referenceType(type.getLowerBound()); + if (base == type.getType() && upper == type.getUpperBounds() && lower == type.getLowerBound()) { + return type; + } + GenericsType corrected = new GenericsType(base, upper, lower); + corrected.setWildcard(type.isWildcard()); + return corrected; + } + + private static ClassNode referenceType(final ClassNode type) { + if (type == null || type.isGenericsPlaceHolder()) return type; + if (ClassHelper.isPrimitiveType(type) && !ClassHelper.isPrimitiveVoid(type)) { + return ClassHelper.getWrapper(type); + } + GenericsType[] arguments = type.getGenericsTypes(); + if (arguments == null || arguments.length == 0) return type; + GenericsType[] corrected = null; + for (int i = 0; i < arguments.length; i += 1) { + GenericsType argument = asReferenceTypeArgument(arguments[i]); + if (argument != arguments[i]) { + if (corrected == null) corrected = Arrays.copyOf(arguments, arguments.length); + corrected[i] = argument; + } + } + if (corrected == null) return type; + ClassNode copy = type.getPlainNodeReference(); + copy.setGenericsTypes(corrected); + return copy; + } + + private static ClassNode[] referenceTypes(final ClassNode[] types) { + if (types == null) return null; + ClassNode[] corrected = null; + for (int i = 0; i < types.length; i += 1) { + ClassNode type = referenceType(types[i]); + if (type != types[i]) { + if (corrected == null) corrected = Arrays.copyOf(types, types.length); + corrected[i] = type; + } + } + return corrected == null ? types : corrected; + } + /** * @since 2.3.0 */ @@ -525,7 +645,8 @@ public static ClassNode correctToGenericsSpecRecurse(Map gene } } } - return makeClassSafeWithGenerics(type, newgTypes); + GenericsType[] legal = legalTypeArguments(type, newgTypes); + return makeClassSafeWithGenerics(type, legal == null ? EMPTY_GENERICS_ARRAY : legal); } /** diff --git a/src/main/java/org/codehaus/groovy/ast/tools/WideningCategories.java b/src/main/java/org/codehaus/groovy/ast/tools/WideningCategories.java index 5d8d5f7e830..955d7a22658 100644 --- a/src/main/java/org/codehaus/groovy/ast/tools/WideningCategories.java +++ b/src/main/java/org/codehaus/groovy/ast/tools/WideningCategories.java @@ -298,9 +298,43 @@ private static ClassNode parameterizeLowestUpperBound(final LowestUpperBoundCont lubGTs[i] = basicType.asGenericsType(); } } + int declared = declaredTypeParameterCount(lub); + if (declared == 0) { + GenericsType[] existing = lub.getGenericsTypes(); + if (existing != null && existing.length > 0) { + return lub.getPlainNodeReference(); + } + return lub; + } + if (declared > 0 && declared != n) { + return lub.getPlainNodeReference(); + } return GenericsUtils.makeClassSafe0(lub, lubGTs); } + /** + * Number of type parameters {@code type}'s declaration has, or {@code -1} + * when that declaration is not known. A lowest upper bound is not a + * generic class of its own. + */ + private static int declaredTypeParameterCount(final ClassNode type) { + if (type == null || type.isGenericsPlaceHolder() || type.isArray()) return -1; + if (type instanceof LowestUpperBoundClassNode) return -1; + ClassNode declared = type.redirect(); + if (declared instanceof LowestUpperBoundClassNode || declared.isArray()) return -1; + if (declared.isPrimaryClassNode()) { + if (declared.getModule() == null) return -1; + GenericsType[] formals = declared.getGenericsTypes(); + return formals == null ? 0 : formals.length; + } + if (!declared.isResolved()) return -1; + if (declared != type) { + GenericsType[] formals = declared.getGenericsTypes(); + if (formals != null) return formals.length; + } + return declared.getTypeClass().getTypeParameters().length; + } + /** * Tracks pairs of types whose LUB is currently being computed by * {@link #lowestUpperBound(ClassNode, ClassNode)}, so the recursion can @@ -635,15 +669,14 @@ public LowestUpperBoundClassNode(final String name, final ClassNode upper, final for (ClassNode i: interfaces) sj.add(i.getText()); text = sj.toString(); - if (isUsingGenerics()) { - List generics = new ArrayList<>(); - if (upper.getGenericsTypes() != null) - Collections.addAll(generics, upper.getGenericsTypes()); - for (ClassNode i : interfaces) { - if (i.getGenericsTypes() != null) - Collections.addAll(generics, i.getGenericsTypes()); - } - setGenericsTypes(generics.toArray(GenericsType.EMPTY_ARRAY)); + // Arguments belong to the class this node is written as. Copying + // every interface's arguments would parameterize a class that + // declares none when getName() reports that class (Serializable + // sorted ahead of Comparable). + GenericsType[] representative = compileTimeClassNode.getGenericsTypes(); + if (representative != null && representative.length > 0 + && representative.length == declaredTypeParameterCount(compileTimeClassNode)) { + setGenericsTypes(representative); } } diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/TypeSignatureWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/TypeSignatureWriter.java index f9ba1d8617c..65791f2b847 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/TypeSignatureWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/TypeSignatureWriter.java @@ -19,6 +19,7 @@ package org.codehaus.groovy.classgen.asm; import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.GenericsType; /** * Writes the JVMS 4.7.9.1 nested form of a parameterized type for a Signature @@ -42,11 +43,54 @@ static void writeParameterizedClass(final StringBuilder ret, final ClassNode pri writeParameterizedClass(ret, owner); ret.append('.'); ret.append(innerClassSimpleName(printType, owner)); - BytecodeHelper.addSubTypes(ret, printType.getGenericsTypes(), "<", ">"); + BytecodeHelper.addSubTypes(ret, signatureArguments(printType), "<", ">"); return; } ret.append(BytecodeHelper.getTypeDescription(printType, false)); - BytecodeHelper.addSubTypes(ret, printType.getGenericsTypes(), "<", ">"); + BytecodeHelper.addSubTypes(ret, signatureArguments(printType), "<", ">"); + } + + /** + * Type arguments safe to write for a resolved declaration. A signature + * cannot name arguments a class does not declare, so a count that does + * not match the declaration is omitted. An unresolved name is left + * unchanged. A source use site that does not match is rejected before + * bytecode; a type built later, such as a lowest upper bound, may still + * carry arguments this method has to drop. + */ + private static GenericsType[] signatureArguments(final ClassNode printType) { + GenericsType[] useSite = printType.getGenericsTypes(); + if (useSite == null || useSite.length == 0) { + return useSite; + } + int declared = declaredTypeParameters(printType); + if (declared >= 0 && declared != useSite.length) { + return null; + } + return useSite; + } + + /** + * Number of type parameters the class declares, or {@code -1} when this + * writer does not know. Unresolved names are not loaded here. A primary + * node with no module is not a source class, so generics on it are not + * a declaration. + */ + private static int declaredTypeParameters(final ClassNode printType) { + if (printType.isGenericsPlaceHolder()) return -1; + ClassNode declared = printType.redirect(); + if (declared.isArray()) return -1; + if (declared.isPrimaryClassNode()) { + if (declared.getModule() == null) return 0; + GenericsType[] formals = declared.getGenericsTypes(); + return formals == null ? 0 : formals.length; + } + if (!declared.isResolved()) return -1; + if (declared != printType) { + GenericsType[] formals = declared.getGenericsTypes(); + if (formals != null) return formals.length; + } + return declared.getTypeClass().getTypeParameters().length; } /** diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java index 3d25e07f810..00d84123dd4 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesClosureWriter.java @@ -322,7 +322,19 @@ protected ClassNode createClosureClass(final ClosureExpression expression, final if (SystemUtil.getBooleanSafe(CompilerConfiguration.CLOSURE_SAM_CONVERSION)) { SamAdapterFactory.prepare(controller, closureClass, doCallMethod, expression); } - closureClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, Boolean.TRUE); + // A closure marked DYNAMIC_RESOLUTION is emitted with the dynamic writer. + // The enclosing method stays static. Nested lambdas then use closure + // capture, which a static lambda does not do for a variable of an + // enclosing closure. The marker is Boolean.TRUE only for that switch; + // a type-checking extension's per-expression makeDynamic stores a type. + boolean dynamic = Boolean.TRUE.equals(expression.getNodeMetaData(DYNAMIC_RESOLUTION)); + Boolean mode = dynamic ? Boolean.FALSE : Boolean.TRUE; + closureClass.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, mode); + for (MethodNode method : closureClass.getMethods()) { + if (method.getDeclaringClass() == closureClass) { + method.putNodeMetaData(StaticCompilationMetadataKeys.STATIC_COMPILE_NODE, mode); + } + } return closureClass; } diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java index e0e2d1b5128..01f9c07ae43 100644 --- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java +++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesMethodReferenceExpressionWriter.java @@ -110,6 +110,12 @@ public StaticTypesMethodReferenceExpressionWriter(final WriterController control /** {@inheritDoc} */ @Override public void writeMethodReferenceExpression(final MethodReferenceExpression methodReferenceExpression) { + // Marked pointers are Groovy method pointers. The metafactory would + // insert a cast the dynamic pointer does not. + if (methodReferenceExpression.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION) != null) { + super.writeMethodReferenceExpression(methodReferenceExpression); + return; + } FunctionalInterfaceContext functionalInterface = resolveFunctionalInterfaceContext(methodReferenceExpression); if (functionalInterface == null) { // generate the default bytecode -- most likely a method closure diff --git a/src/main/java/org/codehaus/groovy/control/ErrorCollector.java b/src/main/java/org/codehaus/groovy/control/ErrorCollector.java index af4760dbb5a..3c8a145ad52 100644 --- a/src/main/java/org/codehaus/groovy/control/ErrorCollector.java +++ b/src/main/java/org/codehaus/groovy/control/ErrorCollector.java @@ -268,10 +268,11 @@ public List getErrors() { } /** - * Returns true if there are any errors pending. + * Returns true if there are any errors pending. An empty list is not + * pending errors: a listener may remove the messages it has handled. */ public boolean hasErrors() { - return (errors != null); + return errors != null && !errors.isEmpty(); } /** diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java index 0b7784aa78f..617eb5bcd73 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java @@ -1809,7 +1809,9 @@ protected static ClassNode fullyResolveType(final ClassNode type, final Map connections, final String placeholderName, final GenericsType gt) { //connections.merge(new GenericsTypeName(placeholderName), gt, (gt1, gt2) -> getCombinedGenericsType(gt1, gt2)); - connections.put(new GenericsTypeName(placeholderName), gt); + connections.put(new GenericsTypeName(placeholderName), GenericsUtils.asReferenceTypeArgument(gt)); } /** @@ -3089,7 +3091,7 @@ private static ClassNode applyGenericsContext(final BoundExpansionContext ctx, f } if (!type.isGenericsPlaceHolder()) { // convert Type to Type<...> ClassNode cn = type.getPlainNodeReference(); - cn.setGenericsTypes(gt); + cn.setGenericsTypes(GenericsUtils.legalTypeArguments(type, gt)); return cn; } diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java index d6173a2eea4..108ede09ed9 100644 --- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java +++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java @@ -4813,6 +4813,12 @@ public void visitClosureExpression(final ClosureExpression expression) { @Override public void visitMethodPointerExpression(final MethodPointerExpression expression) { super.visitMethodPointerExpression(expression); + // A query marks a method pointer so it stays a Groovy pointer. The + // pointer coerces its arguments. A SAM bridge would cast them. + if (expression.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION) != null) { + storeType(expression, CLOSURE_TYPE); + return; + } Expression nameExpr = expression.getMethodName(); if (nameExpr instanceof ConstantExpression && isStringType(getType(nameExpr))) { diff --git a/src/test/groovy/org/codehaus/groovy/ast/tools/GenericsUtilsTest.groovy b/src/test/groovy/org/codehaus/groovy/ast/tools/GenericsUtilsTest.groovy index 21a205cf417..ecab943240b 100644 --- a/src/test/groovy/org/codehaus/groovy/ast/tools/GenericsUtilsTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/ast/tools/GenericsUtilsTest.groovy @@ -861,6 +861,64 @@ final class GenericsUtilsTest { return GenericsUtils.correctToGenericsSpecRecurse([T: carrier], listOfT) } + @Test + void legalTypeArgumentsMatchTheDeclarationAndWrapPrimitives() { + assert GenericsUtils.legalTypeArguments(ClassHelper.STRING_TYPE, null) == null + assert GenericsUtils.legalTypeArguments(null, null) == null + + GenericsType[] oneString = [ClassHelper.STRING_TYPE.asGenericsType()] as GenericsType[] + assert GenericsUtils.legalTypeArguments(ClassHelper.STRING_TYPE, oneString) == null + assert GenericsUtils.legalTypeArguments(ClassHelper.STRING_TYPE.getPlainNodeReference(), oneString) == null + assert GenericsUtils.legalTypeArguments(ClassHelper.STRING_TYPE.makeArray(), oneString).is(oneString) + + ClassNode placeholder = placeholder('T') + assert GenericsUtils.legalTypeArguments(placeholder, oneString).is(oneString) + GenericsType placeholderArgument = placeholder.asGenericsType() + assert GenericsUtils.asReferenceTypeArgument(placeholderArgument).is(placeholderArgument) + assert GenericsUtils.asReferenceTypeArgument(null) == null + + GenericsType[] primitive = [ClassHelper.int_TYPE.asGenericsType()] as GenericsType[] + GenericsType[] wrapped = GenericsUtils.legalTypeArguments(ClassHelper.LIST_TYPE, primitive) + assert wrapped.length == 1 + assert wrapped[0].type == ClassHelper.Integer_TYPE + assert GenericsUtils.legalTypeArguments(ClassHelper.LIST_TYPE, GenericsType.EMPTY_ARRAY).is(GenericsType.EMPTY_ARRAY) + + GenericsType wildcard = wildcardType(ClassHelper.long_TYPE, ClassHelper.int_TYPE) + GenericsType corrected = GenericsUtils.asReferenceTypeArgument(wildcard) + assert corrected.wildcard + assert corrected.upperBounds[0] == ClassHelper.Long_TYPE + assert corrected.lowerBound == ClassHelper.Integer_TYPE + + ClassNode nested = ClassHelper.LIST_TYPE.getPlainNodeReference() + nested.genericsTypes = primitive + GenericsType nestedArgument = GenericsUtils.asReferenceTypeArgument(nested.asGenericsType()) + assert nestedArgument.type.genericsTypes[0].type == ClassHelper.Integer_TYPE + + GenericsType voidArgument = ClassHelper.VOID_TYPE.asGenericsType() + assert GenericsUtils.asReferenceTypeArgument(voidArgument).is(voidArgument) + + ClassNode raw = findClassNode('RawHolder', compile('class RawHolder {}')) + assert GenericsUtils.legalTypeArguments(raw, oneString) == null + ClassNode box = findClassNode('Box', compile('class Box {}')) + assert GenericsUtils.legalTypeArguments(box, primitive)[0].type == ClassHelper.Integer_TYPE + + ClassNode synthetic = new ClassNode('SyntheticCarrier', 0, ClassHelper.OBJECT_TYPE) + assert synthetic.module == null + assert GenericsUtils.legalTypeArguments(synthetic, oneString).is(oneString) + + ClassNode ghost = ClassHelper.makeWithoutCaching('ghost.Unresolved') + ghost.genericsTypes = null + ClassNode use = ghost.getPlainNodeReference() + GenericsType[] onUse = GenericsUtils.legalTypeArguments(use, oneString) + // An unresolved name is not a declaration of zero parameters, so the + // arguments stay. A resolved class with none drops them. + if (ghost.redirect().resolved) { + assert onUse == null + } else { + assert onUse != null + } + } + private static ClassNode placeholder(String name) { ClassNode placeholder = ClassHelper.makeWithoutCaching(name) placeholder.genericsPlaceHolder = true diff --git a/src/test/groovy/org/codehaus/groovy/ast/tools/WideningCategoriesTest.groovy b/src/test/groovy/org/codehaus/groovy/ast/tools/WideningCategoriesTest.groovy index f33918644f1..b401d8923f4 100644 --- a/src/test/groovy/org/codehaus/groovy/ast/tools/WideningCategoriesTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/ast/tools/WideningCategoriesTest.groovy @@ -21,7 +21,11 @@ package org.codehaus.groovy.ast.tools import org.junit.jupiter.api.Test import org.codehaus.groovy.ast.ClassNode +import org.codehaus.groovy.ast.GenericsType import org.codehaus.groovy.ast.GenericsTestCase +import org.codehaus.groovy.classgen.asm.BytecodeHelper + +import java.util.IdentityHashMap import static org.codehaus.groovy.ast.ClassHelper.* import static org.codehaus.groovy.ast.tools.WideningCategories.* @@ -412,6 +416,75 @@ final class WideningCategoriesTest extends GenericsTestCase { assert type.upperBounds[0] instanceof LowestUpperBoundClassNode assert type.upperBounds[0].interfaces.contains(COMPARABLE_TYPE) assert type.upperBounds[0].interfaces.contains(SERIALIZABLE_TYPE) + assertNoZeroArityParameterization(superType) + } + + @Test + void testLubOfStringAndIntegerIsNotAParameterizedSerializable() { + ClassNode lub = lowestUpperBound(STRING_TYPE, Integer_TYPE) + assertNoZeroArityParameterization(lub) + String signature = BytecodeHelper.getGenericsBounds(lub) + assert signature == null || !signature.contains('Serializable<') + } + + private static void assertNoZeroArityParameterization(ClassNode type) { + assertNoZeroArityParameterization(type, new IdentityHashMap()) + } + + private static void assertNoZeroArityParameterization(ClassNode type, IdentityHashMap seen) { + if (type == null || seen.put(type, Boolean.TRUE) != null) return + GenericsType[] arguments = type.genericsTypes + if (arguments != null && arguments.length > 0 && declaresNoTypeParameters(type)) { + assert false : "parameterized ${type.name} with ${arguments.length} type argument(s)" + } + if (arguments != null) { + for (GenericsType argument : arguments) { + assertNoZeroArityParameterization(argument.type, seen) + if (argument.upperBounds != null) { + for (ClassNode bound : argument.upperBounds) { + assertNoZeroArityParameterization(bound, seen) + } + } + assertNoZeroArityParameterization(argument.lowerBound, seen) + } + } + if (type instanceof LowestUpperBoundClassNode) { + assertNoZeroArityParameterization(type.unresolvedSuperClass, seen) + for (ClassNode face : type.interfaces) { + assertNoZeroArityParameterization(face, seen) + } + } + } + + private static boolean declaresNoTypeParameters(ClassNode type) { + ClassNode declared = type.redirect() + if (declared instanceof LowestUpperBoundClassNode) { + ClassNode named = make(type.name) + if (!named.redirect().resolved || named.redirect().array) return false + return named.redirect().typeClass.typeParameters.length == 0 + } + if (!declared.resolved || declared.array) return false + return declared.typeClass.typeParameters.length == 0 + } + + @Test + void testLubOfDifferentlyParameterizedListsStaysAList() { + ClassNode strings = GenericsUtils.makeClassSafeWithGenerics(List, STRING_TYPE) + ClassNode ints = GenericsUtils.makeClassSafeWithGenerics(List, Integer_TYPE) + ClassNode lub = lowestUpperBound(strings, ints) + assert lub.redirect() == LIST_TYPE.redirect() || lub.name.contains('List') || lub.name.contains('Collection') + assertNoZeroArityParameterization(lub) + ClassNode other = lowestUpperBound(ints, strings) + assert other.redirect().name == lub.redirect().name + assertNoZeroArityParameterization(other) + } + + @Test + void testLubOfStringAndStringBuilderDoesNotParameterizeSerializable() { + ClassNode lub = lowestUpperBound(STRING_TYPE, make(StringBuilder)) + assertNoZeroArityParameterization(lub) + String signature = BytecodeHelper.getGenericsBounds(lub) + assert signature == null || !signature.contains('Serializable<') } @Test diff --git a/src/test/groovy/org/codehaus/groovy/classgen/asm/ClosureReturnTypeSignatureTest.groovy b/src/test/groovy/org/codehaus/groovy/classgen/asm/ClosureReturnTypeSignatureTest.groovy index 0db46d7b97a..341335924b1 100644 --- a/src/test/groovy/org/codehaus/groovy/classgen/asm/ClosureReturnTypeSignatureTest.groovy +++ b/src/test/groovy/org/codehaus/groovy/classgen/asm/ClosureReturnTypeSignatureTest.groovy @@ -18,14 +18,22 @@ */ package org.codehaus.groovy.classgen.asm +import org.codehaus.groovy.ast.ClassCodeVisitorSupport +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.expr.MethodCallExpression import org.codehaus.groovy.control.CompilationUnit import org.codehaus.groovy.control.CompilerConfiguration +import org.codehaus.groovy.control.MultipleCompilationErrorsException +import org.codehaus.groovy.control.SourceUnit +import org.codehaus.groovy.transform.stc.StaticTypesMarker import org.junit.jupiter.api.Test import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassVisitor import org.objectweb.asm.MethodVisitor import org.objectweb.asm.Opcodes +import static org.junit.jupiter.api.Assertions.assertThrows + final class ClosureReturnTypeSignatureTest { private static final String PACKED = ClosureWriter.PACKED_METHOD_PREFIX @@ -54,6 +62,17 @@ final class ClosureReturnTypeSignatureTest { }, ClassReader.SKIP_CODE) } + private static String classSignature(byte[] bytes) { + String[] found = new String[1] + new ClassReader(bytes).accept(new ClassVisitor(Opcodes.ASM9) { + @Override + void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + found[0] = signature + } + }, ClassReader.SKIP_CODE) + found[0] + } + private static List doCallSignatures(byte[] bytes) { List signatures = [] eachMethod(bytes) { name, signature -> if (name == 'doCall') signatures << signature } @@ -139,4 +158,103 @@ final class ClosureReturnTypeSignatureTest { ] } } + + // JLS 4.5: Serializable declares no type parameters, so a generic class that + // implements it does not construct Serializable. + @Test + void serializableStaysRawOnAGenericClass() { + File dir = File.createTempDir() + try { + def holder = new File(dir, 'Holder.groovy') + holder.write ''' + class Holder implements java.io.Serializable { + T value + } + ''' + def unit = compile(dir, [holder]) + String signature = classSignature(bytes(unit, 'Holder')) + assert signature != null + assert signature.contains('Ljava/io/Serializable;') + assert !signature.contains('Serializable<') + def face = unit.ast.classes.find { it.name == 'Holder' }.interfaces.find { it.name == 'java.io.Serializable' } + assert face != null + assert face.genericsTypes == null || face.genericsTypes.length == 0 + } finally { + dir.deleteDir() + } + } + + // JLS 4.5: a use site may not parameterize a class that declares no type + // parameters. GenericsVisitor rejects the arguments. + @Test + void nonGenericUseSiteIsRejected() { + File dir = File.createTempDir() + try { + def holder = new File(dir, 'Holder.groovy') + holder.write ''' + class Holder { + java.io.Serializable box + Raw raw + } + class Raw {} + ''' + def ex = assertThrows(MultipleCompilationErrorsException) { + compile(dir, [holder]) + } + assert ex.message.contains('Serializable') + assert ex.message.contains('Raw') + assert ex.message.contains('(supplied with 1 type parameter)') + assert ex.message.contains('which takes no parameters') + } finally { + dir.deleteDir() + } + } + + // JLS 4.5 / javac: of(1, 2) infers T as Integer. The call type is + // List. An int[] is not a T[] (javac rejects that call). + @Test + void primitiveArgumentIsBoxedInTheInferredType() { + File dir = File.createTempDir() + try { + def source = new File(dir, 'Boxes.groovy') + source.write ''' + @groovy.transform.CompileStatic + class Boxes { + static java.util.List of(T a, T b) { null } + static java.util.List ext(T value) { null } + static Object list() { of(1, 2) } + static Object bound() { ext(1) } + } + ''' + def unit = compile(dir, [source]) + def calls = [:] + unit.ast.classes.find { it.name == 'Boxes' }.methods.findAll { it.name in ['list', 'bound'] }.each { method -> + method.code.visit(new ClassCodeVisitorSupport() { + @Override + void visitMethodCallExpression(MethodCallExpression expression) { + if (expression.methodAsString in ['of', 'ext']) calls[expression.methodAsString] = expression + super.visitMethodCallExpression(expression) + } + @Override + protected SourceUnit getSourceUnit() { null } + }) + } + def ofType = calls.of.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE) + assert ofType.name == 'java.util.List' + assert ofType.genericsTypes[0].type.name == 'java.lang.Integer' + assert !ClassHelper.isPrimitiveType(ofType.genericsTypes[0].type) + def extType = calls.ext.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE) + def bound = extType.genericsTypes[0] + assert bound.wildcard + def upper = bound.upperBounds ? bound.upperBounds[0] : bound.type + assert upper.name == 'java.lang.Integer' + assert !ClassHelper.isPrimitiveType(upper) + eachMethod(bytes(unit, 'Boxes')) { name, methodSignature -> + assert !methodSignature.contains(' + * 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..bfe46f68cf1 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlWalker.groovy @@ -0,0 +1,638 @@ +/* + * 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}. + *

+ * Registered window functions are pushed down. Translation uses + * {@link SqlFunctionRegistry#standard()} unless a caller in this package + * passes another registry. A window name the built-in registry does not + * list is rejected, and mixed mode evaluates that clause in memory. + * + * @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() + private SqlFunctionRegistry functions = SqlFunctionRegistry.standard() + + 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 + } + } + + /** + * Replaces the function registry used to translate this query. + * The default is the sealed built-in set, including its window functions. + * + * @param functions the registry, usually {@link SqlFunctionRegistry#standard()} + * or a {@link SqlFunctionRegistry#copy()} with extra mappings + */ + @PackageScope + void setFunctions(SqlFunctionRegistry functions) { + if (functions == null) { + throw new IllegalArgumentException('functions is required') + } + this.functions = functions + } + + /** + * Translates {@code expression} to SQL IR without rendering or executing it. + * Production {@link #visit} does both. Tests use this to inspect a + * {@code SqlWindowCall} produced from a GINQ {@code over} clause. + */ + @PackageScope + SqlQueryNode translate(AbstractGinqExpression expression) { + return translator().translate(expression) + } + + private GinqToSqlTranslator translator() { + return new GinqToSqlTranslator(sourceUnit, providerName, functions, 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..59dc8c01474 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/GinqToSqlTranslator.groovy @@ -0,0 +1,2084 @@ +/* + * 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.ir.SqlWindow +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowBound +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame +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.CodeVisitorSupport +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 java.math.BigDecimal +import java.math.BigInteger + +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. + *

+ * {@code fn(...) over(...)} is a window call. It is translated when + * {@code fn} is registered as {@link SqlFunctionMapping.Kind#WINDOW}. + * {@link SqlFunctionRegistry#standard()} registers the portable GINQ window + * functions. A name that is not registered ({@code median}, {@code stdev}, + * {@code stdevp}, {@code var}, {@code varp}, {@code agg}) is rejected with + * the stable "window functions are deferred" message, and mixed mode keeps + * running 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 SqlFunctionRegistry functions + private final List tableAliases = [] + private String groupAlias + private final Map groupKeysByName = [:] + private String aggregateLambdaParam + private boolean recoverUntranslatable + private final SqlCapabilities capabilities + /** Window calls are legal in {@code select} and query {@code orderby}. */ + private boolean windowAllowed + /** A window function inside another window function has no SQL form. */ + private int windowDepth + /** A window function inside an aggregate has no SQL form. */ + private int aggregateDepth + private final SqlFunctionSite calls = new CallSite() + + GinqToSqlTranslator(SourceUnit sourceUnit, String providerName = 'native-sql') { + this(sourceUnit, providerName, SqlFunctionRegistry.standard(), null) + } + + /** + * @param functions scalar and window mappings. {@link SqlFunctionRegistry#standard()} + * is the sealed built-in set. A {@link SqlFunctionRegistry#copy()} can + * register another {@link SqlFunctionMapping.Kind#WINDOW} name without + * changing that set. + */ + @PackageScope + GinqToSqlTranslator(SourceUnit sourceUnit, String providerName, SqlFunctionRegistry functions) { + this(sourceUnit, providerName, functions, null) + } + + GinqToSqlTranslator(SourceUnit sourceUnit, String providerName, SqlCapabilities capabilities) { + this(sourceUnit, providerName, SqlFunctionRegistry.standard(), capabilities) + } + + @PackageScope + GinqToSqlTranslator(SourceUnit sourceUnit, String providerName, SqlFunctionRegistry functions, SqlCapabilities capabilities) { + this.sourceUnit = sourceUnit + this.outerScope = null + this.providerName = providerName + this.functions = requireFunctions(functions) + 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.functions = outerScope.functions + this.recoverUntranslatable = outerScope.recoverUntranslatable + this.capabilities = outerScope.capabilities + } + + private static SqlFunctionRegistry requireFunctions(SqlFunctionRegistry functions) { + if (functions == null) { + throw new IllegalArgumentException('functions is required') + } + return functions + } + + private GinqToSqlTranslator nest(boolean correlated) { + GinqToSqlTranslator child = correlated + ? new GinqToSqlTranslator(sourceUnit, this) + : new GinqToSqlTranslator(sourceUnit, providerName, functions, 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) + } + if (a instanceof SqlLiteral) { + return Objects.equals(((SqlLiteral) a).value, ((SqlLiteral) b).value) + } + if (a instanceof SqlCaseWhen) { + SqlCaseWhen other = (SqlCaseWhen) b + return sameExpr(a.condition, other.condition) && sameExpr(a.thenExpr, other.thenExpr) + && sameExpr(a.elseExpr, other.elseExpr) + } + if (a instanceof SqlWindowCall) { + SqlWindowCall other = (SqlWindowCall) b + return sameExpr(a.function, other.function) && sameWindow(a.window, other.window) + } + return false // parameters and parameter-bearing expressions are never comparable + } + + private static boolean sameWindow(SqlWindow a, SqlWindow b) { + if (a.partitionBy.size() != b.partitionBy.size() || a.orderBy.size() != b.orderBy.size()) return false + for (int i = 0; i < a.partitionBy.size(); i++) { + if (!sameExpr(a.partitionBy.get(i), b.partitionBy.get(i))) return false + } + for (int i = 0; i < a.orderBy.size(); i++) { + SqlOrderSpec left = a.orderBy.get(i) + SqlOrderSpec right = b.orderBy.get(i) + if (left.asc != right.asc || left.nullsLast != right.nullsLast || !sameExpr(left.expr, right.expr)) return false + } + if (a.frame == null || b.frame == null) return a.frame == null && b.frame == null + return a.frame.unit == b.frame.unit && sameBound(a.frame.lower, b.frame.lower) && sameBound(a.frame.upper, b.frame.upper) + } + + private static boolean sameBound(SqlWindowBound a, SqlWindowBound b) { + if (a.kind != b.kind) return false + if (a.offset == null || b.offset == null) return a.offset == null && b.offset == null + return sameExpr(a.offset, b.offset) + } + + 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) { + boolean previousWindow = windowAllowed + windowAllowed = true + try { + for (SqlOrderSpec orderSpec : translateOrderList(ordersExpr)) { + query.orderBy << orderSpec + } + } finally { + windowAllowed = previousWindow + } + } + + // Shared by query ORDER BY and window ORDER BY so asc/desc/nulls stay one path. + private List translateOrderList(Expression ordersExpr) { + List specs = [] + 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 + } + } + specs << new SqlOrderSpec(translateExpr(target), asc, nullsLast) + } + return specs + } + + 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 + + boolean previousWindow = windowAllowed + windowAllowed = true + try { + 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) + } + } + } finally { + windowAllowed = previousWindow + } + } + + // 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 (isWindowOver(call)) { + return translateWindow(call) + } + 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 : functions.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 + } + + // Same shape the collection provider treats as a window: fn(...).over() or fn(...).over(spec). + // Checked before aggregates so sum(x) over(...) is not a grouped SUM. + private static boolean isWindowOver(MethodCallExpression call) { + if ('over' != call.methodAsString) return false + if (!(call.objectExpression instanceof MethodCallExpression)) return false + if (!(call.arguments instanceof TupleExpression)) return false + return ((TupleExpression) call.arguments).expressions.size() < 2 + } + + private SqlExpr translateWindow(MethodCallExpression overCall) { + if (!windowAllowed) { + reject('`over` is only supported in `select` and `orderby`', overCall, false) + return null + } + if (windowDepth > 0) { + reject('window functions cannot be nested', overCall, false) + return null + } + if (aggregateDepth > 0) { + reject('window functions cannot be nested inside an aggregate', overCall, false) + return null + } + windowDepth++ + try { + return translateWindowCall(overCall) + } finally { + windowDepth-- + } + } + + private SqlExpr translateWindowCall(MethodCallExpression overCall) { + MethodCallExpression functionCall = (MethodCallExpression) overCall.objectExpression + String name = functionCall.methodAsString + SqlFunctionMapping mapping = name == null ? null : functions.find(name, SqlFunctionMapping.Kind.WINDOW) + if (mapping == null) { + reject("${WINDOW_DEFERRED_PREFIX}${providerName} provider", overCall) + return null + } + if (!functionCall.implicitThis) { + reject("`${name}(...) over(...)` is written as a function, not a method on a value", functionCall) + return null + } + if (!(functionCall.arguments instanceof TupleExpression)) { + reject("`${name}` cannot be translated to SQL by the ${providerName} provider", functionCall) + return null + } + List functionArgs = ((TupleExpression) functionCall.arguments).expressions + String arity = mapping.arityError(functionArgs.size()) + if (arity != null) { + reject(arity, functionCall) + return null + } + SqlWindow window = translateWindowSpec(overCall) + if (window == null) return null + if (window.frame != null && mapping.rejectsWindowFrame()) { + String unit = window.frame.unit.name().toLowerCase(Locale.ROOT) + String why = mapping.appliesWindowFrame() + ? 'GINQ applies that frame, and SQL defines the function without one' + : 'SQL defines that function without a frame' + reject("`${name}() over(...)` does not accept `${unit}`. " + why, overCall) + return null + } + if (mapping.requiresWindowOrder() && !window.orderBy) { + reject("`${name}() over(...)` needs `orderby`. Without it GINQ returns null", overCall) + return null + } + SqlWindow effective = window + if (mapping.wholePartitionByDefault() && window.frame == null && window.orderBy) { + effective = new SqlWindow(window.partitionBy, window.orderBy, wholePartitionFrame()) + } + SqlFunctionMapping.WindowForm form = mapping.windowForm() + if (form == SqlFunctionMapping.WindowForm.NTILE) { + return translateNtile(functionCall, functionArgs, effective) + } + if (form == SqlFunctionMapping.WindowForm.AGGREGATE) { + return translateAggregateWindow(functionCall, functionArgs, effective) + } + if ((('lead' == name || 'lag' == name) && functionArgs.size() >= 2 && !acceptWholeOffset(name, functionCall, functionArgs.get(1))) + || (form == SqlFunctionMapping.WindowForm.NTH && !acceptNthIndex(functionCall, functionArgs.get(1)))) { + return null + } + SqlExpr function = mapping.translate(functionCall, functionArgs, calls) + if (function == null) return null + if (form == SqlFunctionMapping.WindowForm.NTH) { + function = shiftNthIndex((SqlFunction) function) + if (function == null) return null + } + SqlWindowCall call = new SqlWindowCall(function, effective) + if (form == SqlFunctionMapping.WindowForm.ZERO_BASED) { + return new SqlBinary('-', call, new SqlLiteral(1)) + } + if (form == SqlFunctionMapping.WindowForm.PERCENT) { + return percentRank(call, effective) + } + return call + } + + // GINQ's default frame is the whole partition. SQL's default, once ORDER BY + // is present, stops at the current row, which would turn lastValue into the + // current row and sum into a running total. + private static SqlWindowFrame wholePartitionFrame() { + return new SqlWindowFrame(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.unboundedPreceding(), SqlWindowBound.unboundedFollowing()) + } + + // (buckets * (row_number() - 1)) div count(*) over the same partition. + // That is GINQ's 0-based bucket formula, using integer division. + // SQL NTILE is 1-based and places the remainder on the first buckets. + private SqlExpr translateNtile(MethodCallExpression call, List args, SqlWindow window) { + if (!acceptNtileBuckets(call, args.get(0))) return null + SqlExpr buckets = translateExpr(args.get(0)) + if (buckets == null) return null + SqlWindow numbering = new SqlWindow(window.partitionBy, window.orderBy, null) + SqlWindow counting = new SqlWindow(window.partitionBy, Collections.emptyList(), null) + SqlExpr rowNumber = emitFunction('ROW_NUMBER', Collections.emptyList(), call) + if (rowNumber == null) return null + SqlExpr row = new SqlBinary('-', + new SqlWindowCall(rowNumber, numbering), + new SqlLiteral(1)) + SqlExpr product = new SqlBinary('*', buckets, row) + SqlExpr count = new SqlWindowCall(new SqlCountStar(), counting) + // Integer division matches GINQ's long division and does not need FLOOR, + // which some dialects do not have. + return new SqlBinary('IDIV', product, count) + } + + private boolean acceptNtileBuckets(MethodCallExpression call, Expression buckets) { + return acceptWholeNumber(buckets, '`ntile` expects a whole number of buckets >= 0', call) + } + + // One row: GINQ returns 1. SQL PERCENT_RANK returns 0. + private static SqlExpr percentRank(SqlWindowCall rank, SqlWindow window) { + SqlWindow counting = new SqlWindow(window.partitionBy, Collections.emptyList(), null) + SqlExpr oneRow = new SqlBinary('=', new SqlWindowCall(new SqlCountStar(), counting), new SqlLiteral(1)) + return new SqlCaseWhen(oneRow, new SqlLiteral(1), rank) + } + + private SqlExpr translateAggregateWindow(MethodCallExpression call, List args, SqlWindow window) { + boolean lambda = 1 == args.size() && args.get(0) instanceof ClosureExpression + SqlExpr function = translateAggregateCall(call, args, lambda) + if (function == null) return null + SqlExpr windowed = new SqlWindowCall(function, window) + // GINQ sum treats null as zero, so an all-null frame is 0 rather than SQL null. + // The coalesce wraps the window call: COALESCE(SUM(x), 0) OVER (...) is not SQL. + if ('sum' == call.methodAsString) { + return emitFunction('COALESCE', [windowed, new SqlLiteral(0)], call) + } + return windowed + } + + // Constants are bound parameters, same as every other GINQ literal. Adding 1 + // in the parameter keeps NTH_VALUE 1-based without putting arithmetic in the SQL. + private SqlExpr shiftNthIndex(SqlFunction function) { + if (function.args.size() != 2 || function.args.get(1) == null) return null + SqlExpr index = function.args.get(1) + SqlExpr shifted + if (index instanceof SqlParam) { + shifted = new SqlParam(plusX(((SqlParam) index).valueExpr, constX(1))) + } else { + shifted = new SqlBinary('+', index, new SqlLiteral(1)) + } + return new SqlFunction(function.name, [function.args.get(0), shifted]) + } + + private boolean acceptNthIndex(MethodCallExpression call, Expression index) { + return acceptWholeNumber(index, '`nthValue` index must be a whole number >= 0. The first row is 0', call) + } + + private boolean acceptWholeOffset(String name, MethodCallExpression call, Expression offset) { + return acceptWholeNumber(offset, "`${name}` offset must be a whole number >= 0", call) + } + + // A non-literal is bound as a parameter and checked by the database. + // ntile(0) is kept: GINQ defines that bucket count as 0. + private boolean acceptWholeNumber(Expression expr, String message, MethodCallExpression call) { + Number literal = signedFrameNumber(expr) + if (literal == null) return true + BigDecimal n = frameDecimal(literal) + if (n == null || n.signum() < 0 || !wholeFrameNumber(n)) { + reject(message, call) + return false + } + return true + } + + private SqlWindow translateWindowSpec(MethodCallExpression overCall) { + List args = ((TupleExpression) overCall.arguments).expressions + if (args.isEmpty()) { + return new SqlWindow([], [], null) + } + WindowClauseFinder finder = new WindowClauseFinder() + args.get(0).visit(finder) + finder.dropNestedArguments() + if (finder.unknown) { + MethodCallExpression unknown = finder.unknown.get(0) + reject("Unknown window clause: `${unknown.methodAsString ?: unknown.text}`", unknown) + return null + } + if (finder.partitionBy.isEmpty() && finder.orderBy.isEmpty() && finder.rows.isEmpty() && finder.range.isEmpty()) { + reject('`over` expects `partitionby`, `orderby`, `rows` or `range`', overCall) + return null + } + if (finder.partitionBy.size() > 1) { + reject('`partitionby` appears more than once in `over`', finder.partitionBy.get(1)) + return null + } + if (finder.orderBy.size() > 1) { + reject('`orderby` appears more than once in `over`', finder.orderBy.get(1)) + return null + } + if (finder.rows.size() > 1) { + reject('`rows` appears more than once in `over`', finder.rows.get(1)) + return null + } + if (finder.range.size() > 1) { + reject('`range` appears more than once in `over`', finder.range.get(1)) + return null + } + if (finder.rows && finder.range) { + reject('`rows` and `range` cannot both be used in one `over`', finder.range.get(0)) + return null + } + MethodCallExpression orderCall = finder.orderBy ? finder.orderBy.get(0) : null + List orderSpecs = [] + if (orderCall != null) { + if (!(orderCall.arguments instanceof TupleExpression)) { + reject('`orderby` in `over` must list its keys', orderCall) + return null + } + orderSpecs = translateOrderList(orderCall.arguments) + for (SqlOrderSpec spec : orderSpecs) { + if (spec.expr == null) return null + } + } + MethodCallExpression frameCall = finder.rows ? finder.rows.get(0) : (finder.range ? finder.range.get(0) : null) + SqlWindowFrame frame = null + if (frameCall != null) { + boolean rows = 'rows' == frameCall.methodAsString + if (finder.range && orderSpecs.size() != 1) { + reject(orderCall == null + ? '`orderby` is expected when using `range`' + : 'Only one field is expected in the `orderby` clause when using `range`', frameCall) + return null + } + if (!(frameCall.arguments instanceof TupleExpression)) { + reject("Both lower bound and upper bound are expected for `${frameCall.methodAsString}`", frameCall) + return null + } + List bounds = ((TupleExpression) frameCall.arguments).expressions + if (bounds.size() != 2) { + reject("Both lower bound and upper bound are expected for `${frameCall.methodAsString}`", frameCall) + return null + } + SqlWindowFrame.Unit unit = rows ? SqlWindowFrame.Unit.ROWS : SqlWindowFrame.Unit.RANGE + SqlWindowBound lower = translateFrameBound(bounds.get(0), true, unit) + if (lower == null) return null + SqlWindowBound upper = translateFrameBound(bounds.get(1), false, unit) + if (upper == null) return null + if (frameEndsBeforeItStarts(lower, upper)) { + reject('the window frame ends before it starts', frameCall) + return null + } + // GINQ range offsets are added to the current value. SQL PRECEDING + // and FOLLOWING point along the sort, so a descending order mirrors + // the bounds and swaps the ends. The value interval stays the same. + if (!rows && !orderSpecs.isEmpty() && !orderSpecs.get(0).asc) { + SqlWindowBound start = mirrorValueBound(upper) + SqlWindowBound end = mirrorValueBound(lower) + lower = start + upper = end + } + frame = new SqlWindowFrame(unit, lower, upper) + } + List partition = [] + if (finder.partitionBy) { + MethodCallExpression partitionCall = finder.partitionBy.get(0) + if (!(partitionCall.arguments instanceof TupleExpression)) { + reject('`partitionby` in `over` must list its expressions', partitionCall) + return null + } + for (Expression part : ((TupleExpression) partitionCall.arguments).expressions) { + SqlExpr sql = translateExpr(part) + if (sql == null) return null + partition << sql + } + } + return new SqlWindow(partition, orderSpecs, frame) + } + + // A value-space bound written as an ascending frame, mirrored into descending order. + private static SqlWindowBound mirrorValueBound(SqlWindowBound bound) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return SqlWindowBound.unboundedFollowing() + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return SqlWindowBound.unboundedPreceding() + case SqlWindowBound.Kind.CURRENT_ROW: return SqlWindowBound.currentRow() + case SqlWindowBound.Kind.PRECEDING: return SqlWindowBound.following(bound.offset) + case SqlWindowBound.Kind.FOLLOWING: return SqlWindowBound.preceding(bound.offset) + default: throw new IllegalArgumentException("Unknown window bound: ${bound.kind}") + } + } + + // GINQ: null is unbounded, 0 is the current row, negative precedes, positive follows. + // Only literals. A variable bound would hide its sign inside a parameter, and + // PRECEDING/FOLLOWING is syntax, so mixed mode keeps that clause in memory. + private SqlWindowBound translateFrameBound(Expression expr, boolean lower, SqlWindowFrame.Unit unit) { + if (expr instanceof ConstantExpression && null == ((ConstantExpression) expr).value) { + return lower ? SqlWindowBound.unboundedPreceding() : SqlWindowBound.unboundedFollowing() + } + Number signed = signedFrameNumber(expr) + if (signed == null) { + reject('window frame bounds must be literals: a number, `0` for the current row, or `null` for an unbounded bound', expr) + return null + } + BigDecimal decimal = frameDecimal(signed) + if (decimal == null) { + reject('window frame bounds must be finite numbers', expr) + return null + } + if (SqlWindowFrame.Unit.ROWS == unit && !wholeFrameNumber(decimal)) { + reject('`rows` bounds must be whole numbers', expr) + return null + } + // RowBound uses these sentinels for the ends of the partition. A numeric + // literal of that magnitude is the same bound; `Long.MIN_VALUE` written + // as a property is not a literal and stays untranslatable. + if (SqlWindowFrame.Unit.ROWS == unit) { + if (lower && decimal.compareTo(BigDecimal.valueOf(Long.MIN_VALUE)) == 0) { + return SqlWindowBound.unboundedPreceding() + } + if (!lower && decimal.compareTo(BigDecimal.valueOf(Long.MAX_VALUE)) == 0) { + return SqlWindowBound.unboundedFollowing() + } + } + int sign = decimal.signum() + if (sign == 0) return SqlWindowBound.currentRow() + SqlLiteral magnitude = new SqlLiteral(frameMagnitude(decimal)) + return sign < 0 ? SqlWindowBound.preceding(magnitude) : SqlWindowBound.following(magnitude) + } + + private static Number signedFrameNumber(Expression expr) { + if (expr instanceof ConstantExpression && ((ConstantExpression) expr).value instanceof Number) { + return (Number) ((ConstantExpression) expr).value + } + if (expr instanceof UnaryMinusExpression) { + Expression inner = ((UnaryMinusExpression) expr).expression + if (inner instanceof ConstantExpression && ((ConstantExpression) inner).value instanceof Number) { + BigDecimal decimal = frameDecimal((Number) ((ConstantExpression) inner).value) + return decimal == null ? null : decimal.negate() + } + } + return null + } + + private static BigDecimal frameDecimal(Number number) { + if (number instanceof BigDecimal) return (BigDecimal) number + if (number instanceof BigInteger) return new BigDecimal((BigInteger) number) + if (number instanceof Integer || number instanceof Long || number instanceof Short || number instanceof Byte) { + return BigDecimal.valueOf(number.longValue()) + } + if (number instanceof Double || number instanceof Float) { + double d = number.doubleValue() + if (Double.isNaN(d) || Double.isInfinite(d)) return null + return new BigDecimal(number.toString()) + } + return null + } + + private static boolean wholeFrameNumber(BigDecimal decimal) { + return decimal.stripTrailingZeros().scale() <= 0 + } + + // Earlier bound has the smaller rank. Equal PRECEDING offsets: the larger + // offset is earlier. Equal FOLLOWING offsets: the smaller offset is earlier. + private static boolean frameEndsBeforeItStarts(SqlWindowBound lower, SqlWindowBound upper) { + int lowerRank = frameRank(lower.kind) + int upperRank = frameRank(upper.kind) + if (lowerRank != upperRank) return lowerRank > upperRank + BigDecimal lowerOffset = frameOffset(lower) + BigDecimal upperOffset = frameOffset(upper) + if (lowerOffset == null || upperOffset == null) return false + if (lower.kind == SqlWindowBound.Kind.PRECEDING) return lowerOffset.compareTo(upperOffset) < 0 + if (lower.kind == SqlWindowBound.Kind.FOLLOWING) return lowerOffset.compareTo(upperOffset) > 0 + return false + } + + private static int frameRank(SqlWindowBound.Kind kind) { + switch (kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return 0 + case SqlWindowBound.Kind.PRECEDING: return 1 + case SqlWindowBound.Kind.CURRENT_ROW: return 2 + case SqlWindowBound.Kind.FOLLOWING: return 3 + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return 4 + default: return 2 + } + } + + private static BigDecimal frameOffset(SqlWindowBound bound) { + if (!(bound.offset instanceof SqlLiteral) || !(((SqlLiteral) bound.offset).value instanceof Number)) return null + return frameDecimal((Number) ((SqlLiteral) bound.offset).value) + } + + private static Object frameMagnitude(BigDecimal decimal) { + BigDecimal magnitude = decimal.abs() + try { + return magnitude.intValueExact() + } catch (ArithmeticException ignored) { + try { + return magnitude.longValueExact() + } catch (ArithmeticException ignoredLong) { + return magnitude.stripTrailingZeros() + } + } + } + + 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) { + SqlExpr function = translateAggregateCall(call, args, lambdaStyle) + if (function == null) return null + return finishAggregate(call.methodAsString, function, call) + } + + // The function alone, without the null-as-zero coalesce. A window sum applies + // that coalesce outside OVER. + private SqlExpr translateAggregateCall(MethodCallExpression call, List args, boolean lambdaStyle) { + aggregateDepth++ + try { + return translateAggregateCallBody(call, args, lambdaStyle) + } finally { + aggregateDepth-- + } + } + + private SqlExpr translateAggregateCallBody(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 emitFunction(functionName, [translateExpr(arg)], 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 emitFunction(functionName, [translateExpr(body)], countDistinct, 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, functions, 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 String WINDOW_DEFERRED_PREFIX = + 'window functions are deferred and are not translated by the ' + + // Collects partitionby/orderby/rows/range and any other call in the over argument. + // Calls nested inside a clause's own arguments are not clauses (e.name.toUpperCase()). + @CompileStatic + private static class WindowClauseFinder extends CodeVisitorSupport { + private final List partitionBy = [] + private final List orderBy = [] + private final List rows = [] + private final List range = [] + private final List unknown = [] + + @Override + void visitMethodCallExpression(MethodCallExpression call) { + super.visitMethodCallExpression(call) + String name = call.methodAsString + if ('partitionby' == name) { + partitionBy.add(call) + } else if ('orderby' == name) { + orderBy.add(call) + } else if ('rows' == name) { + rows.add(call) + } else if ('range' == name) { + range.add(call) + } else { + unknown.add(call) + } + } + + private void dropNestedArguments() { + List arguments = [] + for (MethodCallExpression call : partitionBy) arguments.add(call.arguments) + for (MethodCallExpression call : orderBy) arguments.add(call.arguments) + for (MethodCallExpression call : rows) arguments.add(call.arguments) + for (MethodCallExpression call : range) arguments.add(call.arguments) + if (arguments.isEmpty()) return + new ListExpression(arguments).visit(new CodeVisitorSupport() { + @Override + void visitMethodCallExpression(MethodCallExpression call) { + drop(partitionBy, call) + drop(orderBy, call) + drop(rows, call) + drop(range, call) + drop(unknown, call) + super.visitMethodCallExpression(call) + } + }) + } + + private static void drop(List calls, MethodCallExpression target) { + Iterator it = calls.iterator() + while (it.hasNext()) { + if (it.next().is(target)) it.remove() + } + } + } + + 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..71d8a6e6434 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionMapping.groovy @@ -0,0 +1,518 @@ +/* + * 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}. + *

+ * A window function is a {@link #window} entry of {@link Kind#WINDOW}. + * {@link #translate} returns the function call; the translator attaches + * {@code OVER} and applies {@link WindowForm}. Grouped aggregates stay off + * this registry. The same names registered as {@link Kind#WINDOW} + * ({@code min}, {@code max}, {@code count}, {@code sum}, {@code avg}) are + * the window forms, not {@link Kind#MATH} and not the grouped path. + * + * @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, + /** + * A window function called as {@code fn(...) over(...)}. + * Distinct from the scalar kinds above and from aggregates, which + * are not registry entries: {@code Math.min} is {@link #MATH}, + * aggregate {@code min} is the translator's aggregate path, and a + * window {@code min} is this kind. + * {@link SqlFunctionRegistry#standard()} registers the GINQ window + * functions under this kind, before the registry is sealed. + */ + WINDOW + } + + /** + * How a {@link Kind#WINDOW} mapping is turned into SQL. + *

+ * {@code PLAIN} is the extension point: the call is rendered as written, + * including a frame. The built-in functions use the other forms so the + * SQL matches GINQ where the standard window function would not: + * {@code rowNumber} counts from 0, {@code ntile} uses GINQ's bucket + * formula, {@code nthValue} counts from 0, and a frame on a ranking or + * offset function is rejected because SQL defines those functions + * without one. The public {@code window} factories always use {@code PLAIN}. + */ + enum WindowForm { + /** {@code NAME(args) OVER window}, frame kept as written. */ + PLAIN, + /** {@code LEAD}/{@code LAG}. A frame is rejected. */ + OFFSET, + /** {@code (ROW_NUMBER() OVER window) - 1}. A frame is rejected. */ + ZERO_BASED, + /** GINQ's {@code floor(buckets * (row_number - 1) / count)}. A frame is rejected. */ + NTILE, + /** {@code RANK}, {@code DENSE_RANK} or {@code CUME_DIST}. Needs {@code orderby}. A frame is rejected. */ + RANK, + /** {@code PERCENT_RANK}, with a one-row partition yielding 1. Needs {@code orderby}. A frame is rejected. */ + PERCENT, + /** {@code FIRST_VALUE}/{@code LAST_VALUE}. The default frame is the whole partition. */ + VALUE, + /** {@code NTH_VALUE} with a 0-based index. The default frame is the whole partition. */ + NTH, + /** {@code COUNT}/{@code SUM}/{@code AVG}/{@code MIN}/{@code MAX}. The default frame is the whole partition. */ + AGGREGATE + } + + 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 + /** Non-null for {@link Kind#WINDOW}. */ + private final WindowForm windowForm + + private SqlFunctionMapping(String groovyName, Kind kind, Shape shape, String sqlName, + int minArgs, int maxArgs, String arityMessage, + boolean matchBefore, boolean matchAfter, WindowForm windowForm) { + 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 + this.windowForm = windowForm + } + + /** + * 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, null) + } + + @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, null) + } + + /** + * A window function with no arguments, e.g. {@code rowNumber} to {@code ROW_NUMBER}. + * The translator supplies the {@code OVER} clause; this mapping is only the call. + * + * @param groovyName the Groovy function name + * @param sqlName the ANSI function name + * @return the mapping + */ + static SqlFunctionMapping window(String groovyName, String sqlName) { + return window(groovyName, sqlName, 0, 0, null, WindowForm.PLAIN) + } + + /** + * A window function with a fixed number of arguments, e.g. {@code ntile}. + * + * @param groovyName the Groovy function name + * @param sqlName the ANSI function name + * @param arguments how many arguments the function takes, not counting {@code over} + * @return the mapping + */ + static SqlFunctionMapping window(String groovyName, String sqlName, int arguments) { + return window(groovyName, sqlName, arguments, arguments, null, WindowForm.PLAIN) + } + + /** + * A window function with an argument range, e.g. {@code lead} with 1 to 3. + * + * @param groovyName the Groovy function name + * @param sqlName the ANSI function name + * @param minArgs minimum argument count, not counting {@code over} + * @param maxArgs maximum argument count, not counting {@code over} + * @return the mapping + */ + static SqlFunctionMapping window(String groovyName, String sqlName, int minArgs, int maxArgs) { + return window(groovyName, sqlName, minArgs, maxArgs, null, WindowForm.PLAIN) + } + + @PackageScope + static SqlFunctionMapping window(String groovyName, String sqlName, int minArgs, int maxArgs, String arityMessage) { + return window(groovyName, sqlName, minArgs, maxArgs, arityMessage, WindowForm.PLAIN) + } + + /** + * A built-in window function. Public factories stay {@link WindowForm#PLAIN} + * so a caller-supplied mapping is not rewritten to GINQ's adjustments. + */ + @PackageScope + static SqlFunctionMapping window(String groovyName, String sqlName, int minArgs, int maxArgs, + String arityMessage, WindowForm windowForm) { + checkMethod(groovyName) + checkSql(sqlName) + checkRange(minArgs, maxArgs) + if (windowForm == null) { + throw new IllegalArgumentException('a window mapping needs a form') + } + return new SqlFunctionMapping(groovyName, Kind.WINDOW, Shape.SQL_FUNCTION, sqlName, + minArgs, maxArgs, arityMessage, false, false, windowForm) + } + + @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, null) + } + + @PackageScope + static SqlFunctionMapping concat() { + return new SqlFunctionMapping('concat', Kind.RECEIVER, Shape.CONCAT, null, 1, 1, null, false, false, null) + } + + @PackageScope + static SqlFunctionMapping isEmpty() { + return new SqlFunctionMapping('isEmpty', Kind.RECEIVER, Shape.IS_EMPTY, null, 0, 0, null, false, false, null) + } + + @PackageScope + static SqlFunctionMapping substring() { + return new SqlFunctionMapping('substring', Kind.RECEIVER, Shape.SUBSTRING, null, 1, 2, null, false, false, null) + } + + @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, null) + } + + @PackageScope + static SqlFunctionMapping indexOf() { + return new SqlFunctionMapping('indexOf', Kind.RECEIVER, Shape.INDEX_OF, null, 1, 1, null, false, false, null) + } + + @PackageScope + static SqlFunctionMapping cast() { + return new SqlFunctionMapping('cast', Kind.FREE, Shape.CAST, null, 2, 2, null, false, false, null) + } + + /** + * 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) + } + + /** + * @param argc how many arguments the call has, not counting {@code over} + * @return the diagnostic, or {@code null} when the count is accepted + */ + @PackageScope + String arityError(int argc) { + if (argc < minArgs || argc > maxArgs) return wrongArity() + return null + } + + /** Ranking and offset functions have no SQL frame. */ + @PackageScope + boolean rejectsWindowFrame() { + return windowForm == WindowForm.OFFSET || windowForm == WindowForm.ZERO_BASED + || windowForm == WindowForm.NTILE || windowForm == WindowForm.RANK + || windowForm == WindowForm.PERCENT + } + + /** + * {@code rank} and its relatives are computed on the frame in memory. + * The other functions that reject a frame ignore it. + */ + @PackageScope + boolean appliesWindowFrame() { + return windowForm == WindowForm.RANK || windowForm == WindowForm.PERCENT + } + + /** + * Aggregates and {@code firstValue}/{@code lastValue}/{@code nthValue} + * see the whole partition when GINQ writes no {@code rows} or {@code range}. + * SQL's default with {@code ORDER BY} stops at the current row, so the + * translator supplies the frame. + */ + @PackageScope + boolean wholePartitionByDefault() { + return windowForm == WindowForm.VALUE || windowForm == WindowForm.NTH + || windowForm == WindowForm.AGGREGATE + } + + /** {@code rank} and its relatives return null in GINQ when nothing is ordered. */ + @PackageScope + boolean requiresWindowOrder() { + return windowForm == WindowForm.RANK || windowForm == WindowForm.PERCENT + } + + @PackageScope + WindowForm windowForm() { + return windowForm + } + + 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..415a191d987 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistry.groovy @@ -0,0 +1,194 @@ +/* + * 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. Three uses of a Groovy name stay apart: + *

    + *
  • scalar — {@link SqlFunctionMapping.Kind#RECEIVER}, {@link SqlFunctionMapping.Kind#FREE} + * and {@link SqlFunctionMapping.Kind#MATH}. {@code Math.min} and {@code Math.max} + * are the entries here ({@code LEAST} and {@code GREATEST}).
  • + *
  • aggregate — not registered. Grouped {@code min}, {@code max}, + * {@code count}, {@code sum} and {@code avg}, including {@code count(distinct)}, + * stay on the translator's aggregate path.
  • + *
  • window — {@link SqlFunctionMapping.Kind#WINDOW}, registered with + * {@link SqlFunctionMapping#window} before {@link #standard()} is sealed. + * The built-in set is the GINQ window surface that has a portable SQL + * equivalent: {@code rowNumber}, {@code rank}, {@code denseRank}, + * {@code percentRank}, {@code cumeDist}, {@code ntile}, {@code lead}, + * {@code lag}, {@code firstValue}, {@code lastValue}, {@code nthValue}, + * and the aggregate-as-window forms {@code count}, {@code sum}, {@code avg}, + * {@code min} and {@code max}. {@code median}, {@code stdev}, {@code stdevp}, + * {@code var}, {@code varp} and {@code agg} are not registered. A {@link #copy()} + * can register another name; that does not change {@link #standard()}.
  • + *
+ *

+ * 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()) + // Window functions. Kind.WINDOW, registered before seal, and not the + // grouped aggregate path or Math.min/Math.max. + registry.register(SqlFunctionMapping.window('rowNumber', 'ROW_NUMBER', 0, 0, + '`rowNumber()` takes no arguments', SqlFunctionMapping.WindowForm.ZERO_BASED)) + registry.register(SqlFunctionMapping.window('rank', 'RANK', 0, 0, + '`rank()` takes no arguments', SqlFunctionMapping.WindowForm.RANK)) + registry.register(SqlFunctionMapping.window('denseRank', 'DENSE_RANK', 0, 0, + '`denseRank()` takes no arguments', SqlFunctionMapping.WindowForm.RANK)) + registry.register(SqlFunctionMapping.window('percentRank', 'PERCENT_RANK', 0, 0, + '`percentRank()` takes no arguments', SqlFunctionMapping.WindowForm.PERCENT)) + registry.register(SqlFunctionMapping.window('cumeDist', 'CUME_DIST', 0, 0, + '`cumeDist()` takes no arguments', SqlFunctionMapping.WindowForm.RANK)) + registry.register(SqlFunctionMapping.window('ntile', 'NTILE', 1, 1, + '`ntile` expects one argument, the number of buckets', SqlFunctionMapping.WindowForm.NTILE)) + registry.register(SqlFunctionMapping.window('lead', 'LEAD', 1, 3, + '`lead` expects the value, and optionally an offset and a default', SqlFunctionMapping.WindowForm.OFFSET)) + registry.register(SqlFunctionMapping.window('lag', 'LAG', 1, 3, + '`lag` expects the value, and optionally an offset and a default', SqlFunctionMapping.WindowForm.OFFSET)) + registry.register(SqlFunctionMapping.window('firstValue', 'FIRST_VALUE', 1, 1, + '`firstValue` expects the value', SqlFunctionMapping.WindowForm.VALUE)) + registry.register(SqlFunctionMapping.window('lastValue', 'LAST_VALUE', 1, 1, + '`lastValue` expects the value', SqlFunctionMapping.WindowForm.VALUE)) + registry.register(SqlFunctionMapping.window('nthValue', 'NTH_VALUE', 2, 2, + '`nthValue` expects the value and a 0-based index', SqlFunctionMapping.WindowForm.NTH)) + registry.register(SqlFunctionMapping.window('count', 'COUNT', 0, 1, + '`count` expects no arguments, or one argument', SqlFunctionMapping.WindowForm.AGGREGATE)) + registry.register(SqlFunctionMapping.window('sum', 'SUM', 1, 1, + '`sum` expects one argument', SqlFunctionMapping.WindowForm.AGGREGATE)) + registry.register(SqlFunctionMapping.window('avg', 'AVG', 1, 1, + '`avg` expects one argument', SqlFunctionMapping.WindowForm.AGGREGATE)) + registry.register(SqlFunctionMapping.window('min', 'MIN', 1, 1, + '`min` expects one argument', SqlFunctionMapping.WindowForm.AGGREGATE)) + registry.register(SqlFunctionMapping.window('max', 'MAX', 1, 1, + '`max` expects one argument', SqlFunctionMapping.WindowForm.AGGREGATE)) + 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..29d1686b3c4 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlFunction.groovy @@ -0,0 +1,51 @@ +/* + * 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 ...)}. + *

+ * {@code OVER} is not stored here. A window call is a {@link SqlWindowCall} + * whose function is one of these nodes (or a {@link SqlCountStar}). + * + * @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/SqlWindow.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindow.groovy new file mode 100644 index 00000000000..60fe659d177 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindow.groovy @@ -0,0 +1,44 @@ +/* + * 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 + +/** + * The parenthesized body of {@code OVER}: partition, order, then an + * optional frame. Absent lists are empty. Renderers emit the clauses in + * that SQL order regardless of the order they were written in GINQ. + * An empty specification renders {@code OVER ()}. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlWindow { + final List partitionBy + final List orderBy + final SqlWindowFrame frame + + SqlWindow(List partitionBy, List orderBy, SqlWindowFrame frame) { + this.partitionBy = partitionBy == null ? Collections.emptyList() : List.copyOf(partitionBy) + this.orderBy = orderBy == null ? Collections.emptyList() : List.copyOf(orderBy) + this.frame = frame + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowBound.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowBound.groovy new file mode 100644 index 00000000000..ca807477568 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowBound.groovy @@ -0,0 +1,105 @@ +/* + * 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.math.BigDecimal +import java.math.BigInteger + +/** + * One end of a window frame. GINQ writes a signed bound or {@code null}; + * the translator maps that onto these kinds before rendering: + * {@code null} is unbounded, {@code 0} is the current row, a negative + * number is {@code PRECEDING} of its magnitude, and a positive number is + * {@code FOLLOWING}. + *

+ * A {@link Kind#PRECEDING} or {@link Kind#FOLLOWING} offset is a + * non-negative SQL expression, never a signed GINQ bound. The native + * renderer prints that expression. The jOOQ renderer accepts an integer + * literal and rejects anything else, so a follow-up that binds the offset + * must extend that renderer or keep the offset a literal. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlWindowBound { + enum Kind { + UNBOUNDED_PRECEDING, + PRECEDING, + CURRENT_ROW, + FOLLOWING, + UNBOUNDED_FOLLOWING + } + + final Kind kind + /** Non-null for {@link Kind#PRECEDING} and {@link Kind#FOLLOWING}. */ + final SqlExpr offset + + private SqlWindowBound(Kind kind, SqlExpr offset) { + this.kind = kind + this.offset = offset + } + + static SqlWindowBound unboundedPreceding() { + return new SqlWindowBound(Kind.UNBOUNDED_PRECEDING, null) + } + + static SqlWindowBound unboundedFollowing() { + return new SqlWindowBound(Kind.UNBOUNDED_FOLLOWING, null) + } + + static SqlWindowBound currentRow() { + return new SqlWindowBound(Kind.CURRENT_ROW, null) + } + + static SqlWindowBound preceding(SqlExpr offset) { + return bounded(Kind.PRECEDING, offset) + } + + static SqlWindowBound following(SqlExpr offset) { + return bounded(Kind.FOLLOWING, offset) + } + + private static SqlWindowBound bounded(Kind kind, SqlExpr offset) { + if (offset == null) { + throw new IllegalArgumentException('a bounded window frame offset is required') + } + if (offset instanceof SqlLiteral) { + Object value = ((SqlLiteral) offset).value + if (!(value instanceof Number) || !nonNegative((Number) value)) { + throw new IllegalArgumentException( + 'a window frame offset must be a non-negative number; the direction is PRECEDING or FOLLOWING') + } + } + return new SqlWindowBound(kind, offset) + } + + private static boolean nonNegative(Number number) { + if (number instanceof BigDecimal) return ((BigDecimal) number).signum() >= 0 + if (number instanceof BigInteger) return ((BigInteger) number).signum() >= 0 + if (number instanceof Double || number instanceof Float) { + double d = number.doubleValue() + return !Double.isNaN(d) && !Double.isInfinite(d) && d >= 0d + } + return number.longValue() >= 0L + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowCall.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowCall.groovy new file mode 100644 index 00000000000..6be117dbfe8 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowCall.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.ir + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.sql.SqlFunctionMapping +import org.apache.groovy.lang.annotation.Incubating + +/** + * A window function call: {@code function OVER (window)}. + *

+ * {@code function} is the call without {@code OVER}, usually a + * {@link SqlFunction}. {@code count()} with no argument is a + * {@link SqlCountStar}. The native and jOOQ renderers both visit this node. + *

+ * {@code SqlFunctionRegistry.standard()} registers the portable GINQ window + * functions as {@link SqlFunctionMapping.Kind#WINDOW} before it is sealed. + * {@code GinqToSqlTranslator} recognizes + * {@code fn(...) over(partitionby ... orderby ... rows|range ...)} and wraps + * the function in this node. Adjustments that are not part of the function + * call itself, such as {@code rowNumber}'s {@code - 1}, sit outside this node. + * A name that is not registered is rejected with a stable message so mixed + * mode still evaluates the clause in memory. + *

+ * Window {@code min} is that kind, not {@code Math.min} and not the grouped + * aggregate path. Set-operation {@code ORDER BY} matching treats two window + * calls as the same expression when the function, partition, order and frame + * match, so a window projection can be ordered on a union result. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlWindowCall extends SqlExpr { + final SqlExpr function + final SqlWindow window + + SqlWindowCall(SqlExpr function, SqlWindow window) { + if (function == null || window == null) { + throw new IllegalArgumentException('a window call needs a function and a window specification') + } + this.function = function + this.window = window + } +} diff --git a/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowFrame.groovy b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowFrame.groovy new file mode 100644 index 00000000000..13c8c75d5ae --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/SqlWindowFrame.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 + +/** + * A {@code ROWS} or {@code RANGE} frame, always {@code BETWEEN} a lower + * and an upper bound. GINQ's {@code rows} and {@code range} each take + * both bounds, so a one-sided frame is not represented. + * + * @since 7.0.0 + */ +@Incubating +@CompileStatic +class SqlWindowFrame { + enum Unit { + ROWS, RANGE + } + + final Unit unit + final SqlWindowBound lower + final SqlWindowBound upper + + SqlWindowFrame(Unit unit, SqlWindowBound lower, SqlWindowBound upper) { + if (unit == null || lower == null || upper == null) { + throw new IllegalArgumentException('a window frame needs a unit and both bounds') + } + this.unit = unit + this.lower = lower + this.upper = upper + } +} 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..b5a00acd96b --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/ir/package-info.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. + */ + +/** + * Intermediate representation for SQL queries derived from GINQ queries: a provider-neutral + * model consumed by renderers. Compile-time only; never present in generated code. + *

+ * Window calls are {@link SqlWindowCall}: a function + * plus an {@link SqlWindow} (partition, order, and an + * optional {@code ROWS} or {@code RANGE} frame). Both renderers visit that node. + * The translator builds one for each window function registered on the sealed + * standard registry. + */ +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..bfd3f424ad5 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/jooq/JooqRenderer.groovy @@ -0,0 +1,667 @@ +/* + * 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.ir.SqlWindow +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowBound +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame +import org.apache.groovy.ginq.provider.sql.render.Dialect +import org.apache.groovy.ginq.provider.sql.render.RenderedSql +import org.apache.groovy.lang.annotation.Incubating +import org.codehaus.groovy.GroovyBugError + +import java.math.BigDecimal +import java.math.BigInteger +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.GroupField +import org.jooq.JoinType +import org.jooq.Name +import org.jooq.OrderField +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.WindowSpecification +import org.jooq.WindowSpecificationOrderByStep +import org.jooq.WindowSpecificationRowsAndStep +import org.jooq.WindowSpecificationRowsStep +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 SqlWindowCall) { + return buildWindow(ctx, (SqlWindowCall) 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 'IDIV': return DSL.cast(buildField(ctx, expr.left), integerType()) + .div(DSL.cast(buildField(ctx, expr.right), integerType())) + 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}") + } + + // The function is rendered as a query part and the window specification as another, + // so a registered name such as ROW_NUMBER stays an identifier and is not concatenated + // from the GINQ source. Frame offsets that are not Java int literals have no jOOQ + // API here; the native renderer prints those expressions. + private Field buildWindow(DSLContext ctx, SqlWindowCall call) { + Dialect.rejectCountDistinctOver(call.function, jooqCountDistinctOver(), dialectName()) + Field function = buildField(ctx, call.function) + WindowSpecification specification = windowSpecification(ctx, call.window) + if (specification == null) { + return DSL.field('{0} over ()', Object.class, function) + } + return DSL.field('{0} over ({1})', Object.class, function, specification) + } + + private WindowSpecification windowSpecification(DSLContext ctx, SqlWindow window) { + WindowSpecificationRowsStep step = null + if (window.partitionBy) { + WindowSpecificationOrderByStep partitioned = DSL.partitionBy(groupFields(ctx, window.partitionBy)) + if (window.orderBy) { + step = partitioned.orderBy(orderFields(ctx, window.orderBy)) + } else { + step = partitioned + } + } else if (window.orderBy) { + step = DSL.orderBy(orderFields(ctx, window.orderBy)) + } + if (step == null) { + if (window.frame == null) return null + return frameOnly(window.frame) + } + if (window.frame == null) return step + return applyFrame(step, window.frame) + } + + private GroupField[] groupFields(DSLContext ctx, List exprs) { + GroupField[] fields = new GroupField[exprs.size()] + for (int i = 0; i < exprs.size(); i++) { + fields[i] = buildField(ctx, exprs.get(i)) + } + return fields + } + + private OrderField[] orderFields(DSLContext ctx, List orderBy) { + OrderField[] fields = new OrderField[orderBy.size()] + for (int i = 0; i < orderBy.size(); i++) { + fields[i] = buildSortField(ctx, orderBy.get(i)) + } + return fields + } + + private WindowSpecification applyFrame(WindowSpecificationRowsStep step, SqlWindowFrame frame) { + rejectUnsupportedRange(frame) + boolean rows = frame.unit == SqlWindowFrame.Unit.ROWS + WindowSpecificationRowsAndStep between = rows ? rowsBetween(step, frame.lower) : rangeBetween(step, frame.lower) + return andBound(between, frame.upper) + } + + private WindowSpecification frameOnly(SqlWindowFrame frame) { + rejectUnsupportedRange(frame) + boolean rows = frame.unit == SqlWindowFrame.Unit.ROWS + WindowSpecificationRowsAndStep between = rows ? rowsBetween(frame.lower) : rangeBetween(frame.lower) + return andBound(between, frame.upper) + } + + private static WindowSpecificationRowsAndStep rowsBetween(WindowSpecificationRowsStep step, SqlWindowBound bound) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return step.rowsBetweenUnboundedPreceding() + case SqlWindowBound.Kind.PRECEDING: return step.rowsBetweenPreceding(frameOffset(bound)) + case SqlWindowBound.Kind.CURRENT_ROW: return step.rowsBetweenCurrentRow() + case SqlWindowBound.Kind.FOLLOWING: return step.rowsBetweenFollowing(frameOffset(bound)) + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return step.rowsBetweenUnboundedFollowing() + default: throw new GroovyBugError("Unknown window bound: ${bound.kind}") + } + } + + private static WindowSpecificationRowsAndStep rangeBetween(WindowSpecificationRowsStep step, SqlWindowBound bound) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return step.rangeBetweenUnboundedPreceding() + case SqlWindowBound.Kind.PRECEDING: return step.rangeBetweenPreceding(frameOffset(bound)) + case SqlWindowBound.Kind.CURRENT_ROW: return step.rangeBetweenCurrentRow() + case SqlWindowBound.Kind.FOLLOWING: return step.rangeBetweenFollowing(frameOffset(bound)) + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return step.rangeBetweenUnboundedFollowing() + default: throw new GroovyBugError("Unknown window bound: ${bound.kind}") + } + } + + private static WindowSpecificationRowsAndStep rowsBetween(SqlWindowBound bound) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return DSL.rowsBetweenUnboundedPreceding() + case SqlWindowBound.Kind.PRECEDING: return DSL.rowsBetweenPreceding(frameOffset(bound)) + case SqlWindowBound.Kind.CURRENT_ROW: return DSL.rowsBetweenCurrentRow() + case SqlWindowBound.Kind.FOLLOWING: return DSL.rowsBetweenFollowing(frameOffset(bound)) + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return DSL.rowsBetweenUnboundedFollowing() + default: throw new GroovyBugError("Unknown window bound: ${bound.kind}") + } + } + + private static WindowSpecificationRowsAndStep rangeBetween(SqlWindowBound bound) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return DSL.rangeBetweenUnboundedPreceding() + case SqlWindowBound.Kind.PRECEDING: return DSL.rangeBetweenPreceding(frameOffset(bound)) + case SqlWindowBound.Kind.CURRENT_ROW: return DSL.rangeBetweenCurrentRow() + case SqlWindowBound.Kind.FOLLOWING: return DSL.rangeBetweenFollowing(frameOffset(bound)) + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return DSL.rangeBetweenUnboundedFollowing() + default: throw new GroovyBugError("Unknown window bound: ${bound.kind}") + } + } + + private static WindowSpecification andBound(WindowSpecificationRowsAndStep between, SqlWindowBound bound) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return between.andUnboundedPreceding() + case SqlWindowBound.Kind.PRECEDING: return between.andPreceding(frameOffset(bound)) + case SqlWindowBound.Kind.CURRENT_ROW: return between.andCurrentRow() + case SqlWindowBound.Kind.FOLLOWING: return between.andFollowing(frameOffset(bound)) + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return between.andUnboundedFollowing() + default: throw new GroovyBugError("Unknown window bound: ${bound.kind}") + } + } + + private void rejectUnsupportedRange(SqlWindowFrame frame) { + Dialect.rejectRangeOffset(frame, jooqNumericRangeOffset(), jooqExplicitNullOrdering(), dialectName()) + } + + private String dialectName() { + return dialect.family().name().toLowerCase(Locale.ROOT) + } + + private boolean jooqNumericRangeOffset() { + return SQLDialect.SQLITE != dialect.family() + } + + private boolean jooqExplicitNullOrdering() { + SQLDialect family = dialect.family() + return SQLDialect.MYSQL != family && SQLDialect.MARIADB != family && SQLDialect.SQLITE != family + } + + private boolean jooqCountDistinctOver() { + return SQLDialect.SQLITE != dialect.family() + } + + private DataType integerType() { + return SQLDialect.SQLITE == dialect.family() ? SQLDataType.INTEGER : SQLDataType.BIGINT + } + + private static int frameOffset(SqlWindowBound bound) { + if (!(bound.offset instanceof SqlLiteral) || !(((SqlLiteral) bound.offset).value instanceof Number)) { + throw new IllegalArgumentException( + 'the jooq-sql provider renders a window frame offset only when it is an integer literal') + } + Number number = (Number) ((SqlLiteral) bound.offset).value + try { + if (number instanceof BigDecimal) return ((BigDecimal) number).intValueExact() + if (number instanceof BigInteger) return ((BigInteger) number).intValueExact() + long value = number.longValue() + if ((number instanceof Double || number instanceof Float) && number.doubleValue() != value) { + throw new ArithmeticException('fraction') + } + return Math.toIntExact(value) + } catch (ArithmeticException ignored) { + throw new IllegalArgumentException( + 'the jooq-sql provider renders a window frame offset only when it fits in a Java int') + } + } + + 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..0aeed01db25 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/package-info.java @@ -0,0 +1,36 @@ +/* + * 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. + *

+ * {@code fn(...) over(...)} for a registered window function is pushed down as SQL + * {@code OVER}. The built-in registry lists those functions as {@code Kind.WINDOW}, + * separate from grouped aggregates and from {@code Math.min}/{@code Math.max}. + * {@code median}, {@code stdev}, {@code stdevp}, {@code var}, {@code varp} and + * {@code agg} stay untranslated, so mixed mode still runs them in memory. + * See {@link SqlWindowCall}. + */ +package org.apache.groovy.ginq.provider.sql; + +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall; 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..16f8b76a46c --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialect.java @@ -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 org.apache.groovy.ginq.provider.sql.FunctionSupport; +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.SqlWindowBound; +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame; +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 a {@code RANGE} frame may use a numeric offset + * ({@code n PRECEDING} or {@code n FOLLOWING}). SQLite accepts only + * {@code UNBOUNDED} and {@code CURRENT ROW} in a {@code RANGE} frame. + * {@code ROWS} offsets are not affected. + * + * @return {@code true} when a numeric {@code RANGE} offset is supported + * @since 7.0.0 + */ + default boolean numericRangeOffset() { + 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 for truncating integer division, matching GINQ {@code ntile}. + * + * @return the type name + * @since 7.0.0 + */ + default String integerTypeName() { + return "BIGINT"; + } + + /** + * Whether {@code COUNT(DISTINCT ...)} may be a window function. + * SQLite accepts the aggregate and rejects the window form. + * + * @return {@code true} when the window form is supported + * @since 7.0.0 + */ + default boolean countDistinctOver() { + return true; + } + + /** + * Rejects a {@code RANGE} offset the dialect cannot render without + * changing GINQ's null ordering or the value interval. + * + * @param frame the frame, or {@code null} + * @param numericRangeOffset whether a numeric {@code RANGE} offset is legal + * @param explicitNullOrdering whether {@code NULLS FIRST}/{@code LAST} is legal + * @param dialectName the name to put in the diagnostic + * @since 7.0.0 + */ + static void rejectRangeOffset(SqlWindowFrame frame, boolean numericRangeOffset, + boolean explicitNullOrdering, String dialectName) { + if (frame == null || frame.getUnit() != SqlWindowFrame.Unit.RANGE || !numericOffset(frame)) { + return; + } + if (!numericRangeOffset) { + throw new IllegalArgumentException( + "the " + dialectName + " dialect supports RANGE frames only with UNBOUNDED and CURRENT ROW bounds. " + + "A numeric RANGE offset has no equivalent; use `rows`, or a dialect that supports it"); + } + if (!explicitNullOrdering) { + throw new IllegalArgumentException( + "the " + dialectName + " dialect cannot apply a numeric RANGE offset while ordering nulls. " + + "Null ordering is emulated with an extra sort key, and a numeric RANGE offset needs the single order expression. " + + "Use `rows`, or a dialect with explicit null ordering"); + } + } + + /** + * Rejects a window {@code COUNT(DISTINCT ...)} the dialect cannot render. + * + * @param function the window function, before {@code OVER} + * @param supported whether the dialect accepts the window form + * @param dialectName the name to put in the diagnostic + * @since 7.0.0 + */ + static void rejectCountDistinctOver(SqlExpr function, boolean supported, String dialectName) { + if (supported || !(function instanceof SqlFunction) || !((SqlFunction) function).isDistinct()) { + return; + } + throw new IllegalArgumentException( + "the " + dialectName + " dialect does not support COUNT(DISTINCT) as a window function. " + + "Use `count` without `distinct`, or a dialect that supports it"); + } + + private static boolean numericOffset(SqlWindowFrame frame) { + return frame.getLower().getKind() == SqlWindowBound.Kind.PRECEDING + || frame.getLower().getKind() == SqlWindowBound.Kind.FOLLOWING + || frame.getUpper().getKind() == SqlWindowBound.Kind.PRECEDING + || frame.getUpper().getKind() == SqlWindowBound.Kind.FOLLOWING; + } + + /** + * 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..a298ed0e151 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/Dialects.java @@ -0,0 +1,275 @@ +/* + * 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": + return new MySqlDialect("mysql"); + case "mariadb": + return new MySqlDialect("mariadb"); + 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 { + private final String dialectName; + + private MySqlDialect(String dialectName) { + this.dialectName = dialectName; + } + + @Override + public String name() { + return dialectName; + } + + @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 integerTypeName() { + return "INTEGER"; + } + + @Override + public boolean countDistinctOver() { + return false; + } + + @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 boolean numericRangeOffset() { + 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..7b9b42f1d1f --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/main/groovy/org/apache/groovy/ginq/provider/sql/render/SqlRenderer.groovy @@ -0,0 +1,474 @@ +/* + * 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.ginq.provider.sql.ir.SqlWindow +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowBound +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame +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 + renderDivision(expr, dialect.realTypeName(), sb, parameters) + return + } + if ('IDIV' == expr.op) { + // Truncating division. ntile uses this so the buckets match GINQ + // and dialects without FLOOR can still render it. + renderDivision(expr, dialect.integerTypeName(), sb, parameters) + 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 SqlWindowCall) { + Dialect.rejectCountDistinctOver(expr.function, dialect.countDistinctOver(), dialect.name()) + renderExpr(expr.function, sb, parameters) + sb.append(' OVER (') + renderWindow(expr.window, 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 renderWindow(SqlWindow window, StringBuilder sb, List parameters) { + boolean wrote = false + if (window.partitionBy) { + sb.append('PARTITION BY ') + window.partitionBy.eachWithIndex { SqlExpr part, int i -> + if (i > 0) sb.append(', ') + renderExpr(part, sb, parameters) + } + wrote = true + } + if (window.orderBy) { + if (wrote) sb.append(' ') + sb.append('ORDER BY ') + window.orderBy.eachWithIndex { SqlOrderSpec orderSpec, int i -> + if (i > 0) sb.append(', ') + renderOrderItem(orderSpec, sb, parameters) + } + wrote = true + } + if (window.frame != null) { + if (wrote) sb.append(' ') + renderFrame(window.frame, sb, parameters) + } + } + + private void renderFrame(SqlWindowFrame frame, StringBuilder sb, List parameters) { + Dialect.rejectRangeOffset(frame, dialect.numericRangeOffset(), dialect.explicitNullOrdering(), dialect.name()) + sb.append(frame.unit.name()).append(' BETWEEN ') + renderBound(frame.lower, sb, parameters) + sb.append(' AND ') + renderBound(frame.upper, sb, parameters) + } + + private void renderDivision(SqlBinary expr, String typeName, StringBuilder sb, List parameters) { + sb.append('(CAST(') + renderExpr(expr.left, sb, parameters) + sb.append(' AS ').append(typeName).append(') / CAST(') + renderExpr(expr.right, sb, parameters) + sb.append(' AS ').append(typeName).append('))') + } + + private void renderBound(SqlWindowBound bound, StringBuilder sb, List parameters) { + switch (bound.kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: + sb.append('UNBOUNDED PRECEDING') + return + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: + sb.append('UNBOUNDED FOLLOWING') + return + case SqlWindowBound.Kind.CURRENT_ROW: + sb.append('CURRENT ROW') + return + case SqlWindowBound.Kind.PRECEDING: + renderExpr(bound.offset, sb, parameters) + sb.append(' PRECEDING') + return + case SqlWindowBound.Kind.FOLLOWING: + renderExpr(bound.offset, sb, parameters) + sb.append(' FOLLOWING') + return + default: + throw new GroovyBugError("Unknown window bound: ${bound.kind}") + } + } + + 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..01eefb383d8 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlErrorTest.groovy @@ -0,0 +1,445 @@ +/* + * 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, (median(e.salary) 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 testWindowNestedInsideAggregate() { + def err = shouldFail '''\ + GQ(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select (sum((rowNumber() over(orderby e.id)))) + } + ''' + assert err.message.contains('nested inside an aggregate') + 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..0b6a6c657c7 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlMixedModeTest.groovy @@ -0,0 +1,356 @@ +/* + * 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, (median(e.salary) 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', 4000], ['Bob', 4000]] == result.toList() + } + + @Test + void testRegisteredWindowIsPushed() { + 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)) as rn + } + assert db.sqlText.contains('ROW_NUMBER() OVER (ORDER BY e.name ASC NULLS LAST) - 1') + assert db.sqlText.contains('WHERE e.deptId IS NOT DISTINCT FROM ?') + assert !db.sqlText.contains('e.*') + assert [1] == db.params + assert [['Alice', 0], ['Bob', 1]] == result.collect { [it.name, it.rn] } + } + + @Test + void testRankFrameStaysInMemory() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, (rank() over(orderby e.salary rows 0, 0)) as rk + } + assert !db.sqlText.contains('RANK') + assert result.collect { it.rk } == [1, 1, 1, 1, 1, 1] + } + + @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.. 0 && (from x in 'employees' where x.id == e.id select x.id).exists() && e.deptId in (from d2 in 'departments' where d2.id > 0 select d2.id) && e.salary >= (from z in 'employees' select min(z.salary)) + select e, d.name as dn, (e.salary > 4000 ? e.name.toUpperCase() : e.name) as label + } + ''') + def upper = db.sqlText.toUpperCase(Locale.ROOT) + assert !upper.contains('FULL OUTER JOIN') + assert upper.contains('UNION ALL') + assert upper.contains('EXISTS') + assert upper.contains(' IN (') + assert upper.contains('CASE') + assert rows.any { cell(it, 'e_NAME') == 'Alice' && cell(it, 'dn') == 'Dev' && cell(it, 'label') == 'ALICE' } + assert rows.every { cell(it, 'e_NAME') != 'Dave' } + } + + @Test + void pushedOuterJoinKeepsANullAliasForTheInMemoryTail() { + def rows = eval(''' + 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']] == + rows.toList() + } + + @Test + void derivedTablesSetOperationsAndWindowsExecuteOnH2() { + def derived = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from v in (from e in 'employees' where e.salary >= 4000 select e.name, e.salary) + orderby v.name + select v.name + } + ''') + assert ['Alice', 'Carol', 'Eve', 'Frank'] == derived.collect { it.name } + assert db.sqlText.contains('SELECT') + + def combined = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.name + union + from b in 'employees' + where b.deptId == 2 + orderby b.name + limit 1, 1 + select b.name + } + ''') + assert db.sqlText.toUpperCase(Locale.ROOT).contains('UNION') + assert db.sqlText.toUpperCase(Locale.ROOT).contains('ORDER BY') + assert ['Bob'] == combined.collect { it.name } + + def overlap = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.salary >= 5000 + select a.name + intersect + from b in 'employees' + where b.deptId == 1 + select b.name + } + ''') + assert ['Alice'] == overlap.collect { it.name } + assert db.sqlText.toUpperCase(Locale.ROOT).contains('INTERSECT') + + def remaining = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from a in 'employees' + where a.deptId == 1 + select a.name + minus + from b in 'employees' + where b.salary < 4000 + select b.name + } + ''') + assert ['Alice'] == remaining.collect { it.name } + assert db.sqlText.toUpperCase(Locale.ROOT).contains('EXCEPT') + + def numbered = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId == 1 + orderby e.name + select e.name, (rowNumber() over(orderby e.name)) as rn, + (sum(e.salary) over(partitionby e.deptId orderby e.salary rows -1, 0)) as near + } + ''') + assert db.sqlText.contains('ROW_NUMBER() OVER') + assert db.sqlText.contains('ROWS') + assert [['Alice', 0], ['Bob', 1]] == numbered.collect { [it.name, it.rn] } + assert numbered.every { it.near instanceof Number } + } + + @Test + void mysqlSqliteAndPostgresRenderThroughTheProvider() { + def sink = new RecordingSql(realDb) + eval(sink, ''' + def bound = 1 + def rows = GQL(provider: 'native-sql', dialect: 'mysql', dataSource: db) { + from e in 'employees' + where e.name == bound && e.salary != bound + orderby e.name + limit 1, 2 + select e.name.length() as n + } + rows + ''') + def mysql = sink.sqlText + assert mysql.contains('<=>') + assert mysql.contains('NOT (') + assert mysql.contains('LIMIT') + assert mysql.contains('OFFSET') + assert mysql.contains('`employees`') + assert mysql.contains('CHAR_LENGTH') + + sink = new RecordingSql(realDb) + eval(sink, ''' + def bound = 1 + def rows = GQL(provider: 'native-sql', dialect: 'sqlite', dataSource: db) { + from e in 'employees' + where e.name == bound && e.salary != bound + orderby e.name + limit 2 + select e.name.length() as n, (e.salary / 2) as half + } + rows + ''') + def sqlite = sink.sqlText + assert sqlite.contains(' IS ') + assert sqlite.contains(' IS NOT ') + assert sqlite.contains('LIMIT') + assert sqlite.contains('LENGTH(') + assert sqlite.contains('REAL') + + sink = new RecordingSql(realDb) + eval(sink, ''' + def rows = GQL(provider: 'native-sql', dialect: 'postgres', dataSource: db) { + from e in 'employees' + where e.name == 'Ada' + orderby e.salary in desc + limit 1, 2 + select e.salary / 2 as half + } + rows + ''') + def postgres = sink.sqlText + assert postgres.contains('"employees"') + assert postgres.contains('FETCH') + assert postgres.contains('DOUBLE PRECISION') + assert postgres.contains('IS NOT DISTINCT FROM') + } + + @Test + void jooqRendersJoinsWindowsCastsAndSetOperations() { + def rows = eval(''' + def threshold = 2500 + def floor = 4500 + def needle = 'li' + def listed = GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + where e.salary > threshold && e.name.contains('a') + orderby e.salary in desc, e.name + limit 1, 2 + select e.name, d.name as deptName, + cast(e.id, 'DECIMAL') / 2 as half, + e.name.indexOf(needle) as at, + (rowNumber() over(partitionby e.deptId orderby e.name)) as rn + } + def combined = 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 + } + [listed, combined] + ''') + assert db.sqlText.toLowerCase(Locale.ROOT).contains('union') + assert db.sqlText.toLowerCase(Locale.ROOT).contains('offset') + assert rows[0].size() <= 2 + assert rows[1].size() <= 2 + assert rows[0].every { it.name && it.deptName && it.half instanceof Number && it.at instanceof Number } + } + + @Test + void plusCastSubstringAndRangesFollowTheOperandKinds() { + def rows = eval(''' + String suffix = '!' + int bonus = 1 + def rows = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.id == 1 + select e.name + (suffix as String) as label, e.salary + (bonus as int) as pay, + (e.salary as long) as wide, (e.name as String) as text, + e.name.substring(1, 3) as mid, e.name.length() as n, + Math.max(e.salary, 1000) as hi, -e.salary as neg + } + rows + ''') + assert rows.size() == 1 + assert rows[0].label == 'Alice!' + assert rows[0].pay == 5001 + assert rows[0].mid == 'li' + assert rows[0].n == 5 + assert rows[0].hi == 5000 + assert rows[0].neg == -5000 + assert db.sqlText.contains('||') + assert db.sqlText.contains('BIGINT') + assert db.sqlText.contains('VARCHAR') + + def names = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.salary in 4000..5000 && e.deptId in [1, null] && e.name !in ['Bob'] + orderby e.name + select e.name + } + ''') + assert names.collect { it.name } == ['Alice'] + + def added = eval(''' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where (e.salary - 1000) in (from x in 'employees' select x.salary) + orderby e.name + select e.name + } + ''') + assert added.collect { it.name }.toSet() == ['Alice', 'Bob', 'Carol', 'Eve', 'Frank'] as Set + assert db.sqlText.toUpperCase(Locale.ROOT).contains(' IN (') + + def both = shouldFail { + new GroovyShell(new Binding([db: db])).evaluate(''' + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + select e.name + e.salary + } + ''') + } + assert both.message.contains('not translated') + + def table = shouldFail { + new GroovyShell(new Binding([db: db])).evaluate(''' + def table = 'employees' + GQL(provider: 'native-sql', dataSource: db) { + from e in table + select e.name + } + ''') + } + assert table.message.contains('string literal') + } + + private Object eval(String script) { + eval(db, script) + } + + private static Object eval(Object dataSource, String script) { + new GroovyShell(new Binding([db: dataSource])).evaluate(script) + } + + private static Object cell(row, String key) { + def found = row.keySet().find { String name -> name.equalsIgnoreCase(key) } + return found == null ? null : row[found] + } + + static class RecordingSql extends Sql { + String sqlText + List params + + RecordingSql(Sql parent) { + super(parent) + } + + @Override + List rows(String sql, List params) throws SQLException { + this.sqlText = sql + this.params = new ArrayList(params) + return [] + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlSemanticsTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlSemanticsTest.groovy new file mode 100644 index 00000000000..5ae906414ea --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlSemanticsTest.groovy @@ -0,0 +1,413 @@ +/* + * 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.apache.groovy.ginq.provider.sql.render.Dialects +import org.apache.groovy.ginq.provider.sql.runtime.SqlGinqRuntime +import org.codehaus.groovy.ast.expr.ArgumentListExpression +import org.codehaus.groovy.ast.expr.BinaryExpression +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.GStringExpression +import org.codehaus.groovy.ast.expr.MethodCallExpression +import org.codehaus.groovy.ast.expr.VariableExpression +import org.codehaus.groovy.syntax.Token +import org.codehaus.groovy.syntax.Types +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +import java.sql.SQLException + +import static groovy.test.GroovyAssert.shouldFail + +/** + * The cases called out for the SQL backend: mixed-mode reconstruction, + * null comparisons, operators whose type cannot be decided, and dialect + * push-down. + */ +class GinqSqlSemanticsTest { + 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 testJoinedSourcesKeepBothNameColumns() { + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: db) { + from e in 'employees' + join d in 'departments' on e.deptId == d.id + where e.name == 'Alice' + orderby e.name + select e.name.reverse(), d.name.reverse() + } + assert [['ecilA', 'veD']] == result.toList() + } + + @Test + void testMixedJoinKeyDoesNotHideAColumnOfTheSameName() { + realDb.execute('create table tags (__ginq_mixed_key varchar(20), name varchar(50), deptId integer)') + realDb.execute("insert into tags (__ginq_mixed_key, name, deptId) values ('keep-me', 'Dev', 1)") + def result = GQL(provider: 'native-sql', mixedMode: true, dataSource: realDb) { + from e in 'employees' + join t in 'tags' on e.deptId == t.deptId + where e.name == 'Alice' + select e.name.reverse(), t.__ginq_mixed_key + } + assert [['ecilA', 'keep-me']] == result.toList() + } + + @Test + void testDuplicateSourceLabelsAreRejected() { + def duplicate = shouldFail(SQLException) { + SqlGinqRuntime.rewriteStarSelect( + 'SELECT e.*, d.* FROM employees e INNER JOIN departments d ON e.deptId = d.id', + [['name', 'name'], ['id']], + '"' as char) + } + assert duplicate.message.contains('duplicate column labels') + assert duplicate.message.contains('name') + } + + @Test + void testStarProjectionIsRewrittenToNamedColumns() { + def sql = SqlGinqRuntime.rewriteStarSelect( + 'SELECT e.*, d.* FROM employees e INNER JOIN departments d ON e.deptId = d.id WHERE e.name = ?', + [['id', 'na"me'], ['id', 'name']], + '"' as char) + assert 'SELECT e."id" AS "__ginq0_0", e."na""me" AS "__ginq0_1", d."id" AS "__ginq1_0", d."name" AS "__ginq1_1" ' + + 'FROM employees e INNER JOIN departments d ON e.deptId = d.id WHERE e.name = ?' == sql + + def nested = SqlGinqRuntime.rewriteStarSelect( + 'SELECT v.* FROM (SELECT name FROM employees) v WHERE v.name = ?', + [['name']], + '"' as char) + assert 'SELECT v."name" AS "__ginq0_0" FROM (SELECT name FROM employees) v WHERE v.name = ?' == nested + } + + @Test + void testPresenceColumnIsAddedInsideEachSource() { + def sql = SqlGinqRuntime.prepareMixedSql( + 'SELECT e.*, d.* FROM employees e LEFT JOIN departments d ON e.deptId = d.id WHERE e.name = ?', + [['id', 'name'], ['id', 'name']], + '"' as char) + assert sql.contains('FROM (SELECT "__ginq_src".*, 1 AS "__ginq_present" FROM employees "__ginq_src") e') + assert sql.contains('LEFT JOIN (SELECT "__ginq_src".*, 1 AS "__ginq_present" FROM departments "__ginq_src") d') + assert sql.contains('e."__ginq_present" AS "__ginq0_2"') + assert sql.contains('d."__ginq_present" AS "__ginq1_2"') + assert sql.endsWith('WHERE e.name = ?') + assert !sql.contains('1 AS "__ginq_present" FROM employees e') + + def jooq = SqlGinqRuntime.prepareMixedSql( + 'select e.*, d.* from employees e right outer join departments d on e.deptId is not distinct from d.id', + [['ID', 'NAME'], ['ID', 'NAME']], + '"' as char) + assert jooq.contains('right outer join (SELECT "__ginq_src".*, 1 AS "__ginq_present" FROM departments "__ginq_src") d') + assert jooq.contains('FROM (SELECT "__ginq_src".*, 1 AS "__ginq_present" FROM employees "__ginq_src") e') + + def full = SqlGinqRuntime.prepareMixedSql( + 'SELECT e.*, d.* FROM "employees" "e" FULL OUTER JOIN "departments" "d" ON "e"."deptId" = "d"."id"', + [['id'], ['id']], + '"' as char) + assert full.contains('FULL OUTER JOIN') + assert full.contains('1 AS "__ginq_present"') + assert !full.contains('UNION ALL') + + def nestedJoin = SqlGinqRuntime.prepareMixedSql( + "SELECT e.*, d.* FROM employees e LEFT JOIN departments d ON e.name LIKE ? ESCAPE '!' ORDER BY e.name", + [['name'], ['name']], + '"' as char) + assert nestedJoin.contains("ON e.name LIKE ? ESCAPE '!'") + assert nestedJoin.endsWith('ORDER BY e.name') + + def derived = SqlGinqRuntime.prepareMixedSql( + 'SELECT v.*, d.* FROM (SELECT name FROM employees WHERE name = ?) v INNER JOIN hr.departments d ON v.name = d.name', + [['name'], ['id', 'name']], + '`' as char) + assert derived.contains('FROM (SELECT `__ginq_src`.*, 1 AS `__ginq_present` FROM (SELECT name FROM employees WHERE name = ?) `__ginq_src`) v') + assert derived.contains('INNER JOIN (SELECT `__ginq_src`.*, 1 AS `__ginq_present` FROM hr.departments `__ginq_src`) d') + + def collision = SqlGinqRuntime.prepareMixedSql( + 'SELECT e.*, m.* FROM anchors e CROSS JOIN marks m', + [['id'], ['__ginq_present', 'name']], + '"' as char) + assert collision.contains('1 AS "__ginq_present_1"') + assert !collision.contains('1 AS "__ginq_present"') + + def userColumn = SqlGinqRuntime.prepareMixedSql( + 'SELECT e.*, d.* FROM employees e JOIN departments d ON e.__ginq_present = d.id', + [['id'], ['id']], + '"' as char) + assert userColumn.contains('__ginq_src') + assert userColumn.contains('e.__ginq_present = d.id') + + def mysqlTokens = SqlGinqRuntime.prepareMixedSql( + 'SELECT `__ginqf0_2`.`__ginqref_0_id`, `__ginqf0_2`.`__ginqabs_1`, `__ginqf0_2`.`__ginqord_0_name` FROM `__ginqf0_2`', + [['id', 'name'], ['id']], + '"' as char) + assert !mysqlTokens.contains('__ginqref_') + assert !mysqlTokens.contains('__ginqabs_') + assert !mysqlTokens.contains('__ginqord_') + assert mysqlTokens.contains('`__ginq0_0`') + assert mysqlTokens.contains('`__ginq0_1`') + assert mysqlTokens.contains('`__ginq1_') + + def brackets = SqlGinqRuntime.prepareMixedSql( + 'SELECT [__ginqf0_2].[__ginqref_0_id] FROM [__ginqf0_2]', + [['id', 'name']], + '"' as char) + assert brackets.contains('[__ginq0_0]') + assert !brackets.contains(']"') + assert !brackets.contains('"__ginq0_0"') + } + + @Test + void testJdbcUrlSelectsTheDialect() { + assert 'h2' == Dialects.fromJdbcUrl('jdbc:h2:mem:ginq') + assert 'mysql' == Dialects.fromJdbcUrl('jdbc:mariadb://localhost/db') + assert 'postgres' == Dialects.fromJdbcUrl('jdbc:postgresql://localhost/db') + assert null == Dialects.fromJdbcUrl('jdbc:oracle:thin:@localhost:1521:orcl') + assert 'h2' == GinqSqlWalker.jdbcDialect(new ConstantExpression('jdbc:h2:mem:ginq')) + assert null == GinqSqlWalker.jdbcDialect(new VariableExpression('db')) + def call = new MethodCallExpression(new VariableExpression('Sql'), 'newInstance', + new ArgumentListExpression(new ConstantExpression('jdbc:mysql://localhost/db'))) + assert 'mysql' == GinqSqlWalker.jdbcDialect(call) + + def h2GString = new GStringExpression('jdbc:h2:mem:$name', + [new ConstantExpression('jdbc:h2:mem:'), new ConstantExpression('')], + [new VariableExpression('name')]) + assert 'h2' == GinqSqlWalker.jdbcDialect(h2GString) + def postgresGString = new GStringExpression('jdbc:postgresql://$host/db', + [new ConstantExpression('jdbc:postgresql://'), new ConstantExpression('/db')], + [new VariableExpression('host')]) + assert 'postgres' == GinqSqlWalker.jdbcDialect(postgresGString) + def concatenated = new BinaryExpression( + new ConstantExpression('jdbc:h2:mem:'), + new Token(Types.PLUS, '+', -1, -1), + new VariableExpression('name')) + assert 'h2' == GinqSqlWalker.jdbcDialect(concatenated) + } + + @Test + void testNullParameterMatchesNullColumn() { + def wanted = null + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId == wanted + orderby e.name + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId IS NOT DISTINCT FROM ? ORDER BY e.name ASC NULLS LAST' == db.sqlText + assert [null] == db.params + assert ['Dave'] == result.collect { it.name } + + def present = 1 + db.sqlTexts.clear() + def named = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId == present + orderby e.name + select e.name + } + assert db.sqlText.contains('IS NOT DISTINCT FROM') + assert ['Alice', 'Bob'] == named.collect { it.name } + } + + @Test + void testNotInRangeIncludesNull() { + def result = GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + where e.deptId !in 1..3 + orderby e.name + select e.name + } + assert 'SELECT e.name FROM employees e WHERE e.deptId IS NULL OR e.deptId < ? OR e.deptId > ? 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/GinqSqlWindowExecutionTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlWindowExecutionTest.groovy new file mode 100644 index 00000000000..8a16768eaab --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqSqlWindowExecutionTest.groovy @@ -0,0 +1,645 @@ +/* + * 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 + +/** + * Executes window queries against H2. The native and jOOQ providers must + * both push {@code OVER} down and agree on GINQ's results. + */ +class GinqSqlWindowExecutionTest { + private Sql db + + @BeforeEach + void setUp() { + db = GinqSqlTestSupport.newPopulatedDb() + db.execute 'create table nums (n int)' + [1, 2, 5, 5].each { db.execute 'insert into nums (n) values (?)', [it] } + db.execute 'create table seq (n int)' + (1..10).each { db.execute 'insert into seq (n) values (?)', [it] } + db.execute 'create table scores (n int)' + [60, 60, 80, 80, 100].each { db.execute 'insert into scores (n) values (?)', [it] } + db.execute 'create table gaps (n int)' + [1, 2, null, 3].each { db.execute 'insert into gaps (n) values (?)', [it] } + db.execute 'create table keyed (k int, n int)' + [[1, null], [1, null], [2, 4], [2, null]].each { + db.execute 'insert into keyed (k, n) values (?, ?)', it + } + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void testRowNumberIsZeroBased() { + def expected = [['Alice', 0], ['Bob', 1], ['Carol', 2], ['Dave', 3], ['Eve', 4], ['Frank', 5]] + assert expected == names(nativeRows()) + assert expected == names(jooqRows()) + } + + @Test + void testPartitionOrderNullsAndRanks() { + def partitions = [['Alice', 0], ['Bob', 1], ['Carol', 0], ['Dave', 0], ['Eve', 1], ['Frank', 0]] + assert partitions == nativePartitionNumbers() + assert partitions == jooqPartitionNumbers() + + def ranks = [[2000, 1, 1], [3000, 2, 2], [4000, 3, 3], [5000, 4, 4], [5000, 4, 4], [6000, 6, 5]] + assert ranks == nativeRanks() + assert ranks == jooqRanks() + + def gaps = [[1, 0, 3, null], [2, 1, 2, 1], [3, 2, 1, 2], [null, 3, 0, 3]] + assert gaps == nativeGaps() + assert gaps == jooqGaps() + } + + @Test + void testLeadLagAndValueFunctions() { + def offsets = [ + ['Alice', 'Bob', 'NONE', 'Carol'], + ['Bob', 'Carol', 'Alice', 'Dave'], + ['Carol', 'Dave', 'Bob', 'Eve'], + ['Dave', 'Eve', 'Carol', 'Frank'], + ['Eve', 'Frank', 'Dave', null], + ['Frank', null, 'Eve', null] + ] + assert offsets == nativeOffsets() + assert offsets == jooqOffsets() + + def values = [ + ['Alice', 'Alice', 'Bob', 'Alice', 'Bob'], + ['Bob', 'Alice', 'Bob', 'Alice', 'Bob'], + ['Carol', 'Carol', 'Eve', 'Carol', 'Eve'], + ['Dave', 'Dave', 'Dave', 'Dave', null], + ['Eve', 'Carol', 'Eve', 'Carol', 'Eve'], + ['Frank', 'Frank', 'Frank', 'Frank', null] + ] + assert values == nativeValues() + assert values == jooqValues() + } + + @Test + void testAggregatesUseTheWholePartitionUnlessAFrameIsWritten() { + def totals = nativeTotals() + assert totals.every { it[1] == 6 && it[2] == 25000 && it[3] == 5 } + assert totals == jooqTotals() + + def byDept = [ + ['Alice', 2, 8000, 4000, 3000, 5000, 2], + ['Bob', 2, 8000, 4000, 3000, 5000, 2], + ['Carol', 2, 9000, 4500, 4000, 5000, 2], + ['Dave', 1, 2000, 2000, 2000, 2000, 1], + ['Eve', 2, 9000, 4500, 4000, 5000, 2], + ['Frank', 1, 6000, 6000, 6000, 6000, 1] + ] + assert byDept == nativeByDept() + assert byDept == jooqByDept() + + assert [[1, 0], [1, 0], [2, 4], [2, 4]] == nativeNullSums() + assert [[1, 0], [1, 0], [2, 4], [2, 4]] == jooqNullSums() + } + + @Test + void testRowsAndRangeFrames() { + def rows = [[1, 3, 1, 2], [2, 6, 1, 3], [3, 5, 2, 3]] + assert rows == nativeRowFrame() + assert rows == jooqRowFrame() + + def range = [[1, 1, 1], [2, 2, 3], [5, 2, 10], [5, 2, 10]] + assert range == nativeRange() + assert range == jooqRange() + + assert range == nativeDescendingRange() + assert range == jooqDescendingRange() + } + + @Test + void testDescendingNullRangeAndSeveralOrderKeys() { + db.execute 'create table marks (n int)' + [1, null, 3].each { db.execute 'insert into marks (n) values (?)', [it] } + db.execute 'create table blanks (n int)' + [null, null].each { db.execute 'insert into blanks (n) values (?)', [it] } + + def throughCurrent = [[1, 2, 1], [3, 3, 4], [null, 1, 0]] + assert throughCurrent == nativeThroughCurrent() + assert throughCurrent == jooqThroughCurrent() + + def fromCurrent = [[1, 2, 4], [3, 1, 3], [null, 3, 4]] + assert fromCurrent == nativeFromCurrent() + assert fromCurrent == jooqFromCurrent() + + assert [[null, 2], [null, 2]] == nativeBlankPeers() + assert [[null, 2], [null, 2]] == jooqBlankPeers() + + def ranks = [ + ['Alice', 4, 4], + ['Bob', 2, 2], + ['Carol', 3, 3], + ['Dave', 1, 1], + ['Eve', 5, 5], + ['Frank', 6, 6] + ] + assert ranks == nativeMultiRanks() + assert ranks == jooqMultiRanks() + } + + @Test + void testNtilePercentRankAndCumeDist() { + def buckets = (1..10).collect { n -> + int index = n - 1 + [n, (4 * index).intdiv(10)] + } + assert buckets == nativeNtile() + assert buckets == jooqNtile() + + def scores = [[60, 0, 0.4], [60, 0, 0.4], [80, 0.5, 0.8], [80, 0.5, 0.8], [100, 1, 1]] + assert close(scores, nativeScores()) + assert close(scores, jooqScores()) + + def single = [ + ['Alice', 1, 1], + ['Bob', 0, 0.5], + ['Carol', 0, 0.5], + ['Dave', 1, 1], + ['Eve', 1, 1], + ['Frank', 1, 1] + ] + assert close(single, nativeSingle()) + assert close(single, jooqSingle()) + } + + private List nativeRows() { + GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, (rowNumber() over(orderby e.name)) as rn + } + } + + private List jooqRows() { + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, (rowNumber() over(orderby e.name)) as rn + } + } + + private static List names(List rows) { + rows.collect { [it.name, it.rn] } + } + + private List nativePartitionNumbers() { + rows(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, (rowNumber() over(partitionby e.deptId orderby e.name)) as rn + }) + } + + private List jooqPartitionNumbers() { + rows(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, (rowNumber() over(partitionby e.deptId orderby e.name)) as rn + }) + } + + private List nativeRanks() { + ranks(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.salary, e.id + select e.salary, (rank() over(orderby e.salary)) as r, (denseRank() over(orderby e.salary)) as d + }) + } + + private List jooqRanks() { + ranks(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.salary, e.id + select e.salary, (rank() over(orderby e.salary)) as r, (denseRank() over(orderby e.salary)) as d + }) + } + + private static List ranks(List rows) { + rows.collect { [it.salary, it.r, it.d] } + } + + private List nativeGaps() { + gaps(GQL(provider: 'native-sql', dataSource: db) { + from g in 'gaps' + orderby g.n + select g.n, + (rowNumber() over(orderby g.n)) as ascLast, + (rowNumber() over(orderby g.n in desc(nullsfirst))) as descFirst, + (lag(g.n) over(orderby g.n)) as prev + }) + } + + private List jooqGaps() { + gaps(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from g in 'gaps' + orderby g.n + select g.n, + (rowNumber() over(orderby g.n)) as ascLast, + (rowNumber() over(orderby g.n in desc(nullsfirst))) as descFirst, + (lag(g.n) over(orderby g.n)) as prev + }) + } + + private static List gaps(List rows) { + rows.collect { [it.n, it.ascLast, it.descFirst, it.prev] } + } + + private List nativeOffsets() { + offsets(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.id + select e.name, + (lead(e.name) over(orderby e.id)) as nxt, + (lag(e.name, 1, 'NONE') over(orderby e.id)) as prev, + (lead(e.name, 2) over(orderby e.id)) as skip + }) + } + + private List jooqOffsets() { + offsets(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.id + select e.name, + (lead(e.name) over(orderby e.id)) as nxt, + (lag(e.name, 1, 'NONE') over(orderby e.id)) as prev, + (lead(e.name, 2) over(orderby e.id)) as skip + }) + } + + private static List offsets(List rows) { + rows.collect { [it.name, it.nxt, it.prev, it.skip] } + } + + private List nativeValues() { + values(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (firstValue(e.name) over(partitionby e.deptId orderby e.name)) as firstName, + (lastValue(e.name) over(partitionby e.deptId orderby e.name)) as lastName, + (nthValue(e.name, 0) over(partitionby e.deptId orderby e.name)) as nth0, + (nthValue(e.name, 1) over(partitionby e.deptId orderby e.name)) as nth1 + }) + } + + private List jooqValues() { + values(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (firstValue(e.name) over(partitionby e.deptId orderby e.name)) as firstName, + (lastValue(e.name) over(partitionby e.deptId orderby e.name)) as lastName, + (nthValue(e.name, 0) over(partitionby e.deptId orderby e.name)) as nth0, + (nthValue(e.name, 1) over(partitionby e.deptId orderby e.name)) as nth1 + }) + } + + private static List values(List rows) { + rows.collect { [it.name, it.firstName, it.lastName, it.nth0, it.nth1] } + } + + private List nativeTotals() { + totals(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (count() over(orderby e.salary)) as cnt, + (sum(e.salary) over(orderby e.salary)) as total, + (count(e.deptId) over()) as present + }) + } + + private List jooqTotals() { + totals(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (count() over(orderby e.salary)) as cnt, + (sum(e.salary) over(orderby e.salary)) as total, + (count(e.deptId) over()) as present + }) + } + + private static List totals(List rows) { + rows.collect { [it.name, it.cnt, it.total, it.present] } + } + + private List nativeByDept() { + byDept(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (count() over(partitionby e.deptId)) as cnt, + (sum(e.salary) over(partitionby e.deptId)) as total, + (avg(e.salary) over(partitionby e.deptId)) as avgSalary, + (min(e.salary) over(partitionby e.deptId)) as lo, + (max(e.salary) over(partitionby e.deptId)) as hi, + (count(distinct(e.salary)) over(partitionby e.deptId)) as kinds + }) + } + + private List jooqByDept() { + byDept(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (count() over(partitionby e.deptId)) as cnt, + (sum(e.salary) over(partitionby e.deptId)) as total, + (avg(e.salary) over(partitionby e.deptId)) as avgSalary, + (min(e.salary) over(partitionby e.deptId)) as lo, + (max(e.salary) over(partitionby e.deptId)) as hi, + (count(distinct(e.salary)) over(partitionby e.deptId)) as kinds + }) + } + + private static List byDept(List rows) { + rows.collect { [it.name, it.cnt, it.total, it.avgSalary, it.lo, it.hi, it.kinds] } + } + + private List nativeNullSums() { + nullSums(GQL(provider: 'native-sql', dataSource: db) { + from k in 'keyed' + orderby k.k, k.n + select k.k, (sum(k.n) over(partitionby k.k)) as total + }) + } + + private List jooqNullSums() { + nullSums(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from k in 'keyed' + orderby k.k, k.n + select k.k, (sum(k.n) over(partitionby k.k)) as total + }) + } + + private static List nullSums(List rows) { + rows.collect { [it.k, it.total] } + } + + private List nativeRowFrame() { + frames(GQL(provider: 'native-sql', dataSource: db) { + from s in 'seq' + where s.n <= 3 + orderby s.n + select s.n, + (sum(s.n) over(orderby s.n rows -1, 1)) as total, + (firstValue(s.n) over(orderby s.n rows -1, 1)) as first, + (lastValue(s.n) over(orderby s.n rows -1, 1)) as last + }) + } + + private List jooqRowFrame() { + frames(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from s in 'seq' + where s.n <= 3 + orderby s.n + select s.n, + (sum(s.n) over(orderby s.n rows -1, 1)) as total, + (firstValue(s.n) over(orderby s.n rows -1, 1)) as first, + (lastValue(s.n) over(orderby s.n rows -1, 1)) as last + }) + } + + private static List frames(List rows) { + rows.collect { [it.n, it.total, it.first, it.last] } + } + + private List nativeRange() { + range(GQL(provider: 'native-sql', dataSource: db) { + from n in 'nums' + orderby n.n + select n.n, + (count() over(orderby n.n range -2, 0)) as cnt, + (sum(n.n) over(orderby n.n range -2, 0)) as total + }) + } + + private List jooqRange() { + range(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from n in 'nums' + orderby n.n + select n.n, + (count() over(orderby n.n range -2, 0)) as cnt, + (sum(n.n) over(orderby n.n range -2, 0)) as total + }) + } + + private static List range(List rows) { + rows.collect { [it.n, it.cnt, it.total] } + } + + private List nativeDescendingRange() { + range(GQL(provider: 'native-sql', dataSource: db) { + from n in 'nums' + orderby n.n + select n.n, + (count() over(orderby n.n in desc range -2, 0)) as cnt, + (sum(n.n) over(orderby n.n in desc range -2, 0)) as total + }) + } + + private List jooqDescendingRange() { + range(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from n in 'nums' + orderby n.n + select n.n, + (count() over(orderby n.n in desc range -2, 0)) as cnt, + (sum(n.n) over(orderby n.n in desc range -2, 0)) as total + }) + } + + private List nativeThroughCurrent() { + range(GQL(provider: 'native-sql', dataSource: db) { + from n in 'marks' + orderby n.n + select n.n, + (count() over(orderby n.n in desc range null, 0)) as cnt, + (sum(n.n) over(orderby n.n in desc range null, 0)) as total + }) + } + + private List jooqThroughCurrent() { + range(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from n in 'marks' + orderby n.n + select n.n, + (count() over(orderby n.n in desc range null, 0)) as cnt, + (sum(n.n) over(orderby n.n in desc range null, 0)) as total + }) + } + + private List nativeFromCurrent() { + range(GQL(provider: 'native-sql', dataSource: db) { + from n in 'marks' + orderby n.n + select n.n, + (count() over(orderby n.n in desc range 0, null)) as cnt, + (sum(n.n) over(orderby n.n in desc range 0, null)) as total + }) + } + + private List jooqFromCurrent() { + range(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from n in 'marks' + orderby n.n + select n.n, + (count() over(orderby n.n in desc range 0, null)) as cnt, + (sum(n.n) over(orderby n.n in desc range 0, null)) as total + }) + } + + private List nativeBlankPeers() { + GQL(provider: 'native-sql', dataSource: db) { + from n in 'blanks' + select n.n, (count() over(orderby n.n range -1, 1)) as cnt + }.collect { [it.n, it.cnt] } + } + + private List jooqBlankPeers() { + GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from n in 'blanks' + select n.n, (count() over(orderby n.n range -1, 1)) as cnt + }.collect { [it.n, it.cnt] } + } + + private List nativeMultiRanks() { + ranksByName(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (rank() over(orderby e.salary, e.name)) as rk, + (denseRank() over(orderby e.salary, e.name)) as dense + }) + } + + private List jooqMultiRanks() { + ranksByName(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (rank() over(orderby e.salary, e.name)) as rk, + (denseRank() over(orderby e.salary, e.name)) as dense + }) + } + + private static List ranksByName(List rows) { + rows.collect { [it.name, it.rk, it.dense] } + } + + private List nativeNtile() { + ntile(GQL(provider: 'native-sql', dataSource: db) { + from s in 'seq' + orderby s.n + select s.n, (ntile(4) over(orderby s.n)) as bucket + }) + } + + private List jooqNtile() { + ntile(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from s in 'seq' + orderby s.n + select s.n, (ntile(4) over(orderby s.n)) as bucket + }) + } + + private static List ntile(List rows) { + rows.collect { [it.n, it.bucket] } + } + + private List nativeScores() { + scores(GQL(provider: 'native-sql', dataSource: db) { + from s in 'scores' + orderby s.n + select s.n, + (percentRank() over(orderby s.n)) as pct, + (cumeDist() over(orderby s.n)) as cume + }) + } + + private List jooqScores() { + scores(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from s in 'scores' + orderby s.n + select s.n, + (percentRank() over(orderby s.n)) as pct, + (cumeDist() over(orderby s.n)) as cume + }) + } + + private static List scores(List rows) { + rows.collect { [it.n, it.pct, it.cume] } + } + + private List nativeSingle() { + single(GQL(provider: 'native-sql', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (percentRank() over(partitionby e.deptId orderby e.salary)) as pct, + (cumeDist() over(partitionby e.deptId orderby e.salary)) as cume + }) + } + + private List jooqSingle() { + single(GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db) { + from e in 'employees' + orderby e.name + select e.name, + (percentRank() over(partitionby e.deptId orderby e.salary)) as pct, + (cumeDist() over(partitionby e.deptId orderby e.salary)) as cume + }) + } + + private static List single(List rows) { + rows.collect { [it.name, it.pct, it.cume] } + } + + private static List rows(List result) { + result.collect { [it.name, it.rn] } + } + + private static boolean close(List expected, List actual) { + assert expected.size() == actual.size() + expected.eachWithIndex { List want, int i -> + List got = (List) actual[i] + assert want.size() == got.size() + want.eachWithIndex { Object cell, int j -> + Object value = got[j] + if (cell instanceof BigDecimal || cell instanceof Double) { + assert value != null + assert Math.abs(((Number) value).doubleValue() - ((Number) cell).doubleValue()) < 0.0000001d + } else { + assert cell == value + } + } + } + return true + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqWindowProviderAgreementTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqWindowProviderAgreementTest.groovy new file mode 100644 index 00000000000..031e764c4d2 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/GinqWindowProviderAgreementTest.groovy @@ -0,0 +1,262 @@ +/* + * 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 + +/** + * Runs one GINQ clause shape on the collection provider and on H2 + * ({@code native-sql} and {@code jooq-sql}) and requires the frozen + * window results to agree. + */ +class GinqWindowProviderAgreementTest { + private Sql db + private List oneRow + private List running + private List scores + private List blanks + private List seq + + @BeforeEach + void setUp() { + db = GinqSqlTestSupport.newPopulatedDb() + oneRow = rows(7) + running = rows(10, 20, 30) + scores = rows(60, 60, 80, 80, 100) + blanks = [[n: null], [n: null]] + seq = rows(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + store('one_row', oneRow) + store('running', running) + store('scores', scores) + store('blanks', blanks) + store('seq', seq) + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void testOneRowNumberingIsZeroBased() { + agreeOn('one_row', oneRow, ['rn', 'nth'], ''' + orderby r.n + select (rowNumber() over(orderby r.n)) as rn, (nthValue(r.n, 0) over(orderby r.n)) as nth + ''', [[0, 7]]) + } + + @Test + void testNtileZeroStaysOnBucketZero() { + agreeOn('seq', seq, ['n', 'bucket'], ''' + orderby r.n + select r.n, (ntile(0) over(orderby r.n)) as bucket + ''', seq.collect { [it.n, 0] }) + } + + @Test + void testNtileUsesTheZeroBasedFormula() { + agreeOn('seq', seq, ['n', 'bucket'], ''' + orderby r.n + select r.n, (ntile(4) over(orderby r.n)) as bucket + ''', seq.collect { row -> [row.n, (4 * (row.n - 1)).intdiv(10)] }) + } + + @Test + void testOrderByWithoutAFrameIsTheWholePartition() { + def expected = [[10, 60, 20], [20, 60, 20], [30, 60, 20]] + agreeOn('running', running, ['n', 'total', 'mean'], ''' + orderby r.n + select r.n, (sum(r.n) over(orderby r.n)) as total, (avg(r.n) over(orderby r.n)) as mean + ''', expected) + assert expected.every { it[1] == 60 } + } + + @Test + void testAllNullWindowSumIsZero() { + agreeOn('blanks', blanks, ['total'], ''' + select (sum(r.n) over()) as total + ''', [[0], [0]]) + } + + @Test + void testPercentRankAgreesOnTheFrozenFormula() { + agreeOn('one_row', oneRow, ['pct'], ''' + select (percentRank() over(orderby r.n)) as pct + ''', [[1]]) + // ranks 1, 1, 3, 3, 5 over 5 rows: (rank - 1) / (size - 1) + agreeOn('scores', scores, ['n', 'pct'], ''' + orderby r.n + select r.n, (percentRank() over(orderby r.n)) as pct + ''', [[60, 0], [60, 0], [80, 0.5], [80, 0.5], [100, 1]]) + } + + @Test + void testEmptyFrameAverageStaysNull() { + agreeOn('running', running, ['mean'], ''' + orderby r.n + select (avg(r.n) over(orderby r.n rows 5, 6)) as mean + ''', [[null], [null], [null]]) + } + + @Test + void testRankFrameIsHonoredInMemoryAndRejectedBySql() { + def framed = ''' + orderby r.n + select r.n, (rank() over(orderby r.n rows 0, 0)) as rk + ''' + agree(collection(running, framed), [[10, 1], [20, 1], [30, 1]]) + agree(collection(running, ''' + orderby r.n + select r.n, (rank() over(orderby r.n)) as rk + '''), [[10, 1], [20, 2], [30, 3]]) + + def numbered = ''' + orderby r.n + select r.n, (rowNumber() over(orderby r.n rows 0, 0)) as rn + ''' + agree(collection(running, numbered), [[10, 0], [20, 1], [30, 2]]) + + def nativeRank = sqlError('native-sql', 'running', framed) + assert nativeRank.message.contains('does not accept') + assert nativeRank.message.contains('GINQ applies that frame') + def jooqRank = sqlError('jooq-sql', 'running', framed) + assert jooqRank.message.contains('does not accept') + assert jooqRank.message.contains('GINQ applies that frame') + + def nativeNumber = sqlError('native-sql', 'running', numbered) + assert nativeNumber.message.contains('does not accept') + assert !nativeNumber.message.contains('GINQ applies that frame') + def jooqNumber = sqlError('jooq-sql', 'running', numbered) + assert jooqNumber.message.contains('does not accept') + assert !jooqNumber.message.contains('GINQ applies that frame') + } + + @Test + void testRankWithoutOrderByIsNullInMemoryAndRejectedBySql() { + agree(collection(running, ''' + select (rank() over()) as rk, + (denseRank() over()) as dense, + (percentRank() over()) as pct, + (cumeDist() over()) as cume + '''), [[null, null, null, null], [null, null, null, null], [null, null, null, null]]) + + def rank = 'select (rank() over())' + assert sqlError('native-sql', 'running', rank).message.contains('needs `orderby`') + assert sqlError('jooq-sql', 'running', rank).message.contains('needs `orderby`') + + def percent = 'select (percentRank() over(partitionby r.n))' + assert sqlError('native-sql', 'running', percent).message.contains('needs `orderby`') + assert sqlError('jooq-sql', 'running', percent).message.contains('needs `orderby`') + } + + private void agreeOn(String table, List source, List columns, String clauses, List expected) { + agree(collection(source, clauses), expected) + agree(project(query('native-sql', table, clauses), columns), expected) + agree(project(query('jooq-sql', table, clauses), columns), expected) + } + + private List collection(List source, String clauses) { + evaluate(""" + GQ { + from r in rows + ${clauses} + }.toList() + """, [rows: source]) + } + + private List query(String provider, String table, String clauses) { + String call = provider == 'jooq-sql' + ? "GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db)" + : "GQL(provider: 'native-sql', dataSource: db)" + evaluate(""" + ${call} { + from r in '${checked(table)}' + ${clauses} + } + """, [db: db]) + } + + private static Throwable sqlError(String provider, String table, String clauses) { + String call = provider == 'jooq-sql' + ? "GQL(provider: 'jooq-sql', dialect: 'H2', dataSource: db)" + : "GQL(provider: 'native-sql', dataSource: db)" + shouldFail """ + ${call} { + from r in '${checked(table)}' + ${clauses} + } + """ + } + + private static Object evaluate(String script, Map binding) { + new GroovyShell(new Binding(binding)).evaluate(script) + } + + private static List project(List rows, List columns) { + rows.collect { row -> columns.collect { name -> row[name] } } + } + + private static String checked(String table) { + assert table ==~ /[A-Za-z_][A-Za-z0-9_]*/ + table + } + + private void store(String name, List values) { + db.execute "create table ${checked(name)} (n int)".toString() + values.each { row -> + db.execute "insert into ${checked(name)} (n) values (?)", [row.n] + } + } + + private static List rows(int... values) { + values.collect { [n: it] } + } + + private static void agree(List actual, List expected) { + assert expected.size() == actual.size() + expected.eachWithIndex { Object want, int i -> + same(want, actual[i]) + } + } + + private static void same(Object want, Object got) { + if (want instanceof List) { + List wanted = (List) want + List found = got instanceof List ? (List) got : got.toList() + assert wanted.size() == found.size() + wanted.eachWithIndex { Object cell, int j -> same(cell, found[j]) } + return + } + if (want == null) { + assert got == null + return + } + if (want instanceof Number) { + assert got instanceof Number + assert (((Number) want) as BigDecimal).subtract(((Number) got) as BigDecimal).abs() < 0.0000001G + return + } + assert want == got + } +} 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..a6c0ff56090 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlFunctionRegistryTest.groovy @@ -0,0 +1,319 @@ +/* + * 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 + assert 'ROW_NUMBER' == registry.find('rowNumber', SqlFunctionMapping.Kind.WINDOW).sqlName + assert 'MIN' == registry.find('min', SqlFunctionMapping.Kind.WINDOW).sqlName + assert 'LEAST' == registry.find('min', SqlFunctionMapping.Kind.MATH).sqlName + assert registry.find('rowNumber', SqlFunctionMapping.Kind.FREE) == null + assert registry.find('median', SqlFunctionMapping.Kind.WINDOW) == null + assert registry.find('stdev', SqlFunctionMapping.Kind.WINDOW) == null + assert registry.find('agg', SqlFunctionMapping.Kind.WINDOW) == 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 testWindowKindStaysSeparateFromScalars() { + def standard = SqlFunctionRegistry.standard() + assert 'ROW_NUMBER' == standard.find('rowNumber', SqlFunctionMapping.Kind.WINDOW).sqlName + assert 'LEAD' == standard.find('lead', SqlFunctionMapping.Kind.WINDOW).sqlName + assert 'NTILE' == standard.find('ntile', SqlFunctionMapping.Kind.WINDOW).sqlName + assert 'COUNT' == standard.find('count', SqlFunctionMapping.Kind.WINDOW).sqlName + assert standard.find('rowNumber', SqlFunctionMapping.Kind.FREE) == null + assert standard.find('lead', SqlFunctionMapping.Kind.RECEIVER) == null + assert 'LEAST' == standard.find('min', SqlFunctionMapping.Kind.MATH).sqlName + assert 'MIN' == standard.find('min', SqlFunctionMapping.Kind.WINDOW).sqlName + assert SqlFunctionMapping.WindowForm.ZERO_BASED == standard.find('rowNumber', SqlFunctionMapping.Kind.WINDOW).windowForm() + assert SqlFunctionMapping.WindowForm.PLAIN == SqlFunctionMapping.window('myNumber', 'ROW_NUMBER').windowForm() + + def call = callX(varX('this'), 'rowNumber') + def expr = standard.find('rowNumber', SqlFunctionMapping.Kind.WINDOW).translate(call, [], recordingSite()) + assert expr instanceof SqlFunction + assert 'ROW_NUMBER' == expr.name + assert expr.args.empty + + def extra = standard.copy() + extra.register(SqlFunctionMapping.window('myNumber', 'ROW_NUMBER')) + assert 'ROW_NUMBER' == extra.find('myNumber', SqlFunctionMapping.Kind.WINDOW).sqlName + assert standard.find('myNumber', SqlFunctionMapping.Kind.WINDOW) == null + + def duplicate = shouldFail(IllegalArgumentException) { + extra.register(SqlFunctionMapping.window('rowNumber', 'RANK')) + } + assert duplicate.message.contains('already registered') + assert duplicate.message.contains('WINDOW') + + def sealed = shouldFail(IllegalStateException) { + standard.register(SqlFunctionMapping.window('myRank', 'RANK')) + } + assert sealed.message.contains('sealed') + + def injected = shouldFail(IllegalArgumentException) { + extra.register(SqlFunctionMapping.window('customTile', 'NTILE; DROP')) + } + assert injected.message.contains('uppercase identifier') + } + + @Test + void testPublicFactoriesKeepArityAndTranslate() { + def fixed = SqlFunctionMapping.receiver('replace', 'REPLACE', 2) + assert fixed.groovyName == 'replace' + assert fixed.kind == SqlFunctionMapping.Kind.RECEIVER + def replaced = fixed.translate(callX(propX(varX('e'), 'name'), 'replace'), + [constX('a'), constX('b')], recordingSite()) + assert replaced instanceof SqlFunction + assert 'REPLACE' == replaced.name + assert 3 == replaced.args.size() + def fixedArity = shouldFail(IllegalArgumentException) { + fixed.translate(callX(propX(varX('e'), 'name'), 'replace'), [constX('a')], recordingSite()) + } + assert fixedArity.message.contains('`replace` expects 2 arguments') + + def ranged = SqlFunctionMapping.receiver('round', 'ROUND', 0, 1) + def rounded = ranged.translate(callX(propX(varX('e'), 'salary'), 'round'), [], recordingSite()) + assert rounded instanceof SqlFunction + assert 'ROUND' == rounded.name + assert 1 == rounded.args.size() + def rangedArity = shouldFail(IllegalArgumentException) { + ranged.translate(callX(propX(varX('e'), 'salary'), 'round'), [constX(1), constX(2)], recordingSite()) + } + assert rangedArity.message.contains('`round` expects 0 to 1 arguments') + + def free = SqlFunctionMapping.freeFunction('coalesce', 'COALESCE', 2, Integer.MAX_VALUE) + assert free.kind == SqlFunctionMapping.Kind.FREE + def coalesced = free.translate(callX(varX('this'), 'coalesce'), + [propX(varX('e'), 'name'), constX('x')], recordingSite()) + assert coalesced instanceof SqlFunction + assert 'COALESCE' == coalesced.name + assert 2 == coalesced.args.size() + + def math = SqlFunctionMapping.math('max', 'GREATEST') + assert math.kind == SqlFunctionMapping.Kind.MATH + def greatest = math.translate(callX(varX('Math'), 'max'), + [propX(varX('e'), 'salary'), constX(1)], recordingSite()) + assert greatest instanceof SqlFunction + assert 'GREATEST' == greatest.name + + def window = SqlFunctionMapping.window('nthValue', 'NTH_VALUE', 1, 2) + assert window.kind == SqlFunctionMapping.Kind.WINDOW + def nth = window.translate(callX(varX('this'), 'nthValue'), + [propX(varX('e'), 'name'), constX(1)], recordingSite()) + assert nth instanceof SqlFunction + assert 'NTH_VALUE' == nth.name + def windowArity = shouldFail(IllegalArgumentException) { + SqlFunctionMapping.window('lead', 'LEAD', 1, 3, 'lead takes 1 to 3 arguments') + .translate(callX(varX('this'), 'lead'), [], recordingSite()) + } + assert windowArity.message == 'lead takes 1 to 3 arguments' + + def missingForm = shouldFail(IllegalArgumentException) { + SqlFunctionMapping.window('lead', 'LEAD', 1, 3, null, null) + } + assert missingForm.message.contains('window mapping needs a form') + } + + @Test + void testConcatIsEmptyAndRejectedNames() { + def site = recordingSite() + def concat = SqlFunctionRegistry.standard().find('concat', SqlFunctionMapping.Kind.RECEIVER) + def joined = concat.translate(callX(propX(varX('e'), 'name'), 'concat'), [constX('!')], site) + assert joined instanceof SqlBinary + assert '||' == joined.op + + def concatArity = shouldFail(IllegalArgumentException) { + concat.translate(callX(propX(varX('e'), 'name'), 'concat'), [], site) + } + assert concatArity.message.contains('one argument') + + def empty = SqlFunctionRegistry.standard().find('isEmpty', SqlFunctionMapping.Kind.RECEIVER) + def blank = empty.translate(callX(propX(varX('e'), 'name'), 'isEmpty'), [], site) + assert blank instanceof SqlBinary + assert '=' == blank.op + + def emptyArity = shouldFail(IllegalArgumentException) { + empty.translate(callX(propX(varX('e'), 'name'), 'isEmpty'), [constX(1)], site) + } + assert emptyArity.message.contains('no arguments') + + def badName = shouldFail(IllegalArgumentException) { + SqlFunctionMapping.receiver('1bad', 'UPPER') + } + assert badName.message.contains('1bad') + + def badRange = shouldFail(IllegalArgumentException) { + SqlFunctionMapping.receiver('round', 'ROUND', 2, 1) + } + assert badRange.message.contains('2..1') + + def open = SqlFunctionMapping.freeFunction('coalesce', 'COALESCE', 2, Integer.MAX_VALUE) + def tooFew = shouldFail(IllegalArgumentException) { + open.translate(callX(varX('this'), 'coalesce'), [constX(1)], site) + } + assert tooFew.message.contains('at least 2') + } + + @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/SqlIrRenderingTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlIrRenderingTest.groovy new file mode 100644 index 00000000000..b104757150a --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlIrRenderingTest.groovy @@ -0,0 +1,247 @@ +/* + * 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.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.SqlExists +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.SqlUnary +import org.apache.groovy.ginq.provider.sql.ir.SqlWindow +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowBound +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame +import org.apache.groovy.ginq.provider.sql.jooq.JooqRenderer +import org.apache.groovy.ginq.provider.sql.render.AnsiDialect +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 + +class SqlIrRenderingTest { + + @Test + void fullJoinRewriteKeepsPredicatesInsideTheUnion() { + SqlQuery probe = new SqlQuery() + probe.from = new SqlTableRef('departments', 'd') + probe.projections << new SqlProjection(new SqlFunction('COUNT', [new SqlColumn('d', 'id')], true)) + + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.joins << new SqlJoin(SqlJoin.Type.FULL, new SqlTableRef('departments', 'd'), + new SqlBinary('=', col('e', 'deptId'), col('d', 'id'))) + query.where = new SqlBinary('AND', + new SqlUnary('NOT', new SqlIsNull(col('e', 'name'), false)), + new SqlBinary('AND', + new SqlLike(col('e', 'name'), new SqlParam(new ConstantExpression('%a%'))), + new SqlBinary('AND', + new SqlIn(col('e', 'salary'), [new SqlLiteral(4000), new SqlLiteral(5000)], false), + new SqlBinary('OR', + new SqlExists(probe), + new SqlBinary('=', col('e', 'salary'), + new SqlScalarQuery(countStar('employees', 'z'))))))) + query.projections << new SqlProjection(new SqlCaseWhen( + new SqlBinary('>', col('e', 'salary'), new SqlLiteral(4000)), + new SqlCast(col('e', 'name'), 'VARCHAR'), + new SqlLiteral('low')), 'label') + query.projections << new SqlProjection(new SqlFunction('UPPER', [col('e', 'name')])) + query.groupBy << col('e', 'name') + query.having = new SqlBinary('>', new SqlCountStar(), new SqlLiteral(0)) + query.orderBy << new SqlOrderSpec(col('e', 'name'), false, false) + query.fetch = new SqlLiteral(5) + + String sql = render(MixedSourceLayout.layoutComplete(query)) + String upper = sql.toUpperCase(Locale.ROOT) + assert upper.contains('UNION ALL') + assert !upper.contains('FULL OUTER JOIN') + assert upper.contains('NOT ') + assert upper.contains('LIKE') + assert upper.contains(' IN (') + assert upper.contains('EXISTS') + assert upper.contains('CASE') + assert upper.contains('CAST') + assert upper.contains('UPPER') + assert upper.contains('GROUP BY') + assert upper.contains('HAVING') + assert upper.contains('ORDER BY') + assert upper.contains('FETCH') + } + + @Test + void setQueryCopiesOnlyTheSideWhoseFullJoinChanged() { + SqlQuery plain = new SqlQuery() + plain.from = new SqlTableRef('employees', 'a') + plain.projections << new SqlProjection(col('a', 'name')) + + SqlSetQuery set = new SqlSetQuery(plain, SqlSetQuery.SetOp.UNION, fullJoin()) + set.orderBy << new SqlOrderSpec(new SqlOrdinal(1), true, true) + set.offset = new SqlLiteral(1) + set.fetch = new SqlLiteral(2) + + SqlQueryNode laid = MixedSourceLayout.layoutComplete(set) + assert laid instanceof SqlSetQuery + String sql = render(laid) + assert sql.toUpperCase(Locale.ROOT).contains('UNION ALL') + assert sql.toUpperCase(Locale.ROOT).contains('UNION') + assert sql.toUpperCase(Locale.ROOT).contains('ORDER BY') + assert sql.toUpperCase(Locale.ROOT).contains('OFFSET') + assert !sql.toUpperCase(Locale.ROOT).contains('FULL OUTER JOIN') + } + + @Test + void inQueryAndStarAreRewrittenWithTheOuterFullJoin() { + SqlQuery inner = new SqlQuery() + inner.from = new SqlTableRef('departments', 'd2') + inner.projections << new SqlProjection(col('d2', 'id')) + inner.where = new SqlBinary('=', col('d2', 'id'), col('e', 'deptId')) + + SqlQuery query = fullJoin() + query.where = new SqlInQuery(col('e', 'deptId'), inner, true) + query.projections.clear() + query.projections << new SqlProjection(new SqlStar('e')) + query.projections << new SqlProjection(col('d', 'name'), 'dn') + + String sql = render(MixedSourceLayout.layoutComplete(query)) + String upper = sql.toUpperCase(Locale.ROOT) + assert upper.contains('NOT IN') || upper.contains('NOT (') + assert upper.contains('UNION ALL') + assert !upper.contains('FULL OUTER JOIN') + } + + @Test + void jooqRendersEachFrameBoundAndEachSetOperator() { + String rows = jooq(windowQuery(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.preceding(new SqlLiteral(1)), + SqlWindowBound.following(new SqlLiteral(0)))) + assert rows.toLowerCase(Locale.ROOT).contains('rows between 1 preceding and current row') + + String range = jooq(windowQuery(SqlWindowFrame.Unit.RANGE, + SqlWindowBound.unboundedPreceding(), + SqlWindowBound.unboundedFollowing())) + assert range.toLowerCase(Locale.ROOT).contains('range between unbounded preceding and unbounded following') + + String current = jooq(windowQuery(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.currentRow(), + SqlWindowBound.currentRow())) + assert current.toLowerCase(Locale.ROOT).contains('rows between current row and current row') + + Map words = [ + (SqlSetQuery.SetOp.UNION) : 'union', + (SqlSetQuery.SetOp.UNION_ALL) : 'union all', + (SqlSetQuery.SetOp.INTERSECT) : 'intersect', + (SqlSetQuery.SetOp.MINUS) : 'except' + ] + for (SqlSetQuery.SetOp op : SqlSetQuery.SetOp.values()) { + SqlSetQuery set = new SqlSetQuery(plain('a'), op, plain('b')) + set.orderBy << new SqlOrderSpec(new SqlOrdinal(1), false, true) + set.offset = new SqlParam(new ConstantExpression(1)) + set.fetch = new SqlParam(new ConstantExpression(2)) + String sql = JooqRenderer.render(set, 'H2').sql.toLowerCase(Locale.ROOT) + assert sql.contains(words[op]) + assert sql.contains('order by') + assert sql.contains('offset') + } + + String following = jooq(windowQuery(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.following(new SqlLiteral(1)), + SqlWindowBound.preceding(new SqlLiteral(2)))) + assert following.toLowerCase(Locale.ROOT).contains('1 following') + assert following.toLowerCase(Locale.ROOT).contains('2 preceding') + + def fraction = shouldFail(IllegalArgumentException) { + jooq(windowQuery(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.preceding(new SqlLiteral(1.5d)), + SqlWindowBound.currentRow())) + } + assert fraction.message.contains('Java int') + + assert '`' as char == JooqRenderer.identifierQuote('MYSQL') + assert '"' as char == JooqRenderer.identifierQuote('H2') + assert !FunctionSupport.supports('h2', '') + assert !FunctionSupport.supports('h2', null) + assert 'postgres' == FunctionSupport.canonical('PostgreSQL') + assert 'oracle' == FunctionSupport.canonical('Oracle') + } + + private static SqlQuery fullJoin() { + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.joins << new SqlJoin(SqlJoin.Type.FULL, new SqlTableRef('departments', 'd'), + new SqlBinary('=', col('e', 'deptId'), col('d', 'id'))) + query.projections << new SqlProjection(col('e', 'name'), 'en') + return query + } + + private static SqlQuery plain(String alias) { + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef('employees', alias) + query.projections << new SqlProjection(col(alias, 'name')) + return query + } + + private static SqlQuery countStar(String table, String alias) { + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef(table, alias) + query.projections << new SqlProjection(new SqlCountStar()) + return query + } + + private static SqlQuery windowQuery(SqlWindowFrame.Unit unit, SqlWindowBound lower, SqlWindowBound upper) { + SqlQuery query = plain('e') + SqlWindow window = new SqlWindow( + [col('e', 'deptId')], + [new SqlOrderSpec(col('e', 'salary'), true, true)], + new SqlWindowFrame(unit, lower, upper)) + query.projections << new SqlProjection(new SqlWindowCall( + new SqlFunction('SUM', [col('e', 'salary')]), window), 'near') + return query + } + + private static SqlColumn col(String alias, String name) { + new SqlColumn(alias, name) + } + + private static String render(SqlQueryNode node) { + new SqlRenderer(new AnsiDialect()).render(node).sql + } + + private static String jooq(SqlQueryNode node) { + JooqRenderer.render(node, 'H2').sql + } +} 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..25b5b444d10 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlRendererTest.groovy @@ -0,0 +1,437 @@ +/* + * 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') + } + + @Test + void testOffsetOnlyLimitSyntheticNamesAndRealDivision() { + def query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.offset = param(4) + query.projections << new SqlProjection(col('e', '__ginq_present'), '__ginq_label') + query.projections << new SqlProjection(new SqlBinary('/', col('e', 'salary'), param(2))) + + def mysql = new SqlRenderer(Dialects.resolve('mysql')).render(query) + assert mysql.sql.contains('LIMIT 18446744073709551615 OFFSET ?') + assert mysql.sql.contains('`__ginq_present`') + assert mysql.sql.contains('AS `__ginq_label`') + assert mysql.sql.contains('DOUBLE') + assert [2, 4] == values(mysql) || [4, 2] == values(mysql) + + def postgres = new SqlRenderer(Dialects.resolve('postgres')).render(query) + assert postgres.sql.contains('"__ginq_present"') + assert postgres.sql.contains('DOUBLE PRECISION') + + def sqlite = new SqlRenderer(Dialects.resolve('sqlite')).render(query) + assert sqlite.sql.contains('"__ginq_present"') + assert sqlite.sql.contains('REAL') + + assert null == Dialects.fromJdbcUrl(null) + assert 'sqlite' == Dialects.fromJdbcUrl(' jdbc:sqlite:mem:cov') + assert 'mysql' == Dialects.fromJdbcUrl('jdbc:mariadb://localhost/db') + assert null == Dialects.fromJdbcUrl('jdbc:oracle:thin:@localhost') + assert Dialects.resolve(null) instanceof AnsiDialect + assert Dialects.resolve('') instanceof AnsiDialect + assert 'mariadb' == Dialects.resolve('MariaDB').name() + } + + 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/SqlTranslationReachabilityTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlTranslationReachabilityTest.groovy new file mode 100644 index 00000000000..307faa81f98 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlTranslationReachabilityTest.groovy @@ -0,0 +1,441 @@ +/* + * 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.apache.groovy.ginq.dsl.GinqAstBuilder +import org.apache.groovy.ginq.dsl.expression.AbstractGinqExpression +import org.apache.groovy.ginq.dsl.expression.GinqExpression +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.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.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.SqlUnary +import org.apache.groovy.ginq.provider.sql.ir.SqlWindow +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowBound +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame +import org.apache.groovy.ginq.provider.sql.jooq.JooqRenderer +import org.apache.groovy.ginq.provider.sql.render.AnsiDialect +import org.apache.groovy.ginq.provider.sql.render.SqlRenderer +import org.apache.groovy.ginq.provider.sql.runtime.SqlGinqRuntime +import org.codehaus.groovy.ast.stmt.BlockStatement +import org.codehaus.groovy.ast.stmt.ExpressionStatement +import org.codehaus.groovy.control.CompilationUnit +import org.codehaus.groovy.control.Phases +import org.codehaus.groovy.control.SourceUnit +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test + +import java.sql.SQLException + +import static groovy.test.GroovyAssert.shouldFail + +class SqlTranslationReachabilityTest { + private Sql db + + @BeforeEach + void setUp() { + db = GinqSqlTestSupport.newPopulatedDb() + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void windowBoundsLiteralsErrorsAndDescendingRanges() { + String mirrored = sql(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary in desc range -2, 3)) + ''') + assert mirrored.toUpperCase(Locale.ROOT).contains('3 PRECEDING') + assert mirrored.toUpperCase(Locale.ROOT).contains('2 FOLLOWING') + + String unbounded = sql(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows null, 0)) + ''') + assert unbounded.toUpperCase(Locale.ROOT).contains('UNBOUNDED PRECEDING') + assert unbounded.toUpperCase(Locale.ROOT).contains('CURRENT ROW') + + String huge = sql(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.id rows -9223372036854775808, 9223372036854775807)) + ''') + assert huge.toUpperCase(Locale.ROOT).contains('UNBOUNDED PRECEDING') + assert huge.toUpperCase(Locale.ROOT).contains('UNBOUNDED FOLLOWING') + + assert failure(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows bound, 1)) + ''').contains('literals') + + assert failure(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows 2, -1)) + ''').contains('ends before it starts') + + assert failure(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows 1.5, 2)) + ''').contains('whole numbers') + } + + @Test + void operandKindsCastsAndRejectedOperators() { + String text = sql(''' + from e in 'employees' + where e.id == 1 + select e.name + '!' as label, (e.salary as double) as wide, (e.salary as BigDecimal) as money, + e.name.substring(1) as tail, e.name.length() + 1 as n + ''') + assert text.contains('||') + assert text.toUpperCase(Locale.ROOT).contains('DOUBLE') + assert text.toUpperCase(Locale.ROOT).contains('DECIMAL') + assert text.toUpperCase(Locale.ROOT).contains('SUBSTRING') + + String branches = sql(''' + from e in 'employees' + where e.id in [] || e.id !in [null] || !(e.name == null) + select e.salary > 1000 ? 'high' : e.name + ''') + assert branches.toUpperCase(Locale.ROOT).contains('CASE') + assert branches.contains('1 = 0') || branches.contains('1 = 1') + + assert failure(''' + from e in 'employees' + select e.name ?: 'missing' + ''').contains('Elvis') + + assert failure(''' + from e in 'employees' + where e.salary & 1 + select e.name + ''').contains('Operator') + + assert failure(''' + from e in 'employees' + select e.name.substring(1, 2, 3) + ''').contains('substring') + + assert failure(''' + from e in 'employees' + select e.name + e.salary + ''').contains('not translated') + } + + @Test + void setOperationsHoistMatchingOrderAndRejectTheRest() { + String ordered = sql(''' + from e in 'employees' + select e.name + union + from e in 'employees' + orderby e.name + select e.name + ''') + assert ordered.toUpperCase(Locale.ROOT).contains('UNION') + assert ordered.toUpperCase(Locale.ROOT).contains('ORDER BY 1') + + String minus = render(new SqlSetQuery(plain('a'), SqlSetQuery.SetOp.MINUS, plain('b'))) + assert minus.toUpperCase(Locale.ROOT).contains('EXCEPT') || minus.toUpperCase(Locale.ROOT).contains('MINUS') + + assert failure(''' + from e in 'employees' + select e.name + union + from e in 'employees' + orderby e.salary + select e.name + ''').contains('orderby') + + Parsed left = parse(''' + from e in 'employees' + select e.name + ''') + Parsed right = parse(''' + from d in 'departments' + select d.name + ''') + SetOperationExpression unknown = new SetOperationExpression(left.ginq, 'except', (GinqExpression) right.ginq) + def err = shouldFail { + new GinqSqlWalker(left.sourceUnit).translate(unknown) + } + assert err.message.contains('Unknown set operation') + } + + @Test + void jooqRendersCastTypesFunctionsAndRejectsANonLiteralOffset() { + for (String type : ['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', 'VARCHAR(12)', 'DECIMAL(10)', 'DECIMAL(10,2)']) { + String rendered = jooq(queryOf(new SqlCast(col('e', 'name'), type))).toUpperCase(Locale.ROOT) + assert rendered.contains('CAST') + String expected = type.takeWhile { it != '(' } + String fragment = expected == 'INTEGER' ? 'INT' + : expected == 'DOUBLE PRECISION' ? 'DOUBLE' + : expected == 'CHARACTER' ? 'CHAR' + : expected == 'CHARACTER VARYING' ? 'VARCHAR' + : expected + assert rendered.contains(fragment) + } + + assert jooq(queryOf(new SqlFunction('COALESCE', [col('e', 'name'), new SqlLiteral('x'), new SqlLiteral('y')]))) + .toLowerCase(Locale.ROOT).contains('coalesce') + assert jooq(queryOf(new SqlFunction('COUNT', [col('e', 'id')], true))) + .toLowerCase(Locale.ROOT).contains('distinct') + assert jooq(queryOf(new SqlFunction('SUBSTRING', [col('e', 'name'), new SqlLiteral(1)]))) + .toLowerCase(Locale.ROOT).contains('substring') + assert jooq(queryOf(new SqlFunction('MOD', [col('e', 'salary'), new SqlLiteral(2)]))) + .toLowerCase(Locale.ROOT).contains('mod') + assert jooq(queryOf(new SqlFunction('ROUND', [col('e', 'salary'), new SqlLiteral(2)]))) + .toLowerCase(Locale.ROOT).contains('round') + assert JooqRenderer.render(queryOf(new SqlFunction('POSITION', [new SqlLiteral('a'), col('e', 'name')])), 'SQLITE') + .sql.toLowerCase(Locale.ROOT).contains('instr') + assert JooqRenderer.render(queryOf(new SqlFunction('GREATEST', [col('e', 'salary'), new SqlLiteral(1), new SqlLiteral(2)])), 'SQLITE') + .sql.toLowerCase(Locale.ROOT).contains('max') + assert JooqRenderer.render(queryOf(new SqlFunction('POSITION', [new SqlLiteral('a'), col('e', 'name')])), 'MYSQL') + .sql.toLowerCase(Locale.ROOT).contains('locate') + + SqlQuery window = plain('e') + window.projections << new SqlProjection(new SqlWindowCall( + new SqlFunction('SUM', [col('e', 'salary')]), + new SqlWindow([], [], new SqlWindowFrame(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.preceding(col('e', 'n')), + SqlWindowBound.currentRow()))), 'near') + def offset = shouldFail { + JooqRenderer.render(window, 'H2') + } + assert offset.message.contains('integer literal') || offset.message.contains('offset') + + String custom = jooq(queryOf(new SqlFunction('NOT_A_FUNC', [col('e', 'name')]))) + assert custom.toLowerCase(Locale.ROOT).contains('not_a_func') + + String chars = render(queryOf(new SqlLiteral('a\'b' as Character))) + assert chars.contains("'a'") || chars.contains("a") + String flag = render(queryOf(new SqlLiteral(Boolean.TRUE))) + assert flag.toUpperCase(Locale.ROOT).contains('TRUE') + + SqlQuery inner = plain('i') + SqlQuery outer = new SqlQuery() + outer.from = new SqlDerivedTable(new SqlSetQuery(inner, SqlSetQuery.SetOp.UNION, plain('j')), 'u') + outer.projections << new SqlProjection(new SqlStar('u')) + String derived = render(outer) + assert derived.toUpperCase(Locale.ROOT).contains('UNION') + assert derived.contains('(') + } + + @Test + void mixedModeRejectsMalformedSqlAndRebuildsRows() { + assert message('SELECT a.* FROM (SELECT 1').contains('unclosed parenthesis') + assert message('SELECT a.* FROM "employees a').contains('unclosed quoted') + assert message('SELECT a.* FROM hr.+ a').contains('dangling qualifier') + assert message('SELECT a.* FROM employees').contains('no alias') + assert message('SELECT a.* FROM ').contains('missing a source') + assert message('SELECT a.* FROM .t a').contains('no table name') + + String expanded = SqlGinqRuntime.expandAndExecute(db, + 'select q.__ginqcol_0_name from (select name as "__ginqstarcol_0_name" from employees where id = ?) q', + [1], [['name']], '"').toList() + assert expanded.toString().contains('Alice') + + def outside = shouldFail(SQLException) { + SqlGinqRuntime.expandAndExecute(db, 'select q.__ginqsrc_3 from employees q', [], [['name']], '"') + } + assert outside.message.contains('outside the column layout') + + def unknown = shouldFail(SQLException) { + SqlGinqRuntime.expandAndExecute(db, 'select q.__ginqcol_0_missing from employees q', [], [['name']], '"') + } + assert unknown.message.contains('unknown column') + + def blank = shouldFail(SQLException) { + SqlGinqRuntime.prepareMixedSql( + 'SELECT __ginq_src.*, 1 AS __ginq_marker FROM employees __ginq_src WHERE __ginqref_0_', + [['id']], '"' as char) + } + assert blank.message.contains('blank') || blank.message.contains('unknown') + + assert SqlGinqRuntime.columnCount(db, 'select id, name from employees where id = ?', [1]) == 2 + + def zipped = SqlGinqRuntime.zipAliases(db, + 'SELECT e.*, d.* FROM employees e LEFT JOIN departments d ON e.deptId = d.id WHERE e.id = ?', + [4], + [['id', 'name', 'salary', 'deptId'], ['id', 'name']], + '') + assert zipped[0][0].get('name') == 'Dave' + assert zipped[1][0] == null + assert SqlGinqRuntime.mixedOrdinal(zipped[0][0]) == 0 + } + + @Test + void nestedFullJoinsRewriteEveryExpressionShape() { + SqlQuery nested = new SqlQuery() + nested.from = new SqlTableRef('offices', 'o') + nested.projections << new SqlProjection(col('o', 'id')) + nested.where = new SqlBinary('=', col('e', 'id'), col('o', 'id')) + + SqlQuery query = new SqlQuery() + query.distinct = true + query.from = new SqlTableRef('employees', 'e') + query.joins << new SqlJoin(SqlJoin.Type.FULL, new SqlTableRef('departments', 'd'), + new SqlBinary('=', col('e', 'deptId'), col('d', 'id'))) + query.joins << new SqlJoin(SqlJoin.Type.FULL, new SqlDerivedTable(plain('o'), 'off'), + new SqlBinary('=', col('e', 'id'), col('off', 'id'))) + query.where = new SqlBinary('AND', + new SqlUnary('NOT', new SqlIsNull(col('e', 'name'), false)), + new SqlBinary('OR', + new SqlLike(col('e', 'name'), new SqlLiteral('%a%')), + new SqlIn(col('e', 'salary'), [new SqlLiteral(1), col('e', 'salary')], false))) + query.projections << new SqlProjection(new SqlCaseWhen( + new SqlBinary('>', col('e', 'salary'), new SqlLiteral(0)), + new SqlCast(new SqlFunction('UPPER', [col('e', 'name')], true), 'VARCHAR'), + new SqlLiteral('x')), 'label') + query.projections << new SqlProjection(new SqlExists(nested)) + query.projections << new SqlProjection(new SqlScalarQuery(plain('s'))) + query.groupBy << col('e', 'deptId') + query.having = new SqlBinary('>', col('e', 'salary'), new SqlLiteral(0)) + query.orderBy << new SqlOrderSpec(col('e', 'name'), true, true) + query.fetch = new SqlLiteral(3) + + String laid = render(MixedSourceLayout.layoutComplete(query)) + String upper = laid.toUpperCase(Locale.ROOT) + assert upper.contains('UNION ALL') + assert !upper.contains('FULL OUTER JOIN') + assert upper.contains('__GINQ') + assert upper.contains('EXISTS') + assert upper.contains('CASE') + assert upper.contains('LIKE') + + SqlSetQuery both = new SqlSetQuery(query, SqlSetQuery.SetOp.INTERSECT, fullOf('x', 'y')) + String copied = render(MixedSourceLayout.layoutComplete(both)) + assert copied.toUpperCase(Locale.ROOT).contains('INTERSECT') + assert copied.toUpperCase(Locale.ROOT).count('UNION ALL') >= 2 + } + + private static SqlQuery fullOf(String leftAlias, String rightAlias) { + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef('employees', leftAlias) + query.joins << new SqlJoin(SqlJoin.Type.FULL, new SqlTableRef('departments', rightAlias), + new SqlBinary('=', col(leftAlias, 'id'), col(rightAlias, 'id'))) + query.projections << new SqlProjection(col(leftAlias, 'name')) + return query + } + + private static String message(String sqlText) { + def err = shouldFail { + SqlGinqRuntime.prepareMixedSql(sqlText, [['id']], '"' as char) + } + return err.message + } + + private static String sql(String query) { + Parsed parsed = parse(query) + SqlQueryNode node = new GinqSqlWalker(parsed.sourceUnit).translate(parsed.ginq) + assert parsed.sourceUnit.errorCollector.errorCount == 0 + return render(node) + } + + private static String failure(String query) { + Parsed parsed = parse(query) + def err = shouldFail { + new GinqSqlWalker(parsed.sourceUnit).translate(parsed.ginq) + } + return err.message + } + + private static Parsed parse(String query) { + String code = """ + def hello() { + def gqc = { + ${query} + } + } + """ + SourceUnit sourceUnit + def ast = new CompilationUnit().tap { + sourceUnit = addSource('reach.groovy', code) + compile(Phases.CONVERSION) + }.ast + def method = ast.classes[0].methods.find { it.name == 'hello' } + ExpressionStatement statement = (ExpressionStatement) ((BlockStatement) method.code).statements[0] + def declaration = statement.expression + def closure = declaration.rightExpression + AbstractGinqExpression built = new GinqAstBuilder(sourceUnit).buildAST(closure.code) + return new Parsed(sourceUnit, built) + } + + private static SqlQuery plain(String alias) { + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef('employees', alias) + query.projections << new SqlProjection(col(alias, 'name')) + return query + } + + private static SqlQuery queryOf(SqlExpr expr) { + SqlQuery query = plain('e') + query.projections.clear() + query.projections << new SqlProjection(expr) + return query + } + + private static SqlColumn col(String alias, String name) { + new SqlColumn(alias, name) + } + + private static String render(SqlQueryNode node) { + new SqlRenderer(new AnsiDialect()).render(node).sql + } + + private static String jooq(SqlQueryNode node) { + JooqRenderer.render(node, 'H2').sql + } + + private static final class Parsed { + final SourceUnit sourceUnit + final AbstractGinqExpression ginq + + private Parsed(SourceUnit sourceUnit, AbstractGinqExpression ginq) { + this.sourceUnit = sourceUnit + this.ginq = ginq + } + } +} diff --git a/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlWindowTranslationTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlWindowTranslationTest.groovy new file mode 100644 index 00000000000..e41573dbff4 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/SqlWindowTranslationTest.groovy @@ -0,0 +1,762 @@ +/* + * 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.dsl.GinqAstBuilder +import org.apache.groovy.ginq.dsl.expression.AbstractGinqExpression +import org.apache.groovy.ginq.dsl.expression.GinqExpression +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.SqlColumn +import org.apache.groovy.ginq.provider.sql.ir.SqlCountStar +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.SqlLiteral +import org.apache.groovy.ginq.provider.sql.ir.SqlOrderSpec +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.SqlTableRef +import org.apache.groovy.ginq.provider.sql.ir.SqlWindow +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowBound +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowCall +import org.apache.groovy.ginq.provider.sql.ir.SqlWindowFrame +import org.apache.groovy.ginq.provider.sql.jooq.JooqRenderer +import org.apache.groovy.ginq.provider.sql.render.AnsiDialect +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.ClosureExpression +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.DeclarationExpression +import org.codehaus.groovy.ast.stmt.BlockStatement +import org.codehaus.groovy.ast.stmt.ExpressionStatement +import org.codehaus.groovy.control.CompilationUnit +import org.codehaus.groovy.control.MultipleCompilationErrorsException +import org.codehaus.groovy.control.Phases +import org.codehaus.groovy.control.SourceUnit +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.shouldFail + +/** + * Built-in window functions translate to {@code OVER}. A copy of the registry + * can still add a plain mapping; that mapping is not rewritten with the + * built-in adjustments. + */ +class SqlWindowTranslationTest { + + @Test + void testWalkerBuildsOverForARegisteredWindowFunction() { + def parsed = parse(''' + from e in 'nums' + select (rowNumber() over(orderby n)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + + assert query.projections.size() == 1 + assert query.projections[0].expr instanceof SqlBinary + SqlBinary adjusted = (SqlBinary) query.projections[0].expr + assert '-' == adjusted.op + assert adjusted.right instanceof SqlLiteral + assert 1 == adjusted.right.value + assert adjusted.left instanceof SqlWindowCall + SqlWindowCall call = (SqlWindowCall) adjusted.left + assert call.function instanceof SqlFunction + assert 'ROW_NUMBER' == call.function.name + assert call.function.args.empty + assert call.window.partitionBy.empty + assert call.window.frame == null + assert 1 == call.window.orderBy.size() + assert call.window.orderBy[0].asc + assert call.window.orderBy[0].nullsLast + assert call.window.orderBy[0].expr instanceof SqlParam + assert 'n' == call.window.orderBy[0].expr.valueExpr.text + assert query.orderBy.empty + + def ansi = new SqlRenderer(new AnsiDialect()).render(query) + assert 'SELECT ROW_NUMBER() OVER (ORDER BY ? ASC NULLS LAST) - 1 FROM nums e' == ansi.sql + assert ['n'] == ansi.parameters*.text + + def mysql = new SqlRenderer(Dialects.resolve('mysql')).render(query) + assert 'SELECT ROW_NUMBER() OVER (ORDER BY (? IS NULL) ASC, ? ASC) - 1 FROM `nums` `e`' == mysql.sql + assert ['n', 'n'] == mysql.parameters*.text + + def jooq = JooqRenderer.render(query, 'H2').sql + assert 'select (ROW_NUMBER() over (order by ? asc nulls last) - 1) from nums e' == jooq + } + + @Test + void testEmptyOverRendersEmptyParentheses() { + def parsed = parse(''' + from e in 'nums' + select (rowNumber() over()) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + SqlBinary adjusted = (SqlBinary) query.projections[0].expr + SqlWindowCall call = (SqlWindowCall) adjusted.left + assert call.window.partitionBy.empty + assert call.window.orderBy.empty + assert call.window.frame == null + assert 'SELECT ROW_NUMBER() OVER () - 1 FROM nums e' == new SqlRenderer(new AnsiDialect()).render(query).sql + assert 'select (ROW_NUMBER() over () - 1) from nums e' == JooqRenderer.render(query, 'H2').sql + } + + @Test + void testPartitionOrderAndRowsFrame() { + def registry = plainRegistry() + def parsed = parse(''' + from e in 'employees' + select (myNumber() over(partitionby e.deptId, e.name.toUpperCase() orderby e.salary in desc rows -1, 1)), + (mySum(e.salary) over(orderby e.salary range null, 0)) + ''') + def query = translate(parsed, registry) + assert noErrors(parsed) + + SqlWindowCall rowNumber = (SqlWindowCall) query.projections[0].expr + assert 'ROW_NUMBER' == rowNumber.function.name + assert rowNumber.window.partitionBy[0] instanceof SqlColumn + assert 'deptId' == rowNumber.window.partitionBy[0].column + assert rowNumber.window.partitionBy[1] instanceof SqlFunction + assert 'UPPER' == rowNumber.window.partitionBy[1].name + assert !rowNumber.window.orderBy[0].asc + assert rowNumber.window.orderBy[0].nullsLast + assert SqlWindowFrame.Unit.ROWS == rowNumber.window.frame.unit + assert SqlWindowBound.Kind.PRECEDING == rowNumber.window.frame.lower.kind + assert 1 == rowNumber.window.frame.lower.offset.value + assert SqlWindowBound.Kind.FOLLOWING == rowNumber.window.frame.upper.kind + assert 1 == rowNumber.window.frame.upper.offset.value + + SqlWindowCall sum = (SqlWindowCall) query.projections[1].expr + assert 'SUM' == sum.function.name + assert sum.function.args[0] instanceof SqlColumn + assert SqlWindowFrame.Unit.RANGE == sum.window.frame.unit + assert SqlWindowBound.Kind.UNBOUNDED_PRECEDING == sum.window.frame.lower.kind + assert SqlWindowBound.Kind.CURRENT_ROW == sum.window.frame.upper.kind + + def ansi = new SqlRenderer(new AnsiDialect()).render(query) + assert 'SELECT ROW_NUMBER() OVER (PARTITION BY e.deptId, UPPER(e.name) ORDER BY e.salary DESC NULLS LAST ' + + 'ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING), ' + + 'SUM(e.salary) OVER (ORDER BY e.salary ASC NULLS LAST ' + + 'RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) FROM employees e' == ansi.sql + + def jooq = JooqRenderer.render(query, 'H2').sql + assert 'select ROW_NUMBER() over (partition by e.deptId, upper(e.name) order by e.salary desc nulls last ' + + 'rows between 1 preceding and 1 following), ' + + 'sum(e.salary) over (order by e.salary asc nulls last ' + + 'range between unbounded preceding and current row) from employees e' == jooq + } + + @Test + void testUnregisteredOverStaysDeferred() { + def parsed = parse(''' + from e in 'employees' + select (median(e.salary) over(partitionby e.deptId)), (stdev(e.salary) over(orderby e.salary)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + 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 testRegisteredWindowRejectsANonLiteralFrameBound() { + def parsed = parse(''' + from e in 'employees' + select (rowNumber() over(orderby e.salary rows bound, 1)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + assert err.message.contains('window frame bounds must be literals') + assert !err.message.contains('window functions are deferred') + } + + @Test + void testRegisteredWindowRejectsRowsAndRangeTogether() { + def parsed = parse(''' + from e in 'employees' + select (rowNumber() over(orderby e.salary rows -1, 1 range -1, 0)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + assert err.message.contains('`rows` and `range` cannot both be used in one `over`') + } + + @Test + void testRendererContractForFramesAndCountStar() { + def countStar = queryOf(new SqlWindowCall(new SqlCountStar(), new SqlWindow([], [], null))) + assert 'SELECT COUNT(*) OVER () FROM employees e' == ansi(countStar).sql + assert 'select count(*) over () from employees e' == JooqRenderer.render(countStar, 'H2').sql + + def distinct = queryOf(new SqlWindowCall( + new SqlFunction('COUNT', [new SqlColumn('e', 'id')], true), + new SqlWindow([], [], null))) + assert 'SELECT COUNT(DISTINCT e.id) OVER () FROM employees e' == ansi(distinct).sql + + def paramOffset = queryOf(new SqlWindowCall( + new SqlFunction('ROW_NUMBER', []), + new SqlWindow([], [new SqlOrderSpec(new SqlColumn('e', 'id'), true, true)], + new SqlWindowFrame(SqlWindowFrame.Unit.ROWS, + SqlWindowBound.preceding(new SqlParam(new ConstantExpression(1))), + SqlWindowBound.currentRow())))) + assert 'SELECT ROW_NUMBER() OVER (ORDER BY e.id ASC NULLS LAST ROWS BETWEEN ? PRECEDING AND CURRENT ROW) FROM employees e' == + ansi(paramOffset).sql + def jooqRejected = shouldFail(IllegalArgumentException) { + JooqRenderer.render(paramOffset, 'H2') + } + assert jooqRejected.message.contains('integer literal') + + def negative = shouldFail(IllegalArgumentException) { + SqlWindowBound.preceding(new SqlLiteral(-1)) + } + assert negative.message.contains('non-negative') + + for (SqlWindowFrame.Unit unit : SqlWindowFrame.Unit.values()) { + for (SqlWindowBound.Kind lower : SqlWindowBound.Kind.values()) { + for (SqlWindowBound.Kind upper : SqlWindowBound.Kind.values()) { + SqlWindowFrame frame = new SqlWindowFrame(unit, bound(lower, 2), bound(upper, 3)) + def ordered = queryOf(new SqlWindowCall(new SqlFunction('ROW_NUMBER', []), + new SqlWindow([], [new SqlOrderSpec(new SqlColumn('e', 'id'), true, true)], frame))) + def bare = queryOf(new SqlWindowCall(new SqlFunction('ROW_NUMBER', []), + new SqlWindow([], [], frame))) + String fragment = unit.name() + ' BETWEEN ' + boundText(lower, 2) + ' AND ' + boundText(upper, 3) + assert ansi(ordered).sql.contains(fragment) + assert ansi(bare).sql.contains(fragment) + assert JooqRenderer.render(ordered, 'H2').sql.toLowerCase().contains(fragment.toLowerCase()) + assert JooqRenderer.render(bare, 'H2').sql.toLowerCase().contains(fragment.toLowerCase()) + } + } + } + } + + @Test + void testBuiltInWindowFunctions() { + def parsed = parse(''' + from e in 'employees' + select (rank() over(partitionby e.deptId orderby e.salary)), + (denseRank() over(orderby e.salary in desc)), + (cumeDist() over(orderby e.salary)), + (lead(e.name) over(orderby e.id)), + (lead(e.name, 2, 'NONE') over(orderby e.id)), + (lag(e.salary, 1) over(orderby e.id)), + (firstValue(e.name) over(partitionby e.deptId orderby e.name)), + (lastValue(e.name) over(orderby e.name)), + (nthValue(e.name, 0) over(orderby e.id)), + (nthValue(e.name, 2) over(orderby e.id)), + (count() over(orderby e.id)), + (count(e.deptId) over()), + (count(distinct(e.salary)) over(partitionby e.deptId)), + (sum(e.salary) over(orderby e.id)), + (sum(e -> e.salary) over(partitionby e.deptId)), + (avg(e.salary) over(partitionby e.deptId)), + (min(e.salary) over(partitionby e.deptId)), + (max(e.salary) over()) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def sql = ansi(query).sql + def jooq = JooqRenderer.render(query, 'H2').sql.toLowerCase() + + assert sql.contains('RANK() OVER (PARTITION BY e.deptId ORDER BY e.salary ASC NULLS LAST)') + assert sql.contains('DENSE_RANK() OVER (ORDER BY e.salary DESC NULLS LAST)') + assert sql.contains('CUME_DIST() OVER (ORDER BY e.salary ASC NULLS LAST)') + assert sql.contains('LEAD(e.name) OVER (ORDER BY e.id ASC NULLS LAST)') + assert sql.contains('LEAD(e.name, ?, ?) OVER (ORDER BY e.id ASC NULLS LAST)') + assert sql.contains('LAG(e.salary, ?) OVER (ORDER BY e.id ASC NULLS LAST)') + assert sql.contains('FIRST_VALUE(e.name) OVER (PARTITION BY e.deptId ORDER BY e.name ASC NULLS LAST ' + + 'ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)') + assert sql.contains('LAST_VALUE(e.name) OVER (ORDER BY e.name ASC NULLS LAST ' + + 'ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)') + assert sql.contains('NTH_VALUE(e.name, ?) OVER (ORDER BY e.id ASC NULLS LAST ' + + 'ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)') + assert sql.contains('COUNT(*) OVER (ORDER BY e.id ASC NULLS LAST ' + + 'ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)') + assert sql.contains('COUNT(e.deptId) OVER ()') + assert sql.contains('COUNT(DISTINCT e.salary) OVER (PARTITION BY e.deptId)') + assert sql.contains('COALESCE(SUM(e.salary) OVER (ORDER BY e.id ASC NULLS LAST ' + + 'ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), 0)') + assert sql.contains('COALESCE(SUM(e.salary) OVER (PARTITION BY e.deptId), 0)') + assert sql.contains('AVG(e.salary) OVER (PARTITION BY e.deptId)') + assert sql.contains('MIN(e.salary) OVER (PARTITION BY e.deptId)') + assert sql.contains('MAX(e.salary) OVER ()') + assert !sql.contains('window functions are deferred') + + assert jooq.contains('rank() over (partition by e.deptid order by e.salary asc nulls last)') + assert jooq.contains('nth_value(e.name, ?) over (order by e.id asc nulls last rows between unbounded preceding and unbounded following)') + assert jooq.contains('count(*) over (order by e.id asc nulls last rows between unbounded preceding and unbounded following)') + assert jooq.contains('coalesce(sum(e.salary) over (order by e.id asc nulls last rows between unbounded preceding and unbounded following), 0)') + assert jooq.contains('lead(e.name, ?, ?) over (order by e.id asc nulls last)') + } + + @Test + void testNtileUsesGinqBucketsAndPercentRankKeepsASingleton() { + def parsed = parse(''' + from e in 'employees' + select (ntile(4) over(partitionby e.deptId orderby e.salary)), + (percentRank() over(partitionby e.deptId orderby e.salary)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def sql = ansi(query).sql + assert sql.contains('(CAST(? * (ROW_NUMBER() OVER (PARTITION BY e.deptId ORDER BY e.salary ASC NULLS LAST) - 1) AS BIGINT) ' + + '/ CAST(COUNT(*) OVER (PARTITION BY e.deptId) AS BIGINT))') + assert !sql.contains('FLOOR') + assert sql.contains('CASE WHEN COUNT(*) OVER (PARTITION BY e.deptId) = 1 THEN 1 ' + + 'ELSE PERCENT_RANK() OVER (PARTITION BY e.deptId ORDER BY e.salary ASC NULLS LAST) END') + + def sqlite = new SqlRenderer(Dialects.resolve('sqlite')).render(query).sql + assert sqlite.contains('AS INTEGER') + assert !sqlite.contains('FLOOR') + + def jooq = JooqRenderer.render(query, 'H2').sql.toLowerCase() + assert !jooq.contains('floor') + assert jooq.contains('bigint') + assert jooq.contains('row_number() over (partition by e.deptid order by e.salary asc nulls last)') + assert jooq.contains('count(*) over (partition by e.deptid)') + assert jooq.contains('percent_rank() over (partition by e.deptid order by e.salary asc nulls last)') + assert jooq.contains('case when') + } + + @Test + void testRowsFrameOnAnAggregateAndExplicitBounds() { + def parsed = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.id rows -1, 1)), + (avg(e.salary) over(orderby e.salary range null, 0)), + (min(e.salary) over(rows 0, null)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def sql = ansi(query).sql + assert sql.contains('COALESCE(SUM(e.salary) OVER (ORDER BY e.id ASC NULLS LAST ' + + 'ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING), 0)') + assert sql.contains('AVG(e.salary) OVER (ORDER BY e.salary ASC NULLS LAST ' + + 'RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)') + assert sql.contains('MIN(e.salary) OVER (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)') + def jooq = JooqRenderer.render(query, 'H2').sql.toLowerCase() + assert jooq.contains('sum(e.salary) over (order by e.id asc nulls last rows between 1 preceding and 1 following)') + assert jooq.contains('avg(e.salary) over (order by e.salary asc nulls last range between unbounded preceding and current row)') + } + + @Test + void testRankingFunctionRejectsAFrame() { + def parsed = parse(''' + from e in 'employees' + select (rank() over(orderby e.salary rows -1, 1)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + assert err.message.contains('does not accept `rows`') + assert err.message.contains('GINQ applies that frame') + assert !err.message.contains('window functions are deferred') + } + + @Test + void testOffsetFunctionsRejectAFrameWithoutApplyingIt() { + def parsed = parse(''' + from e in 'employees' + select (lead(e.name) over(orderby e.id rows -1, 1)), + (rowNumber() over(orderby e.id rows 0, 0)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + assert err.message.contains('does not accept `rows`') + assert err.message.contains('SQL defines that function without a frame') + assert !err.message.contains('GINQ applies') + } + + @Test + void testRankWithoutOrderStaysInMemory() { + def parsed = parse(''' + from e in 'employees' + select (denseRank() over(partitionby e.deptId)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + assert err.message.contains('needs `orderby`') + assert err.message.contains('mixedMode: true') + } + + @Test + void testFrameThatEndsBeforeItStarts() { + def parsed = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows 1, -1)) + ''') + def err = shouldFail(MultipleCompilationErrorsException) { + translate(parsed, null) + } + assert err.message.contains('ends before it starts') + } + + @Test + void testNthValueAndOffsetsRejectIllegalLiterals() { + def negativeIndex = parse(''' + from e in 'employees' + select (nthValue(e.name, -1) over(orderby e.id)) + ''') + def indexErr = shouldFail(MultipleCompilationErrorsException) { + translate(negativeIndex, null) + } + assert indexErr.message.contains('whole number >= 0') + + def negativeLead = parse(''' + from e in 'employees' + select (lead(e.name, -2) over(orderby e.id)) + ''') + def leadErr = shouldFail(MultipleCompilationErrorsException) { + translate(negativeLead, null) + } + assert leadErr.message.contains('offset must be a whole number >= 0') + } + + @Test + void testWindowOnlyInSelectAndOrderBy() { + def where = parse(''' + from e in 'employees' + where (rowNumber() over(orderby e.id)) > 0 + select e.name + ''') + def whereErr = shouldFail(MultipleCompilationErrorsException) { + translate(where, null) + } + assert whereErr.message.contains('only supported in `select` and `orderby`') + assert !whereErr.message.contains('mixedMode: true') + + def nested = parse(''' + from e in 'employees' + select (sum(rowNumber() over(orderby e.id)) over()) + ''') + def nestedErr = shouldFail(MultipleCompilationErrorsException) { + translate(nested, null) + } + assert nestedErr.message.contains('cannot be nested') + + def insideAggregate = parse(''' + from e in 'employees' + select (sum((rowNumber() over(orderby e.id)))) + ''') + def aggregateErr = shouldFail(MultipleCompilationErrorsException) { + translate(insideAggregate, null) + } + assert aggregateErr.message.contains('nested inside an aggregate') + assert !aggregateErr.message.contains('mixedMode: true') + + def ordered = parse(''' + from e in 'employees' + orderby (rowNumber() over(orderby e.salary)) + select e.name + ''') + def query = translate(ordered, null) + assert noErrors(ordered) + assert ansi(query).sql.contains('ORDER BY ROW_NUMBER() OVER (ORDER BY e.salary ASC NULLS LAST) - 1') + } + + @Test + void testSetOperationOrdersByAWindowProjection() { + def parsed = parse(''' + from a in 'employees' + select (rowNumber() over(orderby a.id)) + union + from b in 'employees' + orderby (rowNumber() over(orderby b.id)) + select (rowNumber() over(orderby b.id)) + ''') + def node = translateNode(parsed) + assert noErrors(parsed) + assert node instanceof SqlSetQuery + def sql = new SqlRenderer(new AnsiDialect()).render(node).sql + assert sql.contains('UNION') + assert sql.endsWith('ORDER BY 1 ASC NULLS LAST') + assert sql.count('ROW_NUMBER()') == 2 + } + + @Test + void testSqliteRejectsANumericRangeOffset() { + def parsed = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary range -2, 0)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def err = shouldFail(IllegalArgumentException) { + new SqlRenderer(Dialects.resolve('sqlite')).render(query) + } + assert err.message.contains('numeric RANGE offset') + def jooqErr = shouldFail(IllegalArgumentException) { + JooqRenderer.render(query, 'SQLITE') + } + assert jooqErr.message.contains('numeric RANGE offset') + assert new SqlRenderer(Dialects.resolve('sqlite')).render(queryOf(new SqlWindowCall( + new SqlFunction('SUM', [new SqlColumn('e', 'salary')]), + new SqlWindow([], [new SqlOrderSpec(new SqlColumn('e', 'salary'), true, true)], + new SqlWindowFrame(SqlWindowFrame.Unit.RANGE, + SqlWindowBound.unboundedPreceding(), SqlWindowBound.currentRow()))))).sql + .contains('RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW') + } + + @Test + void testDescendingRangeIsMirroredIntoSortOrder() { + def parsed = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary in desc range -2, 0)), + (sum(e.salary) over(orderby e.salary in desc range 1, 2)), + (sum(e.salary) over(orderby e.salary in desc range null, 1)), + (sum(e.salary) over(orderby e.salary in desc range 1, null)), + (sum(e.salary) over(orderby e.salary in desc rows -1, 1)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def sql = ansi(query).sql + assert sql.contains('RANGE BETWEEN CURRENT ROW AND 2 FOLLOWING') + assert sql.contains('RANGE BETWEEN 2 PRECEDING AND 1 PRECEDING') + assert sql.contains('RANGE BETWEEN 1 PRECEDING AND UNBOUNDED FOLLOWING') + assert sql.contains('RANGE BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING') + assert sql.contains('ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING') + def jooq = JooqRenderer.render(query, 'H2').sql.toLowerCase() + assert jooq.contains('range between current row and 2 following') + assert jooq.contains('rows between 1 preceding and 1 following') + } + + @Test + void testSeveralOrderKeysAndNullsFirst() { + def parsed = parse(''' + from e in 'employees' + select (rank() over(orderby e.salary, e.name in asc(nullsfirst))) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def sql = ansi(query).sql + assert sql.contains('RANK() OVER (ORDER BY e.salary ASC NULLS LAST, e.name ASC NULLS FIRST)') + def jooq = JooqRenderer.render(query, 'H2').sql.toLowerCase(Locale.ROOT) + assert jooq.contains('nulls last') + assert jooq.contains('nulls first') + } + + @Test + void testMySqlRejectsANumericRangeOffset() { + def parsed = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary range -2, 0)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + def err = shouldFail(IllegalArgumentException) { + new SqlRenderer(Dialects.resolve('mysql')).render(query) + } + assert err.message.contains('numeric RANGE offset') + assert err.message.contains('extra sort key') + def maria = shouldFail(IllegalArgumentException) { + new SqlRenderer(Dialects.resolve('mariadb')).render(query) + } + assert maria.message.contains('mariadb') + def jooqErr = shouldFail(IllegalArgumentException) { + JooqRenderer.render(query, 'MYSQL') + } + assert jooqErr.message.contains('extra sort key') + def jooqMaria = shouldFail(IllegalArgumentException) { + JooqRenderer.render(query, 'MARIADB') + } + assert jooqMaria.message.contains('numeric RANGE offset') + assert jooqMaria.message.contains('extra sort key') + + def rows = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows -1, 1)) + ''') + def rowsQuery = translate(rows, null) + def mysqlRows = new SqlRenderer(Dialects.resolve('mysql')).render(rowsQuery).sql + assert mysqlRows.contains('ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING') + assert mysqlRows.contains('IS NULL') + } + + @Test + void testSqliteRejectsCountDistinctOver() { + def parsed = parse(''' + from e in 'employees' + select (count(distinct(e.salary)) over(partitionby e.deptId)) + ''') + def query = translate(parsed, null) + assert noErrors(parsed) + assert ansi(query).sql.contains('COUNT(DISTINCT e.salary) OVER (PARTITION BY e.deptId)') + def err = shouldFail(IllegalArgumentException) { + new SqlRenderer(Dialects.resolve('sqlite')).render(query) + } + assert err.message.contains('COUNT(DISTINCT)') + def jooqErr = shouldFail(IllegalArgumentException) { + JooqRenderer.render(query, 'SQLITE') + } + assert jooqErr.message.contains('COUNT(DISTINCT)') + } + + @Test + void testRepeatedAndUnknownWindowClauses() { + def repeated = parse(''' + from e in 'employees' + select (rowNumber() over(partitionby e.deptId partitionby e.active orderby e.id)) + ''') + def repeatedErr = shouldFail(MultipleCompilationErrorsException) { + translate(repeated, null) + } + assert repeatedErr.message.contains('more than once') + + def both = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary rows -1, 1 range -1, 1)) + ''') + def bothErr = shouldFail(MultipleCompilationErrorsException) { + translate(both, null) + } + assert bothErr.message.contains('cannot both be used') + + def unknown = parse(''' + from e in 'employees' + select (rowNumber() over(orderby e.id groups 1)) + ''') + def unknownErr = shouldFail(MultipleCompilationErrorsException) { + translate(unknown, null) + } + assert unknownErr.message.contains('Unknown window clause') + + def noOrder = parse(''' + from e in 'employees' + select (sum(e.salary) over(range 1, 2)) + ''') + def noOrderErr = shouldFail(MultipleCompilationErrorsException) { + translate(noOrder, null) + } + assert noOrderErr.message.contains('`orderby` is expected when using `range`') + + def twoKeys = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.salary, e.name range -1, 1)) + ''') + def twoKeysErr = shouldFail(MultipleCompilationErrorsException) { + translate(twoKeys, null) + } + assert twoKeysErr.message.contains('Only one field is expected') + + def fraction = parse(''' + from e in 'employees' + select (sum(e.salary) over(orderby e.id rows 0.5, 1)) + ''') + def fractionErr = shouldFail(MultipleCompilationErrorsException) { + translate(fraction, null) + } + assert fractionErr.message.contains('whole numbers') + } + + private static SqlFunctionRegistry plainRegistry() { + def registry = SqlFunctionRegistry.standard().copy() + registry.register(SqlFunctionMapping.window('myNumber', 'ROW_NUMBER')) + registry.register(SqlFunctionMapping.window('mySum', 'SUM', 1)) + return registry + } + + private static SqlQuery translate(Parsed parsed, SqlFunctionRegistry registry) { + SqlQueryNode node = translateNode(parsed, registry) + assert node instanceof SqlQuery + return (SqlQuery) node + } + + private static SqlQueryNode translateNode(Parsed parsed, SqlFunctionRegistry registry = null) { + GinqSqlWalker walker = new GinqSqlWalker(parsed.sourceUnit) + if (registry != null) walker.setFunctions(registry) + return walker.translate(parsed.ginq) + } + + private static Parsed parse(String query) { + String code = """ + def hello() { + def gqc = { + ${query} + } + } + """ + SourceUnit sourceUnit + def ast = new CompilationUnit().tap { + sourceUnit = addSource('window.groovy', code) + compile(Phases.CONVERSION) + }.ast + def method = ast.classes[0].methods.find { it.name == 'hello' } + ExpressionStatement statement = (ExpressionStatement) ((BlockStatement) method.code).statements[0] + DeclarationExpression declaration = (DeclarationExpression) statement.expression + ClosureExpression closure = (ClosureExpression) declaration.rightExpression + AbstractGinqExpression built = new GinqAstBuilder(sourceUnit).buildAST(closure.code) + assert built instanceof GinqExpression || built instanceof SetOperationExpression + return new Parsed(sourceUnit, built) + } + + private static boolean noErrors(Parsed parsed) { + return parsed.sourceUnit.errorCollector.errorCount == 0 + } + + private static SqlWindowBound bound(SqlWindowBound.Kind kind, int offset) { + switch (kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return SqlWindowBound.unboundedPreceding() + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return SqlWindowBound.unboundedFollowing() + case SqlWindowBound.Kind.CURRENT_ROW: return SqlWindowBound.currentRow() + case SqlWindowBound.Kind.PRECEDING: return SqlWindowBound.preceding(new SqlLiteral(offset)) + case SqlWindowBound.Kind.FOLLOWING: return SqlWindowBound.following(new SqlLiteral(offset)) + default: throw new AssertionError(kind) + } + } + + private static String boundText(SqlWindowBound.Kind kind, int offset) { + switch (kind) { + case SqlWindowBound.Kind.UNBOUNDED_PRECEDING: return 'UNBOUNDED PRECEDING' + case SqlWindowBound.Kind.UNBOUNDED_FOLLOWING: return 'UNBOUNDED FOLLOWING' + case SqlWindowBound.Kind.CURRENT_ROW: return 'CURRENT ROW' + case SqlWindowBound.Kind.PRECEDING: return offset + ' PRECEDING' + case SqlWindowBound.Kind.FOLLOWING: return offset + ' FOLLOWING' + default: throw new AssertionError(kind) + } + } + + private static SqlQuery queryOf(SqlExpr expr) { + SqlQuery query = new SqlQuery() + query.from = new SqlTableRef('employees', 'e') + query.projections << new SqlProjection(expr) + return query + } + + private static RenderedSql ansi(SqlQuery query) { + return new SqlRenderer(new AnsiDialect()).render(query) + } + + private static class Parsed { + final SourceUnit sourceUnit + final AbstractGinqExpression ginq + + private Parsed(SourceUnit sourceUnit, AbstractGinqExpression ginq) { + this.sourceUnit = sourceUnit + this.ginq = ginq + } + } +} 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-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/runtime/SqlGinqRuntimeBehaviorTest.groovy b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/runtime/SqlGinqRuntimeBehaviorTest.groovy new file mode 100644 index 00000000000..3a4fe0ef504 --- /dev/null +++ b/subprojects/groovy-ginq-sql/src/test/groovy/org/apache/groovy/ginq/provider/sql/runtime/SqlGinqRuntimeBehaviorTest.groovy @@ -0,0 +1,185 @@ +/* + * 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.Sql +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.h2.jdbcx.JdbcDataSource +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 + +import java.sql.Connection +import java.sql.SQLException + +import static groovy.test.GroovyAssert.shouldFail + +class SqlGinqRuntimeBehaviorTest { + private Sql db + + @BeforeEach + void setUp() { + db = GinqSqlTestSupport.newPopulatedDb() + } + + @AfterEach + void tearDown() { + GinqSqlTestSupport.closeDb(db) + } + + @Test + void rewriteStarSelectNamesEverySourceColumn() { + String sql = 'select e.*, d.* from employees e join departments d on e.deptId = d.id' + String quoted = SqlGinqRuntime.rewriteStarSelect(sql, [['id', 'name'], ['id', 'title']], '"' as char) + assert quoted == 'SELECT e."id" AS "__ginq0_0", e."name" AS "__ginq0_1", ' + + 'd."id" AS "__ginq1_0", d."title" AS "__ginq1_1" from employees e join departments d on e.deptId = d.id' + + String plain = SqlGinqRuntime.rewriteStarSelect(sql, [['id'], ['title']], (char) 0) + assert plain.startsWith('SELECT e.id AS __ginq0_0, d.title AS __ginq1_0 ') + } + + @Test + void rewriteStarSelectRejectsALayoutThatCannotBeRebuilt() { + def shape = shouldFail(SQLException) { + SqlGinqRuntime.rewriteStarSelect('select 1', [[]], '"' as char) + } + assert shape.message.contains('no SELECT ... FROM') + + def item = shouldFail(SQLException) { + SqlGinqRuntime.rewriteStarSelect('select e.name from employees e', [['name']], '"' as char) + } + assert item.message.contains('not alias.*') + + def count = shouldFail(SQLException) { + SqlGinqRuntime.rewriteStarSelect('select e.* from employees e', [[], []], '"' as char) + } + assert count.message.contains('aliases') + + def empty = shouldFail(SQLException) { + SqlGinqRuntime.rewriteStarSelect('select e.* from employees e', [[]], '"' as char) + } + assert empty.message.contains('no columns') + + def duplicate = shouldFail(SQLException) { + SqlGinqRuntime.rewriteStarSelect('select e.* from employees e', [['Name', 'name']], '"' as char) + } + assert duplicate.message.contains('duplicate column labels') + } + + @Test + void quoteIdentifierEscapesAndRejectsBlankOrUnquotableNames() { + assert 'plain' == SqlGinqRuntime.quoteIdentifier('plain', (char) 0) + assert '"a""b"' == SqlGinqRuntime.quoteIdentifier('a"b', '"' as char) + assert '`odd`' == SqlGinqRuntime.quoteIdentifier('odd', '`' as char) + + def blank = shouldFail(SQLException) { + SqlGinqRuntime.quoteIdentifier('', '"' as char) + } + assert blank.message.contains('blank') + + def unquoted = shouldFail(SQLException) { + SqlGinqRuntime.quoteIdentifier('a b', (char) 0) + } + assert unquoted.message.contains('needs quoting') + } + + @Test + void prepareMixedSqlWrapsSourcesAndRenamesACollidingPresenceColumn() { + String sql = 'SELECT e.*, d.* FROM employees e LEFT JOIN departments d ON e.deptId = d.id' + String rewritten = SqlGinqRuntime.prepareMixedSql(sql, [['id', 'name'], ['id', '__ginq_present']], '"' as char) + assert !rewritten.toLowerCase().contains('e.*') + assert rewritten.contains('__ginq_src') || rewritten.contains('__ginq') + assert rewritten.toLowerCase().contains('left join') + + def missing = shouldFail(SQLException) { + SqlGinqRuntime.prepareMixedSql('SELECT 1', [['id']], '"' as char) + } + assert missing.message.contains('FROM') || missing.message.contains('SELECT') + } + + @Test + void likePatternEscapesWildcardsAndLeavesNullUnknown() { + assert SqlGinqRuntime.likePattern(null, true, true) == null + assert '%a!%!_!!' == SqlGinqRuntime.likePattern('a%_!', true, false) + assert 'a!%!_!!%' == SqlGinqRuntime.likePattern('a%_!', false, true) + assert 'plain' == SqlGinqRuntime.likePattern('plain', false, false) + } + + @Test + void indexZipRequiresAlignedSources() { + def zipped = SqlGinqRuntime.indexZip(Queryable.from([1, null]), Queryable.from(['a', 'b'])).toList() + assert zipped.collect { [it.v1, it.v2] } == [[1, 'a'], [null, 'b']] + + def missing = shouldFail(IllegalArgumentException) { + SqlGinqRuntime.indexZip(null, Queryable.from([1])) + } + assert missing.message.contains('null') + + def skewed = shouldFail(IllegalStateException) { + SqlGinqRuntime.indexZip(Queryable.from([1]), Queryable.from([1, 2])) + } + assert skewed.message.contains('not aligned') + assert skewed.message.contains('1 and 2') + } + + @Test + void mixedOrdinalIsSeparateFromTheColumnMap() { + MixedSourceRow row = new MixedSourceRow([name: 'Ada', mixedOrdinal: 'column'], 4) + assert row.get('name') == 'Ada' + assert row.get('mixedOrdinal') == 'column' + assert row.mixedOrdinal() == 4 + assert SqlGinqRuntime.mixedOrdinal(row) == 4 + + def absent = shouldFail(IllegalArgumentException) { SqlGinqRuntime.mixedOrdinal(null) } + assert absent.message.contains('null') + def other = shouldFail(IllegalArgumentException) { SqlGinqRuntime.mixedOrdinal('row') } + assert other.message.contains('String') + } + + @Test + void executeAndColumnLabelsAcceptSqlDataSourceAndConnection() { + assert labels(SqlGinqRuntime.columnLabels(db, 'select name from employees where id = ?', [1])) == ['NAME'] + + JdbcDataSource dataSource = new JdbcDataSource() + dataSource.setURL(db.connection.metaData.URL) + dataSource.setUser('sa') + dataSource.setPassword('') + def viaDataSource = SqlGinqRuntime.execute(dataSource, 'select name from employees where id = ?', [1]).toList() + assert viaDataSource[0].name == 'Alice' + + Connection connection = db.connection + def viaConnection = SqlGinqRuntime.execute(connection, 'select name from employees where salary = ?', [6000]).toList() + assert viaConnection[0].name == 'Frank' + + def unsupported = shouldFail(IllegalArgumentException) { + SqlGinqRuntime.execute(42, 'select 1', []) + } + assert unsupported.message.contains('Integer') + + def quote = shouldFail(SQLException) { + SqlGinqRuntime.expandAndExecute(db, 'select name from employees', [], [['name']], '""') + } + assert quote.message.contains('one character') + } + + private static List labels(List names) { + names.collect { it.toUpperCase(Locale.ROOT) } + } +} diff --git a/subprojects/groovy-ginq/STRATEGY.md b/subprojects/groovy-ginq/STRATEGY.md new file mode 100644 index 00000000000..eb08ba17989 --- /dev/null +++ b/subprojects/groovy-ginq/STRATEGY.md @@ -0,0 +1,279 @@ + + +# GINQ static compilation and the fluent query API + +This note is the implementation strategy for GROOVY-12724. It states which +component owns each decision, which alternatives were rejected, and the +behaviour a caller can rely on. + +## What is being compiled + +There are two front ends and one runtime. + +* `GQ`, `GQL`, and `@GQ` are a macro. At conversion the macro lowers the + SQL-like syntax to `Queryable` calls. Clause bodies (`where`, `select`, + joins, ordering, grouping, aggregates) use Groovy's dynamic object protocol, + because a row may be a bean, a map, or a record. That protocol is the + behaviour dynamic `GQ` already has. +* `Ginq.from` is ordinary generic methods (`Query` / `GinqQuery`). There is + no macro and no extra type checker. `@CompileStatic` sees the methods and + infers closure parameters from the SAM types, the same way it infers any + other Groovy lambda. +* Both front ends execute on the in-memory `Queryable` runtime. A SQL provider + still consumes the macro's expression tree; the fluent API is not a second + translator. + +## When static compilation applies + +Static compilation is `StaticCompileTransformation`, which runs at instruction +selection. GINQ does not choose a different phase and does not install a +visitor of its own. + +| Enclosing scope | What the compiler does | +| --- | --- | +| No checking annotation | The macro's lowered tree is left as it is. The whole method is dynamic. The pipeline is built when the expression is evaluated. | +| `@TypeChecked(SKIP)`, or `@CompileStatic` / `@CompileDynamic` on a class or method the static-compilation visitor skips | Same as no checking annotation. | +| `@TypeChecked` class, method `@CompileDynamic` or `@CompileStatic(SKIP)` | The method is still type-checked. `@CompileDynamic` is not `@TypeChecked(SKIP)`. The row extension is installed on the class annotation the type-checked visitor reads. | +| `@TypeChecked` | The enclosing method is type-checked. Clause calls stay dynamic. The checker does not infer clause-lambda parameter types. | +| `@CompileStatic` | The enclosing method and the lowered query closure are statically compiled. A call the checker selects is emitted as that target. | + +`@TypeChecked` does not static-compile. The same extension is registered for +both annotations because both need the row rules. Which annotation counts is +the same decision `StaticTypeCheckingVisitor.isSkipMode` makes: the +type-checked visitor looks only at `@TypeChecked`, and the static-compilation +visitor looks at `@TypeChecked` and `@CompileStatic`. `@CompileDynamic` is +`@CompileStatic(SKIP)` and skips only that second visitor. + +The extension is `GinqRowChecks`. The macro, or the `@GQ` transform, appends +its name to the `extensions` member of the annotation that the checker will +actually read: the class annotation, or an outer class annotation when the +query is in an inner class, or the method annotation when the method carries +its own non-skip checking annotation. That member is the existing registration +point. A string, a class literal, or a list or array of those is updated. Any +other shape is a compile error and is left unchanged, so a value the bridge +does not understand is never dropped silently. Nothing is appended for a scope +the checker will not visit. + +## The query closure stays on the static writer + +Under `@CompileStatic` the lowered query closure is not marked +`DYNAMIC_RESOLUTION`. The static writer emits it. A call the checker selects, +including a target another extension replaced in `onMethodSelection`, is that +call. An extension that selects `choose(CharSequence)` for a `String` argument +is honoured inside `where` and `select` the same way it is honoured in the +enclosing method. + +What stays dynamic is the part the static writer cannot prove, and nothing else: + +* A comparison of two numbers (`n > 1`, `n == m`) stays the operator, and + static compilation emits the primitive comparison. `in` and a regex match + are the same operators the static writer already lowers. A comparison the + checker cannot prove, such as a map row's missing property compared with + a number, is not a legal Java comparison; the static writer still emits + `ScriptBytecodeAdapter` for that operator and the type error is not + reported, because a list of maps is a normal GINQ source. Arithmetic and + a subscript stay operators through type checking: a number added to a + number is a static add, and only an operator the checker cannot prove is + rewritten to `invokeMethodN` afterwards. `orderby n in desc` is already + an `Order` value. The snapshot index `ginqCaptured$[i]` stays an array load. +* A call the checker cannot resolve is rewritten to + `ScriptBytecodeAdapter.invokeMethodN`. That is a real public method. It is + not `invokevirtual` of a stand-in, and the stand-in's declaring class is + not `Object`. +* `Queryable.from` stays dynamic when the chosen parameter is an array and + the argument is not, so a list is not wrapped as one row. +* A target whose declaring class is not public stays dynamic. + `SourceRecord` is public because `navigate` returns it and a caller in + another package has to be able to name the row. It is `@Internal`: not a + published API. `from` of an `int[]` is `Queryable`. A primitive + is not a legal type argument. +* A stream pipeline the checker can type is a static `Stream` call. That + includes `map`, `collect`, `reduce`, and a method reference that is a + legal SAM, such as `Stream.reduce(BigDecimal.ZERO, BigDecimal::add)`. + `Collectors.joining()` on a `Stream` is the same kind of call. + An alias on a group row (`r.n`, `r.s`) has the source element's type, so + the stream does not collapse to `Stream`. +* A parallel clause body is `QueryableHelper.supplyClause`, whose declared + type is `Object`. `supplyAsync`'s type parameters inferred the row as + `CompletableFuture`. + +Under `@TypeChecked` the same closure is not statically compiled. Clause calls +stay dynamic and the checker does not infer clause-lambda parameter types. +Inferring them writes a generic signature the dynamic closure cannot load. +The enclosing method is still type-checked. + +`GinqRowChecks` is a normal type-checking extension, appended after extensions +already on the annotation. Under `@CompileStatic` it does not skip the call, +so those extensions still see it and `onMethodSelection` still runs. Under +`@TypeChecked` it marks the call dynamic. Extensions registered ahead of +`GinqRowChecks` still see the calls the visitor delivers. + +Outside the marked closure the extension has an opinion only for a query result +used as the receiver of `toList`, `get`, `getAt`, or a subscript. That is the +row value the macro leaves typed as `Object`. A field, an enclosing-method +parameter, and `value[0]` on that parameter stay compile errors. A local that +holds the query, such as `result[0].toList()`, is accepted. + +There is no synthetic method and no `CompilationUnit.addNewPhaseOperation`. +The closure the macro already builds is the compiler's capture. + +## Why execution is lazy, and which lazy + +Two different deferrals, deliberately not the same mechanism. + +**Element pull is always deferred.** `where` and `select` on `Queryable` build +a pipeline and do not iterate. `toList`, `count`, and the other terminals +pull. Dynamic `GQ` already works this way. Nothing in the static path changes +it. + +**Fluent operators record until a terminal.** `GinqQuery` stores the predicate, +the selector, and the orderings, and calls `Queryable` from `materialize`, +which only a terminal invokes. This is the LINQ-to-Objects shape (a query +object that runs when it is enumerated), not the LINQ-to-SQL shape (an +expression tree a provider rewrites). Groovy already has the macro for the +expression-tree case. Copying `IQueryable` would duplicate the macro and force +every in-memory operator through a translator. The fluent API therefore stays +a recording object. It does not use `LazyQueryable`, and it does not depend on +static compilation: the same object is lazy in a dynamic method. + +**A static `GQ` also defers building the pipeline.** The lowered form is an +immediately-invoked closure: calling it evaluates `from` and constructs the +`Queryable` chain. Under `@CompileStatic` or `@TypeChecked` that call is moved +behind `LazyQueryable.defer`. The closure value is created when the `GQ` +expression runs, and `call()` runs on the first read. Creating the closure at +the expression is what captures locals then; delaying `call()` is what keeps +`Iterable.iterator` (and any other work inside the lowered tree) off the +expression. `GQL` and `@GQ(List)` call `toList` on the deferred query, so they +still materialize at the expression. Dynamic `GQ` is unchanged: the macro does +not wrap it, and the pipeline is built when the expression is evaluated. +Changing that would change every existing dynamic query. + +`LazyQueryable` is only that thunk. It is not a type checker, not a capture +analysis, and not the fluent implementation. It is public because compiled +code calls `LazyQueryable.defer`, and that method is part of the binary ABI +(`@GroovyABI`). The class is `@Internal`: callers program to `Queryable`. +Joining, grouping, and the aggregates are forwarded to the pipeline built on +first use, and that pipeline is cached, matching `QueryableCollection.toList`. + +## Locals + +The deferred closure is a normal Groovy closure in the enclosing method, and +the closure writer captures it. A local the query assigns is a closure-shared +variable, so the write is visible to the caller. That is the compiler's rule. + +A local the query only reads is different. Dynamic `GQ` creates the clause +lambdas when the expression runs, so a later assignment is not what those +lambdas read. A static `GQ` creates the closure at the expression and calls it +on the first read. If the caller assigns the local again, the closure writer +treats it as shared and the deferred call would see the new value. The bridge +therefore copies those read-only locals into an array when the expression +runs, and the deferred closure reads the array. + +Which locals those are is `VariableScopeVisitor`'s answer, not a set of names. +The visitor links each reference to the declaration in scope. A field or a +property and a local of the same name are distinct, as are a closure parameter, +a local declared in a nested closure, and a name that is not a local. A name +that resolves to nothing is a `DynamicVariable` (an import alias, including one +written in lower case, or a class name the resolver has not rewritten yet) and +is not copied. A field or a property is not copied; it is read when the closure +runs, so an assignment after the expression and before a deferred terminal is +visible. `GQL` and `@GQ(List)` have already read it. The bridge does not +rewrite the caller's declarations, box the variables, or emit stores. Two +locals of the same name in nested scopes are still rejected. + +## `asType` + +`Queryable.asType` special-cases `Queryable` (returns this), and `List`, +`Collection`, and `Iterable` (returns `toList()`). Every other target, +including null, is `DefaultGroovyMethods.asType`. That method throws +`GroovyCastException` when the value is not compatible with the target, and +applies the usual string and collection coercions when it is. `LazyQueryable` +returns this for `LazyQueryable` and `Queryable` without building the pipeline, +and otherwise builds it and uses the built query's `asType`. Returning `this` +for an arbitrary target is not a coercion. `QueryableCollection.asType` throws +`GroovyCastException` for null, the same way. `as Iterator` uses +`iterator()`, and `as Stream` uses `stream()`. `toList()` and `as ArrayList` +do not return the live internal replay buffer, or any list this class +installed as its source; a user-supplied `List` is still returned without +copying. + +## What stays out of the static compiler + +GINQ does not subclass `StaticTypeCheckingVisitor` or +`StaticCompilationVisitor`, does not add a compile phase, and does not teach +the static call-site writer about GINQ operators. The one compiler change is +the existing dynamic-call marker honoured on a closure: `StaticTypesClosureWriter` +emits that closure with the dynamic writer. A type-checking extension already +uses the same marker, with a type as its value, for one expression. `Boolean.TRUE` +on the closure is the switch for the whole closure, and only the lowered query +closure sets it. Row properties that the checker cannot resolve are still +`makeDynamic` on that expression. + +## Re-enumeration + +Two sources, two rules. + +* `Ginq.from` on an `Iterable` or array re-reads that source on every terminal. + `where`, `select`, and the other operators record the work; they do not copy + the elements. Adding to the list between two `toList()` calls is visible. + This is the LINQ-to-Objects rule. Fluent `Ginq.from` / `GinqQuery.from` of + an `int[]` is `Query` and re-boxes the array on each terminal, so a + later mutation of the array is visible. Other primitive arrays are out of + scope for this fluent factory; only `int[]` matches `Queryable.from`. +* `Ginq.from` on a `Stream` reads that stream on the first terminal and replays + the buffered elements after that. A stream cannot be read twice. The first + terminal fully drains a fluent `Stream` source; `take` and `exists` do not + short-circuit the unused tail. The source is marked read only after that + collect succeeds. Operators on `QueryableCollection` may still use + `openStream()` for pipeline construction. +* `Queryable.stream()` and a fluent `stream()` return a new stream every time. + Creating the stream does not pull. A one-shot pipeline is buffered as its + elements are pulled, and a later `stream()` reads that buffer from the start + before pulling anything still unread. A sized pipeline can be counted without + pulling, so a projection with a side effect is not run merely because + `exists` asks for `count`. After the one-shot source has been read to the + end, later calls stream the buffer. A caller is never handed a stream that + has already been consumed. After bind, `openStream()` also uses this replay + path, so `where`, `select`, or `limit` on an instance that already has a + public `stream()` or `iterator()` still sees the source. +* `QueryableCollection.iterator()`, a Groovy `for-in` over the queryable, and + `as Iterator` follow the same rules as `stream()`. Each call builds a new + iterator from `stream()`; a live non-`List` `Iterable` is read again, and a + one-shot stream is replayed. `iterator()` does not hold the read lock. +* A `GQ` / `QueryableCollection` terminal still materializes once and then + reuses that list. Building the pipeline does not iterate. That is the + behaviour dynamic `GQ` already had. The list returned by `toList()` is a + copy when the elements came from an internal buffer; a user-supplied `List` + is returned as-is. + +## Intentional limits + +* Names bound by `from` inside `GQ` are dynamic. A list of maps keeps working. + `Ginq.from` is the front end that checks element types. +* When the checker runs, a `GQ` call is still `MacroStub.macroMethod(query)`. + `toList()` on that call is typed as a raw `List`, so assigning it to + `List` is the unchecked conversion a dynamic query already allowed. +* `@CompileStatic` on an outer class covers an inner class because the outer + visitor visits inner classes and reads the outer annotation. The extension is + attached there. +* Fluent `orderBy` compares keys with their natural order when the query runs. + The macro's `orderby` clause is unchanged. +* `Query` is not `Iterable`. Join, hash-join, and set operators have thin + `Query` overloads alongside the `Iterable` forms, matching `union`. diff --git a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Aggregator.java b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Aggregator.java new file mode 100644 index 00000000000..5cd96167963 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Aggregator.java @@ -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 groovy.ginq; + +import org.apache.groovy.lang.annotation.Incubating; + +/** + * Reduces a {@link Query} to one value. This is the fluent counterpart of the + * GINQ {@code agg} function: the argument is the group, or the whole query when + * there is no grouping. + * + *
+ * Ginq.from(orders).aggregate { rows -> rows.sum { it.amount } }
+ * 
+ * + * Named aggregates used from the SQL-like DSL are a separate extension point, + * {@code org.apache.groovy.ginq.provider.GinqAggregate}. + * + * @param the element type + * @param the aggregate type + * @since 7.0.0 + */ +@Incubating +@FunctionalInterface +public interface Aggregator { + + /** + * Aggregates {@code rows}. + * + * @param rows the query or group to reduce; reading it is terminal + * @return the aggregate value + */ + R apply(Query rows); +} diff --git a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Ginq.java b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Ginq.java new file mode 100644 index 00000000000..73700e70dff --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Ginq.java @@ -0,0 +1,137 @@ +/* + * 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 groovy.ginq; + +import org.apache.groovy.ginq.fluent.GinqQuery; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.stream.Stream; + +/** + * Starts a fluent GINQ query. The operators on {@link Query} follow LINQ's method + * syntax ({@code where}, {@code select}, {@code orderBy}, {@code groupBy}, {@code join}) + * and run on the same in-memory runtime as {@code GQ { ... }}. They are deferred + * until a terminal operation such as {@link Query#toList()}. + *

+ * {@code GQ} remains the SQL-like syntax and is the front end used by other + * providers, including SQL. Use that syntax when the query must be translated. + * Use {@code Ginq.from} when the caller wants generic types under {@code @CompileStatic}. + * + *

+ * List<String> names = Ginq.from(people)
+ *         .where { it.age >= 18 }
+ *         .orderBy { it.name }
+ *         .select { it.name }
+ *         .toList()
+ * 
+ * + * @since 7.0.0 + */ +@Incubating +public final class Ginq { + + private Ginq() { + } + + /** + * Queries {@code source}. + * + * @param source the elements + * @param the element type + * @return a query over {@code source} + * @throws NullPointerException when {@code source} is null + */ + public static Query from(Iterable source) { + return GinqQuery.from(source); + } + + /** + * Queries the elements of {@code source}, in array order. + * + * @param source the elements + * @param the element type + * @return a query over {@code source} + * @throws NullPointerException when {@code source} is null + */ + public static Query from(T[] source) { + return GinqQuery.from(source); + } + + /** + * Queries the boxed elements of a primitive {@code int} array. {@code int[]} + * is not a {@code T[]}, so the query's element type is {@code Integer}. The + * array is boxed again on each terminal. Other primitive arrays are not + * overloaded here. + * + * @param source the elements + * @return a query over the boxed values + * @throws NullPointerException when {@code source} is null + */ + public static Query from(int[] source) { + return GinqQuery.from(source); + } + + /** + * Queries {@code source}. The first terminal fully drains the stream, and + * later terminals replay that read, because a stream can be read only once. + * {@code take} and {@code exists} do not leave an unused tail unread. + * + * @param source the elements + * @param the element type + * @return a query over {@code source} + * @throws NullPointerException when {@code source} is null + */ + public static Query from(Stream source) { + return GinqQuery.from(source); + } + + /** + * Returns {@code source} when it is already a GINQ query, otherwise queries its elements. + * + * @param source the query to continue + * @param the element type + * @return {@code source} + * @throws NullPointerException when {@code source} is null + */ + public static Query from(Query source) { + return GinqQuery.from(source); + } + + /** + * Queries the given elements. + * + * @param elements the elements, which may be empty + * @param the element type + * @return a query over {@code elements} + */ + @SafeVarargs + public static Query of(T... elements) { + return GinqQuery.of(elements); + } + + /** + * Returns a query with no elements. + * + * @param the element type + * @return an empty query + */ + public static Query empty() { + return GinqQuery.empty(); + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Grouping.java b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Grouping.java new file mode 100644 index 00000000000..cf0426cf76a --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Grouping.java @@ -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 groovy.ginq; + +import org.apache.groovy.lang.annotation.Incubating; + +/** + * One group produced by {@link Query#groupBy}. The group is itself a query over + * its elements, and {@link #getKey()} is the value the key selector returned. + * {@code count()} and the other aggregates therefore describe the group, which + * is the same idea as LINQ's {@code IGrouping}. + * + * @param the key type + * @param the element type + * @since 7.0.0 + */ +@Incubating +public interface Grouping extends Query { + + /** + * Returns the group key. + * + * @return the key + */ + K getKey(); +} diff --git a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Query.java b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Query.java new file mode 100644 index 00000000000..0f3dc48bbc1 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/Query.java @@ -0,0 +1,1400 @@ +/* + * 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 groovy.ginq; + +import groovy.lang.Closure; +import groovy.transform.stc.ClosureParams; +import groovy.transform.stc.FromString; +import org.apache.groovy.lang.annotation.Incubating; +import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation; + +import java.math.BigDecimal; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Stream; + +/** + * A deferred in-memory query. Operators return a new query and do not read the + * source; {@link #toList()}, the aggregates, and {@link #iterator()} do. + * {@code orderBy} followed by {@code thenBy} builds one comparison. + *

+ * This is the method syntax for GINQ. The SQL-like {@code GQ { ... }} syntax + * remains the front end that can target other providers. Extension methods on + * this interface are the supported way to add an operator without changing GINQ. + *

+ * Each operator that takes a function also takes a {@link Closure}. The closure + * parameter types are the element type of this query and, for a join or + * {@code selectMany}, the element type of the other source. Callers do not + * write those types. The {@link java.util.function} overloads remain for Java. + * + * @param the element type + * @since 7.0.0 + */ +@Incubating +public interface Query { + + /** + * Keeps elements that match {@code predicate}. Same role as LINQ {@code Where}. + * + * @param predicate the filter + * @return the filtered query + */ + Query where(Predicate predicate); + + /** + * Keeps elements that match {@code predicate}. The closure parameter is {@code T}. + * + * @param predicate the filter + * @return the filtered query + */ + default Query where(@ClosureParams(value = FromString.class, options = "T") Closure predicate) { + Objects.requireNonNull(predicate, "predicate"); + return where(item -> truth(predicate, item)); + } + + /** + * Maps each element. Same role as LINQ {@code Select}. + * + * @param selector the projection + * @param the result element type + * @return the projected query + */ + Query select(Function selector); + + /** + * Maps each element. The closure parameter is {@code T} and {@code R} is the closure's return type. + * + * @param selector the projection + * @param the result element type + * @return the projected query + */ + default Query select(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return select(item -> Query.invoke(selector, item)); + } + + /** + * Maps each element to zero or more results and flattens them. + * Same role as LINQ {@code SelectMany}. + * + * @param selector the collection selector; a {@code null} collection contributes nothing + * @param the result element type + * @return the flattened query + */ + Query selectMany(Function> selector); + + /** + * Maps each element to zero or more results and flattens them. + * The closure parameter is {@code T}. + * + * @param selector the collection selector; a {@code null} collection contributes nothing + * @param the result element type + * @return the flattened query + */ + default Query selectMany(@ClosureParams(value = FromString.class, options = "T") Closure> selector) { + Objects.requireNonNull(selector, "selector"); + return selectMany(item -> Query.>invoke(selector, item)); + } + + /** + * Maps each element to a collection and then each pair to a result. + * + * @param collectionSelector the collection selector + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the flattened query + */ + Query selectMany(Function> collectionSelector, + BiFunction resultSelector); + + /** + * Maps each element to a collection and then each pair to a result. + * The collection closure's parameter is {@code T}. The result closure's + * parameters are {@code T} and the collection's element type. + * + * @param collectionSelector the collection selector + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the flattened query + */ + default Query selectMany( + @ClosureParams(value = FromString.class, options = "T") Closure> collectionSelector, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(collectionSelector, "collectionSelector"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return selectMany( + item -> Query.>invoke(collectionSelector, item), + (item, element) -> Query.invoke(resultSelector, item, element)); + } + + /** + * Orders by {@code keySelector}, ascending, nulls last. Replaces any order already set. + * + * @param keySelector the sort key; the key is compared with its natural order when the query runs + * @return the ordered query + */ + Query orderBy(Function keySelector); + + /** + * Orders by {@code keySelector}, ascending, nulls last. The closure parameter is {@code T}. + * + * @param keySelector the sort key + * @return the ordered query + */ + default Query orderBy(@ClosureParams(value = FromString.class, options = "T") Closure keySelector) { + Objects.requireNonNull(keySelector, "keySelector"); + return orderBy(item -> Query.invoke(keySelector, item)); + } + + /** + * Orders by {@code keySelector}, descending, nulls last. Replaces any order already set. + * + * @param keySelector the sort key + * @return the ordered query + */ + Query orderByDescending(Function keySelector); + + /** + * Orders by {@code keySelector}, descending, nulls last. The closure parameter is {@code T}. + * + * @param keySelector the sort key + * @return the ordered query + */ + default Query orderByDescending(@ClosureParams(value = FromString.class, options = "T") Closure keySelector) { + Objects.requireNonNull(keySelector, "keySelector"); + return orderByDescending(item -> Query.invoke(keySelector, item)); + } + + /** + * Adds an ascending key. Requires a preceding {@link #orderBy} or {@link #orderByDescending} + * on this query, with no operator in between. + * + * @param keySelector the secondary key + * @return the ordered query + * @throws IllegalStateException when this query has no order + */ + Query thenBy(Function keySelector); + + /** + * Adds an ascending key. The closure parameter is {@code T}. + * + * @param keySelector the secondary key + * @return the ordered query + * @throws IllegalStateException when this query has no order + */ + default Query thenBy(@ClosureParams(value = FromString.class, options = "T") Closure keySelector) { + Objects.requireNonNull(keySelector, "keySelector"); + return thenBy(item -> Query.invoke(keySelector, item)); + } + + /** + * Adds a descending key. Same requirement as {@link #thenBy}. + * + * @param keySelector the secondary key + * @return the ordered query + * @throws IllegalStateException when this query has no order + */ + Query thenByDescending(Function keySelector); + + /** + * Adds a descending key. The closure parameter is {@code T}. + * + * @param keySelector the secondary key + * @return the ordered query + * @throws IllegalStateException when this query has no order + */ + default Query thenByDescending(@ClosureParams(value = FromString.class, options = "T") Closure keySelector) { + Objects.requireNonNull(keySelector, "keySelector"); + return thenByDescending(item -> Query.invoke(keySelector, item)); + } + + /** + * Groups elements by key. Same role as LINQ {@code GroupBy}. + * A {@code null} key is one group. + * + * @param keySelector the group key + * @param the key type + * @return a query of groups + */ + Query> groupBy(Function keySelector); + + /** + * Groups elements by key. The closure parameter is {@code T} and {@code K} is what it returns. + * + * @param keySelector the group key + * @param the key type + * @return a query of groups + */ + default Query> groupBy(@ClosureParams(value = FromString.class, options = "T") Closure keySelector) { + Objects.requireNonNull(keySelector, "keySelector"); + return groupBy(item -> Query.invoke(keySelector, item)); + } + + /** + * Groups by key and keeps the groups matched by {@code having}. + * + * @param keySelector the group key + * @param having the group filter, or {@code null} to keep every group + * @param the key type + * @return a query of groups + */ + Query> groupBy(Function keySelector, + Predicate> having); + + /** + * Groups by key and keeps the groups matched by {@code having}. + * The key closure's parameter is {@code T}. The having closure's parameter + * is the group, whose key is the key closure's return type. + * + * @param keySelector the group key + * @param having the group filter + * @param the key type + * @return a query of groups + */ + default Query> groupBy( + @ClosureParams(value = FromString.class, options = "T") Closure keySelector, + @ClosureParams(value = FromString.class, options = "groovy.ginq.Grouping") Closure having) { + Objects.requireNonNull(keySelector, "keySelector"); + Objects.requireNonNull(having, "having"); + return groupBy(item -> Query.invoke(keySelector, item), group -> truth(having, group)); + } + + /** + * Equijoins {@code inner} and projects each matching pair. + * The join is a hash join, so the keys are compared with {@code equals}. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query join(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Equijoins {@code inner}. The outer-key parameter is {@code T}, the inner-key + * parameter is the element type of {@code inner}, and the result parameters are both. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query join(Iterable inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return join(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Inner-joins {@code inner} with an arbitrary predicate and projects each matching pair. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query join(Iterable inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Inner-joins {@code inner} with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query join(Iterable inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return join(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Equijoins another query and projects each matching pair. The join is a hash join, so the keys are compared with {@code equals}. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query join(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Equijoins another query and projects each matching pair. The join is a hash join, so the keys are compared with {@code equals}. Closure parameters are inferred the same way as the {@code Iterable} form. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query join(Query inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return join(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Inner-joins another query with an arbitrary predicate and projects each matching pair. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query join(Query inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Inner-joins another query with an arbitrary predicate and projects each matching pair. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query join(Query inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return join(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Equijoins {@code inner} from the left. An unmatched outer element is passed + * with a {@code null} inner element. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query leftJoin(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Equijoins {@code inner} from the left. Closure parameters are inferred the same way as {@link #join}. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query leftJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return leftJoin(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Left-joins {@code inner} with an arbitrary predicate. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query leftJoin(Iterable inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Left-joins {@code inner} with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query leftJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return leftJoin(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Equijoins another query from the left. An unmatched outer element is passed with a {@code null} inner element. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query leftJoin(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Equijoins another query from the left. An unmatched outer element is passed with a {@code null} inner element. Closure parameters are inferred the same way as the {@code Iterable} form. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query leftJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return leftJoin(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Left-joins another query with an arbitrary predicate. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query leftJoin(Query inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Left-joins another query with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query leftJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return leftJoin(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Equijoins {@code inner} from the right. An unmatched inner element is passed + * with a {@code null} outer element. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query rightJoin(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Equijoins {@code inner} from the right. Closure parameters are inferred the same way as {@link #join}. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query rightJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return rightJoin(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Right-joins {@code inner} with an arbitrary predicate. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query rightJoin(Iterable inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Right-joins {@code inner} with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query rightJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return rightJoin(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Equijoins another query from the right. An unmatched inner element is passed with a {@code null} outer element. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query rightJoin(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Equijoins another query from the right. An unmatched inner element is passed with a {@code null} outer element. Closure parameters are inferred the same way as the {@code Iterable} form. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query rightJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return rightJoin(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Right-joins another query with an arbitrary predicate. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query rightJoin(Query inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Right-joins another query with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query rightJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return rightJoin(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Full equijoin. Unmatched elements on either side are passed with {@code null} + * for the other element. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query fullJoin(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Full equijoin. Closure parameters are inferred the same way as {@link #join}. + * + * @param inner the inner source + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query fullJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return fullJoin(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Full join with an arbitrary predicate. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query fullJoin(Iterable inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Full join with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner source + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query fullJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return fullJoin(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Full equijoin with another query. Unmatched elements on either side are passed with {@code null} for the other element. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + Query fullJoin(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector); + + /** + * Full equijoin with another query. Unmatched elements on either side are passed with {@code null} for the other element. Closure parameters are inferred the same way as the {@code Iterable} form. + * + * @param inner the inner query + * @param outerKey key from this query + * @param innerKey key from {@code inner} + * @param resultSelector the pair projection + * @param the inner element type + * @param the key type + * @param the result element type + * @return the joined query + */ + default Query fullJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T") Closure outerKey, + @ClosureParams(value = FromString.class, options = "U") Closure innerKey, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return fullJoin(inner, + item -> Query.invoke(outerKey, item), + item -> Query.invoke(innerKey, item), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Full join of another query with an arbitrary predicate. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query fullJoin(Query inner, + BiPredicate on, + BiFunction resultSelector); + + /** + * Full join of another query with an arbitrary predicate. + * Both closures receive {@code T} and the element type of {@code inner}. + * + * @param inner the inner query + * @param on the join predicate + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query fullJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure on, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return fullJoin(inner, + (outer, joined) -> truth(on, outer, joined), + (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Cross-joins {@code inner} and projects each pair. + * + * @param inner the inner source + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query crossJoin(Iterable inner, BiFunction resultSelector); + + /** + * Cross-joins {@code inner}. The closure parameters are {@code T} and the element type of {@code inner}. + * + * @param inner the inner source + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query crossJoin(Iterable inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return crossJoin(inner, (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Cross-joins another query and projects each pair. + * + * @param inner the inner query + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + Query crossJoin(Query inner, BiFunction resultSelector); + + /** + * Cross-joins another query. The closure parameters are {@code T} and the element type of {@code inner}. + * + * @param inner the inner query + * @param resultSelector the pair projection + * @param the inner element type + * @param the result element type + * @return the joined query + */ + default Query crossJoin(Query inner, + @ClosureParams(value = FromString.class, options = "T,U") Closure resultSelector) { + Objects.requireNonNull(inner, "inner"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return crossJoin(inner, (outer, joined) -> Query.invoke(resultSelector, outer, joined)); + } + + /** + * Drops duplicate elements. Equality is {@code equals}. + * + * @return the distinct query + */ + Query distinct(); + + /** + * Set union. Drops duplicates. + * + * @param other the other source + * @return the union + */ + Query union(Iterable other); + + /** + * Set union with another query. Drops duplicates. + * + * @param other the other query + * @return the union + */ + Query union(Query other); + + /** + * Concatenates {@code other}, keeping duplicates. Same role as LINQ {@code Concat}. + * + * @param other the other source + * @return the concatenation + */ + Query unionAll(Iterable other); + + /** + * Concatenates another query, keeping duplicates. + * + * @param other the other query + * @return the concatenation + */ + Query unionAll(Query other); + + /** + * Set intersection. + * + * @param other the other source + * @return the intersection + */ + Query intersect(Iterable other); + + /** + * Set intersection with another query. + * + * @param other the other query + * @return the intersection + */ + Query intersect(Query other); + + /** + * Set difference. Same role as LINQ {@code Except}. + * + * @param other the other source + * @return the difference + */ + Query minus(Iterable other); + + /** + * Set difference with another query. + * + * @param other the other query + * @return the difference + */ + Query minus(Query other); + + /** + * Same as {@link #minus(Iterable)}. + * + * @param other the other source + * @return the difference + */ + default Query except(Iterable other) { + return minus(other); + } + + /** + * Same as {@link #minus(Query)}. + * + * @param other the other query + * @return the difference + */ + default Query except(Query other) { + return minus(other); + } + + /** + * Same as {@link #unionAll(Iterable)}. + * + * @param other the other source + * @return the concatenation + */ + default Query concat(Iterable other) { + return unionAll(other); + } + + /** + * Same as {@link #unionAll(Query)}. + * + * @param other the other query + * @return the concatenation + */ + default Query concat(Query other) { + return unionAll(other); + } + + /** + * Drops {@code offset} elements and then keeps {@code size} elements. + * + * @param offset the number of elements to drop; zero keeps from the start + * @param size the maximum number of elements to keep + * @return the limited query + */ + Query limit(long offset, long size); + + /** + * Keeps at most {@code size} elements. + * + * @param size the maximum number of elements + * @return the limited query + */ + default Query limit(long size) { + return limit(0, size); + } + + /** + * Same as {@link #limit(long)}. LINQ calls this {@code Take}. + * + * @param count the maximum number of elements + * @return the limited query + */ + default Query take(long count) { + return limit(count); + } + + /** + * Drops the first {@code count} elements. LINQ calls this {@code Skip}. + * + * @param count the number of elements to drop + * @return the remaining query + */ + default Query skip(long count) { + return limit(count, Long.MAX_VALUE); + } + + /** + * Reads the query into a list. An iterable source is read again on every call, + * so a change made after the previous call is visible. A stream source is read + * on the first call and later calls replay that read. + * + * @return the elements + */ + List toList(); + + /** + * Returns a new stream over the elements. The stream has not been consumed. + * An iterable source is read when the returned stream is consumed, and a + * second call reads it again. + * + * @return a stream that has not been consumed + */ + Stream stream(); + + /** + * Reads the query and returns an iterator over the materialized elements. + * {@code Query} does not extend {@link Iterable}: {@code groupBy}, {@code count}, + * and {@code sum} would otherwise clash with the Groovy extension methods of that name. + * + * @return the elements + */ + Iterator iterator(); + + /** + * Returns whether the query has any elements. + * + * @return {@code true} when there is at least one element + */ + boolean exists(); + + /** + * Same as {@link #exists()}. + * + * @return {@code true} when there is at least one element + */ + default boolean any() { + return exists(); + } + + /** + * Returns whether any element matches {@code predicate}. + * + * @param predicate the filter + * @return {@code true} when an element matches + */ + boolean any(Predicate predicate); + + /** + * Returns whether any element matches {@code predicate}. The closure parameter is {@code T}. + * + * @param predicate the filter + * @return {@code true} when an element matches + */ + default boolean any(@ClosureParams(value = FromString.class, options = "T") Closure predicate) { + Objects.requireNonNull(predicate, "predicate"); + return any(item -> truth(predicate, item)); + } + + /** + * Returns whether every element matches {@code predicate}. An empty query returns {@code true}. + * + * @param predicate the filter + * @return {@code true} when every element matches + */ + boolean all(Predicate predicate); + + /** + * Returns whether every element matches {@code predicate}. The closure parameter is {@code T}. + * An empty query returns {@code true}. + * + * @param predicate the filter + * @return {@code true} when every element matches + */ + default boolean all(@ClosureParams(value = FromString.class, options = "T") Closure predicate) { + Objects.requireNonNull(predicate, "predicate"); + return all(item -> truth(predicate, item)); + } + + /** + * Returns the number of elements. + * + * @return the number of elements + */ + long count(); + + /** + * Returns the number of elements whose selected value is not {@code null}. + * + * @param selector the value to count + * @param the selected type + * @return the number of non-null selected values + */ + long count(Function selector); + + /** + * Returns the number of elements whose selected value is not {@code null}. + * The closure parameter is {@code T}. + * + * @param selector the value to count + * @param the selected type + * @return the number of non-null selected values + */ + default long count(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return count(item -> Query.invoke(selector, item)); + } + + /** + * Returns the sum of the selected numbers. {@code null} selections are ignored. + * + * @param selector the number to sum + * @return the sum, zero when nothing was summed + */ + BigDecimal sum(Function selector); + + /** + * Returns the sum of the selected numbers. The closure parameter is {@code T}. + * {@code null} selections are ignored. + * + * @param selector the number to sum + * @return the sum, zero when nothing was summed + */ + default BigDecimal sum(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return sum(item -> Query.invoke(selector, item)); + } + + /** + * Returns the average of the selected numbers. + * + * @param selector the number to average + * @return the average, or {@code null} when nothing was averaged + */ + BigDecimal avg(Function selector); + + /** + * Returns the average of the selected numbers. The closure parameter is {@code T}. + * + * @param selector the number to average + * @return the average, or {@code null} when nothing was averaged + */ + default BigDecimal avg(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return avg(item -> Query.invoke(selector, item)); + } + + /** + * Returns the minimum selected value. + * + * @param selector the value to compare + * @param the value type + * @return the minimum, or {@code null} when the query is empty + */ + > U min(Function selector); + + /** + * Returns the minimum selected value. The closure parameter is {@code T}. + * + * @param selector the value to compare + * @param the value type + * @return the minimum, or {@code null} when the query is empty + */ + default > U min(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return min(item -> Query.invoke(selector, item)); + } + + /** + * Returns the maximum selected value. + * + * @param selector the value to compare + * @param the value type + * @return the maximum, or {@code null} when the query is empty + */ + > U max(Function selector); + + /** + * Returns the maximum selected value. The closure parameter is {@code T}. + * + * @param selector the value to compare + * @param the value type + * @return the maximum, or {@code null} when the query is empty + */ + default > U max(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return max(item -> Query.invoke(selector, item)); + } + + /** + * Returns the median of the selected numbers. + * + * @param selector the number + * @return the median, or {@code null} when the query is empty + */ + BigDecimal median(Function selector); + + /** + * Returns the median of the selected numbers. The closure parameter is {@code T}. + * + * @param selector the number + * @return the median, or {@code null} when the query is empty + */ + default BigDecimal median(@ClosureParams(value = FromString.class, options = "T") Closure selector) { + Objects.requireNonNull(selector, "selector"); + return median(item -> Query.invoke(selector, item)); + } + + /** + * Reduces the query with {@code aggregator}. Same role as {@code agg} in a GINQ query + * and as LINQ {@code Aggregate} over the whole sequence. + * + * @param aggregator the reduction + * @param the result type + * @return the aggregate value + */ + R aggregate(Aggregator aggregator); + + /** + * Reduces the query with {@code aggregator}. The closure parameter is this query. + * + * @param aggregator the reduction + * @param the result type + * @return the aggregate value + */ + default R aggregate(@ClosureParams(value = FromString.class, options = "groovy.ginq.Query") Closure aggregator) { + Objects.requireNonNull(aggregator, "aggregator"); + return aggregate(rows -> Query.invoke(aggregator, rows)); + } + + /** + * Folds the elements, starting from {@code seed}. Same role as LINQ {@code Aggregate}. + * + * @param seed the initial value + * @param accumulator combines the current value with the next element + * @param the accumulator type + * @return the final value, which is {@code seed} when the query is empty + */ + A aggregate(A seed, BiFunction accumulator); + + /** + * Folds the elements, starting from {@code seed}. + * The closure parameters are the accumulator and {@code T}. + * + * @param seed the initial value + * @param accumulator combines the current value with the next element + * @param the accumulator type + * @return the final value, which is {@code seed} when the query is empty + */ + default A aggregate(A seed, @ClosureParams(value = FromString.class, options = "A,T") Closure accumulator) { + Objects.requireNonNull(accumulator, "accumulator"); + return aggregate(seed, (current, item) -> Query.invoke(accumulator, current, item)); + } + + @SuppressWarnings("unchecked") + private static R invoke(Closure closure, Object arg) { + return (R) closure.call(arg); + } + + @SuppressWarnings("unchecked") + private static R invoke(Closure closure, Object first, Object second) { + return (R) closure.call(first, second); + } + + private static boolean truth(Closure closure, Object arg) { + return DefaultTypeTransformation.castToBoolean(closure.call(arg)); + } + + private static boolean truth(Closure closure, Object first, Object second) { + return DefaultTypeTransformation.castToBoolean(closure.call(first, second)); + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/package-info.java b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/package-info.java new file mode 100644 index 00000000000..0d9749b19ab --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/groovy/ginq/package-info.java @@ -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. + */ + +/** + * GINQ, Groovy Integrated Query. + * + *

+ * Two front ends share the collection query runtime. {@code GQ}, {@code GQL}, and + * {@code @GQ} are the SQL-like syntax. {@link Ginq} and + * {@link Query} are the fluent, LINQ-style method syntax: + * {@code where}, {@code select}, {@code orderBy}, {@code groupBy}, {@code join}, + * and {@code aggregate}. Database providers are driven by the SQL-like syntax, + * which keeps an expression tree. The fluent API runs in memory. + *

+ */ +package groovy.ginq; 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..0a386039ea1 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 @@ -18,7 +18,9 @@ */ package groovy.ginq.transform; +import groovy.ginq.Ginq; 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; @@ -30,7 +32,14 @@ import java.lang.annotation.Target; /** - * Method annotation to make a method call returning GINQ result + * Method annotation to make a method call returning GINQ result. + *

+ * The method body is GINQ syntax, not a Groovy block. It can be used from a + * {@code @CompileStatic} or {@code @TypeChecked} class: the method is checked + * with the enclosing annotation, and the lowered query closure stays dynamically + * dispatched. A {@code def} method is given the result type of {@link #value()} + * when that does not conflict with a superclass method. For a statically typed + * chain of operators, use {@link Ginq} instead of this annotation. * * @since 4.0.0 */ @@ -63,4 +72,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..b52b36f8013 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 @@ -82,7 +83,8 @@ class GinqGroovyMethods { */ @Macro static Expression GQ(final MacroContext ctx, final MapExpression ginqConfigurationMapExpression, final ClosureExpression ginqClosureExpression) { - transformGinqCode(ctx.sourceUnit, ginqConfigurationMapExpression, ginqClosureExpression.code) + Expression query = transformGinqCode(ctx.sourceUnit, ginqConfigurationMapExpression, ginqClosureExpression.code) + GinqStaticBridge.embed(ctx.sourceUnit, ctx.call, query) } /** @@ -111,27 +113,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 +235,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/GinqRowChecks.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqRowChecks.java new file mode 100644 index 00000000000..457abaecf7b --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqRowChecks.java @@ -0,0 +1,938 @@ +/* + * 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; + +import org.codehaus.groovy.ast.AnnotatedNode; +import org.codehaus.groovy.ast.AnnotationNode; +import org.codehaus.groovy.ast.ClassCodeExpressionTransformer; +import org.codehaus.groovy.ast.ClassHelper; +import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.CodeVisitorSupport; +import org.codehaus.groovy.ast.GenericsType; +import org.codehaus.groovy.ast.FieldNode; +import org.codehaus.groovy.ast.MethodNode; +import org.codehaus.groovy.ast.Parameter; +import org.codehaus.groovy.ast.PropertyNode; +import org.codehaus.groovy.ast.Variable; +import org.codehaus.groovy.ast.expr.ArgumentListExpression; +import org.codehaus.groovy.ast.expr.ArrayExpression; +import org.codehaus.groovy.ast.expr.BinaryExpression; +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.Expression; +import org.codehaus.groovy.ast.expr.ListExpression; +import org.codehaus.groovy.ast.expr.MethodCall; +import org.codehaus.groovy.ast.expr.MethodCallExpression; +import org.codehaus.groovy.ast.expr.PropertyExpression; +import org.codehaus.groovy.ast.expr.TupleExpression; +import org.codehaus.groovy.ast.expr.VariableExpression; +import org.codehaus.groovy.ast.stmt.ReturnStatement; +import org.apache.groovy.ginq.provider.collection.runtime.Queryable; +import org.apache.groovy.ginq.provider.collection.runtime.QueryableHelper; +import org.apache.groovy.ginq.provider.collection.runtime.SourceRecord; +import org.codehaus.groovy.ast.tools.GenericsUtils; +import org.codehaus.groovy.control.ErrorCollector; +import org.codehaus.groovy.control.SourceUnit; +import org.codehaus.groovy.control.messages.Message; +import org.codehaus.groovy.control.messages.SyntaxErrorMessage; +import org.codehaus.groovy.runtime.ScriptBytecodeAdapter; +import org.codehaus.groovy.syntax.Types; +import org.codehaus.groovy.transform.stc.AbstractTypeCheckingExtension; +import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor; +import org.codehaus.groovy.transform.stc.StaticTypesMarker; +import org.codehaus.groovy.transform.stc.TypeCheckingContext; + +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +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.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.nullX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.varX; + +/** + * Type-checking extension for a GINQ query under {@code @CompileStatic} and {@code @TypeChecked}. + *

+ * The extension is registered on the checking annotation, so it is present for the whole + * class. Every hook returns immediately unless the expression is inside a closure marked + * {@link #QUERY}. Code outside that closure is left to the ordinary checker. + *

+ * The lowered query closure stays on the static writer. A call the checker selects, + * including a target another extension replaced, is kept. An unresolved call is + * rewritten to {@link ScriptBytecodeAdapter} so the stand-in is not invoked. + * {@code from} stays dynamic when the chosen parameter is an array and the + * argument is not. A target whose declaring class is not public stays dynamic. + * Outside the query, only a query result used as the receiver of {@code toList}, + * {@code get}, {@code getAt}, or a subscript is treated as a row. A field or an + * enclosing-method parameter is left to the ordinary checker. + * + * @since 7.0.0 + */ +public class GinqRowChecks extends AbstractTypeCheckingExtension { + + /** + * Metadata key on a closure that was lowered from a GINQ query. + * The value is {@link Boolean#TRUE}. + */ + static final Object QUERY = GinqRowChecks.class; + + /** + * Metadata on a {@code navigate} call: the alias names of the row, in + * from-then-join order. A static property {@code r.alias} uses them to + * pick the component type of a join tuple. + */ + private static final String ALIAS_NAMES = "ginqAliasNames"; + + /** + * Creates the extension for one type-checking visitor. + * + * @param typeCheckingVisitor the visitor compiling the class that contains the query + */ + public GinqRowChecks(StaticTypeCheckingVisitor typeCheckingVisitor) { + super(typeCheckingVisitor); + } + + @Override + public boolean beforeMethodCall(MethodCall call) { + if (insideQuery() && compileStaticScope() && call instanceof MethodCallExpression methodCall) { + rememberAliases(methodCall); + } + if (!insideQuery() || !(call instanceof Expression expression) || compileStaticScope()) { + // Static compilation has to visit the arguments so a method another + // extension selects is still the target that is emitted. + return false; + } + // @TypeChecked does not emit that target. Inferring clause SAM types + // here writes a generic signature the dynamic closure cannot load. + makeDynamic(call, ClassHelper.OBJECT_TYPE); + storeType(expression, ClassHelper.OBJECT_TYPE); + return true; + } + + @Override + public boolean handleUnresolvedProperty(PropertyExpression expression) { + if (insideQuery() || resultReceiver(expression.getObjectExpression())) { + ClassNode value = sourceRecordValue(expression); + makeDynamic(expression, value != null ? value : ClassHelper.OBJECT_TYPE); + return true; + } + return false; + } + + @Override + public List handleMissingMethod(ClassNode receiver, String name, ArgumentListExpression argumentList, ClassNode[] argumentTypes, MethodCall call) { + if (call == null) { + return Collections.emptyList(); + } + boolean query = insideQuery(); + boolean result = !query && call instanceof MethodCallExpression methodCall && resultReceiver(methodCall.getObjectExpression()); + if (!query && !result) { + return Collections.emptyList(); + } + if (result && !"toList".equals(name) && !"get".equals(name) && !"getAt".equals(name)) { + return Collections.emptyList(); + } + ClassNode type = "toList".equals(name) ? ClassHelper.LIST_TYPE : ClassHelper.OBJECT_TYPE; + MethodNode standIn = makeDynamic(call, type); + // A null declaring class fails later when the target is stored. Object + // is only the stand-in's owner: the call is rewritten to a real adapter + // method before bytecode, so this is not invokevirtual Object.name(). + if (standIn.getDeclaringClass() == null) { + standIn.setDeclaringClass(ClassHelper.OBJECT_TYPE); + } + return Collections.singletonList(standIn); + } + + @Override + public boolean handleIncompatibleReturnType(ReturnStatement statement, ClassNode inferredReturnType) { + // A clause lambda's row value is dynamic. The SAM type is what a + // typed aggregate asked for; the value is coerced when the lambda runs. + return insideQuery(); + } + + @Override + public void afterMethodCall(MethodCall call) { + if (!(call instanceof MethodCallExpression methodCall)) { + return; + } + if (insideQuery() && compileStaticScope() && "navigate".equals(methodCall.getMethodAsString())) { + repairNavigateType(methodCall); + } + if (insideQuery()) { + if (!compileStaticScope()) { + if (methodCall.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION) != null) { + methodCall.setMethodTarget(null); + methodCall.removeNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); + } + } else { + MethodNode target = methodCall.getNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET); + if (standIn(methodCall, target) && !"navigate".equals(methodCall.getMethodAsString())) { + rewriteUnresolved(methodCall); + } else if (target != null && arrayFromMismatch(methodCall, target)) { + methodCall.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, ClassHelper.OBJECT_TYPE); + } else if (target != null && hiddenType(target.getDeclaringClass())) { + methodCall.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, ClassHelper.OBJECT_TYPE); + } + } + } + if (!"toList".equals(methodCall.getMethodAsString())) { + return; + } + Expression receiver = methodCall.getObjectExpression(); + if (!(receiver instanceof MethodCallExpression macro) || !"macroMethod".equals(macro.getMethodAsString())) { + return; + } + // The macro result is still MacroStub.macroMethod(query) when the checker + // runs. toList() on that call is a raw List. + ClassNode list = ClassHelper.LIST_TYPE.getPlainNodeReference(); + list.setGenericsTypes(null); + list.setUsingGenerics(false); + storeType(methodCall, list); + } + + /** + * A subscript on a query result is coerced to {@code List} so static compilation + * can emit {@code getAt}. The coercion stays outside the query closure: inside it + * the dynamic writer handles the subscript, and a method parameter or field is + * left alone so {@code value[0]} on an unrelated {@code Object} is still an error. + */ + @Override + public void afterVisitMethod(MethodNode node) { + if (node.getCode() == null) { + return; + } + if (compileStaticScope()) { + node.getCode().visit(new UnprovableOperatorRewriter()); + // A number comparison stays an operator and is a primitive compare. + // A comparison javac would reject (a dynamic row property) is still + // the static writer's ScriptBytecodeAdapter fallback, so the missing + // compareTo/equals/isCase error is not a failure of the query. + forgiveUnprovableComparison(node); + } + node.getCode().visit(new CodeVisitorSupport() { + private int queryDepth; + + @Override + public void visitClosureExpression(ClosureExpression expression) { + boolean query = Boolean.TRUE.equals(expression.getNodeMetaData(QUERY)); + if (query) { + queryDepth++; + } + super.visitClosureExpression(expression); + if (query) { + queryDepth--; + } + } + + @Override + public void visitBinaryExpression(BinaryExpression expression) { + if (queryDepth == 0 + && expression.getOperation().getType() == Types.LEFT_SQUARE_BRACKET + && resultReceiver(expression.getLeftExpression())) { + CastExpression cast = castX(ClassHelper.LIST_TYPE, expression.getLeftExpression()); + cast.setCoerce(true); + cast.setSourcePosition(expression.getLeftExpression()); + expression.setLeftExpression(cast); + } + super.visitBinaryExpression(expression); + } + }); + } + + /** + * A closure or lambda parameter that holds a query row. A field or a parameter + * of the enclosing method is not a row, so a typo on it stays an error. + */ + private boolean resultReceiver(Expression receiver) { + ClassNode type = typeOf(receiver); + if (namedRow(type)) { + return true; + } + if (receiver instanceof BinaryExpression binary + && binary.getOperation().getType() == Types.LEFT_SQUARE_BRACKET + && heldLocal(binary.getLeftExpression())) { + return true; + } + if (receiver instanceof MethodCallExpression call) { + String name = call.getMethodAsString(); + if (("getAt".equals(name) || "get".equals(name)) && heldLocal(call.getObjectExpression())) { + return true; + } + } + if (!(receiver instanceof VariableExpression variable)) { + return false; + } + Variable accessed = variable.getAccessedVariable(); + if (accessed instanceof FieldNode || accessed instanceof PropertyNode) { + return false; + } + if (accessed instanceof Parameter parameter) { + MethodNode method = typeCheckingVisitor.getTypeCheckingContext().getEnclosingMethod(); + if (method != null) { + for (Parameter declared : method.getParameters()) { + if (declared == parameter) { + return false; + } + } + } + return true; + } + return "it".equals(variable.getName()) + && !typeCheckingVisitor.getTypeCheckingContext().getEnclosingClosureStack().isEmpty(); + } + + /** + * A local or nested row holder. A field and an enclosing-method parameter are excluded, + * so {@code value[0]} on those stays a static error. A local such as the {@code GQ} + * result is included, so {@code result[0].toList()} still type-checks. + */ + private boolean heldLocal(Expression receiver) { + if (resultReceiver(receiver)) { + return true; + } + if (receiver instanceof BinaryExpression binary + && binary.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) { + return heldLocal(binary.getLeftExpression()); + } + if (!(receiver instanceof VariableExpression variable)) { + return false; + } + Variable accessed = variable.getAccessedVariable(); + if (accessed instanceof FieldNode || accessed instanceof PropertyNode) { + return false; + } + if (accessed instanceof Parameter parameter) { + MethodNode method = typeCheckingVisitor.getTypeCheckingContext().getEnclosingMethod(); + if (method != null) { + for (Parameter declared : method.getParameters()) { + if (declared == parameter) { + return false; + } + } + } + } + return true; + } + + /** + * {@code @CompileStatic} emits the method the checker selected. + * {@code @TypeChecked} only checks, and the clause stays a dynamic closure. + */ + private boolean compileStaticScope() { + TypeCheckingContext context = typeCheckingVisitor.getTypeCheckingContext(); + if (annotated(context.getEnclosingMethod(), "groovy.transform.CompileDynamic")) { + return false; + } + if (annotated(context.getEnclosingMethod(), "groovy.transform.CompileStatic")) { + return true; + } + ClassNode type = context.getEnclosingClassNode(); + while (type != null) { + if (annotated(type, "groovy.transform.CompileDynamic")) { + return false; + } + if (annotated(type, "groovy.transform.CompileStatic")) { + return true; + } + type = type.getOuterClass(); + } + return false; + } + + private static boolean annotated(AnnotatedNode node, String name) { + if (node == null) { + return false; + } + for (AnnotationNode annotation : node.getAnnotations()) { + ClassNode type = annotation.getClassNode(); + if (type != null && name.equals(type.getName())) { + return true; + } + } + return false; + } + + private boolean insideQuery() { + List stack = typeCheckingVisitor.getTypeCheckingContext().getEnclosingClosureStack(); + for (TypeCheckingContext.EnclosingClosure enclosing : stack) { + if (Boolean.TRUE.equals(enclosing.getClosureExpression().getNodeMetaData(QUERY))) { + return true; + } + } + return false; + } + + private static ClassNode typeOf(Expression expression) { + ClassNode inferred = expression.getNodeMetaData(StaticTypesMarker.INFERRED_TYPE); + return inferred != null ? inferred : expression.getType(); + } + + private static boolean namedRow(ClassNode type) { + if (type == null) { + return false; + } + String name = type.getName(); + return "org.apache.groovy.ginq.provider.collection.runtime.NamedRecord".equals(name) + || "org.apache.groovy.ginq.provider.collection.runtime.NamedTuple".equals(name) + || "org.apache.groovy.ginq.provider.collection.runtime.SourceRecord".equals(name) + || "org.apache.groovy.ginq.provider.collection.runtime.GroupResult".equals(name); + } + + /** + * A {@code makeDynamic} stand-in has no real parameter list. A selected + * method, including one another extension stored, is not a stand-in. + */ + private static boolean standIn(MethodCallExpression call, MethodNode target) { + if (call.getNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION) == null) { + return false; + } + String name = call.getMethodAsString(); + if ("invokeMethodN".equals(name) || "invokeMethodNSafe".equals(name)) { + return false; + } + if (target == null || target.getDeclaringClass() == null) { + return true; + } + return target.getParameters().length == 0 && target.getName().equals(name); + } + + private static boolean arrayFromMismatch(MethodCallExpression call, MethodNode target) { + if (!"from".equals(target.getName()) || target.getParameters().length != 1) { + return false; + } + if (!target.getParameters()[0].getType().isArray()) { + return false; + } + List arguments = argumentList(call.getArguments()); + if (arguments.size() != 1) { + return false; + } + ClassNode argumentType = arguments.get(0).getNodeMetaData(StaticTypesMarker.INFERRED_TYPE); + if (argumentType == null) { + argumentType = arguments.get(0).getType(); + } + return argumentType == null || !argumentType.isArray(); + } + + private static boolean hiddenType(ClassNode type) { + if (type == null || !type.isResolved()) { + return false; + } + return !Modifier.isPublic(type.redirect().getModifiers()); + } + + /** + * Replaces an unresolved call with {@code ScriptBytecodeAdapter.invokeMethodN}. + * The adapter method is a real public target. The original receiver and + * arguments are the values it dispatches. + */ + private void rewriteUnresolved(MethodCallExpression call) { + String name = call.getMethodAsString(); + if (name == null) { + return; + } + Expression object = call.getObjectExpression(); + // implicitThis stays true on calls the walker built with an explicit + // receiver. Only a real this-call uses the enclosing instance. + boolean implicit = call.isImplicitThis() && thisReceiver(object); + Expression receiver = implicit ? implicitReceiver() : object; + List original = argumentList(call.getArguments()); + ArrayExpression array = new ArrayExpression(ClassHelper.OBJECT_TYPE, new ArrayList<>(original)); + String adapter = call.isSafe() ? "invokeMethodNSafe" : "invokeMethodN"; + call.setObjectExpression(classX(ClassHelper.make(ScriptBytecodeAdapter.class))); + call.setMethod(constX(adapter)); + call.setArguments(args(nullX(), receiver, constX(name), array)); + call.setImplicitThis(false); + call.setSafe(false); + MethodNode target = adapterMethod(adapter); + call.setMethodTarget(target); + call.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, target); + call.removeNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION); + storeType(call, ClassHelper.OBJECT_TYPE); + } + + private static boolean thisReceiver(Expression object) { + return object instanceof VariableExpression variable && "this".equals(variable.getName()); + } + + private Expression implicitReceiver() { + MethodNode enclosing = typeCheckingVisitor.getTypeCheckingContext().getEnclosingMethod(); + if (enclosing != null && enclosing.isStatic()) { + return classX(typeCheckingVisitor.getTypeCheckingContext().getEnclosingClassNode()); + } + return varX("this"); + } + + private static MethodNode adapterMethod(String name) { + ClassNode type = ClassHelper.make(ScriptBytecodeAdapter.class); + for (MethodNode method : type.getDeclaredMethods(name)) { + if (method.getParameters().length == 4) { + return method; + } + } + throw new IllegalStateException(name); + } + + private static List argumentList(Expression arguments) { + if (arguments instanceof TupleExpression tuple) { + return new ArrayList<>(tuple.getExpressions()); + } + List one = new ArrayList<>(); + if (arguments != null) { + one.add(arguments); + } + return one; + } + + /** + * The static type of {@code row.alias} when {@code row} is a + * {@code SourceRecord}. A single source is that element type. A join is + * the matching component of the nested tuple. + */ + private ClassNode sourceRecordValue(PropertyExpression expression) { + if (!compileStaticScope()) { + return null; + } + String name = expression.getPropertyAsString(); + if (name == null) { + return null; + } + ClassNode receiver = typeOf(expression.getObjectExpression()); + if (receiver == null || !"org.apache.groovy.ginq.provider.collection.runtime.SourceRecord".equals(receiver.redirect().getName())) { + return null; + } + ClassNode element = ClassHelper.OBJECT_TYPE; + GenericsType[] arguments = receiver.getGenericsTypes(); + if (arguments != null && arguments.length == 1 && arguments[0].getType() != null) { + element = arguments[0].getType(); + if (ClassHelper.isPrimitiveType(element) && !ClassHelper.isPrimitiveVoid(element)) { + element = ClassHelper.getWrapper(element); + } + } + return aliasType(element, aliasNames(), name); + } + + private void rememberAliases(MethodCallExpression call) { + List names = aliasNames(call.getObjectExpression()); + if (names == null) { + names = aliasNames(call); + } + if (names == null || !(call.getArguments() instanceof TupleExpression tuple)) { + return; + } + for (Expression argument : tuple.getExpressions()) { + if (argument instanceof ClosureExpression closure && closure.getNodeMetaData(ALIAS_NAMES) == null) { + closure.putNodeMetaData(ALIAS_NAMES, names); + } + } + } + + /** + * {@code navigate} is {@code Queryable>}. When the argument + * is still {@code Object}, method selection fails and {@code stream()} binds + * to the single-element DGM instead of {@link Queryable#stream()}. + * Restore the return type from the argument, or from the clause row parameter. + */ + private void repairNavigateType(MethodCallExpression call) { + if (!(call.getObjectExpression() instanceof ClassExpression owner) + || !"org.apache.groovy.ginq.provider.collection.runtime.QueryableHelper".equals(owner.getType().redirect().getName())) { + return; + } + ClassNode result = typeOf(call); + if (result != null && !ClassHelper.OBJECT_TYPE.equals(result) && !ClassHelper.isDynamicTyped(result)) { + return; + } + ClassNode element = elementType(call); + ClassNode record = GenericsUtils.makeClassSafeWithGenerics(SourceRecord.class, element); + ClassNode queryable = GenericsUtils.makeClassSafeWithGenerics(Queryable.class, record); + storeType(call, queryable); + call.removeNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION); + for (MethodNode method : ClassHelper.make(QueryableHelper.class).getDeclaredMethods("navigate")) { + if (method.getParameters().length == 2) { + call.setMethodTarget(method); + call.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, method); + break; + } + } + } + + private ClassNode elementType(MethodCallExpression navigate) { + if (navigate.getArguments() instanceof TupleExpression tuple && !tuple.getExpressions().isEmpty()) { + ClassNode fromArgument = queryableElement(typeOf(tuple.getExpression(0))); + if (fromArgument != null) { + return fromArgument; + } + } + // Only parameters of this query. An enclosing closure such as + // `{ String label -> GQ { ... } }` is not the row type, and a Queryable + // parameter's element type wins over a nested `{ String label -> ... }`. + ClassNode fallback = null; + // Index 0 is the innermost closure. Stop at the first closure that is + // not part of the query, so an outer `{ String label -> GQ { ... } }` + // is not the row type. + List stack = typeCheckingVisitor.getTypeCheckingContext().getEnclosingClosureStack(); + for (int i = 0; i < stack.size(); i += 1) { + ClosureExpression closure = stack.get(i).getClosureExpression(); + if (!Boolean.TRUE.equals(closure.getNodeMetaData(QUERY))) { + break; + } + Parameter[] parameters = closure.getParameters(); + if (parameters == null) { + continue; + } + for (Parameter parameter : parameters) { + ClassNode fromQueryable = queryableElement(parameter.getType()); + if (fromQueryable != null) { + return fromQueryable; + } + if (fallback == null) { + fallback = rowElement(parameter.getType()); + } + } + } + return fallback != null ? fallback : ClassHelper.OBJECT_TYPE; + } + + /** + * The element of a {@code Queryable} parameter or argument. A wildcard + * bound is that bound, so {@code Queryable} is + * {@code Integer}. A {@code SourceRecord} argument is the row already, not + * the element to wrap again. + */ + private static ClassNode queryableElement(ClassNode type) { + if (type == null || !"org.apache.groovy.ginq.provider.collection.runtime.Queryable".equals(type.redirect().getName())) { + return null; + } + GenericsType[] arguments = type.getGenericsTypes(); + if (arguments == null || arguments.length != 1) { + return null; + } + return rowElement(referenceBound(arguments[0])); + } + + private static ClassNode rowElement(ClassNode type) { + if (type == null || ClassHelper.isDynamicTyped(type) || ClassHelper.OBJECT_TYPE.equals(type)) { + return null; + } + if (ClassHelper.isPrimitiveType(type)) { + return ClassHelper.isPrimitiveVoid(type) ? null : ClassHelper.getWrapper(type); + } + String name = type.redirect().getName(); + if ("org.apache.groovy.ginq.provider.collection.runtime.Queryable".equals(name) + || "org.apache.groovy.ginq.provider.collection.runtime.SourceRecord".equals(name)) { + return null; + } + return type; + } + + private static ClassNode referenceBound(GenericsType type) { + if (type == null) { + return null; + } + if (type.isWildcard()) { + if (type.getLowerBound() != null) { + return type.getLowerBound(); + } + ClassNode[] upper = type.getUpperBounds(); + if (upper != null && upper.length > 0 && upper[0] != null) { + return upper[0]; + } + } + return type.getType(); + } + + /** + * Drops a missing {@code compareTo}, {@code equals}, or {@code isCase} + * error on a comparison inside the query. The static writer already emits + * {@code ScriptBytecodeAdapter} for a comparison it cannot turn into a + * primitive compare. A number comparison does not produce this error. + */ + private void forgiveUnprovableComparison(MethodNode node) { + SourceUnit source = node.getDeclaringClass().getModule() == null ? null : node.getDeclaringClass().getModule().getContext(); + if (source == null || source.getErrorCollector() == null || !source.getErrorCollector().hasErrors()) { + return; + } + Set positions = new HashSet<>(); + node.getCode().visit(new CodeVisitorSupport() { + private int queryDepth; + + @Override + public void visitClosureExpression(ClosureExpression expression) { + boolean query = Boolean.TRUE.equals(expression.getNodeMetaData(QUERY)); + if (query) { + queryDepth += 1; + } + super.visitClosureExpression(expression); + if (query) { + queryDepth -= 1; + } + } + + @Override + public void visitBinaryExpression(BinaryExpression expression) { + if (queryDepth > 0 && comparison(expression.getOperation().getType()) + && expression.getLineNumber() > 0 && expression.getColumnNumber() > 0) { + positions.add((((long) expression.getLineNumber()) << 32) + expression.getColumnNumber()); + } + super.visitBinaryExpression(expression); + } + }); + if (positions.isEmpty()) { + return; + } + ErrorCollector collector = source.getErrorCollector(); + synchronized (collector) { + Iterator messages = collector.getErrors().iterator(); + while (messages.hasNext()) { + Message message = messages.next(); + if (!(message instanceof SyntaxErrorMessage syntax)) { + continue; + } + String text = syntax.getCause().getMessage(); + if (text == null || !(text.contains("#compareTo") || text.contains("#equals") + || text.contains("#isCase") || text.contains("#isNotCase"))) { + continue; + } + long key = (((long) syntax.getCause().getStartLine()) << 32) + syntax.getCause().getStartColumn(); + if (positions.contains(key)) { + messages.remove(); + } + } + } + } + + private static boolean comparison(int operation) { + return switch (operation) { + case Types.COMPARE_EQUAL, Types.COMPARE_NOT_EQUAL, Types.COMPARE_GREATER_THAN, + Types.COMPARE_GREATER_THAN_EQUAL, Types.COMPARE_LESS_THAN, Types.COMPARE_LESS_THAN_EQUAL, + Types.COMPARE_TO, Types.COMPARE_IDENTICAL, Types.COMPARE_NOT_IDENTICAL, + Types.KEYWORD_IN, Types.COMPARE_NOT_IN, Types.FIND_REGEX, Types.MATCH_REGEX -> true; + default -> false; + }; + } + + private List aliasNames() { + for (Expression call : typeCheckingVisitor.getTypeCheckingContext().getEnclosingMethodCalls()) { + List names = aliasNames(call); + if (names != null) { + return names; + } + } + List stack = typeCheckingVisitor.getTypeCheckingContext().getEnclosingClosureStack(); + for (TypeCheckingContext.EnclosingClosure enclosing : stack) { + Object metadata = enclosing.getClosureExpression().getNodeMetaData(ALIAS_NAMES); + if (metadata instanceof List names && !names.isEmpty() && names.get(0) instanceof String) { + List aliases = new ArrayList<>(); + for (Object name : names) { + if (name instanceof String text) { + aliases.add(text); + } + } + return aliases; + } + } + return null; + } + + private static List aliasNames(Expression expression) { + Expression current = expression; + while (current instanceof MethodCallExpression call) { + if ("navigate".equals(call.getMethodAsString()) && call.getArguments() instanceof TupleExpression tuple + && tuple.getExpressions().size() >= 2) { + List names = constantStrings(tuple.getExpression(1)); + if (names != null) { + return names; + } + } + current = call.getObjectExpression(); + } + return null; + } + + private static List constantStrings(Expression expression) { + if (!(expression instanceof ListExpression list)) { + return null; + } + List names = new ArrayList<>(); + for (Expression element : list.getExpressions()) { + if (!(element instanceof ConstantExpression constant) || !(constant.getValue() instanceof String text)) { + return null; + } + names.add(text); + } + return names.isEmpty() ? null : names; + } + + private static ClassNode aliasType(ClassNode element, List aliases, String name) { + if (element == null) { + return ClassHelper.OBJECT_TYPE; + } + if (aliases == null || aliases.isEmpty() || !tuple(element)) { + return element; + } + ClassNode current = element; + for (int i = aliases.size() - 1; i >= 0 && current != null; i -= 1) { + if (name.equals(aliases.get(i))) { + return tuple(current) ? tupleComponent(current, 1) : current; + } + if (!tuple(current)) { + break; + } + current = tupleComponent(current, 0); + } + return element; + } + + private static boolean tuple(ClassNode type) { + return type != null && "groovy.lang.Tuple2".equals(type.redirect().getName()); + } + + private static ClassNode tupleComponent(ClassNode tuple, int index) { + GenericsType[] arguments = tuple.getGenericsTypes(); + if (arguments == null || arguments.length <= index || arguments[index].getType() == null) { + return ClassHelper.OBJECT_TYPE; + } + ClassNode type = arguments[index].getType(); + if (ClassHelper.isPrimitiveType(type) && !ClassHelper.isPrimitiveVoid(type)) { + return ClassHelper.getWrapper(type); + } + return type; + } + + /** + * Rewrites an arithmetic operator or subscript the static writer cannot + * prove into {@code ScriptBytecodeAdapter.invokeMethodN}. A number, a + * string concatenation, a map read, and an array read stay operators. + */ + private static final class UnprovableOperatorRewriter extends ClassCodeExpressionTransformer { + private int queryDepth; + + @Override + protected SourceUnit getSourceUnit() { + return null; + } + + @Override + public Expression transform(Expression expression) { + if (expression instanceof ClosureExpression closure) { + boolean query = Boolean.TRUE.equals(closure.getNodeMetaData(QUERY)); + if (query) { + queryDepth += 1; + } + closure.visit(this); + if (query) { + queryDepth -= 1; + } + return closure; + } + if (expression instanceof BinaryExpression binary && Types.isAssignment(binary.getOperation().getType())) { + Expression left = binary.getLeftExpression(); + if (left instanceof BinaryExpression index && index.getOperation().getType() == Types.LEFT_SQUARE_BRACKET) { + index.setLeftExpression(transform(index.getLeftExpression())); + index.setRightExpression(transform(index.getRightExpression())); + } else { + binary.setLeftExpression(transform(left)); + } + binary.setRightExpression(transform(binary.getRightExpression())); + return binary; + } + Expression transformed = super.transform(expression); + if (queryDepth > 0 && transformed instanceof BinaryExpression binary) { + Expression rewritten = unprovable(binary); + if (rewritten != null) { + return rewritten; + } + } + return transformed; + } + + private static Expression unprovable(BinaryExpression binary) { + String name = operatorName(binary.getOperation().getType()); + if (name == null || provable(binary)) { + return null; + } + ArrayExpression array = new ArrayExpression(ClassHelper.OBJECT_TYPE, new ArrayList<>(List.of(binary.getRightExpression()))); + MethodCallExpression call = callX(classX(ClassHelper.make(ScriptBytecodeAdapter.class)), "invokeMethodN", + args(nullX(), binary.getLeftExpression(), constX(name), array)); + call.setImplicitThis(false); + call.setSourcePosition(binary); + return call; + } + + private static boolean provable(BinaryExpression binary) { + int operation = binary.getOperation().getType(); + ClassNode left = typeOf(binary.getLeftExpression()); + ClassNode right = typeOf(binary.getRightExpression()); + if (operation == Types.LEFT_SQUARE_BRACKET) { + if (binary.getLeftExpression() instanceof VariableExpression variable && "ginqCaptured$".equals(variable.getName())) { + return true; + } + if (left != null && left.isArray() && number(right)) { + return true; + } + return left != null && (left.implementsInterface(ClassHelper.MAP_TYPE) || ClassHelper.MAP_TYPE.equals(left.redirect())); + } + if (operation == Types.PLUS && left != null && ClassHelper.isStringType(left)) { + return true; + } + return number(left) && number(right); + } + + private static boolean number(ClassNode type) { + if (type == null || ClassHelper.isDynamicTyped(type) || ClassHelper.OBJECT_TYPE.equals(type)) { + return false; + } + if (ClassHelper.isPrimitiveType(type)) { + return !ClassHelper.isPrimitiveBoolean(type) && !ClassHelper.isPrimitiveVoid(type); + } + return ClassHelper.getWrapper(type).isDerivedFrom(ClassHelper.Number_TYPE); + } + + private static String operatorName(int operation) { + return switch (operation) { + case Types.PLUS -> "plus"; + case Types.MINUS -> "minus"; + case Types.MULTIPLY -> "multiply"; + case Types.DIVIDE -> "div"; + case Types.INTDIV -> "intdiv"; + case Types.MOD -> "mod"; + case Types.REMAINDER -> "remainder"; + case Types.POWER -> "power"; + case Types.LEFT_SQUARE_BRACKET -> "getAt"; + case Types.LEFT_SHIFT -> "leftShift"; + case Types.RIGHT_SHIFT -> "rightShift"; + case Types.RIGHT_SHIFT_UNSIGNED -> "rightShiftUnsigned"; + case Types.BITWISE_AND -> "and"; + case Types.BITWISE_OR -> "or"; + case Types.BITWISE_XOR -> "xor"; + default -> null; + }; + } + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqStaticBridge.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqStaticBridge.java new file mode 100644 index 00000000000..132eaf0b815 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/GinqStaticBridge.java @@ -0,0 +1,915 @@ +/* + * 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; + +import groovy.transform.Internal; +import org.apache.groovy.ginq.provider.collection.runtime.LazyQueryable; +import org.apache.groovy.ginq.provider.collection.runtime.Queryable; +import org.codehaus.groovy.ast.ASTNode; +import org.codehaus.groovy.ast.AnnotatedNode; +import org.codehaus.groovy.ast.AnnotationNode; +import org.codehaus.groovy.ast.ClassCodeExpressionTransformer; +import org.codehaus.groovy.ast.ClassCodeVisitorSupport; +import org.codehaus.groovy.ast.ClassHelper; +import org.codehaus.groovy.ast.ClassNode; +import org.codehaus.groovy.ast.CodeVisitorSupport; +import org.codehaus.groovy.ast.DynamicVariable; +import org.codehaus.groovy.ast.FieldNode; +import org.codehaus.groovy.ast.MethodNode; +import org.codehaus.groovy.ast.Parameter; +import org.codehaus.groovy.ast.PropertyNode; +import org.codehaus.groovy.ast.Variable; +import org.codehaus.groovy.ast.expr.ArrayExpression; +import org.codehaus.groovy.ast.expr.BinaryExpression; +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.DeclarationExpression; +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.PostfixExpression; +import org.codehaus.groovy.ast.expr.PrefixExpression; +import org.codehaus.groovy.ast.expr.PropertyExpression; +import org.codehaus.groovy.ast.expr.TupleExpression; +import org.codehaus.groovy.ast.expr.VariableExpression; +import org.codehaus.groovy.ast.stmt.Statement; +import org.codehaus.groovy.classgen.VariableScopeVisitor; +import org.codehaus.groovy.control.SourceUnit; +import org.codehaus.groovy.syntax.SyntaxException; +import org.codehaus.groovy.syntax.Types; +import org.objectweb.asm.Opcodes; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; + +import static org.codehaus.groovy.ast.ClassHelper.makeWithoutCaching; +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.castX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.classX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.closureX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.constX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.declX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.indexX; +import static org.codehaus.groovy.ast.tools.GeneralUtils.returnS; +import static org.codehaus.groovy.ast.tools.GeneralUtils.stmt; +import static org.codehaus.groovy.ast.tools.GeneralUtils.varX; + +/** + * Connects a lowered GINQ query to {@code @CompileStatic} and {@code @TypeChecked}. + *

+ * The macro runs at conversion, before either checker. This class does not type-check + * or emit bytecode. It asks the same question {@code StaticTypeCheckingVisitor.isSkipMode} + * asks, registers {@link GinqRowChecks} on the annotation that visitor will read, and + * marks the lowered closures so the extension can see them. The lowered query closure + * stays on the static writer. A call the checker selects is emitted as that target. + * A comparison or arithmetic operator the checker can prove stays an operator, so + * a number compared with a number is the static comparison. The enclosing method + * stays static. + *

+ * A {@link Queryable} result is handed to {@link LazyQueryable#defer}. Read-only locals + * are copied when the expression runs. Which names those are comes from + * {@link VariableScopeVisitor}, not from a walk of declared names. + */ +@Internal +public final class GinqStaticBridge { + + private static final String ROW_CHECKS = "org.apache.groovy.ginq.GinqRowChecks"; + private static final String HOLDER = "ginqShell$"; + private static final String CAPTURED = "ginqCaptured$"; + private static final String COMPILE_STATIC = "CompileStatic"; + private static final String TYPE_CHECKED = "TypeChecked"; + private static final String COMPILE_DYNAMIC = "CompileDynamic"; + + private GinqStaticBridge() { + } + + /** + * Adapts a macro result. A scope the type checker will not visit is returned unchanged. + * + * @param sourceUnit the source unit being compiled + * @param call the original {@code GQ} or {@code GQL} call + * @param query the lowered query + * @return the expression that replaces the macro call + */ + static Expression embed(SourceUnit sourceUnit, MethodCallExpression call, Expression query) { + if (sourceUnit == null || sourceUnit.getAST() == null || call == null || query == null) { + return query; + } + Host host = findHost(sourceUnit, call); + if (host == null || !host.checked()) { + return query; + } + attachRowChecks(sourceUnit, host.owner, host.executable); + boolean defer = returnsQueryable(query); + List readOnly = defer ? capture(sourceUnit, host.owner, call, query) : List.of(); + return wrap(query, call, defer, readOnly); + } + + /** + * Adapts the body of a {@code @GQ} method. {@code defer} is false when the + * method returns a list or a coerced value, because that result is read + * before the method returns. + * + * @param sourceUnit the source unit being compiled + * @param method the annotated method + * @param query the lowered query + * @param defer whether a {@link Queryable} result should wait for its first read + * @return the method body expression + */ + public static Expression prepare(SourceUnit sourceUnit, MethodNode method, Expression query, boolean defer) { + if (sourceUnit == null || method == null || query == null || !checked(method)) { + return query; + } + attachRowChecks(sourceUnit, method.getDeclaringClass(), method); + boolean deferQuery = defer && returnsQueryable(query); + List readOnly = deferQuery ? captureMethod(sourceUnit, method, query) : List.of(); + return wrap(query, method, deferQuery, readOnly); + } + + private static Expression wrap(Expression query, ASTNode position, boolean defer, List readOnly) { + boolean queryable = returnsQueryable(query); + Expression body = readOnly.isEmpty() ? query : rewriteReadOnly(query, readOnly); + ClosureExpression shell = closureX(Parameter.EMPTY_ARRAY, returnS(body)); + shell.setSourcePosition(position); + // The closure stays on the static writer. Row checks use the QUERY mark. + // A Boolean.TRUE DYNAMIC_RESOLUTION on this closure would compile every + // call inside it dynamically, including one another extension selected. + markQuery(shell); + if (!defer) { + MethodCallExpression call = callX(shell, "call"); + call.setImplicitThis(false); + call.setSourcePosition(position); + return queryable ? castToQueryable(call) : call; + } + + List statements = new ArrayList<>(); + if (!readOnly.isEmpty()) { + List elements = new ArrayList<>(); + for (Variable variable : readOnly) { + elements.add(varX(variable)); + } + VariableExpression array = new VariableExpression(CAPTURED, ClassHelper.OBJECT_TYPE.makeArray()); + array.setModifiers(Opcodes.ACC_FINAL); + statements.add(stmt(declX(array, new ArrayExpression(ClassHelper.OBJECT_TYPE, elements)))); + } + VariableExpression holder = new VariableExpression(HOLDER, ClassHelper.CLOSURE_TYPE); + holder.setModifiers(Opcodes.ACC_FINAL); + DeclarationExpression decl = declX(holder, shell); + decl.setSourcePosition(position); + statements.add(stmt(decl)); + + MethodCallExpression run = callX(new VariableExpression(holder), "call"); + run.setImplicitThis(false); + run.setSourcePosition(position); + ClosureExpression supplier = closureX(Parameter.EMPTY_ARRAY, returnS(castToQueryable(run))); + supplier.setSourcePosition(position); + + MethodCallExpression deferred = callX(classX(makeWithoutCaching(LazyQueryable.class)), "defer", args(supplier)); + deferred.setImplicitThis(false); + deferred.setSourcePosition(position); + deferred.setType(rawQueryable()); + statements.add(returnS(deferred)); + + ClosureExpression outer = closureX(Parameter.EMPTY_ARRAY, block(statements.toArray(Statement[]::new))); + outer.setSourcePosition(position); + MethodCallExpression invoked = callX(outer, "call"); + invoked.setImplicitThis(false); + invoked.setSourcePosition(position); + return castToQueryable(invoked); + } + + private static void markQuery(Expression expression) { + expression.visit(new CodeVisitorSupport() { + @Override + public void visitClosureExpression(ClosureExpression closure) { + closure.putNodeMetaData(GinqRowChecks.QUERY, Boolean.TRUE); + super.visitClosureExpression(closure); + } + }); + } + + private static Expression castToQueryable(Expression expression) { + var cast = castX(rawQueryable(), expression); + cast.setSourcePosition(expression); + return cast; + } + + private static boolean returnsQueryable(Expression query) { + if (query instanceof MethodCallExpression call && "shutdown".equals(call.getMethodAsString())) { + return false; + } + ClassNode type = query.getType(); + return type != null && Queryable.class.getName().equals(type.getName()); + } + + private static ClassNode rawQueryable() { + ClassNode type = makeWithoutCaching(Queryable.class).getPlainNodeReference(); + type.setGenericsTypes(null); + type.setUsingGenerics(false); + return type; + } + + // ----------------------------------------------------------------------- + // Checking mode. Mirrors StaticTypeCheckingVisitor.isSkipMode. + // @CompileDynamic and @CompileStatic(SKIP) skip the static-compilation + // visitor only. A @TypeChecked visitor does not look at those annotations, + // so a method that carries them is still type-checked when the class is + // @TypeChecked. @TypeChecked(SKIP) skips both visitors. + // ----------------------------------------------------------------------- + + private static boolean checked(MethodNode method) { + if (method == null) { + return false; + } + ClassNode owner = method.getDeclaringClass(); + if (staticVisitorReaches(owner) && !isSkipMode(method, true)) { + return true; + } + if (typeCheckedVisitorReaches(owner) && !isSkipMode(method, false)) { + return true; + } + return methodChecksItself(method); + } + + private static boolean checkedClass(ClassNode type) { + return staticVisitorReaches(type) || typeCheckedVisitorReaches(type); + } + + private static boolean methodChecksItself(MethodNode method) { + if (hasAnnotation(method, COMPILE_DYNAMIC) || isSkipAnnotation(method, COMPILE_STATIC)) { + return false; + } + if (isSkipAnnotation(method, TYPE_CHECKED)) { + return false; + } + return hasAnnotation(method, COMPILE_STATIC) || hasAnnotation(method, TYPE_CHECKED); + } + + /** + * A non-skip {@code @CompileStatic} on {@code type} or an outer class, whose visitor + * is not stopped by skip mode on the way in. + */ + private static boolean staticVisitorReaches(ClassNode type) { + for (ClassNode current = type; current != null; current = current.getOuterClass()) { + if (winning(current) == Winner.COMPILE_STATIC && !skippedAlong(current, type, true)) { + return true; + } + } + return false; + } + + /** + * A non-skip {@code @TypeChecked} that is the annotation the collector will run. + */ + private static boolean typeCheckedVisitorReaches(ClassNode type) { + for (ClassNode current = type; current != null; current = current.getOuterClass()) { + if (winning(current) == Winner.TYPE_CHECKED && !skippedAlong(current, type, false)) { + return true; + } + } + return false; + } + + private static boolean skippedAlong(ClassNode start, ClassNode type, boolean staticVisitor) { + for (ClassNode current = type; current != null; current = current.getOuterClass()) { + if (isSkipMode(current, staticVisitor)) { + return true; + } + if (current == start) { + return false; + } + } + return false; + } + + /** + * Same priority {@code ASTTransformationVisitor.distinctAnnotations} uses: + * {@code @CompileDynamic} and {@code @CompileStatic(SKIP)} outrank + * {@code @CompileStatic}, which outranks {@code @TypeChecked}. + */ + private static Winner winning(AnnotatedNode node) { + if (hasAnnotation(node, COMPILE_DYNAMIC) || isSkipAnnotation(node, COMPILE_STATIC)) { + return Winner.SKIP_STATIC; + } + if (hasAnnotation(node, COMPILE_STATIC)) { + return Winner.COMPILE_STATIC; + } + if (isSkipAnnotation(node, TYPE_CHECKED)) { + return Winner.SKIP_TYPE; + } + if (hasAnnotation(node, TYPE_CHECKED)) { + return Winner.TYPE_CHECKED; + } + return Winner.NONE; + } + + /** + * {@code StaticTypeCheckingVisitor.isSkipMode}, with {@code staticVisitor} selecting + * the annotation set. The static-compilation visitor sees {@code @TypeChecked} and + * {@code @CompileStatic}. The type-checked visitor sees only {@code @TypeChecked}. + * A skip value wins over another annotation on the same node, which is what + * {@code isSkipMode} does. + */ + private static boolean isSkipMode(AnnotatedNode node, boolean staticVisitor) { + if (node == null) { + return false; + } + boolean explicit = false; + if (hasAnnotation(node, TYPE_CHECKED)) { + if (isSkipAnnotation(node, TYPE_CHECKED)) { + return true; + } + explicit = true; + } + if (staticVisitor && hasAnnotation(node, COMPILE_STATIC)) { + if (isSkipAnnotation(node, COMPILE_STATIC)) { + return true; + } + explicit = true; + } + if (staticVisitor && hasAnnotation(node, COMPILE_DYNAMIC)) { + return true; + } + if (explicit) { + return false; + } + if (node instanceof MethodNode method) { + return isSkipMode(method.getDeclaringClass(), staticVisitor); + } + if (node instanceof ClassNode type && type.getOuterClass() != null) { + MethodNode enclosing = type.getEnclosingMethod(); + if (enclosing != null && isSkipMode(enclosing, staticVisitor)) { + return true; + } + } + return false; + } + + private enum Winner { + NONE, TYPE_CHECKED, COMPILE_STATIC, SKIP_TYPE, SKIP_STATIC + } + + private static void attachRowChecks(SourceUnit source, ClassNode owner, MethodNode executable) { + if (executable != null && methodChecksItself(executable)) { + addToActiveAnnotations(source, executable); + } + for (ClassNode current = owner; current != null; current = current.getOuterClass()) { + Winner winner = winning(current); + if (winner == Winner.COMPILE_STATIC || winner == Winner.TYPE_CHECKED) { + addToActiveAnnotations(source, current); + return; + } + } + } + + private static void addToActiveAnnotations(SourceUnit source, AnnotatedNode node) { + for (AnnotationNode annotation : node.getAnnotations()) { + String simple = simpleName(annotation.getClassNode()); + if ((COMPILE_STATIC.equals(simple) || TYPE_CHECKED.equals(simple)) && !isSkip(annotation)) { + addExtension(source, annotation); + } + } + } + + /** + * Appends {@link GinqRowChecks} to an {@code extensions} member. + * A string, a class literal, or a list or array of those is updated. + * Any other shape is reported and left unchanged. + * + * @param source the source unit that receives the error when the member cannot be updated + * @param annotation the checking annotation + */ + static void addExtension(SourceUnit source, AnnotationNode annotation) { + Expression existing = annotation.getMember("extensions"); + if (existing == null) { + annotation.setMember("extensions", constX(ROW_CHECKS)); + return; + } + List items = extensionItems(existing); + if (items == null) { + if (source != null) { + source.addErrorAndContinue(new SyntaxException( + "Cannot add the GINQ type-checking extension because the extensions member is not a string, a class, or a list of those", + annotation)); + } + return; + } + for (Expression item : items) { + if (ROW_CHECKS.equals(extensionName(item))) { + return; + } + } + List copy = new ArrayList<>(); + for (Expression item : items) { + copy.add(normalizeExtension(item)); + } + copy.add(constX(ROW_CHECKS)); + annotation.setMember("extensions", new ListExpression(copy)); + } + + private static List extensionItems(Expression existing) { + if (existing instanceof ConstantExpression || existing instanceof ClassExpression) { + return List.of(existing); + } + if (existing instanceof ListExpression list) { + return supported(list.getExpressions()) ? list.getExpressions() : null; + } + if (existing instanceof ArrayExpression array) { + return supported(array.getExpressions()) ? array.getExpressions() : null; + } + return null; + } + + private static boolean supported(List expressions) { + for (Expression expression : expressions) { + if (!(expression instanceof ConstantExpression || expression instanceof ClassExpression)) { + return false; + } + } + return true; + } + + private static Expression normalizeExtension(Expression item) { + if (item instanceof ClassExpression type) { + return constX(type.getType().getName()); + } + return item; + } + + private static String extensionName(Expression item) { + if (item instanceof ConstantExpression constant) { + return String.valueOf(constant.getValue()); + } + if (item instanceof ClassExpression type) { + return type.getType().getName(); + } + return null; + } + + private static boolean hasAnnotation(AnnotatedNode node, String simple) { + if (node == null) { + return false; + } + for (AnnotationNode annotation : node.getAnnotations()) { + if (simple.equals(simpleName(annotation.getClassNode()))) { + return true; + } + } + return false; + } + + private static boolean isSkipAnnotation(AnnotatedNode node, String simple) { + if (node == null) { + return false; + } + for (AnnotationNode annotation : node.getAnnotations()) { + if (simple.equals(simpleName(annotation.getClassNode())) && isSkip(annotation)) { + return true; + } + } + return false; + } + + private static boolean isSkip(AnnotationNode annotation) { + Expression value = annotation.getMember("value"); + if (value instanceof PropertyExpression property) { + return "SKIP".equals(property.getPropertyAsString()); + } + if (value instanceof ConstantExpression constant) { + return "SKIP".equals(String.valueOf(constant.getValue())); + } + return false; + } + + private static String simpleName(ClassNode type) { + String raw = type.getName(); + int dot = raw.lastIndexOf('.'); + return dot < 0 ? raw : raw.substring(dot + 1); + } + + // ----------------------------------------------------------------------- + // Captured locals. VariableScopeVisitor links each reference to the + // declaration that is actually in scope, so a shadowing local, a closure + // parameter, and a class name (a dynamic variable, or a field) are not + // mistaken for the enclosing local. + // ----------------------------------------------------------------------- + + private static List capture(SourceUnit source, ClassNode owner, Expression call, Expression query) { + boolean swapped = SlotReplacer.swap(owner, call, query); + try { + if (swapped) { + new SilentScopeVisitor(source).visitClass(owner); + } + } finally { + if (swapped) { + SlotReplacer.swap(owner, query, call); + } + } + return swapped ? readOnlyCaptured(query) : List.of(); + } + + private static List captureMethod(SourceUnit source, MethodNode method, Expression query) { + Statement original = method.getCode(); + method.setCode(returnS(query)); + try { + new SilentScopeVisitor(source).visitClass(method.getDeclaringClass()); + } finally { + method.setCode(original); + } + return readOnlyCaptured(query); + } + + private static List readOnlyCaptured(Expression query) { + List captured = new ArrayList<>(); + query.visit(new CodeVisitorSupport() { + @Override + public void visitVariableExpression(VariableExpression expression) { + Variable accessed = expression.getAccessedVariable(); + if (outerLocal(accessed, query) && !containsSame(captured, accessed)) { + captured.add(accessed); + } + } + }); + List mutated = mutated(query, captured); + List readOnly = new ArrayList<>(); + for (Variable variable : captured) { + if (!containsSame(mutated, variable)) { + readOnly.add(variable); + } + } + return readOnly; + } + + private static boolean outerLocal(Variable variable, Expression query) { + if (variable == null || variable instanceof DynamicVariable || variable instanceof FieldNode || variable instanceof PropertyNode) { + return false; + } + if (!(variable instanceof Parameter) && !(variable instanceof VariableExpression)) { + return false; + } + return !containsNode(query, (ASTNode) variable); + } + + private static List mutated(Expression query, List captured) { + List mutated = new ArrayList<>(); + query.visit(new CodeVisitorSupport() { + private void consider(Expression expression) { + if (expression instanceof VariableExpression variable && containsSame(captured, variable.getAccessedVariable())) { + if (!containsSame(mutated, variable.getAccessedVariable())) { + mutated.add(variable.getAccessedVariable()); + } + } + } + + @Override + public void visitPostfixExpression(PostfixExpression expression) { + consider(expression.getExpression()); + super.visitPostfixExpression(expression); + } + + @Override + public void visitPrefixExpression(PrefixExpression expression) { + consider(expression.getExpression()); + super.visitPrefixExpression(expression); + } + + @Override + public void visitBinaryExpression(BinaryExpression expression) { + if (Types.isAssignment(expression.getOperation().getType())) { + consider(expression.getLeftExpression()); + } + super.visitBinaryExpression(expression); + } + }); + return mutated; + } + + private static Expression rewriteReadOnly(Expression query, List readOnly) { + return new ClassCodeExpressionTransformer() { + @Override + protected SourceUnit getSourceUnit() { + return null; + } + + @Override + public Expression transform(Expression expression) { + if (expression instanceof ClosureExpression closure) { + closure.visit(this); + return closure; + } + if (expression instanceof VariableExpression variable) { + int index = indexOf(readOnly, variable.getAccessedVariable()); + if (index >= 0) { + Expression read = indexX(varX(CAPTURED, ClassHelper.OBJECT_TYPE.makeArray()), constX(index)); + ClassNode type = variable.getAccessedVariable().getOriginType(); + if (type != null && !ClassHelper.isDynamicTyped(type) && !ClassHelper.OBJECT_TYPE.equals(type)) { + CastExpression cast = castX(type, read); + cast.setSourcePosition(variable); + return cast; + } + read.setSourcePosition(variable); + return read; + } + } + return super.transform(expression); + } + }.transform(query); + } + + private static boolean containsSame(List variables, Variable target) { + return indexOf(variables, target) >= 0; + } + + private static int indexOf(List variables, Variable target) { + if (target == null) { + return -1; + } + for (int i = 0; i < variables.size(); i++) { + if (variables.get(i) == target) { + return i; + } + } + return -1; + } + + private static boolean containsNode(Expression root, ASTNode target) { + if (root == target) { + return true; + } + final boolean[] found = {false}; + root.visit(new CodeVisitorSupport() { + private void hit(ASTNode node) { + if (node == target) { + found[0] = true; + } + } + + @Override + public void visitClosureExpression(ClosureExpression expression) { + hit(expression); + if (expression.getParameters() != null) { + for (Parameter parameter : expression.getParameters()) { + hit(parameter); + } + } + if (!found[0]) { + super.visitClosureExpression(expression); + } + } + + @Override + public void visitVariableExpression(VariableExpression expression) { + hit(expression); + } + }); + return found[0]; + } + + private static final class SilentScopeVisitor extends VariableScopeVisitor { + private SilentScopeVisitor(SourceUnit source) { + super(source); + } + + @Override + public void addError(String msg, ASTNode node) { + // Linking only. The ordinary scope visitor reports errors later. + } + } + + /** + * Replaces one expression in a class without copying its neighbours. + * A copying transformer would detach the call the macro visitor is updating. + */ + private static final class SlotReplacer extends ClassCodeVisitorSupport { + private final Expression from; + private final Expression to; + private boolean done; + + private SlotReplacer(Expression from, Expression to) { + this.from = from; + this.to = to; + } + + private static boolean swap(ClassNode owner, Expression from, Expression to) { + SlotReplacer replacer = new SlotReplacer(from, to); + replacer.visitClass(owner); + return replacer.done; + } + + @Override + protected SourceUnit getSourceUnit() { + return null; + } + + private boolean replace(ASTNode node) { + if (done || node == null) { + return false; + } + if (node instanceof TupleExpression tuple) { + List expressions = tuple.getExpressions(); + for (int i = 0; i < expressions.size(); i++) { + if (expressions.get(i) == from) { + expressions.set(i, to); + done = true; + return true; + } + } + } + for (Method getter : node.getClass().getMethods()) { + if (getter.getParameterCount() != 0 || !Expression.class.isAssignableFrom(getter.getReturnType())) { + continue; + } + if (!getter.getName().startsWith("get") && !getter.getName().startsWith("is")) { + continue; + } + try { + if (getter.invoke(node) != from) { + continue; + } + String suffix = getter.getName().startsWith("get") ? getter.getName().substring(3) : getter.getName().substring(2); + Method setter = node.getClass().getMethod("set" + suffix, getter.getReturnType()); + setter.invoke(node, to); + done = true; + return true; + } catch (ReflectiveOperationException ignored) { + // this getter has no matching setter + } + } + return false; + } + + @Override + public void visitField(FieldNode node) { + if (!done && node.getInitialExpression() == from) { + node.setInitialValueExpression(to); + done = true; + return; + } + super.visitField(node); + } + + @Override + public void visitProperty(PropertyNode node) { + if (replace(node)) { + return; + } + super.visitProperty(node); + } + + @Override + protected void visitStatement(Statement statement) { + if (replace(statement)) { + return; + } + super.visitStatement(statement); + } + + @Override + public void visitMethodCallExpression(MethodCallExpression call) { + if (replace(call)) { + return; + } + super.visitMethodCallExpression(call); + } + + @Override + public void visitBinaryExpression(BinaryExpression expression) { + if (replace(expression)) { + return; + } + super.visitBinaryExpression(expression); + } + + @Override + public void visitDeclarationExpression(DeclarationExpression expression) { + if (replace(expression)) { + return; + } + super.visitDeclarationExpression(expression); + } + + @Override + public void visitClosureExpression(ClosureExpression expression) { + if (replace(expression)) { + return; + } + super.visitClosureExpression(expression); + } + + @Override + public void visitPropertyExpression(PropertyExpression expression) { + if (replace(expression)) { + return; + } + super.visitPropertyExpression(expression); + } + + @Override + public void visitTupleExpression(TupleExpression expression) { + if (replace(expression)) { + return; + } + super.visitTupleExpression(expression); + } + } + + private static Host findHost(SourceUnit sourceUnit, MethodCallExpression call) { + for (ClassNode type : sourceUnit.getAST().getClasses()) { + for (MethodNode method : new ArrayList<>(type.getMethods())) { + if (method.getDeclaringClass() == type && contains(method.getCode(), call)) { + return new Host(type, method); + } + } + for (MethodNode constructor : type.getDeclaredConstructors()) { + if (contains(constructor.getCode(), call)) { + return new Host(type, constructor); + } + } + for (FieldNode field : type.getFields()) { + if (field.getDeclaringClass() == type && contains(field.getInitialExpression(), call)) { + return new Host(type, null); + } + } + for (Statement initializer : type.getObjectInitializerStatements()) { + if (contains(initializer, call)) { + return new Host(type, null); + } + } + } + return null; + } + + private static boolean contains(Statement statement, MethodCallExpression call) { + if (statement == null) { + return false; + } + Finder finder = new Finder(call); + statement.visit(finder); + return finder.found; + } + + private static boolean contains(Expression expression, MethodCallExpression call) { + if (expression == null) { + return false; + } + Finder finder = new Finder(call); + expression.visit(finder); + return finder.found; + } + + private static final class Host { + private final ClassNode owner; + private final MethodNode executable; + + private Host(ClassNode owner, MethodNode executable) { + this.owner = owner; + this.executable = executable; + } + + private boolean checked() { + if (executable != null) { + return GinqStaticBridge.checked(executable); + } + return checkedClass(owner); + } + } + + private static final class Finder extends CodeVisitorSupport { + private final MethodCallExpression target; + private boolean found; + + private Finder(MethodCallExpression target) { + this.target = target; + } + + @Override + public void visitMethodCallExpression(MethodCallExpression call) { + if (call == target) { + found = true; + return; + } + super.visitMethodCallExpression(call); + } + } +} 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/fluent/GinqGrouping.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/fluent/GinqGrouping.java new file mode 100644 index 00000000000..658a7122bf8 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/fluent/GinqGrouping.java @@ -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. + */ +package org.apache.groovy.ginq.fluent; + +import groovy.transform.Internal; +import groovy.ginq.Grouping; +import org.apache.groovy.ginq.provider.collection.runtime.GroupResult; + +/** + * {@link Grouping} backed by a GINQ group. + * + * @param the key type + * @param the element type + * @since 7.0.0 + */ +@Internal +final class GinqGrouping extends GinqQuery implements Grouping { + + private final K key; + + GinqGrouping(GroupResult group) { + super(group, null); + this.key = group.getKey(); + } + + @Override + public K getKey() { + return key; + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/fluent/GinqQuery.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/fluent/GinqQuery.java new file mode 100644 index 00000000000..2dde9cc3bd3 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/fluent/GinqQuery.java @@ -0,0 +1,623 @@ +/* + * 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.fluent; + +import groovy.lang.Tuple2; +import groovy.transform.Internal; +import groovy.ginq.Aggregator; +import groovy.ginq.Grouping; +import groovy.ginq.Query; +import org.apache.groovy.ginq.provider.collection.runtime.GroupResult; +import org.apache.groovy.ginq.provider.collection.runtime.Queryable; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +/** + * In-memory {@link Query} backed by {@link Queryable}. Operators record work and + * do not read the source. Each terminal calls {@link #materialize()} again, so an + * {@link Iterable} source is re-read and a change made after the previous terminal + * is visible. A {@link Stream} source can be read only once; the first terminal + * buffers it and later terminals replay that buffer. Ordering keys stay on the + * query so {@code thenBy} is one comparison. Grouping runs at the terminal, not + * when {@code groupBy} is called. + * + * @param the element type + * @since 7.0.0 + */ +@Internal +public class GinqQuery implements Query { + + private final Supplier> sourceSupplier; + private final List> orders; + + GinqQuery(Queryable ready, List> orders) { + this(() -> ready, orders); + } + + GinqQuery(Supplier> sourceSupplier, List> orders) { + this.sourceSupplier = sourceSupplier; + this.orders = orders; + } + + /** + * Queries {@code source}. + * + * @param source the elements + * @param the element type + * @return the query + */ + public static Query from(Iterable source) { + Objects.requireNonNull(source, "source"); + if (source instanceof GinqQuery query) { + @SuppressWarnings("unchecked") + Query typed = (Query) query; + return typed; + } + return new GinqQuery<>(() -> Queryable.from(source), null); + } + + /** + * Queries {@code source} in array order. + * + * @param source the elements + * @param the element type + * @return the query + */ + public static Query from(T[] source) { + Objects.requireNonNull(source, "source"); + return new GinqQuery<>(() -> Queryable.from(source), null); + } + + /** + * Queries the boxed elements of a primitive {@code int} array. {@code int[]} is + * not a {@code T[]}, so the query's element type is {@code Integer}. The array + * is boxed again on each terminal, and is not copied when this factory runs. + * Other primitive arrays are not overloaded here. + * + * @param source the elements + * @return a query of the boxed values + */ + public static Query from(int[] source) { + Objects.requireNonNull(source, "source"); + return new GinqQuery<>(() -> Queryable.from(source), null); + } + + /** + * Queries {@code source}. The first terminal fully drains the stream into a + * buffer; later terminals replay that buffer. {@code take} and {@code exists} + * therefore do not leave an unused tail unread. The source is marked read + * only after that collect succeeds, so a failed drain can be retried. + * + * @param source the elements + * @param the element type + * @return the query + */ + public static Query from(Stream source) { + Objects.requireNonNull(source, "source"); + List buffered = new ArrayList<>(); + return new GinqQuery<>(new Supplier>() { + private boolean read; + + @Override + public Queryable get() { + synchronized (buffered) { + if (!read) { + buffered.addAll(source.collect(Collectors.toList())); + read = true; + } + } + return Queryable.fromOwned(buffered); + } + }, null); + } + + /** + * Continues {@code source}. + * + * @param source the query + * @param the element type + * @return {@code source} + */ + public static Query from(Query source) { + Objects.requireNonNull(source, "source"); + return source; + } + + /** + * Queries the given elements. + * + * @param elements the elements + * @param the element type + * @return the query + */ + @SafeVarargs + public static Query of(T... elements) { + if (elements == null || elements.length == 0) { + return empty(); + } + return from(Arrays.asList(elements)); + } + + /** + * Returns a query with no elements. + * + * @param the element type + * @return an empty query + */ + public static Query empty() { + return new GinqQuery<>(Queryable.emptyQueryable(), null); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + Queryable materialize() { + Queryable base = sourceSupplier.get(); + if (orders != null && !orders.isEmpty()) { + Queryable.Order[] array = orders.toArray(Queryable.Order.EMPTY_ARRAY); + base = base.orderBy(array); + } + return base; + } + + @Override + public Query where(Predicate predicate) { + Objects.requireNonNull(predicate, "predicate"); + return new GinqQuery<>(() -> materialize().where(predicate), null); + } + + @Override + public Query select(Function selector) { + Objects.requireNonNull(selector, "selector"); + return new GinqQuery<>(() -> materialize().select((item, rows) -> selector.apply(item)), null); + } + + @Override + public Query selectMany(Function> selector) { + Objects.requireNonNull(selector, "selector"); + return new GinqQuery<>(() -> { + Stream flattened = materialize().stream().flatMap(item -> { + Iterable inner = selector.apply(item); + if (inner == null) { + return Stream.empty(); + } + return StreamSupport.stream(inner.spliterator(), false).map(value -> value); + }); + return Queryable.from(flattened); + }, null); + } + + @Override + public Query selectMany(Function> collectionSelector, + BiFunction resultSelector) { + Objects.requireNonNull(collectionSelector, "collectionSelector"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return selectMany(item -> { + Iterable inner = collectionSelector.apply(item); + if (inner == null) { + return List.of(); + } + List mapped = new ArrayList<>(); + for (U element : inner) { + mapped.add(resultSelector.apply(item, element)); + } + return mapped; + }); + } + + @Override + public Query orderBy(Function keySelector) { + return appendOrder(keySelector, true, true); + } + + @Override + public Query orderByDescending(Function keySelector) { + return appendOrder(keySelector, false, true); + } + + @Override + public Query thenBy(Function keySelector) { + requireOrder(); + return appendOrder(keySelector, true, false); + } + + @Override + public Query thenByDescending(Function keySelector) { + requireOrder(); + return appendOrder(keySelector, false, false); + } + + @Override + public Query> groupBy(Function keySelector) { + return groupBy(keySelector, null); + } + + @Override + public Query> groupBy(Function keySelector, + Predicate> having) { + Objects.requireNonNull(keySelector, "keySelector"); + return new GinqQuery<>(() -> { + Queryable> grouped = materialize().groupByInto(keySelector); + Queryable> wrapped = grouped.select((group, rows) -> new GinqGrouping<>(group)); + return having == null ? wrapped : wrapped.where(having); + }, null); + } + + @Override + public Query join(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().innerHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query join(Iterable inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().innerJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query join(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().innerHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query join(Query inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().innerJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query leftJoin(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().leftHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query leftJoin(Iterable inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().leftJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query leftJoin(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().leftHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query leftJoin(Query inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().leftJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query rightJoin(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().rightHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query rightJoin(Iterable inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().rightJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query rightJoin(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().rightHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query rightJoin(Query inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().rightJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query fullJoin(Iterable inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().fullHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query fullJoin(Iterable inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().fullJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query fullJoin(Query inner, + Function outerKey, + Function innerKey, + BiFunction resultSelector) { + requireJoinKeys(outerKey, innerKey, resultSelector); + return project(() -> materialize().fullHashJoin(queryableOf(inner), outerKey, innerKey), resultSelector); + } + + @Override + public Query fullJoin(Query inner, + BiPredicate on, + BiFunction resultSelector) { + Objects.requireNonNull(on, "on"); + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().fullJoin(queryableOf(inner), on), resultSelector); + } + + @Override + public Query crossJoin(Iterable inner, BiFunction resultSelector) { + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().crossJoin(queryableOf(inner)), resultSelector); + } + + @Override + public Query crossJoin(Query inner, BiFunction resultSelector) { + Objects.requireNonNull(resultSelector, "resultSelector"); + return project(() -> materialize().crossJoin(queryableOf(inner)), resultSelector); + } + + @Override + public Query distinct() { + return later(base -> base.distinct()); + } + + @Override + public Query union(Iterable other) { + return later(base -> base.union(queryableOf(other))); + } + + @Override + public Query union(Query other) { + return later(base -> base.union(queryableOf(other))); + } + + @Override + public Query unionAll(Iterable other) { + return later(base -> base.unionAll(queryableOf(other))); + } + + @Override + public Query unionAll(Query other) { + return later(base -> base.unionAll(queryableOf(other))); + } + + @Override + public Query intersect(Iterable other) { + return later(base -> base.intersect(queryableOf(other))); + } + + @Override + public Query intersect(Query other) { + return later(base -> base.intersect(queryableOf(other))); + } + + @Override + public Query minus(Iterable other) { + return later(base -> base.minus(queryableOf(other))); + } + + @Override + public Query minus(Query other) { + return later(base -> base.minus(queryableOf(other))); + } + + @Override + public Query limit(long offset, long size) { + return later(base -> base.limit(offset, size)); + } + + @Override + public List toList() { + return materialize().toList(); + } + + @Override + public Stream stream() { + return materialize().stream(); + } + + @Override + public Iterator iterator() { + return toList().iterator(); + } + + @Override + public boolean exists() { + return materialize().exists(); + } + + @Override + public boolean any(Predicate predicate) { + Objects.requireNonNull(predicate, "predicate"); + return materialize().where(predicate).exists(); + } + + @Override + public boolean all(Predicate predicate) { + Objects.requireNonNull(predicate, "predicate"); + return !any(predicate.negate()); + } + + @Override + public long count() { + return materialize().count(); + } + + @Override + public long count(Function selector) { + Objects.requireNonNull(selector, "selector"); + return materialize().count(selector); + } + + @Override + public BigDecimal sum(Function selector) { + Objects.requireNonNull(selector, "selector"); + return materialize().sum(selector); + } + + @Override + public BigDecimal avg(Function selector) { + Objects.requireNonNull(selector, "selector"); + return materialize().avg(selector); + } + + @Override + public > U min(Function selector) { + Objects.requireNonNull(selector, "selector"); + return materialize().min(selector); + } + + @Override + public > U max(Function selector) { + Objects.requireNonNull(selector, "selector"); + return materialize().max(selector); + } + + @Override + public BigDecimal median(Function selector) { + Objects.requireNonNull(selector, "selector"); + return materialize().median(selector); + } + + @Override + public R aggregate(Aggregator aggregator) { + Objects.requireNonNull(aggregator, "aggregator"); + return aggregator.apply(this); + } + + @Override + public A aggregate(A seed, BiFunction accumulator) { + Objects.requireNonNull(accumulator, "accumulator"); + A current = seed; + for (T element : toList()) { + current = accumulator.apply(current, element); + } + return current; + } + + private Query later(Function, Queryable> operator) { + return new GinqQuery<>(() -> operator.apply(materialize()), null); + } + + private void requireOrder() { + if (orders == null || orders.isEmpty()) { + throw new IllegalStateException("thenBy requires a preceding orderBy or orderByDescending"); + } + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private Query appendOrder(Function keySelector, boolean ascending, boolean reset) { + Objects.requireNonNull(keySelector, "keySelector"); + List> next = new ArrayList<>(); + if (!reset && orders != null) { + next.addAll(orders); + } + next.add(new Queryable.Order(keySelector, ascending)); + return new GinqQuery<>(sourceSupplier, Collections.unmodifiableList(next)); + } + + private Query project(Supplier>> joined, + BiFunction resultSelector) { + return new GinqQuery<>(() -> joined.get().select((pair, rows) -> resultSelector.apply(pair.getV1(), pair.getV2())), null); + } + + private static void requireJoinKeys(Function outerKey, + Function innerKey, + Object resultSelector) { + Objects.requireNonNull(outerKey, "outerKey"); + Objects.requireNonNull(innerKey, "innerKey"); + Objects.requireNonNull(resultSelector, "resultSelector"); + } + + @SuppressWarnings("unchecked") + private static Queryable queryableOf(Query source) { + Objects.requireNonNull(source, "source"); + if (source instanceof GinqQuery query) { + return (Queryable) query.materialize(); + } + return Queryable.from((List) source.toList()); + } + + @SuppressWarnings("unchecked") + private static Queryable queryableOf(Iterable source) { + Objects.requireNonNull(source, "source"); + if (source instanceof GinqQuery query) { + return (Queryable) query.materialize(); + } + if (source instanceof Queryable queryable) { + return (Queryable) queryable; + } + return Queryable.from((Iterable) source); + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqAggregate.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqAggregate.java new file mode 100644 index 00000000000..ede2189b1be --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqAggregate.java @@ -0,0 +1,60 @@ +/* + * 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.provider.collection.runtime.Queryable; +import org.apache.groovy.lang.annotation.Incubating; + +import java.util.ServiceLoader; +import java.util.function.Function; + +/** + * A named aggregate that the GINQ DSL can call from {@code select} and {@code having} + * after {@code groupby}, in addition to the built-in aggregates. + *

+ * Implementations are discovered with {@link ServiceLoader}. The public type must have + * a public no-arg constructor and be listed in + * {@code META-INF/services/org.apache.groovy.ginq.provider.GinqAggregate}. + * Built-in names ({@code count}, {@code sum}, {@code agg}, ...) are never overridden. + * A call has either no argument ({@code total()}) or one argument ({@code total(n.amount)}), + * which is evaluated once per element. The fluent API does not use this SPI; + * pass a lambda to {@code Query#aggregate} instead. + * + * @since 7.0.0 + */ +@Incubating +public interface GinqAggregate { + + /** + * Returns the name used in a GINQ query, for example {@code total}. + * + * @return the aggregate name + */ + String name(); + + /** + * Aggregates one group. + * + * @param group the elements of the group; the same instance may be read more than once + * @param selector the argument expression as a function of one element, or {@code null} + * when the call had no argument + * @return the aggregate value + */ + Object apply(Queryable group, Function selector); +} diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqAggregates.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqAggregates.java new file mode 100644 index 00000000000..1ecb5f0f7a3 --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/GinqAggregates.java @@ -0,0 +1,126 @@ +/* + * 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 groovy.lang.Closure; +import groovy.transform.Internal; +import org.apache.groovy.ginq.provider.collection.runtime.Queryable; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.ServiceConfigurationError; +import java.util.ServiceLoader; +import java.util.WeakHashMap; +import java.util.function.Function; + +/** + * Loads {@link GinqAggregate} services for the compiler. The generated query + * instantiates the implementation itself, so a query does not look the service + * up again at runtime. + * + * @since 7.0.0 + */ +@Internal +public final class GinqAggregates { + + private static final Map>> CACHE = + Collections.synchronizedMap(new WeakHashMap<>()); + + private GinqAggregates() { + } + + /** + * Returns the aggregate implementation registered under {@code name}, or {@code null}. + * The loader and its parents are searched. The first registration of a name wins. + * + * @param name the aggregate name used in a query + * @param loader the compilation class loader, or {@code null} to use this class's loader + * @return the implementation class, or {@code null} when the name is not registered + */ + public static Class find(String name, ClassLoader loader) { + if (name == null || name.isEmpty()) { + return null; + } + ClassLoader resolved = loader == null ? GinqAggregates.class.getClassLoader() : loader; + return aggregates(resolved).get(name); + } + + /** + * Creates the aggregate named by {@code type} and applies it to {@code group}. + * Called from queries lowered by the GINQ compiler. + * + * @param type the implementation class recorded at compile time + * @param group the current group + * @param selector a closure or function of one element, or {@code null} + * @return the aggregate value + * @throws IllegalStateException when {@code type} cannot be constructed + */ + public static Object apply(Class type, Queryable group, Object selector) { + try { + GinqAggregate aggregate = type.getDeclaredConstructor().newInstance(); + return aggregate.apply(group, asFunction(selector)); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new IllegalStateException("Cannot create GINQ aggregate " + type.getName(), e); + } + } + + @SuppressWarnings("unchecked") + private static Function asFunction(Object selector) { + if (selector == null) { + return null; + } + if (selector instanceof Closure closure) { + return value -> closure.call(value); + } + if (selector instanceof Function function) { + return (Function) function; + } + throw new IllegalArgumentException("GINQ aggregate selector must be a closure or a function"); + } + + private static Map> aggregates(ClassLoader loader) { + Map> cached = CACHE.get(loader); + if (cached != null) { + return cached; + } + Map> loaded = load(loader); + CACHE.put(loader, loaded); + return loaded; + } + + private static Map> load(ClassLoader loader) { + Map> found = new LinkedHashMap<>(); + for (ClassLoader current = loader; current != null; current = current.getParent()) { + try { + for (GinqAggregate aggregate : ServiceLoader.load(GinqAggregate.class, current)) { + String name = aggregate.name(); + if (name != null && !name.isEmpty()) { + found.putIfAbsent(name, aggregate.getClass()); + } + } + } catch (ServiceConfigurationError ignored) { + // A provider listed for this loader is not loadable yet. Keep looking. + } + } + return found; + } +} 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/GinqAstWalker.groovy b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/GinqAstWalker.groovy index 8f8a5c5d419..388ce6735b2 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/GinqAstWalker.groovy +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/GinqAstWalker.groovy @@ -39,6 +39,7 @@ 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.GinqAggregates import org.apache.groovy.ginq.provider.collection.runtime.NamedRecord import org.apache.groovy.ginq.provider.collection.runtime.Queryable import org.apache.groovy.ginq.provider.collection.runtime.QueryableHelper @@ -239,6 +240,7 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable def result = parallelEnabled ? callX(callX(QUERYABLE_HELPER_TYPE, 'submit', args(resultLambda)), "get") : callX(resultLambda, "call") + result.setType(QUERYABLE_TYPE) ginqExpressionStack.pop() return result @@ -269,7 +271,7 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable return useWindowFunction } - private static boolean isAggregateFunction(Expression expression) { + private boolean isAggregateFunction(Expression expression) { Expression expr = expression if (expression instanceof CastExpression) { expr = expression.expression @@ -277,9 +279,18 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable if (expr instanceof MethodCallExpression) { MethodCallExpression call = (MethodCallExpression) expr - if (call.implicitThis && AGG_FUNCTION_NAME_SET.contains(call.methodAsString)) { - def argumentCnt = ((ArgumentListExpression) call.getArguments()).getExpressions().size() - if (1 == argumentCnt || (FUNCTION_COUNT == call.methodAsString && 0 == argumentCnt)) { + if (call.implicitThis) { + String name = call.methodAsString + // Not every call stores its arguments as an ArgumentListExpression; GString and + // some transformed calls use a plain TupleExpression. + int argumentCnt = call.arguments instanceof TupleExpression + ? ((TupleExpression) call.arguments).expressions.size() + : 1 + if (AGG_FUNCTION_NAME_SET.contains(name)) { + if (1 == argumentCnt || (FUNCTION_COUNT == name && 0 == argumentCnt)) { + return true + } + } else if ((0 == argumentCnt || 1 == argumentCnt) && customAggregate(name) != null) { return true } } @@ -288,6 +299,11 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable return false } + private Class customAggregate(String name) { + ClassLoader loader = sourceUnit == null ? null : sourceUnit.classLoader + GinqAggregates.find(name, loader) + } + private static boolean isOverMethodCall(Expression expression) { return expression instanceof MethodCallExpression && expression.methodAsString == 'over' @@ -867,7 +883,7 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable return callX( classX(QUERYABLE_HELPER_TYPE), "navigate", - args(varX(windowFunctionLambdaName), getMetaDataMethodCall(MD_ALIAS_NAME_LIST)) + args(varX(windowFunctionLambdaName), aliasNameListExpression) ) } } @@ -953,7 +969,9 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable default: throw new GroovyBugError("Unknown set operation: ${setOperationExpression.operation}") } - return callX(leftExpr, methodName, args(rightExpr)) + MethodCallExpression result = callX(leftExpr, methodName, args(rightExpr)) + result.setType(QUERYABLE_TYPE) + return result } /** @@ -1394,7 +1412,7 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable callX( classX(QUERYABLE_HELPER_TYPE), "navigate", - args(varX(lambdaParamName), getMetaDataMethodCall(MD_ALIAS_NAME_LIST)) + args(varX(lambdaParamName), aliasNameListExpression) ) } else { transformedExpression = varX(lambdaParamName) @@ -1439,6 +1457,21 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable callXWithLambda( varX(__GROUP), methodName, dataSourceExpression, lambdaCode) + } else { + Class aggregateClass = customAggregate(methodName) + if (aggregateClass != null) { + List aggregateArgs = ((TupleExpression) expression.arguments).getExpressions() + Expression selector = nullX() + if (!aggregateArgs.isEmpty()) { + Expression lambdaCode = aggregateArgs.get(0) + lambdaCode.putNodeMetaData(__LAMBDA_PARAM_NAME, findRootObjectExpression(lambdaCode).text) + selector = constructLambdaExpression(dataSourceExpression, false, lambdaCode) + } + transformedExpression = callX( + classX(GINQ_AGGREGATES_TYPE), + 'apply', + args(classX(makeWithoutCaching(aggregateClass)), varX(__GROUP), selector)) + } } visitingAggregateFunctionStack.pop() } @@ -1546,7 +1579,7 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable transformedLambdCode = callX( classX(QUERYABLE_HELPER_TYPE), - "supplyAsync", + "supplyClause", argumentListExpression ) } @@ -1695,6 +1728,7 @@ class GinqAstWalker implements GinqAstVisitor, SyntaxErrorReportable private static final ClassNode ORDER_TYPE = makeWithoutCaching(Queryable.Order.class) private static final ClassNode NAMED_RECORD_TYPE = makeWithoutCaching(NamedRecord.class) private static final ClassNode QUERYABLE_HELPER_TYPE = makeWithoutCaching(QueryableHelper.class) + private static final ClassNode GINQ_AGGREGATES_TYPE = makeWithoutCaching(GinqAggregates.class) private static final ClassNode WINDOW_DEFINITION_TYPE = makeWithoutCaching(WindowDefinition.class) private static final ClassNode ROWBOUND_TYPE = makeCached(RowBound.class) private static final ClassNode VALUEBOUND_TYPE = makeWithoutCaching(ValueBound.class) diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/LazyQueryable.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/LazyQueryable.java new file mode 100644 index 00000000000..3099ff02b1b --- /dev/null +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/LazyQueryable.java @@ -0,0 +1,356 @@ +/* + * 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.collection.runtime; + +import groovy.lang.Closure; +import groovy.lang.Tuple2; +import groovy.transform.Internal; +import org.apache.groovy.lang.annotation.GroovyABI; + +import java.math.BigDecimal; +import java.util.Iterator; +import java.util.List; +import org.codehaus.groovy.runtime.typehandling.GroovyCastException; + +import java.util.Objects; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Stream; + +/** + * A {@link Queryable} whose pipeline is built on first use. + *

+ * Statically checked {@code GQ} expressions return one of these. The closure is + * created when the expression runs, so it captures locals then, and it is called + * by the first terminal or consuming operation. Sources inside the closure are + * therefore not opened until that read. The built pipeline is cached, matching + * {@link QueryableCollection#toList()}'s single materialization. Fluent queries + * do not use this type: {@code Ginq.from} records operators on its own query + * object and runs them at the terminal. + * + * @param the element type + * @since 7.0.0 + */ +@Internal +public final class LazyQueryable implements Queryable { + + private Supplier> supplier; + private Queryable delegate; + + private LazyQueryable(Supplier> supplier) { + this.supplier = supplier; + } + + /** + * Returns a query that calls {@code body} the first time it is used. + * The closure is retained, not invoked, by this method. The return type is + * raw so a static {@code toList()} is a raw {@code List}, which a caller can + * assign to {@code List} the same way a dynamic query can. + * + * @param body builds the pipeline; invoked at most once + * @return the deferred query + * @throws NullPointerException when {@code body} is null + */ + @GroovyABI(since = "7.0.0") + @SuppressWarnings({"unchecked", "rawtypes"}) + public static Queryable defer(Closure body) { + Objects.requireNonNull(body, "body"); + return new LazyQueryable(() -> (Queryable) body.call()); + } + + @SuppressWarnings("unchecked") + private Queryable unwrap() { + if (delegate == null) { + synchronized (this) { + if (delegate == null) { + Queryable built = supplier.get(); + supplier = null; + if (built == null) { + throw new IllegalStateException("GINQ query supplier returned null"); + } + delegate = (Queryable) built; + } + } + } + return delegate; + } + + @Override + public Queryable> innerJoin(Queryable queryable, BiPredicate joiner) { + return unwrap().innerJoin(queryable, joiner); + } + + @Override + public Queryable> innerHashJoin(Queryable queryable, Function fieldsExtractor1, Function fieldsExtractor2) { + return unwrap().innerHashJoin(queryable, fieldsExtractor1, fieldsExtractor2); + } + + @Override + public Queryable> leftJoin(Queryable queryable, BiPredicate joiner) { + return unwrap().leftJoin(queryable, joiner); + } + + @Override + public Queryable> leftHashJoin(Queryable queryable, Function fieldsExtractor1, Function fieldsExtractor2) { + return unwrap().leftHashJoin(queryable, fieldsExtractor1, fieldsExtractor2); + } + + @Override + public Queryable> rightJoin(Queryable queryable, BiPredicate joiner) { + return unwrap().rightJoin(queryable, joiner); + } + + @Override + public Queryable> rightHashJoin(Queryable queryable, Function fieldsExtractor1, Function fieldsExtractor2) { + return unwrap().rightHashJoin(queryable, fieldsExtractor1, fieldsExtractor2); + } + + @Override + public Queryable> fullJoin(Queryable queryable, BiPredicate joiner) { + return unwrap().fullJoin(queryable, joiner); + } + + @Override + public Queryable> fullHashJoin(Queryable queryable, Function fieldsExtractor1, Function fieldsExtractor2) { + return unwrap().fullHashJoin(queryable, fieldsExtractor1, fieldsExtractor2); + } + + @Override + public Queryable> crossJoin(Queryable queryable) { + return unwrap().crossJoin(queryable); + } + + @Override + public Queryable where(Predicate filter) { + return unwrap().where(filter); + } + + @Override + public Queryable>> groupBy(Function classifier, Predicate>> having) { + return unwrap().groupBy(classifier, having); + } + + @Override + public Queryable> groupByInto(Function classifier, Predicate> having) { + return unwrap().groupByInto(classifier, having); + } + + @Override + @SuppressWarnings("unchecked") + public > Queryable orderBy(Queryable.Order... orders) { + return unwrap().orderBy(orders); + } + + @Override + public Queryable limit(long offset, long size) { + return unwrap().limit(offset, size); + } + + @Override + public Queryable select(BiFunction, ? extends U> mapper) { + return unwrap().select(mapper); + } + + @Override + public Queryable distinct() { + return unwrap().distinct(); + } + + @Override + public Queryable unionAll(Queryable queryable) { + return unwrap().unionAll(queryable); + } + + @Override + public Queryable intersect(Queryable queryable) { + return unwrap().intersect(queryable); + } + + @Override + public Queryable minus(Queryable queryable) { + return unwrap().minus(queryable); + } + + @Override + public Long count() { + return unwrap().count(); + } + + @Override + public Long count(Function mapper) { + return unwrap().count(mapper); + } + + @Override + public BigDecimal sum(Function mapper) { + return unwrap().sum(mapper); + } + + @Override + public BigDecimal avg(Function mapper) { + return unwrap().avg(mapper); + } + + @Override + public > U min(Function mapper) { + return unwrap().min(mapper); + } + + @Override + public > U max(Function mapper) { + return unwrap().max(mapper); + } + + @Override + public List list(Function mapper) { + return unwrap().list(mapper); + } + + @Override + public BigDecimal median(Function mapper) { + return unwrap().median(mapper); + } + + @Override + public BigDecimal stdev(Function mapper) { + return unwrap().stdev(mapper); + } + + @Override + public BigDecimal stdevp(Function mapper) { + return unwrap().stdevp(mapper); + } + + @Override + public BigDecimal var(Function mapper) { + return unwrap().var(mapper); + } + + @Override + public BigDecimal varp(Function mapper) { + return unwrap().varp(mapper); + } + + @Override + public U agg(Function, ? extends U> mapper) { + return unwrap().agg(mapper); + } + + @Override + public List toList() { + return unwrap().toList(); + } + + @Override + public long size() { + return unwrap().size(); + } + + @Override + public Stream stream() { + return unwrap().stream(); + } + + /** + * Materializes and iterates. Provided so a deferred query can be used from dynamic Groovy, + * which looks up {@code iterator()} even though {@link Queryable} does not declare it. + * + * @return an iterator over the materialized elements + */ + public Iterator iterator() { + return toList().iterator(); + } + + /** + * Same coercions as {@link Queryable#asType(Class)}. Asking for this query + * does not build the pipeline. Every other target does, then uses the + * built query's coercion, which delegates to {@code DefaultGroovyMethods} + * when the target is not a list, collection, or iterable. + * + * @param type the requested type + * @return the coerced value + * @throws GroovyCastException when {@code type} is null or the value cannot be coerced + */ + public Object asType(Class type) { + if (type == null) { + throw new GroovyCastException("Cannot cast '" + getClass().getName() + "' to null"); + } + if (type == LazyQueryable.class || type == Queryable.class) { + return this; + } + Queryable built = unwrap(); + return built.asType(type); + } + + /** + * Returns one materialized element. + * + * @param index the element index + * @return the element at that index + */ + public T getAt(int index) { + return toList().get(index); + } + + /** + * Compares the materialized elements with another query or collection. + * + * @param other the object to compare + * @return {@code true} when the materialized elements are equal + */ + @Override + public boolean equals(Object other) { + if (other == this) { + return true; + } + Queryable built = unwrap(); + if (other instanceof LazyQueryable lazy) { + return built.equals(lazy.unwrap()); + } + return built.equals(other); + } + + /** + * Returns the hash code of the materialized query. + * + * @return the hash code + */ + @Override + public int hashCode() { + return unwrap().hashCode(); + } + + /** + * Returns the same text as the materialized query. + * + * @return the string form + */ + @Override + public String toString() { + return String.valueOf(unwrap()); + } + + @Override + public > Window over(Tuple2 currentRecord, WindowDefinition windowDefinition) { + return unwrap().over(currentRecord, windowDefinition); + } +} diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Queryable.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Queryable.java index 304ac82fce7..02e39e447c2 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Queryable.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Queryable.java @@ -21,9 +21,14 @@ import groovy.lang.Tuple2; import groovy.transform.Internal; import org.apache.groovy.lang.annotation.GroovyABI; +import org.codehaus.groovy.runtime.DefaultGroovyMethods; +import org.codehaus.groovy.runtime.typehandling.GroovyCastException; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.function.BiFunction; @@ -91,6 +96,24 @@ static Queryable from(T[] array) { return new QueryableCollection<>(Arrays.asList(array)); } + /** + * Factory for a primitive {@code int} array. {@code int[]} is not a + * {@code T[]}, so the elements are boxed and the queryable's element + * type is {@code Integer}. + * + * @param array the source values + * @return a queryable of the boxed values + * @since 7.0.0 + */ + @GroovyABI(since = "7.0.0") + static Queryable from(int[] array) { + List boxed = new ArrayList<>(array.length); + for (int value : array) { + boxed.add(value); + } + return new QueryableCollection<>(boxed); + } + /** * Factory method to create {@link Queryable} instance * @@ -117,6 +140,22 @@ static Queryable from(Queryable queryable) { return queryable; } + /** + * Factory for a list owned by the queryable, not supplied by the caller. + * {@link #toList()} returns a copy, so mutating that result does not change + * later terminals or {@code list} itself. + * + * @param list the owned elements + * @param the type of element + * @return the {@link Queryable} instance + * @since 7.0.0 + */ + @GroovyABI(since = "7.0.0") + static Queryable fromOwned(List list) { + Objects.requireNonNull(list, "list"); + return new QueryableCollection<>(list, false); + } + /** * Inner join another {@link Queryable} instance, similar to SQL's {@code inner join} * @@ -516,6 +555,56 @@ default Queryable union(Queryable queryable) { */ List toList(); + /** + * Iterates the materialized elements. A static {@code for} loop calls this + * rather than wrapping the query as a single value. + * + * @return an iterator over the elements + * @since 7.0.0 + */ + default Iterator iterator() { + return toList().iterator(); + } + + /** + * Coerces this query. {@link List} is {@link #toList()}. {@link Collection}, + * {@link Iterable} and any other collection type are that list passed to + * {@link DefaultGroovyMethods#asType(Collection, Class)}: this query does + * not implement those types, so {@link DefaultGroovyMethods#asType(Object, Class)} + * cannot walk its elements. Every other target, including {@link Queryable}, + * is delegated to {@link DefaultGroovyMethods#asType(Object, Class)}, which + * throws {@link GroovyCastException} when the value is not compatible with + * the target. + * + * @param type the requested type + * @return the coerced value + * @throws GroovyCastException when {@code type} is null or the value cannot be coerced + * @since 7.0.0 + */ + default Object asType(Class type) { + if (type == null) { + throw new GroovyCastException("Cannot cast '" + getClass().getName() + "' to null"); + } + if (type == List.class) { + return toList(); + } + if (type == Iterable.class || Collection.class.isAssignableFrom(type)) { + return DefaultGroovyMethods.asType(toList(), type); + } + return DefaultGroovyMethods.asType((Object) this, type); + } + + /** + * Returns one materialized element. + * + * @param index the element index + * @return the element at that index + * @since 7.0.0 + */ + default T getAt(int index) { + return toList().get(index); + } + /** * Returns the count of elements of the {@link Queryable} instance * @@ -525,9 +614,10 @@ default Queryable union(Queryable queryable) { long size(); /** - * Create {@link Stream} object for the {@link Queryable} instance + * Returns a new stream over the elements. The stream has not been consumed. + * The default implementation streams the list from {@link #toList()}. * - * @return the result stream + * @return a stream that has not been consumed * @since 4.0.0 */ default Stream stream() { diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollection.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollection.java index e0bd13df1c6..50776d99e11 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollection.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollection.java @@ -25,6 +25,7 @@ import groovy.transform.Internal; import org.apache.groovy.internal.util.Supplier; import org.codehaus.groovy.runtime.DefaultGroovyMethods; +import org.codehaus.groovy.runtime.typehandling.GroovyCastException; import org.codehaus.groovy.runtime.dgmimpl.NumberNumberMinus; import org.codehaus.groovy.runtime.typehandling.NumberMath; @@ -37,6 +38,7 @@ import java.util.Collections; import java.util.Comparator; import java.util.Deque; +import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; @@ -46,7 +48,9 @@ import java.util.Objects; import java.util.Queue; import java.util.Set; +import java.util.Spliterator; import java.util.TreeSet; +import java.util.function.Consumer; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; @@ -88,7 +92,19 @@ class QueryableCollection implements Queryable, Serializable { * @param sourceIterable the source elements */ QueryableCollection(Iterable sourceIterable) { + this(sourceIterable, sourceIterable instanceof List); + } + + /** + * Creates a queryable collection backed by an iterable. + * + * @param sourceIterable the source elements + * @param sourceListIsUserSupplied {@code true} when {@code sourceIterable} is a + * user-supplied {@link List} that {@link #toList()} may return as-is + */ + QueryableCollection(Iterable sourceIterable, boolean sourceListIsUserSupplied) { this.sourceIterable = sourceIterable; + this.sourceListIsUserSupplied = sourceListIsUserSupplied; } /** @@ -101,21 +117,17 @@ class QueryableCollection implements Queryable, Serializable { } /** - * Returns an iterator over the current source. + * Returns an iterator over the current source. The iterator is created + * from {@link #stream()}, so it follows the same re-enumeration rules: a + * live iterable is read again, and a one-shot stream is replayed from the + * buffer. The read lock is not held around this call; taking it and then + * calling {@link #stream()} would deadlock on a lock upgrade. * * @return an iterator over the elements */ + @Override public Iterator iterator() { - readLock.lock(); - try { - if (null != sourceIterable) { - return sourceIterable.iterator(); - } - - return sourceStream.iterator(); - } finally { - readLock.unlock(); - } + return stream().iterator(); } /** @@ -131,7 +143,7 @@ public Iterator iterator() { @Override public Queryable> innerJoin(Queryable queryable, BiPredicate joiner) { Stream> stream = - this.stream() + openStream() .flatMap(p -> { if (queryable instanceof QueryableCollection) { ((QueryableCollection) queryable).makeReusable(); @@ -161,7 +173,7 @@ public Queryable> innerJoin(Queryable queryable, B public Queryable> innerHashJoin(Queryable queryable, Function fieldsExtractor1, Function fieldsExtractor2) { final ConcurrentObjectHolder>>> hashTableHolder = new ConcurrentObjectHolder<>(createHashTableSupplier(queryable, fieldsExtractor2)); if (isParallel()) hashTableHolder.getObject(); // avoid nested parallel querying, which results in deadlock sometimes - Stream> stream = this.stream().flatMap(p -> { + Stream> stream = openStream().flatMap(p -> { // build hash table Map>> hashTable = hashTableHolder.getObject(); @@ -328,7 +340,7 @@ public Queryable> fullHashJoin(Queryable queryable @Override public Queryable> crossJoin(Queryable queryable) { Stream> stream = - this.stream() + openStream() .flatMap(p -> { if (queryable instanceof QueryableCollection) { ((QueryableCollection) queryable).makeReusable(); @@ -349,7 +361,7 @@ public Queryable> crossJoin(Queryable queryable) { */ @Override public Queryable where(Predicate filter) { - Stream stream = this.stream().filter(filter); + Stream stream = openStream().filter(filter); return from(stream); } @@ -366,13 +378,8 @@ public Queryable where(Predicate filter) { */ @Override public Queryable>> groupBy(Function classifier, Predicate>> having) { - Collector>> groupingBy = - isParallel() ? Collectors.groupingByConcurrent(classifier, Collectors.toList()) - : Collectors.groupingBy(classifier, Collectors.toList()); - Stream>> stream = - this.stream() - .collect(groupingBy) + groupAllowingNullKeys(openStream(), classifier, isParallel()) .entrySet().stream() .filter(m -> null == having || having.test(tuple(m.getKey(), from(m.getValue())))) .map(m -> tuple(m.getKey(), from(m.getValue()))); @@ -393,22 +400,48 @@ public Queryable>> groupBy(Function classif */ @Override public Queryable> groupByInto(Function classifier, Predicate> having) { - Collector>> groupingBy = - isParallel() ? Collectors.groupingByConcurrent(classifier, Collectors.toList()) - : Collectors.groupingBy(classifier, Collectors.toList()); - // Materialize group elements as lists so they can be iterated multiple times // (e.g., having g.count() > 1 followed by select g.count()) Stream> stream = - this.stream() - .collect(groupingBy) + groupAllowingNullKeys(openStream(), classifier, isParallel()) .entrySet().stream() - .map(m -> GroupResult.of(m.getKey(), from(m.getValue()))) + .map(m -> GroupResult.of(castGroupKey(m.getKey()), from(m.getValue()))) .filter(gr -> null == having || having.test(gr)); return from(stream); } + /** + * Groups a stream, keeping a single group for null keys. + * {@code Collectors.groupingBy} rejects a null key, which made + * {@code partitionby} of a null value fail. + */ + private static Map> groupAllowingNullKeys(Stream stream, Function classifier, boolean parallel) { + if (!parallel) { + Map> grouped = new HashMap<>(); + stream.forEach(item -> grouped.computeIfAbsent(classifier.apply(item), key -> new ArrayList<>()).add(item)); + return grouped; + } + // ConcurrentHashMap cannot store a null key, so null is masked while grouping. + Map> masked = stream.collect(Collectors.groupingByConcurrent(item -> { + Object key = classifier.apply(item); + return null == key ? NULL_GROUP : key; + }, Collectors.toList())); + if (!masked.containsKey(NULL_GROUP)) { + return masked; + } + Map> grouped = new HashMap<>(masked.size()); + for (Map.Entry> entry : masked.entrySet()) { + grouped.put(entry.getKey() == NULL_GROUP ? null : entry.getKey(), entry.getValue()); + } + return grouped; + } + + @SuppressWarnings("unchecked") + private static K castGroupKey(Object key) { + return (K) key; + } + /** * Sorts by the supplied orders. When no orders are given, returns this queryable unchanged. * @@ -424,7 +457,7 @@ public final > Queryable orderBy(Order> Comparator makeComparat */ @Override public Queryable limit(long offset, long size) { - Stream stream = this.stream().skip(offset).limit(size); + Stream stream = openStream().skip(offset).limit(size); return from(stream); } @@ -514,7 +547,7 @@ public Queryable select(BiFunction mapper.apply(t, this)); + stream = openStream().map((T t) -> mapper.apply(t, this)); } if (TRUE_STR.equals(originalParallel)) { @@ -547,7 +580,7 @@ public Queryable select(BiFunction distinct() { - Stream stream = this.stream().distinct(); + Stream stream = openStream().distinct(); return from(stream); } @@ -560,7 +593,7 @@ public Queryable distinct() { */ @Override public Queryable unionAll(Queryable queryable) { - Stream stream = Stream.concat(this.stream(), queryable.stream()); + Stream stream = Stream.concat(openStream(), queryable.stream()); return from(stream); } @@ -573,7 +606,7 @@ public Queryable unionAll(Queryable queryable) { */ @Override public Queryable intersect(Queryable queryable) { - Stream stream = this.stream().filter(a -> { + Stream stream = openStream().filter(a -> { if (queryable instanceof QueryableCollection) { ((QueryableCollection) queryable).makeReusable(); } @@ -592,7 +625,7 @@ public Queryable intersect(Queryable queryable) { */ @Override public Queryable minus(Queryable queryable) { - Stream stream = this.stream().filter(a -> { + Stream stream = openStream().filter(a -> { if (queryable instanceof QueryableCollection) { ((QueryableCollection) queryable).makeReusable(); } @@ -637,7 +670,7 @@ public Long count(Function mapper) { */ @Override public BigDecimal sum(Function mapper) { - return agg(q -> this.stream() + return agg(q -> openStream() .map(e -> { Number n = mapper.apply(e); if (null == n) return BigDecimal.ZERO; @@ -667,7 +700,11 @@ public BigDecimal avg(Function mapper) { }, (o1, o2) -> o1) ); - return ((BigDecimal) result[1]).divide(toBigDecimal((Long) result[0]), 16, RoundingMode.HALF_UP); + long count = (Long) result[0]; + if (0L == count) { + return null; + } + return ((BigDecimal) result[1]).divide(toBigDecimal(count), 16, RoundingMode.HALF_UP); } /** @@ -799,6 +836,9 @@ public BigDecimal varp(Function mapper) { private BigDecimal vr(Function mapper, int diff) { BigDecimal avg = this.avg(mapper); + if (null == avg) { + return null; + } Object[] result = agg(q -> q.stream() .map(mapper) .filter(Objects::nonNull) @@ -809,12 +849,20 @@ private BigDecimal vr(Function mapper, int diff) { return r; }, (o1, o2) -> o1)); - return ((BigDecimal) result[1]).divide(toBigDecimal((Long) result[0] - diff), 16, RoundingMode.HALF_UP); + long divisor = (Long) result[0] - diff; + if (0L == divisor) { + return null; + } + return ((BigDecimal) result[1]).divide(toBigDecimal(divisor), 16, RoundingMode.HALF_UP); } private BigDecimal sd(Function mapper, int diff) { + BigDecimal variance = vr(mapper, diff); + if (null == variance) { + return null; + } // `BigDecimal.sqrt` is introduced since Java9, so we can not use it for now. - return toBigDecimal(sqrt(vr(mapper, diff).doubleValue())); + return toBigDecimal(sqrt(variance.doubleValue())); } /** @@ -891,13 +939,20 @@ public List toList() { writeLock.lock(); try { if (sourceIterable instanceof @SuppressWarnings("unchecked")List list) { - return list; + if (sourceListIsUserSupplied) { + return list; + } + return new ArrayList<>(list); + } + + if (upstreamBound) { + return new ArrayList<>(drainOneShot()); } - final List result = stream().collect(Collectors.toList()); + final List result = openStream().collect(Collectors.toList()); sourceIterable = result; - return result; + return new ArrayList<>(result); } finally { writeLock.unlock(); } @@ -914,14 +969,185 @@ public long size() { } /** - * Returns a reusable stream over the current elements. + * Returns a new stream over the current elements. Creating the stream does not + * pull. An iterable source is read again by every stream. A one-shot stream is + * pulled into a buffer as it is consumed, and a later call replays that buffer + * instead of returning the stream that was already handed out. * - * @return the element stream + * @return a stream that has not been consumed */ @Override public Stream stream() { writeLock.lock(); try { + if (sourceIterable != null) { + Stream fresh = toStream(sourceIterable); + if (!fresh.isParallel() && isParallel()) { + fresh = fresh.parallel(); + } + return fresh; + } + bindUpstream(); + return StreamSupport.stream(ReplaySpliterator::new, upstreamCharacteristics, false); + } finally { + writeLock.unlock(); + } + } + + /** + * Binds the one-shot source. The size is recorded before any element is pulled, + * so a later {@code count} can use it without running projections. + */ + private void bindUpstream() { + if (upstreamBound) { + return; + } + upstreamBound = true; + upstream = openStream().spliterator(); + long exact = upstream.getExactSizeIfKnown(); + upstreamExactSize = exact; + upstreamCharacteristics = Spliterator.ORDERED; + if (exact >= 0) { + upstreamCharacteristics |= Spliterator.SIZED | Spliterator.SUBSIZED; + } + } + + /** + * One cursor over a one-shot source. Elements are appended to {@link #replay} + * as they are pulled, so another stream can read them from the start. + * A sized source reports that size, and {@code Stream.count} then does not pull. + */ + private final class ReplaySpliterator implements Spliterator { + private int cursor; + + /** + * The read lock, or the write lock when this cursor has caught up, + * covers only the buffer. The element is copied and this cursor + * advances before the lock is released; {@code action} runs after + * that. A throwing action has consumed the element, and the buffer + * still holds it for other cursors. + */ + @Override + public boolean tryAdvance(Consumer action) { + if (serveReplayed(action)) { + return true; + } + T item = null; + boolean present = false; + writeLock.lock(); + try { + // Lost the race with a writer, or this cursor is the one pulling. + if (cursor < replay.size() || pullIntoReplay()) { + item = replay.get(cursor); + cursor++; + present = true; + } + } finally { + writeLock.unlock(); + } + if (!present) { + return false; + } + action.accept(item); + return true; + } + + /** + * Appends one upstream element to {@link #replay}. Caller holds the write lock. + * + * @return {@code true} when a new element was appended + */ + private boolean pullIntoReplay() { + if (oneShotDone) { + return false; + } + boolean[] advanced = {false}; + boolean more = upstream.tryAdvance(pulled -> { + replay.add(pulled); + advanced[0] = true; + }); + if (!more || !advanced[0]) { + finishOneShot(); + return false; + } + return true; + } + + /** + * Serves an element already in {@link #replay}. The read lock covers + * the buffer only; the callback runs after it is released so a reader + * does not take the write lock, and does not hold the read lock across + * a callback that may need the write lock. The cursor advances after + * the element is read, so a throwing callback has consumed it. + */ + private boolean serveReplayed(Consumer action) { + T item; + readLock.lock(); + try { + if (cursor >= replay.size()) { + return false; + } + item = replay.get(cursor); + cursor++; + } finally { + readLock.unlock(); + } + action.accept(item); + return true; + } + + @Override + public Spliterator trySplit() { + return null; + } + + @Override + public long estimateSize() { + if (upstreamExactSize >= 0) { + return Math.max(0L, upstreamExactSize - cursor); + } + return Long.MAX_VALUE; + } + + @Override + public int characteristics() { + return upstreamCharacteristics; + } + } + + private List drainOneShot() { + List result = new ArrayList<>(); + new ReplaySpliterator().forEachRemaining(result::add); + sourceIterable = result; + sourceStream = null; + return result; + } + + private void finishOneShot() { + oneShotDone = true; + if (sourceIterable == null) { + sourceIterable = replay; + sourceStream = null; + } + } + + /** + * Opens the source for pipeline construction. An iterable is streamed again on + * every call. After a one-shot source has been bound, this returns a fresh + * stream on the public replay path instead of the already-spliterated + * {@link #sourceStream}. {@link #stream()} may call this while binding; + * the replay route is taken only when {@link #upstream} is already set, so + * that bind does not re-enter itself. + * + * @return a stream over the source, which may be a replay stream + */ + private Stream openStream() { + writeLock.lock(); + try { + if (upstream != null) { + return stream(); + } + if (isReusable()) { sourceStream = toStream(sourceIterable); // we have to create new stream every time because Java stream can not be reused } @@ -1004,7 +1230,7 @@ private static class PartitionCacheKey { public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof PartitionCacheKey that)) return false; - return partitionKey.equals(that.partitionKey) && partitionId.equals(that.partitionId); + return Objects.equals(partitionKey, that.partitionKey) && Objects.equals(partitionId, that.partitionId); } /** @@ -1076,6 +1302,11 @@ private void makeReusable() { try { if (null != this.sourceIterable) return; + if (upstreamBound) { + drainOneShot(); + return; + } + this.sourceIterable = this.sourceStream.collect(Collectors.toList()); } finally { writeLock.unlock(); @@ -1089,6 +1320,9 @@ private void makeReusable() { * @return the coerced value */ public Object asType(Class clazz) { + if (clazz == null) { + throw new GroovyCastException("Cannot cast '" + getClass().getName() + "' to null"); + } if (Queryable.class == clazz || QueryableCollection.class == clazz) { return this; } @@ -1175,10 +1409,21 @@ public String toString() { private final Map, Partition>> sortedPartitionCache = new ConcurrentHashMap<>(4); private Stream sourceStream; private volatile Iterable sourceIterable; + /** True when {@link #sourceIterable} is a user-supplied {@link List}, which {@link #toList()} may return as-is. */ + private boolean sourceListIsUserSupplied; + /** Elements pulled from a one-shot {@link #sourceStream}, in order. */ + private final List replay = new ArrayList<>(); + private transient Spliterator upstream; + private boolean upstreamBound; + private long upstreamExactSize = -1L; + private int upstreamCharacteristics = Spliterator.ORDERED; + private boolean oneShotDone; private final ReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock readLock = rwl.readLock(); private final Lock writeLock = rwl.writeLock(); private static final BigDecimal BD_TWO = BigDecimal.valueOf(2); + /** Stands in for a null group key in a concurrent map, which cannot store null. */ + private static final Object NULL_GROUP = new Object(); private static final String USE_WINDOW_FUNCTION = "useWindowFunction"; private static final String PARALLEL = "parallel"; private static final String TRUE_STR = "true"; diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableHelper.groovy b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableHelper.groovy index 644df785a25..e3cc09b3ace 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableHelper.groovy +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableHelper.groovy @@ -111,6 +111,42 @@ class QueryableHelper { return CompletableFuture.supplyAsync(() -> { function.apply(param) }, ThreadPoolHolder.THREAD_POOL) } + /** + * Runs one clause body on the shared pool. The declared type is {@code Object} + * so static inference never sees {@code CompletableFuture}: a parallel row + * was being typed as that future, and the generated bridge then cast the row. + * The value returned to the runtime is still the future {@code select} unwraps + * with {@code CompletableFuture.get}. + *

+ * {@code async} is not used. It schedules on the runtime async executor + * rather than this helper's pool, and it returns an {@code Awaitable}. + * {@code select} casts the row to {@code CompletableFuture}. + * + * @param supplier the clause body + * @return the asynchronous result + * @since 7.0.0 + */ + @GroovyABI(since = "7.0.0") + static Object supplyClause(Supplier supplier) { + return CompletableFuture.supplyAsync(supplier, ThreadPoolHolder.THREAD_POOL) + } + + /** + * Runs one clause body on the shared pool. The function types and the + * declared result are {@code Object}, so a row number is not inferred as + * {@code CompletableFuture}. The pool and the returned future are the same + * as {@link #supplyClause(Supplier)}. + * + * @param function the clause body + * @param param the row number, or another value the body reads + * @return the asynchronous result + * @since 7.0.0 + */ + @GroovyABI(since = "7.0.0") + static Object supplyClause(Function function, Object param) { + return CompletableFuture.supplyAsync(() -> function.apply(param), ThreadPoolHolder.THREAD_POOL) + } + /** * Submits work to the shared fork-join pool. * @@ -168,6 +204,28 @@ class QueryableHelper { * * @param mode 0: immediate, 1: abort */ + /** + * Reports whether {@link #shutdown(int)} has been requested. + * + * @return {@code true} after shutdown + * @since 7.0.0 + */ + @GroovyABI(since = "7.0.0") + static boolean isShutdown() { + ThreadPoolHolder.THREAD_POOL.isShutdown() + } + + /** + * Reports whether the worker pool has finished shutting down. + * + * @return {@code true} when the pool is terminated + * @since 7.0.0 + */ + @GroovyABI(since = "7.0.0") + static boolean isTerminated() { + ThreadPoolHolder.THREAD_POOL.isTerminated() + } + @GroovyABI(since = "4.0.0") static void shutdown(int mode) { if (0 == mode) { diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/SourceRecord.groovy b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/SourceRecord.groovy index 3bde1e44b00..4c50a2490b3 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/SourceRecord.groovy +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/SourceRecord.groovy @@ -19,15 +19,18 @@ package org.apache.groovy.ginq.provider.collection.runtime import groovy.transform.CompileStatic -import groovy.transform.PackageScope +import groovy.transform.Internal import groovy.transform.stc.POJO /** - * Represents source record, which is constructed by {@code from}/joins clauses + * Represents source record, which is constructed by {@code from}/joins clauses. + * Public because {@code navigate} returns it and a statically compiled caller + * in another package has to be able to name the row. Internal: not a published + * API. * * @since 4.0.0 */ -@PackageScope +@Internal @POJO @CompileStatic class SourceRecord implements Serializable { diff --git a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Window.java b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Window.java index aa7a0630547..a107302e4b0 100644 --- a/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Window.java +++ b/subprojects/groovy-ginq/src/main/groovy/org/apache/groovy/ginq/provider/collection/runtime/Window.java @@ -21,14 +21,15 @@ import groovy.lang.Tuple2; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.Collections; +import java.util.Comparator; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Collections.binarySearch; import static java.util.Comparator.comparing; -import static org.apache.groovy.ginq.provider.collection.runtime.Queryable.from; /** * Represents window which stores elements used by window functions @@ -50,12 +51,8 @@ public interface Window extends Queryable { */ static > Window of(Tuple2 currentRecord, Partition> partition, WindowDefinition windowDefinition) { final List> orderList = windowDefinition.orderBy(); - Order order; - if (null != orderList && 1 == orderList.size()) { - order = orderList.get(0); - } else { - order = null; - } + // Range offsets use the single order key. Ranking uses every key. + Order singleOrder = null != orderList && 1 == orderList.size() ? orderList.get(0) : null; List> listWithIndex = partition.toList(); @@ -63,15 +60,25 @@ static > Window of(Tuple2 current ? binarySearch(listWithIndex, currentRecord, comparing(Tuple2::getV2)) : binarySearch(listWithIndex, currentRecord, WindowImpl.makeComparator(WindowImpl.composeOrders(orderList)).thenComparing(Tuple2::getV2)); int index = tmpIndex >= 0 ? tmpIndex : -tmpIndex - 1; - U value = null == order ? null : order.getKeyExtractor().apply(currentRecord.getV1()); + U value = null == singleOrder ? null : singleOrder.getKeyExtractor().apply(currentRecord.getV1()); RowBound validRowBound = WindowImpl.getValidRowBound(windowDefinition, index, value, listWithIndex); - List list = null == validRowBound ? Collections.emptyList() - : from(listWithIndex.stream().map(Tuple2::getV1).collect(Collectors.toList())) - .limit(validRowBound.getLower(), validRowBound.getUpper() - validRowBound.getLower() + 1) - .toList(); + List orderedPartition = listWithIndex.stream().map(Tuple2::getV1).collect(Collectors.toList()); + List frame; + if (null == validRowBound) { + frame = Collections.emptyList(); + } else { + int from = validRowBound.getLower().intValue(); + int to = validRowBound.getUpper().intValue(); + frame = 0 == from && to == orderedPartition.size() - 1 + ? orderedPartition + : new ArrayList<>(orderedPartition.subList(from, to + 1)); + } + Comparator ordering = null == orderList || orderList.isEmpty() + ? null + : QueryableCollection.makeComparator(orderList); - return new WindowImpl<>(currentRecord, index, value, list, order); + return new WindowImpl<>(currentRecord, index, frame, ordering, orderedPartition); } /** 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..211c1dcb5de 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 @@ -37,28 +37,29 @@ * Represents window which stores elements used by window functions * * @param the type of {@link Queryable} element - * @param the type of field to sort * @since 4.0.0 */ -class WindowImpl> extends QueryableCollection implements Window { +class WindowImpl extends QueryableCollection implements Window { /** * Creates a window for the current record. * * @param currentRecord the current record and row index * @param index the current zero-based row index - * @param value the current order value - * @param list the window contents - * @param order the order rule backing the window + * @param list the frame contents, the rows aggregates and value functions see + * @param comparator the full window order, or {@code null} when the window is unordered. + * Ranking uses every key. A single key is not required + * @param orderedPartition the ordered partition. {@code lead}, {@code lag}, {@code rowNumber} + * and {@code ntile} address this list, not the frame */ - WindowImpl(Tuple2 currentRecord, int index, U value, List list, Order order) { + WindowImpl(Tuple2 currentRecord, int index, List list, + Comparator comparator, List orderedPartition) { super(list); this.currentRecord = currentRecord; - this.order = order; - this.comparator = null == order ? null : makeComparator(order); + this.comparator = comparator; this.index = index; - this.value = value; this.list = list; + this.orderedPartition = orderedPartition; } /** @@ -78,15 +79,16 @@ public long rowNumber() { */ @Override public V lead(Function extractor, long lead, V def) { - V field; - if (0 == lead) { - field = extractor.apply(currentRecord.getV1()); - } else if (0 <= index + lead && index + lead < list.size()) { - field = extractor.apply(list.get(index + (int) lead)); - } else { - field = def; + if (0L == lead) { + return extractor.apply(currentRecord.getV1()); } - return field; + // The offset is within the ordered partition. The frame list is shorter + // and is not indexed by the partition position. + long target = (long) index + lead; + if (0L <= target && target < orderedPartition.size()) { + return extractor.apply(orderedPartition.get((int) target)); + } + return def; } /** @@ -143,7 +145,7 @@ public V nthValue(Function extractor, long index) { */ @Override public Long rank() { - if (null == order) { + if (null == comparator) { return null; } @@ -165,17 +167,21 @@ public Long rank() { */ @Override public Long denseRank() { - if (null == order) { + if (null == comparator) { return null; } 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; } @@ -187,21 +193,19 @@ public Long denseRank() { */ @Override public BigDecimal percentRank() { - if (null == order) { + if (null == comparator) { return null; } final int size = list.size(); + if (0 == size) { + return null; + } if (1 == size) { return BigDecimal.ONE; } - Long r = rank(); - if (null == r) { - return null; - } - - return toBigDecimal(r - 1).divide(toBigDecimal(size - 1), 16, RoundingMode.HALF_UP); + return toBigDecimal(rank() - 1).divide(toBigDecimal(size - 1), 16, RoundingMode.HALF_UP); } /** @@ -211,7 +215,7 @@ public BigDecimal percentRank() { */ @Override public BigDecimal cumeDist() { - if (null == order) { + if (null == comparator || list.isEmpty()) { return null; } long cnt = list.stream() @@ -228,7 +232,13 @@ public BigDecimal cumeDist() { */ @Override public long ntile(long bucketCnt) { - return bucketCnt * rowNumber() / list.size(); + int size = orderedPartition.size(); + if (0 == size) { + return 0L; + } + // 0-based buckets over the partition. rowNumber() is the partition index, + // so the denominator is the partition size even when a frame is present. + return bucketCnt * rowNumber() / size; } private static > long getFirstIndex(WindowDefinition windowDefinition, int index) { @@ -265,45 +275,210 @@ 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 partition edge in that value direction. + RowBound bound = nullKeyRange(lower, upper, keyCount, numericStart, numericEnd, order.isNullsLast(), order.isAsc()); + 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) { + // Every key is null, so the null peer group is the partition. + RowBound bound = nullKeyRange(lower, upper, keyCount, numericStart, numericEnd, order.isNullsLast(), order.isAsc()); + if (null == bound) { + return null; + } + firstIndex = bound.getLower(); + lastIndex = bound.getUpper(); + } 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); + // Nulls are not numbers. Include the null peer group only when + // an unbounded bound runs off the numeric edge that group sits + // against. Ascending nulls-last puts that group after the high + // values; descending nulls-last puts it after the low values. + boolean ascOrder = order.isAsc(); + boolean coversLow = ascOrder ? absFirst == numericStart : absLast == numericEnd; + boolean coversHigh = ascOrder ? absLast == numericEnd : absFirst == numericStart; + if (order.isNullsLast()) { + boolean throughTrailing = ascOrder ? coversHigh && null == upper : coversLow && null == lower; + if (throughTrailing) { + absLast = keyCount - 1L; + } } else { - final List reversedList = new ReversedList<>(list); - lastIndex = size - 1 - getIndexByValue(lowerValue, true, reversedList); - firstIndex = size - 1 - getIndexByValue(upperValue, false, reversedList); + boolean throughLeading = ascOrder ? coversLow && null == lower : coversHigh && null == upper; + if (throughLeading) { + absFirst = 0L; + } + } + if (absFirst > absLast) { + return null; } + firstIndex = absFirst; + lastIndex = absLast; } + } else if (!(null == lower && null == upper)) { + throw new IllegalArgumentException( + "range bounds apply to one numeric order key; this order key or these bounds are not numeric"); } } if ((firstIndex < 0 && lastIndex < 0) || (firstIndex >= size && lastIndex >= size)) { return null; } - return new RowBound(Math.max(firstIndex, 0L), Math.min(lastIndex, size - 1L)); + long from = Math.max(firstIndex, 0L); + long to = Math.min(lastIndex, size - 1L); + // A frame that ends before it starts is empty. Clamping each side + // independently would ask limit() for a negative length. + if (from > to) { + return null; + } + return new RowBound(from, to); + } + + /** + * 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(); + if (0 == size) { + return null; + } + // Null offsets are truly unbounded. A long sentinel would drop values + // outside the long range, such as 1e20. + BigDecimal lowerValue = null == lower ? null : toBigDecimal(plus(value, lower)); + BigDecimal upperValue = null == upper ? null : toBigDecimal(plus(value, upper)); + BigDecimal smallest = toBigDecimal((Number) (asc ? keys.get(0) : keys.get(size - 1))); + BigDecimal largest = toBigDecimal((Number) (asc ? keys.get(size - 1) : keys.get(0))); + if ((null != upperValue && upperValue.compareTo(smallest) < 0) + || (null != lowerValue && lowerValue.compareTo(largest) > 0)) { + return null; + } + long firstIndex; + long lastIndex; + if (asc) { + firstIndex = null == lowerValue ? 0L : getIndexByValue(lowerValue, true, keys); + lastIndex = null == upperValue ? size - 1L : getIndexByValue(upperValue, false, keys); + } else { + List reversedList = new ReversedList<>(keys); + lastIndex = null == lowerValue ? size - 1L : size - 1L - getIndexByValue(lowerValue, true, reversedList); + firstIndex = null == upperValue ? 0L : 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 + * @param asc whether the window order is ascending + * @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, boolean asc) { + long peerStart = nullsLast ? numericEnd + 1L : 0L; + long peerEnd = nullsLast ? size - 1L : numericStart - 1L; + if (peerStart > peerEnd) { + return null; + } + // A finite offset stays on the null peer group. An unbounded low or high + // bound runs to the partition edge in that value direction, which is the + // opposite end of the list when the order is descending. + boolean lowUnbounded = null == lower; + boolean highUnbounded = null == upper; + long start = asc + ? (lowUnbounded ? 0L : peerStart) + : (highUnbounded ? 0L : peerStart); + long end = asc + ? (highUnbounded ? size - 1L : peerEnd) + : (lowUnbounded ? size - 1L : peerEnd); + if (start > end) { + return null; + } + return new RowBound(start, end); } private static > long getIndexByValue(BigDecimal value, boolean isLower, List list) { @@ -369,12 +544,9 @@ static > List, U>> comp } private final Tuple2 currentRecord; - private final Order order; private final Comparator comparator; private final int index; - private final U value; private final List list; - private static final BigDecimal MIN_VALUE = toBigDecimal(Long.MIN_VALUE); - private static final BigDecimal MAX_VALUE = toBigDecimal(Long.MAX_VALUE); + private final List orderedPartition; @Serial private static final long serialVersionUID = -3458969297047398621L; } 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..18e4f10c42a 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 @@ -19,6 +19,7 @@ package org.apache.groovy.ginq.transform; import groovy.ginq.transform.GQ; +import org.apache.groovy.ginq.GinqStaticBridge; import org.codehaus.groovy.GroovyBugError; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.AnnotatedNode; @@ -26,6 +27,7 @@ import org.codehaus.groovy.ast.ClassHelper; import org.codehaus.groovy.ast.ClassNode; import org.codehaus.groovy.ast.MethodNode; +import org.codehaus.groovy.ast.tools.ParameterUtils; import org.codehaus.groovy.ast.expr.CastExpression; import org.codehaus.groovy.ast.expr.ClassExpression; import org.codehaus.groovy.ast.expr.Expression; @@ -47,6 +49,7 @@ import static org.apache.groovy.ginq.GinqGroovyMethods.transformGinqCode; import static org.codehaus.groovy.ast.ClassHelper.LIST_TYPE; import static org.codehaus.groovy.ast.ClassHelper.make; +import static org.codehaus.groovy.ast.ClassHelper.isDynamicTyped; 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.castX; @@ -91,7 +94,11 @@ public void visit(ASTNode[] nodes, SourceUnit sourceUnit) { } Expression resultExpression = transformGinqCode(sourceUnit, ginqConfigurationMapExpression, origCode); - if (DEFAULT_RESULT_TYPE.equals(targetType)) { // same as `GQ {...}` + boolean keepQueryable = DEFAULT_RESULT_TYPE.equals(targetType); + // A Queryable result waits for its first read. A list or a coerced + // value is read before the method returns, so the query runs here. + resultExpression = GinqStaticBridge.prepare(sourceUnit, methodNode, resultExpression, keepQueryable); + if (keepQueryable) { // same as `GQ {...}` // DO NOTHING } else if (LIST_TYPE.equals(targetType)) { // same as `GQL {...}` resultExpression = callX(resultExpression, "toList"); @@ -104,11 +111,71 @@ public void visit(ASTNode[] nodes, SourceUnit sourceUnit) { BlockStatement newCode = block(stmt(resultExpression)); newCode.setSourcePosition(origCode); methodNode.setCode(newCode); + widenDynamicReturn(methodNode, targetType); VariableScopeVisitor variableScopeVisitor = new VariableScopeVisitor(sourceUnit); variableScopeVisitor.visitClass(methodNode.getDeclaringClass()); } } + /** + * A {@code def} query method is widened to the declared GINQ result type so callers + * compiled statically can use the result. An explicit return type is left alone. + * A method that actually overrides a superclass or interface method is left alone + * when the widened type is not a legal covariant return. + */ + private static void widenDynamicReturn(MethodNode methodNode, ClassNode targetType) { + if (!isDynamicTyped(methodNode.getReturnType()) || targetType == null) { + return; + } + ClassNode widened = targetType.getPlainNodeReference(); + widened.setGenericsTypes(null); + if (incompatibleSuperReturn(methodNode, widened)) { + return; + } + methodNode.setReturnType(widened); + } + + /** + * True when {@code methodNode} overrides a method whose return type cannot be + * widened. The override must be the same method: name, static-ness, and parameter + * types including generics ({@link ParameterUtils#parametersEqual}). Interface + * methods count, as do methods inherited through the superclass chain. + */ + private static boolean incompatibleSuperReturn(MethodNode methodNode, ClassNode widened) { + ClassNode type = methodNode.getDeclaringClass(); + for (ClassNode current = type.getSuperClass(); current != null; current = current.getSuperClass()) { + if (incompatibleDeclared(current, methodNode, widened)) { + return true; + } + } + for (ClassNode face : type.getAllInterfaces()) { + if (incompatibleDeclared(face, methodNode, widened)) { + return true; + } + } + return false; + } + + private static boolean incompatibleDeclared(ClassNode owner, MethodNode methodNode, ClassNode widened) { + for (MethodNode candidate : owner.getDeclaredMethods(methodNode.getName())) { + if (candidate.isPrivate() || candidate.isStatic() != methodNode.isStatic()) { + continue; + } + if (!ParameterUtils.parametersEqual(methodNode.getParameters(), candidate.getParameters())) { + continue; + } + ClassNode returned = candidate.getReturnType(); + if (returned == null || isDynamicTyped(returned) || ClassHelper.OBJECT_TYPE.equals(returned)) { + continue; + } + if (widened.equals(returned) || widened.isDerivedFrom(returned) || widened.implementsInterface(returned)) { + continue; + } + return true; + } + return false; + } + private MapExpression makeGinqConfigurationMapExpression(AnnotationNode annotationNode) { Map resultMembers = new HashMap<>(DEFAULT_OPTION_MAP); Map currentMembers = new HashMap<>(annotationNode.getMembers()); @@ -129,11 +196,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..93dfbde1353 100644 --- a/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc +++ b/subprojects/groovy-ginq/src/spec/doc/ginq-userguide.adoc @@ -121,6 +121,16 @@ include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_datasource_03, include::../test/org/apache/groovy/ginq/GinqTest.groovy[tags=ginq_datasource_01,indent=0] ---- +A Java `Stream` source is one-shot. The stream object itself cannot be read again the way +a list can. The query pulls that stream into a buffer, so a later `stream()` on the query +replays the buffer instead of restarting the source. `GQ` stays lazy: building the query +does not pull elements. `toList()` materializes the query. A user-supplied `List`, or a +live `Iterable` that is not a list, is read again while the query still uses that source. +After `toList()`, a later terminal on the composed `GQ` result reads the materialized +list, a copy of the query buffer, and does not run the query against the original source +again. `GQL`, and an `@GQ` method whose result type is a list, call `toList()` at the +expression, so they run then. + ==== Array Data Source [source, sql] ---- @@ -586,6 +596,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: @@ -674,6 +687,11 @@ over( * `0` used as bound of `rows` and `range` clause is equivalent to SQL's `CURRENT ROW`, and negative means `PRECEDING`, positive means `FOLLOWING` * `null` used as the lower bound of `rows` and `range` clause is equivalent to SQL's `UNBOUNDED PRECEDING` * `null` used as the upper bound of `rows` and `range` clause is equivalent to SQL's `UNBOUNDED FOLLOWING` +* When `orderby` is present and neither `rows` nor `range` is written, the frame is the whole partition. `sum` and `avg` are then partition totals, not a running total. SQL's default, which stops at the current row, is not used. +* `rowNumber` and `nthValue` count from `0`. The first row of a one-row partition is `0`. +* `percentRank` of a one-row partition is `1`. With more than one row it is `(rank - 1) / (total rows - 1)`. +* An all-null `sum` is `0`. An empty `avg` frame stays null. `avg` is not turned into `0`. +* `ntile(buckets)` is `buckets * rowNumber() / partitionSize`, using integer division. `ntile(0)` is bucket `0` for every row of a non-empty partition. Also, GINQ provides some built-in window functions: |=== @@ -697,7 +715,7 @@ Also, GINQ provides some built-in window functions: |percentRank() | |java.math.BigDecimal -|relative rank of the current row: (rank - 1) / (total rows - 1) +|relative rank of the current row. A one-row partition is `1`. Otherwise `(rank - 1) / (total rows - 1)`. Without `orderby` this is null |cumeDist() | @@ -707,7 +725,7 @@ Also, GINQ provides some built-in window functions: |ntile(_expression_) |java.lang.Long |java.lang.Long -|bucket index ranging from `0` to `expression - 1`, dividing the partition as equally as possible +|0-based bucket `expression * rowNumber() / partitionSize`. `ntile(0)` yields `0` on a non-empty partition |lead(_expression_ [, _offset_ [, _default_]]) |any [, java.lang.Long [, same as _expression_ type]] @@ -732,7 +750,7 @@ Also, GINQ provides some built-in window functions: |nthValue(_expression_, _n_) |any, java.lang.Long |same type as _expression_ -|returns _expression_ evaluated at the row that is the _nth_ row of the window frame +|returns _expression_ at row _n_ of the window frame. _n_ counts from `0`, so `0` is the first row |count() @@ -758,12 +776,12 @@ Also, GINQ provides some built-in window functions: |sum(_expression_) |java.lang.Number |java.math.BigDecimal -|sum of expression across all non-null values +|sum of _expression_. A null contributes nothing, and an all-null window is `0` |avg(_expression_) |java.lang.Number |java.math.BigDecimal -|the average (arithmetic mean) of all non-null values +|the average (arithmetic mean) of all non-null values. An empty frame stays null |median(_expression_) |java.lang.Number @@ -1166,8 +1184,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 +1195,346 @@ 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 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. + +Portable GINQ window functions translate in strict mode under `native-sql` and `jooq-sql`: +`fn(...) over(...)` becomes ANSI `OVER`. That covers `rowNumber`, `rank`, `denseRank`, +`percentRank`, `cumeDist`, `ntile`, `lead`, `lag`, `firstValue`, `lastValue` and `nthValue`, +and the window aggregates `count`, `sum`, `avg`, `min` and `max`. The window forms of +`median`, `stdev`, `stdevp`, `var`, `varp` and `agg` remain deferred and are not translated; +strict mode rejects them, and `mixedMode: true` still evaluates that clause in memory. +`rowNumber` and `nthValue` stay 0-based. SQL renders `ROW_NUMBER() OVER (...) - 1`, and the +`nthValue` index is shifted by one in the bound parameter so the first row remains `0`. +When `orderby` is present and no `rows` or `range` is written, the default frame is the +whole partition, not SQL's running frame. The translator inserts +`ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING`, so `sum` and `avg` equal the +partition aggregate. `percentRank` of a one-row partition is `1`; SQL `PERCENT_RANK` would +be `0`, and the translator rewrites that case. A window `sum` is +`COALESCE(SUM(...) OVER (...), 0)`, with `COALESCE` outside `OVER`. An all-null window +`sum` is `0`. `avg` is not coalesced, so an empty frame stays null. +`rows` offsets count rows in window order. `range` offsets are added to the current +order value in either sort direction, so `range -2, 0` runs from two below the current +value through the current value. A descending `orderby` keeps that value interval, and +the generated `RANGE` frame is rewritten so `PRECEDING` and `FOLLOWING` still point +along the sort. `rank`, `denseRank`, `percentRank`, `cumeDist` and `ntile` accept +several `orderby` keys. `rank` and its relatives need `orderby`: without it the +collection provider returns null, and strict SQL rejects the query. `rows` and `range` +on `rowNumber`, `rank`, `denseRank`, `percentRank`, `cumeDist`, `ntile`, `lead` and +`lag` are rejected, because SQL defines those functions without a frame. In memory, +`rank` and its relatives still honor a frame, and the others ignore it. `ntile` is +GINQ's 0-based formula, rendered with integer division, so it does not depend on +`FLOOR`. SQLite accepts a `RANGE` frame only when every bound is `UNBOUNDED` or +`CURRENT ROW`. MySQL and MariaDB cannot combine a numeric `RANGE` offset with GINQ's +null ordering, which those dialects emulate with a second sort key; use `rows`, or +`h2` or `postgres`. `COUNT(DISTINCT) OVER` is not available on SQLite. +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. A window `sum` is `COALESCE(SUM(...) OVER (...), 0)`, with `COALESCE` outside `OVER`. 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`. + +=== GINQ and LINQ + +GINQ stays SQL-shaped. The table is a map for readers who know language-integrated LINQ. +It does not add C# query syntax, and window functions have no `System.Linq` counterpart. + +[cols="2,2,3"] +|=== +|GINQ |Language-integrated LINQ |What stays different + +|`from` / `where` / `select` +|`from` / `where` / `select` +|GINQ writes `select` last, as SQL does. + +|`orderby x in desc` +|`orderby x descending` +|`in asc` is the default. `nullsfirst` and `nullslast` are part of the order key. + +|`groupby x into g` +|`group ... by ... into g` +|GINQ also keeps classic `groupby` and `having`. + +|`join ... on ` +|`join ... on ... equals ...` +|A GINQ `on` clause is any predicate. An equality joined with `&&` can use a hash join. + +|`leftjoin` / `rightjoin` / `fulljoin` +|no outer-join keywords in query syntax +|Outer joins are written in the GINQ query. C# query syntax has none of those keywords. `LeftJoin`, `RightJoin` and `FullJoin` are methods since .NET 10 / 11. + +|`union` / `intersect` / `minus` +|`Union` / `Intersect` / `Except` methods +|Set operations are clauses. On the collection provider a trailing `orderby` orders the last operand. SQL orders the combined result. + +|`limit offset, size` +|`Skip` / `Take` +|`limit n` keeps the first `n` rows. `limit offset, size` skips, then takes. + +|`rowNumber`, `rank`, `ntile`, `lead`, `sum(...) over(...)` +|no language-integrated window +|`rowNumber` and `nthValue` count from `0`. The default frame is the whole partition. + +|`GQ` +|a deferred `IEnumerable` query +|`GQ` returns a lazy `Queryable`. A terminal pulls the elements. + +|`GQL`, or `@GQ` returning a list +|`ToList` +|Those forms call `toList()` at the expression. + +|`native-sql` / `jooq-sql` +|`IQueryable` +|Translation is compile-time and fails closed. GINQ does not hand the provider an expression tree to rewrite later. + +|`mixedMode: true` +|`AsEnumerable` +|Opt-in, and never the default. A dialect limit is still a render-time error. It is not moved into memory. +|=== + === Optimize GINQ GINQ optimizer is enabled by default for better performance. It will transform the GINQ AST to achieve better execution plan. @@ -1218,10 +1576,85 @@ so the order of clauses should be kept as the above structure. __ONLY ONE__ `from` clause is required per query. Multiple data sources are supported through `from` and the related joins. Set operations chain left-to-right, so `Q1 union Q2 minus Q3` is evaluated as `(Q1 union Q2) minus Q3`. -=== Known Limitations - -[WARNING] -Currently GINQ can not work well when STC is enabled. +=== CompileStatic + +`GQ`, `GQL`, and `@GQ` can be used from a `@CompileStatic` or `@TypeChecked` class. +Static compilation is the ordinary `@CompileStatic` transform, which runs at +instruction selection. GINQ does not add a compilation phase and does not type-check +the query with a checker of its own. + +The `GQ` macro lowers the SQL-like syntax at conversion, before either checker. +The lowered tree is a closure. Under `@CompileStatic` that closure stays on the +static writer. A call the checker selects is the call that runs, including a +target another transform already chose and a well-typed `Stream` pipeline +(`map`, `collect`, `reduce`, and a method reference that is a legal SAM). +An operator on a row that the static writer cannot prove, and a call the +checker cannot resolve, go through `ScriptBytecodeAdapter`. The enclosing method +is type-checked, and under `@CompileStatic` it is statically compiled. +`GinqRowChecks` is added to the enclosing annotation's extension list, which is how +a caller writes `row.powerOfN`, `row[0]`, and `it.toList()` on a result whose static +type is not a bean. `@TypeChecked` uses the same extension and does not static-compile; +clause calls stay dynamic there. No annotation, `@CompileDynamic`, and `TypeCheckingMode.SKIP` leave the lowered query +on the fully dynamic path. + +The query expression's static type is `Queryable` (`List` for `GQL`). A `@GQ` method +whose return type is `def` is widened to the annotation's result type when that does +not conflict with a superclass method. + +Under `@CompileStatic` or `@TypeChecked` the lowered closure is created when the `GQ` +expression is evaluated, so it captures locals then, and it is called the first time +the `Queryable` is read (`toList`, `count`, and the other terminals). The source is +not opened until that read. A local the query only reads keeps the value from the +expression, because that is when the closure is built. A local the query writes is +shared with the caller through ordinary closure capture. Fields are read when the +closure runs. A field and a local, or a closure parameter, of the same name are +different declarations: the one in scope is the one the query uses. `GQL` and `@GQ(List)` call `toList` immediately, so they still +materialize at the expression. Under dynamic compilation the pipeline is built when +the expression is evaluated; `where` and `select` do not pull elements until a +terminal, which is the existing behaviour. + +=== Fluent queries + +`Ginq.from` is the method-call syntax. It runs on the same in-memory runtime as `GQ` +and is deferred until a terminal operation such as `toList()`. Operators are generic, +so `@CompileStatic` and `@TypeChecked` know the element type. Closure parameters are +inferred from that type: `{ p -> p.name }` is enough, and the same inference applies +to `where`, `select`, `selectMany`, ordering, `groupBy`, joins, and the aggregates. +Database providers still use the `GQ` +syntax, which keeps an expression tree they can translate. A custom reduction is a +lambda passed to `aggregate`. A named aggregate used from `GQ` implements +`org.apache.groovy.ginq.provider.GinqAggregate` and is listed in +`META-INF/services/org.apache.groovy.ginq.provider.GinqAggregate`. + +[source, groovy] +---- +include::../../test/groovy/org/apache/groovy/ginq/GinqFluentTest.groovy[tags=ginq_fluent_01,indent=0] +---- + +=== Known limitations + +A closure written at a fluent call infers its parameter types. A closure stored +in a `Predicate`, `Function`, `BiPredicate`, or `BiFunction` infers them from +that target type, and the variable can then be passed to the query. An untyped +`Closure` or `def` closure has no parameter target type when it is created, so +the parameter stays `Object`. The type has to be known where the closure is +written. A later call cannot reach back into it. Java and C# type a lambda the +same way. + +A local `def` or raw `Query` keeps the element type of the expression assigned +to it, including a later assignment. A `Query` parameter or field has no element +type unless it is declared as `Query` (or whatever the element is). +Inventing one would accept a property that belongs to a different element type. + +Under `@CompileStatic` the lowered query is type-checked. A name bound by +`from` has the source element type when the source has one. A property the +checker cannot resolve, such as `from r in rows where r.a` when `rows` is a +list of maps, stays a dynamic read. A well-typed `Stream` pipeline inside a +clause is a static `Stream` call, including a method reference that is a +legal SAM. An operator or call the checker cannot prove still goes through +`ScriptBytecodeAdapter`. Use `Ginq.from` when the fluent API should check the +element type. `orderBy` keys are compared with their natural order when the +fluent query runs. == GINQ Examples 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..2e4bb6db737 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 @@ -36,7 +36,6 @@ import org.codehaus.groovy.syntax.Types import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.Test -import static groovy.test.GroovyAssert.assertScript import static groovy.test.GroovyAssert.isAtLeastJdk import static org.junit.jupiter.api.Assumptions.assumeTrue @@ -2924,7 +2923,7 @@ class GinqTest { // tag::ginq_grouping_03[] from n in [1, 1, 3, 3, 6, 6, 6] groupby n - select n, agg(_g.stream().map(r -> r.n).reduce(BigDecimal.ZERO, BigDecimal::add)) + select n, agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) // end::ginq_grouping_03[] }.toList() ''' @@ -3624,7 +3623,10 @@ class GinqTest { @Test void "testGinq - complex example transformed"() { - assertScript ''' + // The maps mix strings and ints. Static checking resolves s.amount to + // that shared type and rejects comparing it with an int, and the group + // key is erased to Object. Dynamic execution is unchanged. + String script = ''' import static org.apache.groovy.ginq.provider.collection.runtime.Queryable.from import org.apache.groovy.ginq.provider.collection.runtime.Queryable.Order @@ -3648,6 +3650,9 @@ class GinqTest { assert result[0].toList() == ['Alice', 2, 1280] assert result[1].toList() == ['Bob', 2, 1950] ''' + GinqScriptModes.expectUnchecked(script) + GinqScriptModes.expectCheckedRejection(script, + 'compareTo', 'No such property: key', 'lambda expecting java.lang.Number') } @Test @@ -3768,6 +3773,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 +3922,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 ''' @@ -4014,6 +4055,33 @@ class GinqTest { ''' } + @Test + void "testGinq - stream source is consumed once"() { + assertGinqScript ''' + import static groovy.test.GroovyAssert.shouldFail + + def source = [1, 2, 3].stream() + def query = GQ { from n in source select n } + assert [1, 2, 3] == query.stream().toList() + // the query replays its buffer; the original stream does not restart + assert [1, 2, 3] == query.stream().toList() + def sourceAgain = shouldFail(IllegalStateException) { source.toList() } + assert sourceAgain.message.contains('stream has already been operated upon') + + def held = [4, 5].stream() + def materialized = GQ { from n in held select n } + assert [4, 5] == materialized.toList() + assert [4, 5] == materialized.toList() + shouldFail(IllegalStateException) { held.toList() } + + def reusable = GQ { from n in [1, 2, 3] select n } + assert [1, 2, 3] == reusable.toList() + assert [1, 2, 3] == reusable.toList() + assert [1, 2, 3] == reusable.stream().toList() + assert [1, 2, 3] == reusable.stream().toList() + ''' + } + @Test void "testGinq - from stream - 1"() { assertGinqScript ''' @@ -4453,7 +4521,7 @@ class GinqTest { innerjoin m in [2, 3, 4] on m == n where n > 1 && m < 5 groupby n, m - select n, m, agg(_g.stream().map(r -> r.n + r.m + cnt++).reduce(BigDecimal.ZERO, BigDecimal::add)) + select n, m, agg(_g.stream().map(r -> BigDecimal.valueOf(r.n + r.m + cnt++)).reduce(BigDecimal.ZERO, BigDecimal::add)) } assert 0 == cnt def stream = result.stream() @@ -4473,7 +4541,7 @@ class GinqTest { where n > 1 && m < 5 groupby n, m orderby n in desc, m in asc - select n, m, agg(_g.stream().map(r -> r.n + r.m + cnt++).reduce(BigDecimal.ZERO, BigDecimal::add)) + select n, m, agg(_g.stream().map(r -> BigDecimal.valueOf(r.n + r.m + cnt++)).reduce(BigDecimal.ZERO, BigDecimal::add)) } assert 0 == cnt def stream = result.stream() @@ -4498,7 +4566,7 @@ class GinqTest { ).exists() groupby n, m orderby n in desc, m in asc - select n, m, agg(_g.stream().map(r -> r.n + r.m + cnt++).reduce(BigDecimal.ZERO, BigDecimal::add)) + select n, m, agg(_g.stream().map(r -> BigDecimal.valueOf(r.n + r.m + cnt++)).reduce(BigDecimal.ZERO, BigDecimal::add)) } assert 0 == cnt def stream = result.stream() @@ -4524,7 +4592,7 @@ class GinqTest { groupby n, m orderby n in desc, m in asc limit 0, 1 - select n, m, agg(_g.stream().map(r -> r.n + r.m + cnt++).reduce(BigDecimal.ZERO, BigDecimal::add)) + select n, m, agg(_g.stream().map(r -> BigDecimal.valueOf(r.n + r.m + cnt++)).reduce(BigDecimal.ZERO, BigDecimal::add)) } assert 0 == cnt def stream = result.stream() @@ -4621,7 +4689,7 @@ class GinqTest { assert [[1, 3, 2, 2, 6, 3, 3, 6]] == GQ { from n in [1, 2, 3] select min(n), max(n), avg(n), median(n), sum(n), count(n), count(), - agg(_g.stream().map(r -> r.n).reduce(BigDecimal.ZERO, BigDecimal::add)) + agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) }.toList() // end::ginq_aggfunction_01[] ''' @@ -4694,7 +4762,7 @@ class GinqTest { assertGinqScript ''' assert [6] == GQ { from n in [1, 2, 3] - select agg(_g.stream().map(r -> r.n).reduce(BigDecimal.ZERO, BigDecimal::add)) + select agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) }.toList() ''' } @@ -6779,7 +6847,7 @@ class GinqTest { assert [[1, 3], [2, 3]] == GQ { from n in [1, 2] select n, - (agg(_g.stream().map(r -> r.n).reduce(BigDecimal.ZERO, BigDecimal::add)) over()) + (agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) over()) }.toList() ''' } @@ -6791,7 +6859,7 @@ class GinqTest { assert [[1, 4], [2, 2], [3, 4]] == GQ { from n in [1, 2, 3] select n, - (agg(_g.stream().map(r -> r.n).reduce(BigDecimal.ZERO, BigDecimal::add)) over(partitionby n % 2)) + (agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) over(partitionby n % 2)) }.toList() // end::ginq_winfunction_42[] ''' @@ -6804,7 +6872,98 @@ class GinqTest { from n in [1, 2, 3] join m in [1, 2, 3] on m == n select n, - (agg(_g.stream().map(r -> r.n).reduce(BigDecimal.ZERO, BigDecimal::add)) over(partitionby n % 2)) + (agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) over(partitionby n % 2)) + }.toList() + ''' + } + + @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() ''' } @@ -7321,7 +7480,7 @@ class GinqTest { shutdown } // end::ginq_tips_09[] - assert QueryableHelper.ThreadPoolHolder.THREAD_POOL.isShutdown() && QueryableHelper.ThreadPoolHolder.THREAD_POOL.isTerminated() + assert QueryableHelper.isShutdown() && QueryableHelper.isTerminated() ''' } @@ -7334,7 +7493,7 @@ class GinqTest { shutdown immediate } // end::ginq_tips_10[] - assert QueryableHelper.ThreadPoolHolder.THREAD_POOL.isShutdown() && QueryableHelper.ThreadPoolHolder.THREAD_POOL.isTerminated() + assert QueryableHelper.isShutdown() && QueryableHelper.isTerminated() ''' } @@ -7347,7 +7506,7 @@ class GinqTest { shutdown abort } // end::ginq_tips_11[] - assert QueryableHelper.ThreadPoolHolder.THREAD_POOL.isShutdown() + assert QueryableHelper.isShutdown() ''' } @@ -7388,4 +7547,13 @@ class GinqTest { assertScript(c) } } + + /** + * Every script in this class, including the optimize and smart-join + * variants, runs under default dynamic, {@code @CompileDynamic}, + * {@code @TypeChecked} and {@code @CompileStatic}. + */ + private static void assertScript(String script) { + GinqScriptModes.runAll(script) + } } diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/ChooseChecks.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/ChooseChecks.groovy new file mode 100644 index 00000000000..3ba8f6936e0 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/ChooseChecks.groovy @@ -0,0 +1,53 @@ +/* + * 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 + +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.MethodNode +import org.codehaus.groovy.ast.expr.Expression +import org.codehaus.groovy.transform.stc.AbstractTypeCheckingExtension +import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor +import org.codehaus.groovy.transform.stc.StaticTypesMarker + +/** + * Replaces {@code choose(String)} with {@code choose(CharSequence)} so a query + * clause can be checked against a target another extension already selected. + */ +class ChooseChecks extends AbstractTypeCheckingExtension { + + ChooseChecks(StaticTypeCheckingVisitor typeCheckingVisitor) { + super(typeCheckingVisitor) + } + + @Override + void onMethodSelection(Expression expression, MethodNode method) { + if (method.name != 'choose' || method.parameters.length != 1) { + return + } + if (method.parameters[0].type.name != ClassHelper.STRING_TYPE.name) { + return + } + MethodNode sequence = method.declaringClass.getDeclaredMethods('choose').find { MethodNode candidate -> + candidate.parameters.length == 1 && candidate.parameters[0].type.name == 'java.lang.CharSequence' + } + if (sequence != null) { + expression.putNodeMetaData(StaticTypesMarker.DIRECT_METHOD_CALL_TARGET, sequence) + } + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqCompileStaticTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqCompileStaticTest.groovy new file mode 100644 index 00000000000..c15c1c6dfe3 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqCompileStaticTest.groovy @@ -0,0 +1,237 @@ +/* + * 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 + +import groovy.ginq.transform.GQ +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.assertScript + +/** + * GINQ SQL-like queries compiled with {@code @CompileStatic}. + */ +@CompileStatic +final class GinqCompileStaticTest { + + private final int minimum = 18 + + @Test + void macroFiltersAndProjects() { + List numbers = [1, 2, 3, 4] + assert [4, 6, 8] == GQ { + from n in numbers + where n > 1 + select n * 2 + }.toList() + } + + @Test + void macroAsList() { + assert [2, 3] == GQL { + from n in [1, 2, 3] + where n > 1 + select n + } + } + + @Test + void readsFieldsAndLocals() { + int extra = 1 + assert [18, 21] == GQ { + from n in [15, 18, 21] + where n >= minimum - extra + select n + }.toList() + } + + @Test + void localIsReadWhenTheQueryIsBuilt() { + int extra = 1 + Queryable query = GQ { + from n in [1, 2, 3, 4] + where n > extra + select n + } + extra = 3 + // Locals are copied when the expression is evaluated. The copy is what runs later. + assert [2, 3, 4] == query.toList() + } + + @Test + void joinsProjectsAndGroups() { + List items = [new Item(1, 'Orange'), new Item(2, 'Apple')] + List sales = [new Sale(1), new Sale(1), new Sale(2)] + assert ['Orange', 'Orange', 'Apple'] == GQ { + from s in sales + join i in items on i.id == s.item + select i.name + }.toList() + + assert [[0, 6.0], [1, 4.0]] == GQ { + from n in [1, 2, 3, 4] + groupby n % 2 as parity + orderby parity + select parity, sum(n) + }.toList() + } + + @Test + void windowRowNumber() { + assert [[1, 0], [2, 1], [3, 2]] == GQ { + from n in [1, 2, 3] + select n, (rowNumber() over(orderby n)) + }.toList() + } + + @Test + void nestedQueryAndMapRows() { + assert [3] == GQ { + from n in [1, 2, 3] + where n > (from m in [1, 2] select max(m)) + select n + }.toList() + + List> rows = [[a: 1, b: 10], [a: 3, b: 30]] + assert [30] == GQ { + from r in rows + where r.a > 1 + select r.b + }.toList() + } + + @Test + void queryInsideClosure() { + List numbers = [1, 2, 3] + List found = [] + numbers.each { Integer n -> + if (n == 1) { + found.addAll(GQ { + from m in numbers + where m >= n + select m + }.toList()) + } + } + assert [1, 2, 3] == found + } + + @Test + void orderByDescendingAndMembership() { + assert [3, 2, 1] == GQ { + from n in [1, 2, 3] + orderby n in desc + select n + }.toList() + + assert [1, 3] == GQ { + from n in [1, 2, 3] + where n in [1, 3] + select n + }.toList() + } + + @Test + void parallelClauseKeepsRowValues() { + assert [3, 2, 1] == GQ(parallel: true) { + from n in [1, 2, 3] + orderby n in desc + select n + }.toList() + } + + @Test + void staticMethodAndAnnotation() { + assert [1, 2, 3] == staticNumbers() + assert [2, 3] == above([1, 2, 3], 2).toList() + assert [3, 4] == listed(2) + } + + @Test + void compiledClassInAScript() { + assertScript ''' + import groovy.transform.CompileStatic + + @CompileStatic + class Shop { + List names(List items) { + GQ { + from item in items + where item.size() > 3 + select item.toUpperCase() + }.toList() + } + } + + assert ['PEAR'] == new Shop().names(['pear', 'fig']) + ''' + } + + @Test + void customAggregateFromTheDsl() { + assertScript ''' + def result = GQ { + from n in [1, 2, 3] + groupby n % 2 as k + select total(n) + }.toList() + assert result.toSet() == [4.0, 2.0].toSet() + ''' + } + + private static List staticNumbers() { + GQ { + from n in [1, 2, 3] + select n + }.toList() + } + + @GQ + private Queryable above(List values, int floor) { + from n in values + where n >= floor + select n + } + + @GQ(List) + private List listed(int floor) { + from n in [1, 2, 3, 4] + where n > floor + select n + } + + static final class Item { + final int id + final String name + + Item(int id, String name) { + this.id = id + this.name = name + } + } + + static final class Sale { + final int item + + Sale(int item) { + this.item = item + } + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqDeferredQueryTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqDeferredQueryTest.groovy new file mode 100644 index 00000000000..8a0552b72a6 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqDeferredQueryTest.groovy @@ -0,0 +1,245 @@ +/* + * 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 + +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.collection.runtime.LazyQueryable +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.codehaus.groovy.runtime.typehandling.GroovyCastException +import org.junit.jupiter.api.Test + +import java.lang.reflect.InvocationHandler +import java.lang.reflect.Proxy +import java.util.function.BiFunction +import java.util.function.BiPredicate +import java.util.function.Function + +/** + * Exercises the deferred query wrapper and the {@link Queryable} defaults + * that a static {@code for} loop and coercion call. + */ +@CompileStatic +class GinqDeferredQueryTest { + + private static Queryable numbers() { + (Queryable) GQ { + from n in [1, 2, 3] + select n + } + } + + @Test + void deferredOperationsMaterializeTheSameElements() { + BiPredicate same = (Integer a, Integer b) -> a == b + Function id = (Integer n) -> n + assert numbers().innerJoin(Queryable.from(List.of(2, 3)), same).toList().size() == 2 + assert numbers().innerHashJoin(Queryable.from(List.of(2, 3)), id, id).toList().size() == 2 + assert numbers().leftJoin(Queryable.from(List.of(2, 3)), same).toList().size() == 3 + assert numbers().leftHashJoin(Queryable.from(List.of(2, 3)), id, id).toList().size() == 3 + assert numbers().rightJoin(Queryable.from(List.of(2, 3)), same).toList().size() == 2 + assert numbers().rightHashJoin(Queryable.from(List.of(2, 3)), id, id).toList().size() == 2 + assert numbers().fullJoin(Queryable.from(List.of(2, 3)), same).toList().size() == 3 + assert numbers().fullHashJoin(Queryable.from(List.of(2, 3)), id, id).toList().size() == 3 + assert numbers().crossJoin(Queryable.from(List.of(2, 3))).toList().size() == 6 + + Function key = (Integer n) -> n + assert numbers().groupBy(key, (Object group) -> true).toList().size() == 3 + assert numbers().groupByInto(key, (Object group) -> true).toList().size() == 3 + assert numbers().orderBy(new Queryable.Order<>(id, true)).toList() == [1, 2, 3] + assert numbers().limit(1L, 1L).toList() == [2] + assert numbers().unionAll(Queryable.from(List.of(2, 3))).toList() == [1, 2, 3, 2, 3] + assert numbers().intersect(Queryable.from(List.of(2, 3))).toList() == [2, 3] + assert numbers().minus(Queryable.from(List.of(2, 3))).toList() == [1] + + Function value = (Integer n) -> n + assert numbers().count() == 3L + assert numbers().count(value) == 3L + assert numbers().sum(value) == 6 + assert numbers().avg(value) == 2 + assert numbers().min(value) == 1 + assert numbers().max(value) == 3 + assert numbers().list(value) == [1, 2, 3] + assert numbers().median(value) == 2 + Queryable reusable = LazyQueryable.defer { Queryable.from(List.of(1, 2, 3)) } + assert reusable.stdev(value) > 0 + assert reusable.stdevp(value) > 0 + assert reusable.var(value) > 0 + assert reusable.varp(value) > 0 + assert numbers().agg((Queryable rows) -> rows.count()) == 3L + assert numbers().size() == 3L + assert numbers().getAt(1) == 2 + Queryable once = numbers() + assert once.iterator().toList() == [1, 2, 3] + assert (once as List) == [1, 2, 3] + assert (numbers() as Set) == [1, 2, 3] as Set + assert (numbers() as Iterable).iterator().next() == 1 + assert (numbers() as Collection) == [1, 2, 3] + Queryable held = numbers() + assert held.asType(Queryable).is(held) + assert held.asType(LazyQueryable).is(held) + assert held.asType(String) == held.toString() + GroovyCastException incompatible = null + try { + numbers().asType(Incompatible) + } catch (GroovyCastException caught) { + incompatible = caught + } + assert incompatible != null + assert incompatible.message.contains('Incompatible') + + Queryable again = numbers() + assert once.equals(once) + assert once.equals(again) + assert !once.equals(List.of(1, 2, 3)) + assert once.hashCode() == again.hashCode() + assert once.toString() != null + + BiFunction, Integer> select = (Integer n, Queryable rows) -> n + assert numbers().select(select).toList() == [1, 2, 3] + } + + @Test + void nullSupplierIsRejectedAndDefaultsRun() { + NullPointerException missingBody = null + try { + LazyQueryable.defer((Closure) null) + } catch (NullPointerException caught) { + missingBody = caught + } + assert missingBody != null + + Queryable lazy = LazyQueryable.defer { null } + IllegalStateException error = null + try { + lazy.toList() + } catch (IllegalStateException caught) { + error = caught + } + assert error != null + assert error.message.contains('null') + + Queryable plain = (Queryable) Proxy.newProxyInstance( + Queryable.classLoader, + new Class[]{Queryable}, + (InvocationHandler) (proxy, method, args) -> { + if (method.name == 'toList') { + return List.of(4, 5) + } + if (method.name == 'toString' && method.parameterCount == 0) { + return 'plain' + } + if (method.default) { + return InvocationHandler.invokeDefault(proxy, method, args) + } + throw new UnsupportedOperationException(method.name) + }) + assert plain.iterator().toList() == [4, 5] + assert plain.getAt(0) == 4 + assert plain.asType(List) == [4, 5] + assert plain.asType(Collection) == [4, 5] + assert plain.asType(Iterable) == [4, 5] + assert plain.asType(Queryable).is(plain) + assert plain.asType(String) instanceof String + assert plain.asType(String) != plain + GroovyCastException rejected = null + try { + plain.asType(Incompatible) + } catch (GroovyCastException caught) { + rejected = caught + } + assert rejected != null + GroovyCastException missingType = null + try { + plain.asType(null) + } catch (GroovyCastException caught) { + missingType = caught + } + assert missingType != null + + Queryable wrapped = LazyQueryable.defer { plain } + assert wrapped.asType(String) instanceof String + assert wrapped.asType(Queryable).is(wrapped) + GroovyCastException wrappedReject = null + try { + wrapped.asType(Incompatible) + } catch (GroovyCastException caught) { + wrappedReject = caught + } + assert wrappedReject != null + GroovyCastException wrappedNull = null + try { + wrapped.asType(null) + } catch (GroovyCastException caught) { + wrappedNull = caught + } + assert wrappedNull != null + } + + @Test + void writtenLocalsAndExistingExtensions() { + assert BoxedInteger.ids() == [0] + assert AlreadyExtended.ids() == [1] + assert ExtraExtension.ids() == [1] + assert ListedExtension.ids() == [1] + } + + @CompileStatic + static class BoxedInteger { + static List ids() { + Integer cnt = 0 + (List) GQ { + from n in [1] + select cnt++ + }.toList() + } + } + + @CompileStatic(extensions = 'org.apache.groovy.ginq.GinqRowChecks') + static class AlreadyExtended { + static List ids() { + (List) GQ { + from n in [1] + select n + }.toList() + } + } + + @CompileStatic(extensions = 'org.codehaus.groovy.transform.stc.TraitTypeCheckingExtension') + static class ExtraExtension { + static List ids() { + (List) GQ { + from n in [1] + select n + }.toList() + } + } + + static final class Incompatible { + } + + @CompileStatic(extensions = ['org.codehaus.groovy.transform.stc.TraitTypeCheckingExtension']) + static class ListedExtension { + static List ids() { + (List) GQ { + from n in [1] + select n + }.toList() + } + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqEdgePathTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqEdgePathTest.groovy new file mode 100644 index 00000000000..6c246c06755 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqEdgePathTest.groovy @@ -0,0 +1,546 @@ +/* + * 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 + +import groovy.ginq.Ginq +import groovy.lang.Tuple +import org.apache.groovy.ginq.provider.GinqAggregate +import org.apache.groovy.ginq.provider.GinqAggregates +import org.apache.groovy.ginq.provider.collection.runtime.LazyQueryable +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.apache.groovy.ginq.provider.collection.runtime.WindowDefinition +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.junit.jupiter.api.Test + +import java.lang.reflect.InvocationHandler +import java.lang.reflect.Proxy +import java.nio.file.Files +import java.util.function.Function + +import static groovy.ginq.Ginq.from + +/** + * Product paths that the main GINQ suite does not happen to call: + * fluent defaults, aggregate construction failures, windows, and queries + * compiled in fields, constructors, and checked methods. + *

+ * Some changed branches stay uncovered because nothing the compiler + * produces can enter them: + *

    + *
  • {@code GinqQuery.from(Iterable)} treating its argument as a + * {@code GinqQuery}, and the same test in {@code queryableOf}. + * {@code GinqQuery} implements {@code Query}, not {@code Iterable}.
  • + *
  • {@code queryableOf(Query)} for a query that is not a {@code GinqQuery}. + * That is the only {@code Query} implementation.
  • + *
  • The non-tuple arm of the aggregate argument count. + * {@code MethodCallExpression} always wraps arguments in a {@code TupleExpression}.
  • + *
  • {@code customAggregate} with a null source unit. The macro always + * passes the live {@code SourceUnit}.
  • + *
+ */ +class GinqEdgePathTest { + + @Test + void fluentDefaultsAndEmptySources() { + assert Ginq.of().toList().isEmpty() + assert Ginq.of(null).toList().isEmpty() + assert from([1, 2, 3]).any() + assert !from([]).any() + assert from([1, 2, 3]).except([2]).toList() == [1, 3] + assert from([1, 2, 3]).except(from([2])).toList() == [1, 3] + assert from([1, 2]).concat([3]).toList() == [1, 2, 3] + + assert from([1, 2]).selectMany { n -> null }.toList().isEmpty() + assert from([1]).selectMany({ n -> null }, { a, b -> a }).toList().isEmpty() + + def right = from([1, 2, 3]).rightJoin([2, 3], { a, b -> a == b }, { a, b -> a }).toList() + assert right.contains(2) + def full = from([1, 2]).fullJoin([2, 4], { a, b -> a == b }, { a, b -> a == null ? b : a }).toList() + assert full.contains(1) + assert full.contains(4) + + Queryable alsoQueryable = Queryable.from([2, 3]) + Iterable both = (Iterable) Proxy.newProxyInstance( + Queryable.classLoader, + new Class[]{Iterable, Queryable}, + (InvocationHandler) (proxy, method, args) -> { + if (method.name == 'iterator' && method.parameterCount == 0) { + return alsoQueryable.toList().iterator() + } + return method.invoke(alsoQueryable, args) + }) + assert from([1, 2, 3]).rightJoin(both, { a, b -> a == b }, { a, b -> a }).toList().contains(2) + + assert from([1, 2]).union(from([2, 4])).toList() == [1, 2, 4] + assert from([1]).union([2]).toList() == [1, 2] + assert from([1, 2, 2]).intersect(from([2, 9])).toList() == [2] + assert from([1, 2, 2]).intersect([2, 9]).toList() == [2] + def calls = 0 + def ordered = from([[k: 1, v: 1], [k: 1, v: 3], [k: 1, v: 2]]) + .orderBy { it.k } + .thenByDescending { row -> calls++; row.v } + .toList() + assert ordered*.v == [3, 2, 1] + assert calls > 0 + assert from([1, 2, 3]).stream().count() == 3 + assert from([1, 2]).iterator().toList() == [1, 2] + assert from([1, 2, 3]).all { it > 0 } + assert !from([1, -1]).all { it > 0 } + } + + @Test + void aggregateArgumentShapes() { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + assert GQ { + from n in [1, 1, 2] + groupby n + select count() + }.toList().sum() == 3 + + assert GQ { + from n in [1, 1, 2] + groupby n + select count(n) + }.toList().sum() == 3 + + assert GQ { + from n in [1, 2, 3] + groupby n % 2 + select total() + }.toList()*.toString().toSet() == ['2', '4'] as Set + + assert GQ { + from n in [1, 2, 3] + groupby n % 2 + select total(n) + }.toList().toSet() == [new BigDecimal('2'), new BigDecimal('4')].toSet() + ''') + + def zeroSum = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + GQ { + from n in [1, 2, 3] + groupby n % 2 + select sum() + }.toList() + ''') + } catch (AssertionError caught) { + zeroSum = caught + } + assert zeroSum != null + + def twoCount = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + GQ { + from n in [1, 2, 3] + groupby n % 2 + select count(n, n) + }.toList() + ''') + } catch (AssertionError caught) { + twoCount = caught + } + assert twoCount != null + + def unknown = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + GQ { + from n in [1, 2] + groupby n + select notAnAggregate(n) + }.toList() + ''') + } catch (AssertionError caught) { + unknown = caught + } + assert unknown != null + + def unknownNone = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + GQ { + from n in [1, 2] + groupby n + select notAnAggregate() + }.toList() + ''') + } catch (AssertionError caught) { + unknownNone = caught + } + assert unknownNone != null + + def unknownTwo = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + GQ { + from n in [1, 2] + groupby n + select notAnAggregate(n, n) + }.toList() + ''') + } catch (AssertionError caught) { + unknownTwo = caught + } + assert unknownTwo != null + } + + @Test + void aggregateLookupAndConstruction() { + assert GinqAggregates.find(null, null) == null + assert GinqAggregates.find('', GinqAggregates.class.classLoader) == null + assert GinqAggregates.find('missing', null) == null + assert GinqAggregates.find('total', null) == TotalAggregate + + Queryable group = Queryable.from([1, 2, 3]) + assert GinqAggregates.apply(TotalAggregate, group, null) == 6 + assert GinqAggregates.apply(TotalAggregate, group, { n -> n }) == 6 + Function selector = (Object n) -> n + assert GinqAggregates.apply(TotalAggregate, group, selector) == 6 + + IllegalArgumentException badSelector = null + try { + GinqAggregates.apply(TotalAggregate, group, 'nope') + } catch (IllegalArgumentException caught) { + badSelector = caught + } + assert badSelector != null + assert badSelector.message.contains('closure or a function') + + IllegalStateException hidden = null + try { + GinqAggregates.apply(HiddenAggregate, group, null) + } catch (IllegalStateException caught) { + hidden = caught + } + assert hidden != null + assert hidden.message.contains(HiddenAggregate.name) + + IllegalStateException boom = null + try { + GinqAggregates.apply(BoomAggregate, group, null) + } catch (IllegalStateException caught) { + boom = caught + } + assert boom != null + + File root = Files.createTempDirectory('ginq-agg').toFile() + try { + File services = new File(root, 'META-INF/services') + assert services.mkdirs() + new File(services, 'org.apache.groovy.ginq.provider.GinqAggregate').text = 'missing.Aggregate\n' + URLClassLoader loader = new URLClassLoader([root.toURI().toURL()] as URL[], GinqEdgePathTest.class.classLoader) + assert GinqAggregates.find('total', loader) == TotalAggregate + } finally { + root.deleteDir() + } + } + + @Test + void deferredWindowDelegates() { + Queryable query = LazyQueryable.defer { Queryable.from([1, 2, 3]) } + def window = WindowDefinition.of().setId(Tuple.tuple('p', 'o', 'w')) + assert query.over(Tuple.tuple(1, 0L), window) != null + } + + @Test + void bridgeGuardsAndCheckedHosts() { + ConstantExpression query = new ConstantExpression(1) + assert GinqStaticBridge.embed(null, null, query).is(query) + assert GinqStaticBridge.prepare(null, null, query, true).is(query) + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + class Probe { + @CompileStatic + static List run() { + return GQ { from n in [1, 2] select n }.toList() + } + } + assert Probe.run() == [1, 2] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Holder { + List values = GQ { from n in [1, 2] select n }.toList() + } + assert new Holder().values == [1, 2] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Built { + List values + Built() { + values = GQ { from n in [3] select n }.toList() + } + } + assert new Built().values == [3] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Caught { + static List run() { + try { + throw new IllegalStateException('x') + } catch (IllegalStateException e) { + return GQ { from n in [e.message] select n }.toList() + } + } + } + assert Caught.run() == ['x'] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Multi { + static List run() { + def (a, b) = [1, 2] + return GQ { from n in [a, b] select n }.toList() + } + } + assert Multi.run() == [1, 2] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Box { + static List run() { + Integer cnt = 0 + return GQ { from n in [1, 2] select cnt++ }.toList() + } + } + assert Box.run() == [0, 1] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic(extensions = 'org.codehaus.groovy.transform.stc.TraitTypeCheckingExtension') + class Extra { + static List run() { + return GQ { from n in [1] select n }.toList() + } + } + assert Extra.run() == [1] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic(extensions = ['org.codehaus.groovy.transform.stc.TraitTypeCheckingExtension']) + class Listed { + static List run() { + return GQ { from n in [1] select n }.toList() + } + } + assert Listed.run() == [1] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic(extensions = ['org.codehaus.groovy.transform.stc.TraitTypeCheckingExtension', 'org.apache.groovy.ginq.GinqRowChecks']) + class Already { + static List run() { + return GQ { from n in [1] select n }.toList() + } + } + assert Already.run() == [1] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Outer { + static class Inner { + static List run() { + return GQ { from n in [7] select n }.toList() + } + } + } + assert Outer.Inner.run() == [7] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + class Base { + String ginq(list, extra) { 'no' } + Object ginq(list) { null } + } + class Child extends Base { + @groovy.ginq.transform.GQ + def ginq(list) { + from n in list + select n + } + @groovy.ginq.transform.GQ + @groovy.transform.CompileDynamic + def tagged(list) { + from n in list + select n + } + @groovy.ginq.transform.GQ + @groovy.transform.CompileStatic(groovy.transform.TypeCheckingMode.SKIP) + def skipped(list) { + from n in list + select n + } + } + def child = new Child() + assert child.ginq([1, 2]).toList() == [1, 2] + assert child.tagged([4]).toList() == [4] + assert child.skipped([5]).toList() == [5] + ''') + + AssertionError incompatible = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.DYNAMIC, ''' + class Base { + String ginq(list) { 'no' } + } + class Child extends Base { + @groovy.ginq.transform.GQ + def ginq(list) { + from n in list + select n + } + } + ''') + } catch (AssertionError caught) { + incompatible = caught + } + assert incompatible != null + assert incompatible.message.contains('incompatible with java.lang.String') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Indexed { + static List run() { + def found = [] + for (i, n in [9]) { + found << GQ { from x in [n, i] select x }.toList()[0] + } + return found + } + } + assert Indexed.run() == [9] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Named { + static void ginqQuery$0() { } + static List run() { + return GQ { from n in [1] select n }.toList() + } + } + assert Named.run() == [1] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Init { + List values + { + values = GQ { from n in [8] select n }.toList() + } + } + assert new Init().values == [8] + ''') + + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + abstract class Checked { + abstract void unused() + static List run() { + return GQ { from n in [1] select n }.toList() + } + } + assert Checked.run() == [1] + ''') + + AssertionError rejected = null + try { + GinqScriptModes.runOne(GinqScriptModes.Kind.COMPILE_STATIC, ''' + import groovy.transform.CompileStatic + @CompileStatic + class Checked { + static List run() { + return GQ { from n in [1] select n }.toList() + } + static Object badProperty() { + return 'ab'.notAProperty + } + static Object badCall() { + Object value = new Object() + return value.missingMethod() + } + } + Checked.badProperty() + Checked.badCall() + ''') + } catch (AssertionError caught) { + rejected = caught + } + assert rejected != null + assert rejected.message.contains('notAProperty') + assert rejected.message.contains('missingMethod') + } + + static class HiddenAggregate implements GinqAggregate { + private HiddenAggregate() { + } + + @Override + String name() { + return 'hidden' + } + + @Override + Object apply(Queryable group, Function selector) { + return null + } + } + + static class BoomAggregate implements GinqAggregate { + BoomAggregate() { + throw new IllegalStateException('boom') + } + + @Override + String name() { + return 'boom' + } + + @Override + Object apply(Queryable group, Function selector) { + return null + } + } +} 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..fe28cad1ebf 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 @@ -240,7 +240,7 @@ final class GinqErrorTest { assert [[1, 2], [3, 6], [6, 18]] == GQ { from n in [1, 1, 3, 3, 6, 6, 6] groupby n - select n, agg(_g.stream().map(r -> r.x).reduce(BigDecimal.ZERO, BigDecimal::add)) + select n, agg(_g.stream().map(r -> BigDecimal.valueOf(r.x)).reduce(BigDecimal.ZERO, BigDecimal::add)) }.toList() ''' @@ -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/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentDynamicTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentDynamicTest.groovy new file mode 100644 index 00000000000..78b5506174e --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentDynamicTest.groovy @@ -0,0 +1,85 @@ +/* + * 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 + +import groovy.ginq.Ginq +import groovy.ginq.Query +import groovy.lang.Closure +import org.junit.jupiter.api.Test + +import java.util.function.BiPredicate + +import static org.apache.groovy.ginq.GinqFluentTest.Order +import static org.apache.groovy.ginq.GinqFluentTest.Person + +/** + * Dynamic (non-{@code @CompileStatic}) coverage of the {@link Query} Closure + * join defaults. {@link GinqFluentTest} is compiled statically and binds the + * same calls to the {@link BiPredicate} overloads. + */ +final class GinqFluentDynamicTest { + + @Test + void queryToQueryPredicateJoinsUseTheClosureDefaults() { + Query people = Ginq.from([ + new Person(1, 'Ann', 20), + new Person(2, 'Bob', 15) + ]) + Query orders = Ginq.from([new Order(1, 5), new Order(1, 7), new Order(3, 4)]) + + Closure on = { Person p, Order o -> + assertCalledViaQueryDefault('truth') + return p.id == o.personId + } + Closure leftSelect = { Person p, Order o -> + assertCalledViaQueryDefault('invoke') + return o == null ? 'none' : o.amount.toString() + } + Closure rightSelect = { Person p, Order o -> + assertCalledViaQueryDefault('invoke') + return p == null ? 'none' : o.amount.toString() + } + Closure fullSelect = { Person p, Order o -> + assertCalledViaQueryDefault('invoke') + return p == null ? 'none' : (o == null ? p.name : o.amount.toString()) + } + + List left = people.leftJoin(orders, on, leftSelect).toList() + assert left.toSet() == ['5', '7', 'none'] as Set + + List right = people.rightJoin(orders, on, rightSelect).toList() + assert right.toSet() == ['5', '7', 'none'] as Set + + List full = people.fullJoin(orders, on, fullSelect).toList() + assert full.toSet() == ['5', '7', 'none', 'Bob'] as Set + } + + /** + * The Closure defaults wrap the caller closures with {@code Query.truth} + * and {@code Query.invoke}. A direct dispatch to the {@code BiPredicate} + * overload would call the closures without those helpers. + */ + private static void assertCalledViaQueryDefault(String helper) { + boolean seen = Arrays.stream(new Throwable().stackTrace) + .anyMatch { StackTraceElement frame -> + frame.className == Query.name && frame.methodName == helper + } + assert seen: "expected Query.${helper} on the stack (Closure default path)" + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentInferenceTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentInferenceTest.groovy new file mode 100644 index 00000000000..86102aa1f52 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentInferenceTest.groovy @@ -0,0 +1,360 @@ +/* + * 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 + +import groovy.ginq.Ginq +import groovy.ginq.Query +import groovy.transform.CompileStatic +import groovy.transform.TypeChecked +import org.codehaus.groovy.control.MultipleCompilationErrorsException +import org.junit.jupiter.api.Test + +import java.util.function.BiFunction +import java.util.function.BiPredicate +import java.util.function.Function +import java.util.function.Predicate + +import static org.apache.groovy.ginq.GinqFluentInferenceTest.Order +import static org.apache.groovy.ginq.GinqFluentInferenceTest.Person + +import static groovy.test.GroovyAssert.assertScript +import static groovy.test.GroovyAssert.shouldFail + +/** + * Closure parameters of the fluent operators are inferred from the query element + * type. Callers do not write those parameter types. + */ +final class GinqFluentInferenceTest { + + @Test + void untypedClosuresUnderCompileStatic() { + assert new CompileStaticQueries().labels() == ['9', 'none'] + new CompileStaticQueries().operators() + } + + @Test + void untypedClosuresUnderTypeChecked() { + assert new TypeCheckedQueries().labels() == ['9', 'none'] + assert new TypeCheckedQueries().projected() == ['Ann', 'Cyd'] + } + + @Test + void untypedClosuresUnderDynamicCompilation() { + assert new DynamicQueries().labels() == ['9', 'none'] + assert new DynamicQueries().projected() == ['Ann', 'Cyd'] + } + + @Test + void samVariableAndDefQueryInferParameters() { + assert new CompileStaticQueries().storedSam() == ['Ann', 'Ann:9'] + assert new CompileStaticQueries().defQuery() == ['Ann'] + assert new CompileStaticQueries().rawQuery() == ['Ann'] + assert new CompileStaticQueries().reassignedQuery() == ['9'] + assert new TypeCheckedQueries().storedSam() == ['Ann', 'Ann:9'] + } + + @Test + void untypedClosureVariableIsCheckedWhereItIsWritten() { + def message = shouldFail(MultipleCompilationErrorsException) { + assertScript ''' + import groovy.ginq.Ginq + import groovy.transform.CompileStatic + import org.apache.groovy.ginq.GinqFluentInferenceTest.Person + + @CompileStatic + class Probe { + static Object run() { + List people = [new Person(1, 'Ann', 20, [])] + Closure adults = { p -> p.age >= 18 } + Ginq.from(people).where(adults) + } + } + ''' + }.message + assert message.contains('No such property: age for class: java.lang.Object') + } + + @Test + void rawQueryParameterHasNoElementType() { + def message = shouldFail(MultipleCompilationErrorsException) { + assertScript ''' + import groovy.ginq.Ginq + import groovy.ginq.Query + import groovy.transform.CompileStatic + + @CompileStatic + class Probe { + static Object run(Query query) { + query.where { p -> p.age >= 18 } + } + } + ''' + }.message + assert message.contains('No such property: age for class: java.lang.Object') + } + + @Test + void gqNestedClosureStaysDynamic() { + assert new CompileStaticQueries().nestedClosureInsideGq() == ['Ann'] + } + + @Test + void typeCheckedGqStillBindsRangeVariables() { + assertScript ''' + import groovy.ginq.transform.GQ + import groovy.transform.TypeChecked + import org.apache.groovy.ginq.GinqFluentInferenceTest.Person + import org.apache.groovy.ginq.provider.collection.runtime.Queryable + + @TypeChecked + class Probe { + static List run() { + List people = [new Person(1, 'Ann', 20, [])] + GQ { + from p in people + where p.age >= 18 + select p.name + }.toList() + } + + @GQ + Queryable adults(List people) { + from p in people + where p.age >= 18 + select p.name + } + } + assert Probe.run() == ['Ann'] + assert new Probe().adults([new Person(1, 'Ann', 20, []), new Person(2, 'Bob', 15, [])]).toList() == ['Ann'] + ''' + } + + static final class Person { + final int id + final String name + final int age + final List orders + + Person(int id, String name, int age, List orders) { + this.id = id + this.name = name + this.age = age + this.orders = orders + } + } + + static final class Order { + final int personId + final int amount + + Order(int personId, int amount) { + this.personId = personId + this.amount = amount + } + } +} + +@CompileStatic +final class CompileStaticQueries { + + List labels() { + List labels = Ginq.of(1, 2).leftJoin([new Order(1, 9)]) { id -> id } { o -> o.personId } { id, o -> + o == null ? 'none' : o.amount.toString() + }.toList() + return labels + } + + void operators() { + List people = [ + new Person(1, 'Ann', 20, [new Order(1, 9), new Order(1, 8)]), + new Person(2, 'Bob', 15, []), + new Person(3, 'Cyd', 30, [new Order(3, 4)]) + ] + List orders = [new Order(1, 9), new Order(3, 4), new Order(9, 1)] + + List names = Ginq.from(people) + .where { p -> p.age >= 18 } + .orderByDescending { p -> p.age } + .thenByDescending { p -> p.name } + .select { p -> p.name } + .where { name -> name.length() > 0 } + .toList() + assert names == ['Cyd', 'Ann'] + + Person[] array = new Person[] { people[0], people[1], people[2] } + assert Ginq.from(array).any { p -> p.age < 18 } + assert Ginq.from(people.stream()).all { p -> p.name != null } + Query continued = Ginq.from(Ginq.from(people)) + assert continued.count { p -> p.name } == 3L + assert continued.sum { p -> p.age } == 65 + assert continued.avg { p -> p.age } > 21 + assert continued.min { p -> p.name } == 'Ann' + assert continued.max { p -> p.age } == 30 + assert continued.median { p -> p.age } == 20 + assert continued.aggregate(0) { acc, p -> acc + p.age } == 65 + assert continued.aggregate { rows -> rows.where { p -> p.age >= 18 }.count() } == 2L + + List flat = Ginq.from(people) + .selectMany({ p -> p.orders }, { p, o -> p.name + ':' + o.amount }) + .toList() + assert flat == ['Ann:9', 'Ann:8', 'Cyd:4'] + + List keys = Ginq.from(people) + .groupBy({ p -> p.name }, { g -> g.key.length() == 3 && g.count() > 0L }) + .select { g -> g.key } + .toList() + assert keys.toSorted() == ['Ann', 'Bob', 'Cyd'] + + List equi = Ginq.from(people) + .rightJoin(orders) { p -> p.id } { o -> o.personId } { p, o -> + p == null ? 'none:' + o.amount : p.name + ':' + o.amount + }.toList() + assert equi.toSorted() == ['Ann:9', 'Cyd:4', 'none:1'] + + List full = Ginq.from(people) + .fullJoin(orders) { p -> p.id } { o -> o.personId } { p, o -> + (p == null ? 'none' : p.name) + ':' + (o == null ? 'none' : o.amount.toString()) + }.toList() + assert full.toSorted() == ['Ann:9', 'Bob:none', 'Cyd:4', 'none:1'] + + List cross = Ginq.from(people).crossJoin(orders) { p, o -> p.name + ':' + o.personId }.toList() + assert cross.size() == 9 + assert cross.contains('Bob:9') + + List predicated = Ginq.from(people) + .join(orders) { p, o -> p.id == o.personId } { p, o -> p.name + ':' + o.amount } + .toList() + assert predicated.toSorted() == ['Ann:9', 'Cyd:4'] + + List leftOn = Ginq.from(people) + .leftJoin(orders) { p, o -> p.id == o.personId } { p, o -> + o == null ? p.name + ':none' : p.name + ':' + o.amount + }.toList() + assert leftOn.toSorted() == ['Ann:9', 'Bob:none', 'Cyd:4'] + + List amounts = Ginq.from(people) + .selectMany { p -> p.orders } + .select { o -> o.amount } + .toList() + assert amounts == [9, 8, 4] + } + + List storedSam() { + List people = [ + new Person(1, 'Ann', 20, []), + new Person(2, 'Bob', 15, []) + ] + List orders = [new Order(1, 9)] + Predicate adults = { p -> p.age >= 18 } + Function names = { p -> p.name } + BiPredicate same = { p, o -> p.id == o.personId } + BiFunction label = { p, o -> p.name + ':' + o.amount } + List projected = Ginq.from(people).where(adults).select(names).toList() + List joined = Ginq.from(people).join(orders, same, label).toList() + return projected + joined + } + + List defQuery() { + List people = [ + new Person(1, 'Ann', 20, []), + new Person(2, 'Bob', 15, []) + ] + def query = Ginq.from(people) + return query.where { p -> p.age >= 18 }.select { p -> p.name }.toList() + } + + List rawQuery() { + List people = [new Person(1, 'Ann', 20, [])] + Query query = Ginq.from(people) + return query.where { p -> p.age >= 18 }.select { p -> p.name }.toList() + } + + List reassignedQuery() { + List people = [new Person(1, 'Ann', 20, [])] + List orders = [new Order(1, 9)] + Query query = Ginq.from(people) + query = Ginq.from(orders) + return query.select { o -> o.amount.toString() }.toList() + } + + List nestedClosureInsideGq() { + List people = [new Person(1, 'Ann', 20, [new Order(1, 9)]), new Person(2, 'Bob', 15, [])] + GQ { + from p in people + where p.orders.any { o -> o.amount > 0 } + select p.name + }.toList() + } +} + +@TypeChecked +final class TypeCheckedQueries { + + List labels() { + Ginq.of(1, 2).leftJoin([new Order(1, 9)]) { id -> id } { o -> o.personId } { id, o -> + o == null ? 'none' : o.amount.toString() + }.toList() + } + + List projected() { + List people = [ + new Person(1, 'Ann', 20, []), + new Person(2, 'Bob', 15, []), + new Person(3, 'Cyd', 30, []) + ] + Ginq.from(people) + .where { p -> p.age >= 18 } + .orderBy { p -> p.name } + .select { p -> p.name } + .toList() + } + + List storedSam() { + List people = [new Person(1, 'Ann', 20, []), new Person(2, 'Bob', 15, [])] + List orders = [new Order(1, 9)] + Predicate adults = { p -> p.age >= 18 } + Function names = { p -> p.name } + BiPredicate same = { p, o -> p.id == o.personId } + BiFunction label = { p, o -> p.name + ':' + o.amount } + Ginq.from(people).where(adults).select(names).toList() + + Ginq.from(people).join(orders, same, label).toList() + } +} + +final class DynamicQueries { + + List labels() { + Ginq.of(1, 2).leftJoin([new Order(1, 9)]) { id -> id } { o -> o.personId } { id, o -> + o == null ? 'none' : o.amount.toString() + }.toList() + } + + List projected() { + List people = [ + new Person(1, 'Ann', 20, []), + new Person(2, 'Bob', 15, []), + new Person(3, 'Cyd', 30, []) + ] + Ginq.from(people) + .where { p -> p.age >= 18 } + .orderBy { p -> p.name } + .select { p -> p.name } + .toList() + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentTest.groovy new file mode 100644 index 00000000000..a976061f6f0 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqFluentTest.groovy @@ -0,0 +1,262 @@ +/* + * 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 + +import groovy.ginq.Ginq +import groovy.ginq.Query +import groovy.transform.CompileStatic +import org.junit.jupiter.api.Test + +import java.util.stream.Stream + +import static groovy.test.GroovyAssert.shouldFail + +/** + * Fluent GINQ queries, including queries compiled with {@code @CompileStatic}. + */ +@CompileStatic +final class GinqFluentTest { + + @Test + void whereSelectAndOrder() { + List people = [ + new Person(1, 'Ann', 20), + new Person(2, 'Bob', 15), + new Person(3, 'Cyd', 30) + ] + List names = Ginq.from(people) + .where { p -> p.age >= 18 } + .orderBy { p -> p.name } + .select { p -> p.name } + .toList() + assert names == ['Ann', 'Cyd'] + } + + @Test + void implicitParameterIsTypedFromTheSource() { + // tag::ginq_fluent_01[] + List doubled = Ginq.from([1, 2, 3, 4]) + .where { it > 1 } + .orderByDescending { it } + .select { it * 2 } + .take(2) + .toList() + assert doubled == [8, 6] + // end::ginq_fluent_01[] + } + + @Test + void thenByGroupsAndJoins() { + List names = Ginq.from([ + new Person(1, 'Zoe', 20), + new Person(2, 'Ann', 20), + new Person(3, 'Bob', 15) + ]).orderBy { p -> p.age }.thenBy { p -> p.name } + .select { p -> p.name } + .toList() + assert names == ['Bob', 'Ann', 'Zoe'] + + List sizes = Ginq.from([ + new Person(1, 'Ann', 20), + new Person(2, 'Bob', 15), + new Person(3, 'Cyd', 30) + ]).groupBy { p -> p.age >= 18 } + .select { g -> g.count() } + .toList() + assert sizes.toSorted() == [1L, 2L] + + List orders = [new Order(1, 5), new Order(1, 7), new Order(3, 4)] + List amounts = Ginq.from([ + new Person(1, 'Ann', 20), + new Person(2, 'Bob', 15) + ]).join(orders) { p -> p.id } { o -> o.personId } { p, o -> o.amount } + .orderBy { it } + .toList() + assert amounts == [5, 7] + } + + @Test + void selectManySetOperatorsAndTerminalAggregates() { + assert [1, 2, 3, 4] == Ginq.from([[1, 2], [3, 4]]).selectMany { row -> row }.toList() + assert [1, 2, 3] == Ginq.of(1, 2).concat(Ginq.of(2, 3)).distinct().orderBy { it }.toList() + assert [1] == Ginq.of(1, 2).intersect(Ginq.of(1, 3)).toList() + assert [2] == Ginq.of(1, 2).except(Ginq.of(1)).toList() + assert [2, 3] == Ginq.of(1, 2, 3).skip(1).toList() + assert Ginq.empty().toList().isEmpty() + + assert Ginq.of(1, 2, 3).sum { it } == 6 + assert Ginq.of(1, 2, 3).aggregate(0) { acc, n -> acc + n } == 6 + assert Ginq.of(1, 2, 3).aggregate { rows -> rows.max { it } } == 3 + } + + @Test + void operatorsWaitUntilTheQueryIsRead() { + List seen = [] + Query query = Ginq.from([1, 2, 3]).where { n -> + seen.add(n) + return n > 1 + } + assert seen.isEmpty() + assert query.toList() == [2, 3] + assert seen == [1, 2, 3] + } + + @Test + void thenByRequiresAnOrder() { + shouldFail(IllegalStateException) { + Ginq.of(1, 2).thenBy { it } + } + } + + @Test + void leftJoinKeepsUnmatchedOuterElements() { + List labels = Ginq.of(1, 2).leftJoin([new Order(1, 9)]) { id -> id } { o -> o.personId } { id, o -> + o == null ? 'none' : o.amount.toString() + }.toList() + assert labels == ['9', 'none'] + } + + + @Test + void fromIntArrayIsQueryOfIntegerAndReboxesEachTerminal() { + int[] nums = [1, 2, 3] as int[] + Query query = Ginq.from(nums) + assert query.toList() == [1, 2, 3] + nums[1] = 9 + assert query.toList() == [1, 9, 3] + } + + @Test + void fromNullIntArrayIsRejected() { + shouldFail(NullPointerException) { + Ginq.from((int[]) null) + } + } + + @Test + void fluentStreamSourceIsFullyDrainedOnTheFirstTerminal() { + List seen = new ArrayList<>() + Query query = Ginq.from(Stream.of(1, 2, 3, 4).peek(n -> { seen.add(n); })).take(1) + assert query.toList() == [1] + assert seen == [1, 2, 3, 4] + assert query.toList() == [1] + + List existsSeen = new ArrayList<>() + assert Ginq.from(Stream.of(5, 6, 7).peek(n -> { existsSeen.add(n); })).exists() + assert existsSeen == [5, 6, 7] + } + + @Test + void fluentStreamSourceIsMarkedReadOnlyAfterASuccessfulCollect() { + Stream failing = Stream.of(1, 2).map(n -> { + if (n == 2) { + throw new IllegalStateException('boom') + } + return n + }) + Query query = Ginq.from(failing) + def first = shouldFail(IllegalStateException) { + query.toList() + } + assert first.message == 'boom' + // The stream has already been operated on, so a retry must still fail + // rather than returning the empty buffer that an early read flag would yield. + shouldFail { + query.toList() + } + } + + @Test + void fluentStreamToListDoesNotReturnTheLiveBuffer() { + Query query = Ginq.from(Stream.of(1, 2, 3)) + List first = query.toList() + first.add(99) + assert query.toList() == [1, 2, 3] + assert query.count() == 3L + } + + @Test + void queryToQueryJoinsCompileStatically() { + Query people = Ginq.from([ + new Person(1, 'Ann', 20), + new Person(2, 'Bob', 15) + ]) + Query orders = Ginq.from([new Order(1, 5), new Order(1, 7), new Order(3, 4)]) + List inner = people.join(orders) { p -> p.id } { o -> o.personId } { p, o -> o.amount }.orderBy { it }.toList() + assert inner == [5, 7] + + List left = people.leftJoin(orders) { p -> p.id } { o -> o.personId } { p, o -> + o == null ? 'none' : o.amount.toString() + }.toList() + assert left.toSet() == ['5', '7', 'none'] as Set + + List right = people.rightJoin(orders) { p -> p.id } { o -> o.personId } { p, o -> + p == null ? 'none' : o.amount.toString() + }.toList() + assert right.toSet() == ['5', '7', 'none'] as Set + + List full = people.fullJoin(orders) { p -> p.id } { o -> o.personId } { p, o -> + p == null ? 'none' : (o == null ? p.name : o.amount.toString()) + }.toList() + assert full.toSet() == ['5', '7', 'none', 'Bob'] as Set + + List crossed = Ginq.of(1, 2).crossJoin(Ginq.of(10, 20)) { a, b -> a + b }.toList() + assert crossed.toSet() == [11, 21, 12, 22] as Set + + List pred = people.join(orders) { p, o -> p.id == o.personId } { p, o -> o.amount }.orderBy { it }.toList() + assert pred == [5, 7] + + List predLeft = people.leftJoin(orders, { p, o -> p.id == o.personId }, { p, o -> + o == null ? 'none' : o.amount.toString() + }).toList() + assert predLeft.toSet() == ['5', '7', 'none'] as Set + + List predRight = people.rightJoin(orders, { p, o -> p.id == o.personId }, { p, o -> + p == null ? 'none' : o.amount.toString() + }).toList() + assert predRight.toSet() == ['5', '7', 'none'] as Set + + List predFull = people.fullJoin(orders, { p, o -> p.id == o.personId }, { p, o -> + p == null ? 'none' : (o == null ? p.name : o.amount.toString()) + }).toList() + assert predFull.toSet() == ['5', '7', 'none', 'Bob'] as Set + } + + static final class Person { + final int id + final String name + final int age + + Person(int id, String name, int age) { + this.id = id + this.name = name + this.age = age + } + } + + static final class Order { + final int personId + final int amount + + Order(int personId, int amount) { + this.personId = personId + this.amount = amount + } + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqLazinessTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqLazinessTest.groovy new file mode 100644 index 00000000000..6e4aef8c948 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqLazinessTest.groovy @@ -0,0 +1,184 @@ +/* + * 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 + +import groovy.ginq.Ginq +import groovy.ginq.transform.GQ +import groovy.transform.CompileStatic +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.assertScript + +/** + * Deferred execution of GINQ. Elements are pulled by a terminal operation. + * A second {@code toList()} uses the list already materialized. + */ +@CompileStatic +final class GinqLazinessTest { + + private final List seen = [] + + @Test + void dynamicWhereDoesNotPullUntilToListAndRereadsLocals() { + assertScript ''' + int opened = 0 + int pulls = 0 + def gate = [ + iterator: { + opened++ + def raw = [1, 2, 3].iterator() + [ + hasNext: { raw.hasNext() }, + next: { pulls++; raw.next() } + ] as Iterator + } + ] as Iterable + def filtered = [] + int min = 0 + def query = GQ { + from n in gate + where (filtered << n) != null && n > min + select n + } + assert filtered.isEmpty() + assert pulls == 0 + min = 1 + // The local is bound when the pipeline is built, which is this expression. + assert [1, 2, 3] == query.toList() + assert filtered == [1, 2, 3] + assert pulls == 3 + int after = pulls + assert [1, 2, 3] == query.toList() + assert pulls == after + ''' + } + + @Test + void staticQueryWaitsForTheTerminalAndKeepsTheCapturedLocal() { + Gate gate = new Gate([1, 2, 3]) + int min = 0 + Queryable query = GQ { + from n in gate + where note(n) && n > min + select n + } + assert seen.isEmpty() + assert gate.opened == 0 + assert gate.pulls == 0 + min = 1 + // Same binding as a dynamic query: min was 0 when the expression ran. + assert [1, 2, 3] == query.toList() + assert seen == [1, 2, 3] + assert gate.opened == 1 + assert gate.pulls == 3 + int after = gate.pulls + assert [1, 2, 3] == query.toList() + assert gate.pulls == after + } + + @Test + void gqlMaterializesImmediately() { + Gate gate = new Gate([1, 2, 3]) + List values = GQL { + from n in gate + select n + } + assert values == [1, 2, 3] + assert gate.pulls == 3 + } + + @Test + void annotationReturnsAQueryableThatHasNotRun() { + List values = [1, 2, 3] + Queryable query = aboveOne(values) + assert seen.isEmpty() + assert [2, 3] == query.toList() + assert seen == [1, 2, 3] + } + + @Test + void fluentOperatorsWaitUntilTheTerminal() { + Gate gate = new Gate([1, 2, 3, 4]) + int keys = 0 + def grouped = Ginq.from(gate) + .where { n -> n > 0 } + .groupBy { n -> + keys++ + n % 2 + } + assert gate.opened == 0 + assert keys == 0 + grouped.toList() + assert gate.pulls == 4 + assert keys == 4 + + Gate ordered = new Gate([3, 1, 2]) + int comparisons = 0 + def query = Ginq.from(ordered).orderBy { n -> + comparisons++ + n + }.select { n -> n * 10 } + assert ordered.opened == 0 + assert comparisons == 0 + assert query.toList() == [10, 20, 30] + assert ordered.pulls == 3 + assert comparisons > 0 + } + + private boolean note(int n) { + seen.add(n) + return true + } + + @GQ + private Queryable aboveOne(List values) { + from n in values + where note(n) && n > 1 + select n + } + + static final class Gate implements Iterable { + private final List data + int opened + int pulls + + Gate(List data) { + this.data = data + } + + @Override + Iterator iterator() { + opened++ + Iterator raw = data.iterator() + return new Iterator() { + @Override + boolean hasNext() { + return raw.hasNext() + } + + @Override + Integer next() { + pulls++ + return raw.next() + } + } + } + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqMultiKeyGroupTypeTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqMultiKeyGroupTypeTest.groovy new file mode 100644 index 00000000000..a138923840b --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqMultiKeyGroupTypeTest.groovy @@ -0,0 +1,168 @@ +/* + * 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 + +import groovy.transform.CompileStatic +import org.codehaus.groovy.ast.AnnotationNode +import org.codehaus.groovy.ast.ClassCodeVisitorSupport +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.ClassNode +import org.codehaus.groovy.ast.FieldNode +import org.codehaus.groovy.ast.GenericsType +import org.codehaus.groovy.ast.MethodNode +import org.codehaus.groovy.ast.Parameter +import org.codehaus.groovy.ast.tools.WideningCategories +import org.codehaus.groovy.control.CompilationUnit +import org.codehaus.groovy.control.CompilerConfiguration +import org.codehaus.groovy.control.Phases +import org.codehaus.groovy.control.SourceUnit +import org.junit.jupiter.api.Test + +import java.util.IdentityHashMap + +/** + * A multi-key group infers a map value from names and numbers. That lowest + * upper bound must not be a parameterized {@code Serializable}. + */ +final class GinqMultiKeyGroupTypeTest { + + @Test + void multiKeyGroupValueIsNotAParameterizedSerializable() { + String script = ''' + import groovy.ginq.transform.GQ + def result = GQ { + from n in [[name: 'a', val: 1], [name: 'b', val: 2]] + groupby n.name as name, n.val as val into g + select g["name"], g["val"], g.count() + }.toList().collect { it.toList() }.sort() + assert result == [['a', 1, 1], ['b', 2, 1]] + ''' + CompilationUnit unit = compileStatic(script) + List illegal = [] + Set seen = Collections.newSetFromMap(new IdentityHashMap()) + unit.iterator().each { SourceUnit source -> + source.AST.classes.each { ClassNode type -> + new ClassCodeVisitorSupport() { + @Override + void visitClass(ClassNode node) { + check(node, illegal, seen) + super.visitClass(node) + } + + @Override + void visitField(FieldNode node) { + check(node.type, illegal, seen) + check(node.originType, illegal, seen) + super.visitField(node) + } + + @Override + void visitMethod(MethodNode node) { + check(node.returnType, illegal, seen) + super.visitMethod(node) + } + + @Override + void visitConstructorOrMethod(MethodNode node, boolean isConstructor) { + for (Parameter parameter : node.parameters) { + check(parameter.type, illegal, seen) + check(parameter.originType, illegal, seen) + } + super.visitConstructorOrMethod(node, isConstructor) + } + + @Override + protected SourceUnit getSourceUnit() { source } + }.visitClass(type) + } + } + assert illegal.isEmpty() : illegal.toString() + for (generated in unit.classes) { + String pool = new String(generated.bytes, 'ISO-8859-1') + assert !pool.contains('Serializable<') : generated.name + } + } + + private static void check(ClassNode type, List illegal, Set seen) { + if (type == null || !seen.add(type)) return + GenericsType[] arguments = type.genericsTypes + if (arguments != null && arguments.length > 0 && declaresNoTypeParameters(type)) { + illegal << "${type.name} with ${arguments.length} type argument(s)" + } + if (arguments != null) { + for (GenericsType argument : arguments) { + check(argument.type, illegal, seen) + if (argument.upperBounds != null) { + for (ClassNode bound : argument.upperBounds) { + check(bound, illegal, seen) + } + } + check(argument.lowerBound, illegal, seen) + } + } + if (type instanceof WideningCategories.LowestUpperBoundClassNode) { + check(type.unresolvedSuperClass, illegal, seen) + for (ClassNode face : type.interfaces) { + check(face, illegal, seen) + } + } + } + + private static boolean declaresNoTypeParameters(ClassNode type) { + String writtenName = type.name + ClassNode declared = type.redirect() + if (declared instanceof WideningCategories.LowestUpperBoundClassNode) { + ClassNode named = ClassHelper.make(writtenName).redirect() + if (!named.resolved || named.array) return writtenName == 'java.io.Serializable' + return named.typeClass.typeParameters.length == 0 + } + if (!declared.resolved || declared.array) return false + return declared.typeClass.typeParameters.length == 0 + } + + /** + * The macro lowers {@code GQ} at semantic analysis, so {@code @CompileStatic} + * has to be on the script class before that transform runs. + */ + private static CompilationUnit compileStatic(String script) { + CompilerConfiguration configuration = new CompilerConfiguration() + GroovyClassLoader loader = new GroovyClassLoader(GinqMultiKeyGroupTypeTest.classLoader, configuration) + CompilationUnit unit = new CompilationUnit(configuration, null, loader) + unit.addSource('GroupKey.groovy', script) + def field = CompilationUnit.getDeclaredField('phaseOperations') + field.accessible = true + def operations = field.get(unit) as Deque[] + Deque conversion = operations[Phases.CONVERSION] + List existing = new ArrayList(conversion) + conversion.clear() + conversion.add(existing.get(0)) + conversion.add((CompilationUnit.ISourceUnitOperation) { SourceUnit source -> + for (ClassNode type : source.AST.classes) { + if (type.script) { + type.addAnnotation(new AnnotationNode(ClassHelper.make(CompileStatic))) + } + } + }) + for (int i = 1; i < existing.size(); i++) { + conversion.add(existing.get(i)) + } + unit.compile() + return unit + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqScriptModes.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqScriptModes.groovy new file mode 100644 index 00000000000..3483bafaf23 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqScriptModes.groovy @@ -0,0 +1,224 @@ +/* + * 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 + +import groovy.test.GroovyAssert +import groovy.transform.CompileDynamic +import groovy.transform.CompileStatic +import groovy.transform.TypeChecked +import org.codehaus.groovy.ast.AnnotationNode +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.ClassNode +import org.codehaus.groovy.control.CompilationUnit +import org.codehaus.groovy.control.CompilerConfiguration +import org.codehaus.groovy.control.Phases +import org.codehaus.groovy.control.SourceUnit +import org.codehaus.groovy.tools.GroovyClass + +import java.lang.reflect.Field +import java.util.concurrent.atomic.AtomicInteger + +/** + * Runs one existing GINQ script in each real checking mode. + * The script text is not copied: the same characters are compiled four times. + * {@link Kind#DYNAMIC} is the default {@code GroovyShell}. The other modes put + * the checking annotation on the script class before macro expansion, so + * {@code GQ} / {@code GQL} and the surrounding script see that mode. + */ +@CompileStatic +final class GinqScriptModes { + + static enum Kind { + DYNAMIC, + COMPILE_DYNAMIC, + TYPE_CHECKED, + COMPILE_STATIC + } + + private static final AtomicInteger NEXT_ID = new AtomicInteger() + private static final EnumMap EXECUTIONS = new EnumMap<>(Kind) + static { + for (Kind kind : Kind.values()) { + EXECUTIONS.put(kind, new AtomicInteger()) + } + Runtime.runtime.addShutdownHook { + System.err.println(audit()) + } + } + + private GinqScriptModes() { + } + + /** + * Compiles and runs {@code script} in every {@link Kind}. + * A failure names the mode and leaves the original cause attached. + * + * @param script the script already used by a GINQ test + */ + static void runAll(String script) { + for (Kind kind : Kind.values()) { + run(kind, script) + } + } + + /** + * Compiles and runs {@code script} in one mode. Used for paths that are + * reached while the script is compiled, such as a query in a field. + * + * @param kind the checking mode + * @param script the script to compile and run + */ + static void runOne(Kind kind, String script) { + run(kind, script) + } + + /** + * Runs the script in the two dynamic modes. Used when static checking + * rejects the script for a reason the dynamic assertions do not have. + * + * @param script the script already used by a GINQ test + */ + static void expectUnchecked(String script) { + run(Kind.DYNAMIC, script) + run(Kind.COMPILE_DYNAMIC, script) + } + + /** + * Compiles the script in the checked modes and requires each one to + * reject it with every listed diagnostic. The modes still run. + * + * @param script the script already used by a GINQ test + * @param diagnostics text that each checked failure must contain + */ + static void expectCheckedRejection(String script, String... diagnostics) { + for (Kind kind : [Kind.TYPE_CHECKED, Kind.COMPILE_STATIC]) { + AssertionError error = null + try { + run(kind, script) + } catch (AssertionError caught) { + error = caught + } + if (error == null) { + throw new AssertionError('[' + kind.name() + '] compiled a script that static checking rejects') + } + String message = error.message == null ? '' : error.message + for (String diagnostic : diagnostics) { + if (!message.contains(diagnostic)) { + throw error + } + } + } + } + + /** + * @return how many scripts each mode has executed in this JVM + */ + static String audit() { + StringBuilder report = new StringBuilder('GINQ script modes:') + for (Kind kind : Kind.values()) { + report.append(' ').append(kind.name()).append('=').append(EXECUTIONS.get(kind).get()) + } + return report.toString() + } + + private static void run(Kind kind, String script) { + EXECUTIONS.get(kind).incrementAndGet() + try { + if (kind == Kind.DYNAMIC) { + GroovyAssert.assertScript(script) + } else { + compileAndRun(kind, script) + } + } catch (Throwable failure) { + throw new AssertionError('[' + kind.name() + '] ' + messageOf(failure), failure) + } + } + + private static void compileAndRun(Kind kind, String script) { + ClassLoader parent = Thread.currentThread().contextClassLoader + if (parent == null) { + parent = GinqScriptModes.classLoader + } + CompilerConfiguration configuration = new CompilerConfiguration() + GroovyClassLoader loader = new GroovyClassLoader(parent, configuration) + CompilationUnit unit = new CompilationUnit(configuration, null, loader) + String className = 'GinqCase' + NEXT_ID.incrementAndGet() + unit.addSource(className + '.groovy', script) + applyModeBeforeMacros(unit, kind) + unit.compile() + + Class scriptClass = null + for (GroovyClass generated : unit.classes) { + Class defined = loader.defineClass(generated.name, generated.bytes) + if (className == generated.name) { + scriptClass = defined + } + } + if (scriptClass == null) { + throw new IllegalStateException('no script class ' + className) + } + Script instance = (Script) scriptClass.getDeclaredConstructor().newInstance() + instance.run() + } + + /** + * The macro transform is registered when the compilation unit is constructed, + * after {@code source.convert()}. The checking annotation has to exist before + * that transform lowers {@code GQ}, so it is inserted between those two operations. + */ + private static void applyModeBeforeMacros(CompilationUnit unit, Kind kind) { + Field field = CompilationUnit.getDeclaredField('phaseOperations') + field.accessible = true + Deque[] operations = (Deque[]) field.get(unit) + Deque conversion = operations[Phases.CONVERSION] + List existing = new ArrayList(conversion) + conversion.clear() + conversion.add(existing.get(0)) + conversion.add((CompilationUnit.ISourceUnitOperation) { SourceUnit source -> + for (ClassNode type : source.AST.classes) { + if (type.script) { + type.addAnnotation(modeAnnotation(kind)) + } + } + }) + for (int i = 1; i < existing.size(); i++) { + conversion.add(existing.get(i)) + } + } + + private static AnnotationNode modeAnnotation(Kind kind) { + Class annotationType + if (kind == Kind.TYPE_CHECKED) { + annotationType = TypeChecked + } else if (kind == Kind.COMPILE_DYNAMIC) { + annotationType = CompileDynamic + } else { + annotationType = CompileStatic + } + return new AnnotationNode(ClassHelper.make(annotationType)) + } + + private static String messageOf(Throwable failure) { + String message = failure.message + if (message == null || message.isEmpty()) { + return failure.getClass().name + } + return message + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqStaticExpressionTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqStaticExpressionTest.groovy new file mode 100644 index 00000000000..32a94cbd45e --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqStaticExpressionTest.groovy @@ -0,0 +1,281 @@ +/* + * 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 + +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.assertScript + +/** + * Static queries compiled from source while the test runs. + */ +class GinqStaticExpressionTest { + + @Test + void prefixIncrementIsSharedWithTheCaller() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + Integer cnt = 0 + List values = GQ { from n in [1, 2] select ++cnt }.toList() + return values + [cnt] + } + } + assert Example.run() == [1, 2, 2] + ''' + } + + @Test + void fieldAndConstructorQueriesCaptureTheirBounds() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Held { + static int bound = 1 + static List values = GQ { from n in [0, 1, 2] where n > bound select n }.toList() + } + @CompileStatic + class Built { + final List values + Built(int bound) { + values = GQ { from n in [0, 1, 2] where n > bound select n }.toList() + } + } + assert Held.values == [2] + assert new Built(0).values == [1, 2] + ''' + } + + @Test + void typeCheckedSkipStillRunsTheQuery() { + assertScript ''' + import groovy.transform.TypeChecked + import groovy.transform.TypeCheckingMode + @TypeChecked(TypeCheckingMode.SKIP) + class Example { + static List run() { + GQ { + from row in [[a: 1], [a: 4]] + where row.a > 2 && !(row.a == 0) + select row.a + }.toList() + } + } + assert Example.run() == [4] + ''' + } + + @Test + void primitiveArrayAndWildcardQueryableKeepTheirElementTypes() { + assertScript ''' + import groovy.transform.CompileStatic + import org.apache.groovy.ginq.provider.collection.runtime.Queryable + @CompileStatic + class Example { + static List ints() { + int[] nums = [1, 2, 3] as int[] + GQ { from n in nums where n > 1 select n * 2 }.toList() + } + static List boxed(Queryable rows) { + GQ { from n in rows where n > 1 select n }.toList() + } + } + assert Example.ints() == [4, 6] + assert Example.boxed(Queryable.from([1, 4])) == [4] + ''' + } + + @Test + void arithmeticOnADynamicRowUsesTheRuntimeOperators() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + def rows = [[value: 8]] + GQ { + from r in rows + select r.value % 3 + r.value.intdiv(2) + (r.value ** 2) + (r.value << 1) + + (r.value >> 1) + (r.value >>> 1) + (r.value & 3) + (r.value | 1) + (r.value ^ 1) + }.toList() + } + } + assert Example.run() == [112] + ''' + } + + @Test + void stringConcatenationAndAMapSubscriptStayInTheQuery() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + def rows = [[name: 'Ann', extra: [flag: true]]] + GQ { + from r in rows + where r.extra['flag'] + select r.name + '!' + }.toList() + } + } + assert Example.run() == ['Ann!'] + ''' + } + + @Test + void staticQueryCallsAnUnresolvedMethodOnTheClass() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + GQ { + from n in [1, 2] + select helper(n) + }.toList() + } + } + Example.metaClass.static.helper = { Object n -> 'helper' + n } + assert Example.run() == ['helper1', 'helper2'] + ''' + } + + @Test + void instanceQueryCallsAnUnresolvedMethodOnThis() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + Object methodMissing(String name, Object args) { + Object[] values = args instanceof Object[] ? (Object[]) args : [args] as Object[] + return name + values[0] + } + List run() { + GQ { + from n in [3] + select helper(n) + }.toList() + } + } + assert new Example().run() == ['helper3'] + ''' + } + + @Test + void compileDynamicMethodSkipsTheStaticQueryCheck() { + assertScript ''' + import groovy.transform.CompileDynamic + import groovy.transform.CompileStatic + @CompileStatic + class Example { + @CompileDynamic + static List run() { + GQ { + from row in [[a: 1], [a: 3]] + where row.a > 1 + select row.a + }.toList() + } + } + assert Example.run() == [3] + ''' + } + + @Test + void compileDynamicOuterClassSkipsAnInnerStaticQuery() { + assertScript ''' + import groovy.transform.CompileDynamic + import groovy.transform.CompileStatic + @CompileDynamic + class Outer { + @CompileStatic + static class Inner { + static List run() { + def rows = [[n: 2], [n: 5]] + GQ { + from r in rows + where r.n > 3 + select r.n + }.toList() + } + } + } + assert Outer.Inner.run() == [5] + ''' + } + + @Test + void nestedSubscriptOnAQueryResultReadsTheInnerValue() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static Object run() { + def result = GQ { + from n in [[9], [8]] + select n + } + result[0][0] + } + } + assert Example.run() == 9 + ''' + } + + @Test + void lowestUpperBoundDropsArgumentsAClassDoesNotDeclare() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + List ints = [1, 2] + List longs = [3L] + def rows = true ? ints : longs + GQ { + from n in rows + select n + 1 + }.toList() + } + } + assert Example.run() == [2, 3] + ''' + } + + @Test + void safeCallInsideTheQueryReadsAMissingMapPropertyAsNull() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + def rows = [[missing: 4], [:]] + GQ { + from r in rows + select r?.missing + }.toList() + } + } + assert Example.run() == [4, null] + ''' + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqStaticModeTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqStaticModeTest.groovy new file mode 100644 index 00000000000..f81c1cc9ded --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/GinqStaticModeTest.groovy @@ -0,0 +1,738 @@ +/* + * 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 + +import groovy.ginq.Ginq +import groovy.transform.CompileStatic +import groovy.transform.Internal +import org.apache.groovy.ginq.provider.collection.runtime.LazyQueryable +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.codehaus.groovy.ast.AnnotationNode +import org.codehaus.groovy.ast.ClassHelper +import org.codehaus.groovy.ast.expr.ArrayExpression +import org.codehaus.groovy.ast.expr.ClassExpression +import org.codehaus.groovy.ast.expr.ConstantExpression +import org.codehaus.groovy.ast.expr.ListExpression +import org.codehaus.groovy.ast.expr.MethodCallExpression +import org.codehaus.groovy.control.SourceUnit +import org.junit.jupiter.api.Test + +import java.util.stream.Stream + +import static groovy.test.GroovyAssert.assertScript +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.varX + +/** + * Behaviour called out on the static GINQ review: checking mode, query scope, + * lexical capture, return-type widening, per-expression dynamic calls, + * extension registration, and re-enumeration. + */ +final class GinqStaticModeTest { + + @Test + void compileDynamicInsideTypeCheckedStillChecksTheQuery() { + assertScript ''' + import groovy.transform.TypeChecked + import groovy.transform.CompileDynamic + @TypeChecked + class Example { + @CompileDynamic + def query(List rows) { + GQ { + from r in rows + where r.value > 10 + select r.value + } + } + } + def rows = [[value: 5], [value: 12], [value: 20]] + assert new Example().query(rows).toList() == [12, 20] + ''' + } + + @Test + void compileStaticSkipInsideTypeCheckedStillChecksTheQuery() { + assertScript ''' + import groovy.transform.TypeChecked + import groovy.transform.CompileStatic + import groovy.transform.TypeCheckingMode + @TypeChecked + class Example { + @CompileStatic(TypeCheckingMode.SKIP) + def query(List rows) { + GQ { + from r in rows + select r.value + } + } + } + assert new Example().query([[value: 4], [value: 1]]).toList() == [4, 1] + ''' + } + + @Test + void typeCheckedClassStillChecksAMethodThatIsNotSkipped() { + def err = shouldFail ''' + import groovy.transform.TypeChecked + import groovy.transform.CompileDynamic + @TypeChecked + class Example { + @CompileDynamic + def query(List rows) { + GQ { from r in rows select r.value } + } + int bad() { 'no' } + } + ''' + assert err.message.contains('bad') + } + + @Test + void compileDynamicInsideCompileStaticIsNotTypeChecked() { + assertScript ''' + import groovy.transform.CompileStatic + import groovy.transform.CompileDynamic + @CompileStatic + class Example { + @CompileDynamic + def query(List rows) { + GQ { from r in rows select r.notARealProperty } + } + } + assert new Example().query([[notARealProperty: 7]]).toList() == [7] + ''' + } + + @Test + void rowChecksDoNotLeakToOtherMethods() { + def property = shouldFail ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + Object value + def query(List rows) { + GQ { from r in rows select r.value } + } + String unrelated() { value.mispelledProperty } + } + ''' + assert property.message.contains('mispelledProperty') + + def subscript = shouldFail ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + def query(List rows) { + GQ { from r in rows select r.value } + } + Object getValue(Object value) { value[0] } + } + ''' + assert subscript.message.contains('[') || subscript.message.contains('getAt') || subscript.message.contains('value') + } + + @Test + void subscriptInsideTheQueryStaysDynamic() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + GQ { from r in [[10, 20], [30, 40]] select r[0] }.toList() + } + } + assert Example.run() == [10, 30] + ''' + } + + @Test + void shadowingAndAliasesUseRealScope() { + assertScript ''' + import groovy.transform.CompileStatic + import java.util.concurrent.TimeUnit as TU + @CompileStatic + class Example { + static List capturedParameter(List rows) { + int threshold = 10 + def filtered = { int bound -> + GQ { + from row in rows + where row.value > bound + select row.value + } + } + threshold = 100 + // bound is the closure parameter, not the method local. + return filtered(10).toList() + } + static List alias() { + def classes = GQ { + from row in [1] + select TU + }.toList() + return classes + } + } + assert Example.capturedParameter([[value: 12], [value: 4]]) == [12] + assert Example.alias()[0] == java.util.concurrent.TimeUnit + ''' + } + + @Test + void mutatedLocalIsSharedAndReadOnlyLocalIsCopied() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List writes() { + Integer cnt = 0 + List values = GQ { from n in [1, 2] select cnt++ }.toList() + return values + [cnt] + } + static List reads() { + int extra = 1 + def query = GQ { from n in [1, 2, 3, 4] where n > extra select n } + extra = 3 + return query.toList() + } + } + assert Example.writes() == [0, 1, 2] + assert Example.reads() == [2, 3, 4] + ''' + } + + @Test + void returnTypeWidensOnlyForARealOverride() { + assertScript ''' + class Base { + String query(String name) { name } + } + class Child extends Base { + @groovy.ginq.transform.GQ + def query(List rows) { + from n in rows + select n + } + } + assert Child.getDeclaredMethod('query', List).returnType.name.contains('Queryable') + assert new Child().query([1, 2]).toList() == [1, 2] + ''' + + assertScript ''' + import org.apache.groovy.ginq.provider.collection.runtime.Queryable + class Hidden { + private String query(List rows) { 'hidden' } + } + class Child extends Hidden { + @groovy.ginq.transform.GQ + def query(List rows) { + from n in rows + select n + } + } + class Statics { + static String load(String name) { name } + Queryable rows(List rows) { Queryable.from(rows) } + } + class Other extends Statics { + @groovy.ginq.transform.GQ + def load(List rows) { + from n in rows + select n + } + @groovy.ginq.transform.GQ + def rows(List rows) { + from n in rows + select n + } + } + assert Child.getDeclaredMethod('query', List).returnType.name.contains('Queryable') + assert Other.getDeclaredMethod('load', List).returnType.name.contains('Queryable') + assert Other.getDeclaredMethod('rows', List).returnType.name.contains('Queryable') + assert new Child().query([4]).toList() == [4] + ''' + + def err = shouldFail ''' + interface Api { + String load(List rows) + } + class Impl implements Api { + @groovy.ginq.transform.GQ + def load(List rows) { + from n in rows + select n + } + } + ''' + assert err.message.contains('incompatible with java.lang.String') + assert !err.message.contains('Queryable') + } + + @Test + void otherExtensionsStillSeeTheQuery() { + RecordingChecks.NAMES.clear() + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic(extensions = 'org.apache.groovy.ginq.RecordingChecks') + class Example { + static List run() { + return GQ { from n in [1, 2] where n > 0 select n * 2 }.toList() + } + } + assert Example.run() == [2, 4] + ''' + // The extension on the enclosing method sees the wrapper the macro leaves + // behind, and the clause calls the static writer type-checks. + assert RecordingChecks.NAMES.contains('toList') + assert RecordingChecks.NAMES.contains('defer') || RecordingChecks.NAMES.contains('call') + } + + @Test + void lazyQueryableIsInternalAndDeferIsAbi() { + assert LazyQueryable.getAnnotation(Internal) != null + // GroovyABI is CLASS retention, so it is in the class file and not on the reflective method. + def bytes = LazyQueryable.getResourceAsStream('LazyQueryable.class').bytes + String utf = new String(bytes, 'ISO-8859-1') + assert utf.contains('GroovyABI') + assert utf.contains('7.0.0') + assert utf.contains('defer') + } + + @Test + void extensionMemberThatCannotBeMergedIsReported() { + SourceUnit source = SourceUnit.create('ginq.groovy', '') + AnnotationNode annotation = new AnnotationNode(ClassHelper.make(CompileStatic)) + MethodCallExpression call = callX(varX('builder'), 'extensions', args(constX('other.Extension'))) + call.setImplicitThis(false) + annotation.setMember('extensions', call) + + GinqStaticBridge.addExtension(source, annotation) + + assert source.errorCollector.hasErrors() + assert annotation.getMember('extensions').is(call) + + source = SourceUnit.create('ginq.groovy', '') + annotation = new AnnotationNode(ClassHelper.make(CompileStatic)) + annotation.setMember('extensions', new ConstantExpression('other.Extension')) + GinqStaticBridge.addExtension(source, annotation) + assert !source.errorCollector.hasErrors() + assert annotation.getMember('extensions') instanceof ListExpression + + source = SourceUnit.create('ginq.groovy', '') + annotation = new AnnotationNode(ClassHelper.make(CompileStatic)) + annotation.setMember('extensions', new ClassExpression(ClassHelper.make(RecordingChecks))) + GinqStaticBridge.addExtension(source, annotation) + assert !source.errorCollector.hasErrors() + def member = annotation.getMember('extensions') + assert member instanceof ListExpression + assert member.expressions*.text.contains(RecordingChecks.name) + + source = SourceUnit.create('ginq.groovy', '') + annotation = new AnnotationNode(ClassHelper.make(CompileStatic)) + annotation.setMember('extensions', new ArrayExpression(ClassHelper.STRING_TYPE, [constX('other.Extension')])) + GinqStaticBridge.addExtension(source, annotation) + assert !source.errorCollector.hasErrors() + assert annotation.getMember('extensions') instanceof ListExpression + + source = SourceUnit.create('ginq.groovy', '') + annotation = new AnnotationNode(ClassHelper.make(CompileStatic)) + annotation.setMember('extensions', new ListExpression([callX(varX('builder'), 'extensions', args(constX('other.Extension')))])) + GinqStaticBridge.addExtension(source, annotation) + assert source.errorCollector.hasErrors() + } + + @Test + void fluentIterableIsRereadAndStreamIsNeverConsumed() { + List numbers = [1, 2, 3] + def query = Ginq.from(numbers).where { Integer n -> n > 1 } + List first = query.toList() + numbers.add(4) + List second = query.toList() + assert first == [2, 3] + assert second == [2, 3, 4] + + def streamed = Ginq.from([1, 2, 3].stream()).where { Integer n -> n > 1 } + assert streamed.toList() == [2, 3] + assert streamed.toList() == [2, 3] + + Queryable gq = GQ { from n in [1, 2, 3] where n > 1 select n } + Stream s1 = gq.stream() + Stream s2 = gq.stream() + assert !s1.is(s2) + assert s1.count() == 2 + assert s2.count() == 2 + assert gq.toList() == [2, 3] + Stream s3 = gq.stream() + assert !s3.is(s1) + assert s3.count() == 2 + + def listed = Queryable.from([1, 2, 3]) + assert listed.stream().count() == 3 + assert listed.stream().count() == 3 + + int seen = 0 + Queryable sized = GQ { from n in [1, 2, 3] select (seen++) } + assert sized.stream().spliterator().trySplit() == null + assert sized.stream().count() == 3 + assert seen == 0 + def cursor = sized.stream().spliterator() + assert cursor.tryAdvance { } + assert cursor.estimateSize() == 2L + assert sized.toList().size() == 3 + + def right = Queryable.from([1, 2, 3].stream()) + right.stream() + def joined = Queryable.from([1, 2]).innerJoin(right) { a, b -> a == b } + assert joined.toList().size() == 2 + } + + @Test + void skippedTypeCheckedClassDoesNotCheckTheQuery() { + assertScript ''' + import groovy.transform.TypeChecked + import groovy.transform.TypeCheckingMode + @TypeChecked(TypeCheckingMode.SKIP) + class Example { + def query(List rows) { + GQ { from r in rows select r.notARealProperty } + } + } + assert new Example().query([[notARealProperty: 3]]).toList() == [3] + ''' + } + + @Test + void queryInALocalClassInsideASkippedMethodIsNotChecked() { + assertScript ''' + import groovy.transform.CompileStatic + import groovy.transform.TypeChecked + import groovy.transform.TypeCheckingMode + @CompileStatic + class Example { + @TypeChecked(TypeCheckingMode.SKIP) + def outer(List rows) { + def inner = new Object() { + def run() { + GQ { from r in rows select r.notARealProperty } + } + } + inner.run() + } + } + assert new Example().outer([[notARealProperty: 4]]).toList() == [4] + ''' + } + + @Test + void subscriptOnAQueryResultIsCheckedAndAFieldIsNot() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + Object first() { + def result = GQ { from n in [[9], [8]] select n } + result.getAt(0) + } + Object nested() { + def result = GQ { from n in [[9], [8]] select n } + result[0][0] + } + } + assert new Example().first() == [9] + assert new Example().nested() == 9 + ''' + + def field = shouldFail ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + Object value + def query(List rows) { + GQ { from r in rows select r.value } + } + List bad() { value[0].toList() } + } + ''' + assert field.message.contains('toList') || field.message.contains('value') + + def parameter = shouldFail ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + def query(List rows) { + GQ { from r in rows select r.value } + } + List getValue(Object value) { value[0].toList() } + } + ''' + assert parameter.message.contains('toList') || parameter.message.contains('value') + } + + // GROOVY-12724 + @Test + void fieldAndPropertyAreNotShadowedByASameNamedLocal() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + int threshold = 10 + List mixed() { + def query = GQ { + from n in [1, 2, 6, 12] + where n > threshold + select ({ int threshold -> n + threshold }(5)) + } + this.threshold = 4 + return query.toList() + } + } + assert new Example().mixed() == [11, 17] + ''' + + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + private int stored = 1 + int getThreshold() { stored } + void setThreshold(int value) { stored = value } + List later() { + def query = GQ { + from n in [1, 2, 3] + where n > threshold + select n + } + this.threshold = 2 + return query.toList() + } + } + assert new Example().later() == [3] + ''' + + assertScript ''' + import groovy.transform.TypeChecked + @TypeChecked + class Example { + int threshold = 1 + List later() { + def query = GQ { + from n in [1, 2, 3] + where n > threshold + select n + } + this.threshold = 2 + return query.toList() + } + } + assert new Example().later() == [3] + ''' + + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + int threshold = 1 + List immediate() { + def listed = GQL { + from n in [1, 2, 3] + where n > threshold + select n + } + this.threshold = 2 + return listed + } + } + assert new Example().immediate() == [2, 3] + ''' + } + + // GROOVY-12724 + @Test + void closureParameterShadowsTheFieldAndAnAliasIsNotALocal() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + int threshold = 10 + List parameterWins(int ignored) { + def filtered = { int threshold -> + def query = GQ { + from n in [1, 2, 6] + where n > threshold + select n + } + this.threshold = 100 + return query.toList() + } + return filtered(4) + } + } + assert new Example().parameterWins(0) == [6] + ''' + + assertScript ''' + import java.util.concurrent.TimeUnit as threshold + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + return GQ { + from n in [1] + select threshold + }.toList() + } + } + assert Example.run()[0] == java.util.concurrent.TimeUnit + ''' + + def err = shouldFail ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + List run() { + int threshold = 10 + return GQ { + from n in [1, 2, 3] + where ({ -> int threshold = 5; n > threshold }()) + select n + }.toList() + } + } + ''' + assert err.message.contains('threshold') + } + + // GROOVY-12724 + @Test + void unknownRowPropertyStaysDynamic() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + def rows = [[a: 1], [a: 2]] + return GQ { + from r in rows + select r.vlue + }.toList() + } + } + assert Example.run() == [null, null] + ''' + } + + @Test + void clauseCallKeepsTheMethodAnotherExtensionSelected() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic(extensions = 'org.apache.groovy.ginq.ChooseChecks') + class Example { + static String choose(CharSequence value) { 'seq' } + static String choose(String value) { 'str' } + static List run() { + String outside = choose('x') + List inside = GQ { + from n in [1] + select choose('x') + }.toList() + return [outside, inside[0]] + } + } + assert Example.run() == ['seq', 'seq'] + ''' + } + + @Test + void staticClauseKeepsAWellTypedStream() { + assertScript ''' + import groovy.transform.CompileStatic + import java.util.stream.Collectors + @CompileStatic + class Example { + static List sums() { + GQ { + from n in [1, 1, 3, 3, 6, 6, 6] + groupby n + select n, agg(_g.stream().map(r -> BigDecimal.valueOf(r.n)).reduce(BigDecimal.ZERO, BigDecimal::add)) + }.toList() + } + static List joined() { + GQ { + from s in ['a', 'bc', 'def'] + groupby s.size() + select s.size(), agg(_g.stream().map(r -> r.s).collect(Collectors.joining())) + }.toList() + } + } + assert Example.sums() == [[1, 2], [3, 6], [6, 18]] + assert Example.joined() == [[1, 'a'], [2, 'bc'], [3, 'def']] + ''' + } + + @Test + void staticRowTypeIgnoresAnEnclosingClosureParameter() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic + class Example { + static List run() { + def query = { String label -> + GQ { + from n in [1, 1, 3, 3, 6, 6, 6] + groupby n + select n, agg({ String ignored -> + _g.stream().map(r -> r.n).reduce(0, Integer::sum) + }.call(label)) + }.toList() + } + query.call('unused') + } + } + assert Example.run() == [[1, 2], [3, 6], [6, 18]] + ''' + } + + @Test + void markedMethodReferenceInAClauseStaysAGroovyPointer() { + assertScript ''' + import groovy.transform.CompileStatic + @CompileStatic(extensions = 'org.apache.groovy.ginq.MarkQueryPointers') + class Example { + static String label(String s) { + return s + '!' + } + static List run() { + def rows = ["${'a'}", "${'bc'}"] + GQ { + from s in rows + groupby s.toString() + select s.toString(), agg(_g.stream().map(r -> r.s).map(Example::label).findFirst().get()) + }.toList() + } + } + // A SAM bridge would checkcast the GString argument to String and throw. + // A Groovy method pointer coerces the GString when the pointer is called. + assert Example.run().toSet() == [['a', 'a!'], ['bc', 'bc!']] as Set + ''' + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/MarkQueryPointers.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/MarkQueryPointers.groovy new file mode 100644 index 00000000000..39dc19f8387 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/MarkQueryPointers.groovy @@ -0,0 +1,75 @@ +/* + * 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 + +import org.codehaus.groovy.ast.MethodNode +import org.codehaus.groovy.ast.expr.ClosureExpression +import org.codehaus.groovy.ast.expr.MethodPointerExpression +import org.codehaus.groovy.ast.expr.MethodReferenceExpression +import org.codehaus.groovy.ast.CodeVisitorSupport +import org.codehaus.groovy.transform.stc.AbstractTypeCheckingExtension +import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor +import org.codehaus.groovy.transform.stc.StaticTypesMarker + +/** + * Marks method pointers inside a GINQ query closure so the static writer + * must keep them as Groovy pointers. Used to cover the + * {@code DYNAMIC_RESOLUTION} guard in the method-reference writer. + */ +class MarkQueryPointers extends AbstractTypeCheckingExtension { + + MarkQueryPointers(StaticTypeCheckingVisitor typeCheckingVisitor) { + super(typeCheckingVisitor) + } + + @Override + void afterVisitMethod(MethodNode node) { + if (node.code == null) { + return + } + node.code.visit(new CodeVisitorSupport() { + private int queryDepth + + @Override + void visitClosureExpression(ClosureExpression expression) { + boolean query = Boolean.TRUE.equals(expression.getNodeMetaData(GinqRowChecks.QUERY)) + if (query) { + queryDepth++ + } + super.visitClosureExpression(expression) + if (query) { + queryDepth-- + } + } + + @Override + void visitMethodPointerExpression(MethodPointerExpression expression) { + if (queryDepth > 0) { + expression.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE) + } + super.visitMethodPointerExpression(expression) + } + + @Override + void visitMethodReferenceExpression(MethodReferenceExpression expression) { + visitMethodPointerExpression(expression) + } + }) + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/RecordingChecks.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/RecordingChecks.groovy new file mode 100644 index 00000000000..2935bfa2963 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/RecordingChecks.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 + +import org.codehaus.groovy.ast.expr.MethodCall +import org.codehaus.groovy.transform.stc.AbstractTypeCheckingExtension +import org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor + +/** + * Records method names the type checker asks an extension about. + * A query compiled as one dynamic closure would not reach this hook. + */ +class RecordingChecks extends AbstractTypeCheckingExtension { + + static final List NAMES = [] + + RecordingChecks(StaticTypeCheckingVisitor typeCheckingVisitor) { + super(typeCheckingVisitor) + } + + @Override + boolean beforeMethodCall(MethodCall call) { + String name = call.methodAsString + if (name != null) { + NAMES.add(name) + } + return false + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/TotalAggregate.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/TotalAggregate.groovy new file mode 100644 index 00000000000..4a9814e1d39 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/TotalAggregate.groovy @@ -0,0 +1,47 @@ +/* + * 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 + +import org.apache.groovy.ginq.provider.GinqAggregate +import org.apache.groovy.ginq.provider.collection.runtime.Queryable + +import java.util.function.Function + +/** + * Test aggregate registered as {@code total}. Sums the selected numbers in a group. + */ +class TotalAggregate implements GinqAggregate { + + @Override + String name() { + return 'total' + } + + @Override + Object apply(Queryable group, Function selector) { + BigDecimal sum = BigDecimal.ZERO + for (Object row : group.toList()) { + Object value = selector == null ? row : selector.apply(row) + if (value instanceof Number) { + sum = sum.add(new BigDecimal(value.toString())) + } + } + return sum + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/fluent/GinqQuerySourceTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/fluent/GinqQuerySourceTest.groovy new file mode 100644 index 00000000000..778f72001dc --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/fluent/GinqQuerySourceTest.groovy @@ -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.fluent + +import groovy.ginq.Ginq +import org.apache.groovy.ginq.fluent.GinqQuery +import org.apache.groovy.ginq.provider.GinqProvider +import org.apache.groovy.ginq.provider.collection.runtime.Queryable +import org.apache.groovy.ginq.provider.collection.runtime.QueryableHelper +import org.junit.jupiter.api.Test + +class GinqQuerySourceTest { + + @Test + void fromAnExistingQueryReturnsThatQuery() { + IterableQuery original = new IterableQuery(Queryable.from([1, 2, 2])) + assert GinqQuery.from(original).is(original) + assert original.distinct().toList() == [1, 2] + } + + @Test + void joinAcceptsAQueryPassedAsAnIterable() { + Iterable inner = new IterableQuery(Queryable.from([10, 20])) + List sums = Ginq.of(1).crossJoin(inner) { Integer a, Integer b -> a + b }.toList() + assert sums.toSet() == [11, 21] as Set + } + + @Test + void emptySourceVarianceIsNullAndAParallelStreamStaysParallel() { + assert Queryable.from([]).varp { it } == null + assert Queryable.from([null, null]).var { it } == null + QueryableHelper.setVar('parallel', 'true') + try { + assert Queryable.from([1, 2, 3]).stream().parallel + } finally { + QueryableHelper.setVar('parallel', 'false') + } + } + + @Test + void defaultProviderHasNoExtraOptionsOrDependencies() { + GinqProvider provider = new GinqProvider() { + @Override + String getName() { 'example' } + + @Override + String getAstWalkerClassName() { 'example.Walker' } + } + assert provider.additionalOptionNames.empty + assert provider.unavailableReason(GinqQuerySourceTest.classLoader) == null + } + + private static final class IterableQuery extends GinqQuery implements Iterable { + IterableQuery(Queryable ready) { + super(ready, null) + } + + @Override + Iterator iterator() { + return toList().iterator() + } + } +} diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollectionTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollectionTest.groovy index e9256da4369..f5ab41b1e47 100644 --- a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollectionTest.groovy +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/QueryableCollectionTest.groovy @@ -22,11 +22,18 @@ import groovy.transform.CompileDynamic import groovy.transform.CompileStatic import groovy.transform.EqualsAndHashCode import groovy.transform.ToString +import org.codehaus.groovy.runtime.typehandling.GroovyCastException import org.junit.jupiter.api.Test +import java.util.concurrent.CountDownLatch +import java.util.concurrent.CyclicBarrier +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicReference +import java.util.function.Consumer import java.util.stream.Collectors import java.util.stream.Stream +import static groovy.test.GroovyAssert.shouldFail import static org.apache.groovy.ginq.provider.collection.runtime.Queryable.from @CompileStatic @@ -38,6 +45,12 @@ class QueryableCollectionTest { assert [1, 2, 3] == from(from(Arrays.asList(1, 2, 3))).toList() } + @Test + void fromIntArrayBoxesToInteger() { + int[] nums = [1, 2, 3] as int[] + assert from(nums).toList() == [1, 2, 3] + } + @Test void testInnerJoin0() { def nums1 = [1, 2, 3] @@ -1022,6 +1035,19 @@ class QueryableCollectionTest { assert nums == result } + @Test + void testParallelStreamRebuildsFromTheList() { + def previous = QueryableHelper.getVar('parallel') + QueryableHelper.setVar('parallel', 'true') + try { + def query = from([1, 2, 3]) + assert [1, 2, 3] == query.toList() + assert [1, 2, 3] == query.stream().collect(Collectors.toList()) + } finally { + QueryableHelper.setVar('parallel', previous) + } + } + @Test void testExists() { def nums = [1, 2, 3] @@ -1029,6 +1055,495 @@ class QueryableCollectionTest { assert result } + @Test + void replayServesSharedElementsUnderConcurrentReaders() { + Queryable once = from(Stream.of(1, null, 2, 3)) + List> results = [new ArrayList(), new ArrayList()] + Thread[] threads = new Thread[2] + for (int i = 0; i < threads.length; i++) { + int index = i + threads[i] = new Thread(new Runnable() { + @Override + void run() { + results[index].addAll(once.stream().collect(Collectors.toList())) + } + }) + } + for (Thread thread : threads) { + thread.start() + } + for (Thread thread : threads) { + thread.join() + } + assert results[0] == [1, null, 2, 3] + assert results[1] == [1, null, 2, 3] + } + + // GROOVY-12724 + // Each cursor of a one-shot source is both a writer, when it appends the + // next element, and a reader, when it takes an element another cursor + // already appended. The action waits until every cursor has reserved the + // same element, so holding the write lock across the action deadlocks. + @Test + void replayKeepsEachElementOnceAcrossConcurrentReadersAndWriters() { + List expected = new ArrayList<>() + for (int i = 0; i < 16; i++) { + if (i % 5 == 0) { + expected.add(null) + } else { + expected.add(i) + } + } + Queryable once = from(expected.stream()) + int parties = 8 + List> results = new ArrayList<>() + for (int i = 0; i < parties; i++) { + results.add(new ArrayList()) + } + CyclicBarrier start = new CyclicBarrier(parties) + CyclicBarrier step = new CyclicBarrier(parties) + AtomicReference failure = new AtomicReference<>() + Thread[] threads = new Thread[parties] + for (int i = 0; i < parties; i++) { + int index = i + threads[i] = new Thread(new Runnable() { + @Override + void run() { + try { + Spliterator cursor = once.stream().spliterator() + start.await(5, TimeUnit.SECONDS) + boolean more = true + while (more) { + more = cursor.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + results[index].add(item) + step.await(5, TimeUnit.SECONDS) + } + }) + } + } catch (Throwable thrown) { + failure.compareAndSet(null, thrown) + } + } + }) + } + for (Thread thread : threads) { + thread.start() + } + for (Thread thread : threads) { + thread.join(10_000) + assert !thread.isAlive() : 'reader or writer did not finish' + } + Throwable thrown = failure.get() + if (thrown != null) { + throw thrown + } + for (List result : results) { + assert result == expected + } + } + + // GROOVY-12724 + @Test + void replayCallbackReentersTheSameQueryableWithoutDeadlock() { + Queryable once = from(Stream.of(1, null, 2)) + List expected = [1, null, 2] + Spliterator cursor = once.stream().spliterator() + List seen = new ArrayList<>() + AtomicReference> otherResult = new AtomicReference<>() + AtomicReference otherFailure = new AtomicReference<>() + CountDownLatch otherDone = new CountDownLatch(1) + boolean advanced = cursor.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + seen.add(item) + assert once.stream().collect(Collectors.toList()) == expected + Thread other = new Thread(new Runnable() { + @Override + void run() { + try { + otherResult.set(once.stream().collect(Collectors.toList())) + } catch (Throwable thrown) { + otherFailure.set(thrown) + } finally { + otherDone.countDown() + } + } + }) + other.setDaemon(true) + other.start() + assert otherDone.await(5, TimeUnit.SECONDS) : 'write lock held across the user action' + } + }) + assert advanced + assert otherFailure.get() == null + assert otherResult.get() == expected + List rest = new ArrayList<>() + cursor.forEachRemaining(new Consumer() { + @Override + void accept(Integer item) { + rest.add(item) + } + }) + assert seen == [1] + assert rest == [null, 2] + } + + // GROOVY-12724 + // Cursor policy: tryAdvance reads the element and advances this cursor + // under the lock, releases the lock, then runs the action. If the action + // throws, this cursor has consumed the element and does not deliver it + // again. The element stays in the replay buffer for every other cursor. + // The write lock is not held while the action runs, nor after it throws. + @Test + void replayActionExceptionConsumesTheElementAndKeepsTheBuffer() { + Queryable once = from(Stream.of(10, 20, 30, 40)) + List expected = [10, 20, 30, 40] + Spliterator throwing = once.stream().spliterator() + Spliterator other = once.stream().spliterator() + AtomicReference> during = new AtomicReference<>() + AtomicReference duringFailure = new AtomicReference<>() + CountDownLatch duringDone = new CountDownLatch(1) + try { + throwing.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + assert item == 10 + Thread reader = new Thread(new Runnable() { + @Override + void run() { + try { + during.set(once.stream().collect(Collectors.toList())) + } catch (Throwable thrown) { + duringFailure.set(thrown) + } finally { + duringDone.countDown() + } + } + }) + reader.setDaemon(true) + reader.start() + assert duringDone.await(5, TimeUnit.SECONDS) : 'write lock held across the user action' + throw new IllegalStateException('consumed ' + item) + } + }) + throw new AssertionError('action should have thrown') + } catch (IllegalStateException e) { + assert e.message == 'consumed 10' + } + assert duringFailure.get() == null + assert during.get() == expected + + CountDownLatch afterDone = new CountDownLatch(1) + AtomicReference> after = new AtomicReference<>() + Thread afterReader = new Thread(new Runnable() { + @Override + void run() { + try { + after.set(once.stream().collect(Collectors.toList())) + } finally { + afterDone.countDown() + } + } + }) + afterReader.setDaemon(true) + afterReader.start() + assert afterDone.await(5, TimeUnit.SECONDS) : 'write lock still held after the action threw' + assert after.get() == expected + + List throwingRest = new ArrayList<>() + throwing.forEachRemaining(new Consumer() { + @Override + void accept(Integer item) { + throwingRest.add(item) + } + }) + assert throwingRest == [20, 30, 40] + + List otherSeen = new ArrayList<>() + other.forEachRemaining(new Consumer() { + @Override + void accept(Integer item) { + otherSeen.add(item) + } + }) + assert otherSeen == expected + } + + // GROOVY-12724 + // After another cursor has already pulled elements into the buffer, a + // later cursor takes them under the read lock in serveReplayed. The + // element is copied and this cursor advances before the lock is released; + // the action runs afterwards. A throw mid-stream, after a successful + // serveReplayed pull, still consumes that element and leaves it in the + // buffer for other cursors. The read lock is not held across the action. + @Test + void replayServeReplayedActionExceptionConsumesTheElementAndKeepsTheBuffer() { + Queryable once = from(Stream.of(10, 20, 30, 40)) + List expected = [10, 20, 30, 40] + Spliterator writer = once.stream().spliterator() + assert writer.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + assert item == 10 + } + }) + assert writer.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + assert item == 20 + } + }) + + Spliterator throwing = once.stream().spliterator() + Spliterator other = once.stream().spliterator() + assert throwing.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + assert item == 10 + } + }) + + AtomicReference> during = new AtomicReference<>() + AtomicReference duringFailure = new AtomicReference<>() + CountDownLatch duringDone = new CountDownLatch(1) + try { + throwing.tryAdvance(new Consumer() { + @Override + void accept(Integer item) { + assert item == 20 + Thread reader = new Thread(new Runnable() { + @Override + void run() { + try { + during.set(once.stream().collect(Collectors.toList())) + } catch (Throwable thrown) { + duringFailure.set(thrown) + } finally { + duringDone.countDown() + } + } + }) + reader.setDaemon(true) + reader.start() + assert duringDone.await(5, TimeUnit.SECONDS) : 'read lock held across the user action' + throw new IllegalStateException('consumed ' + item) + } + }) + throw new AssertionError('action should have thrown') + } catch (IllegalStateException e) { + assert e.message == 'consumed 20' + } + assert duringFailure.get() == null + assert during.get() == expected + + CountDownLatch afterDone = new CountDownLatch(1) + AtomicReference> after = new AtomicReference<>() + Thread afterReader = new Thread(new Runnable() { + @Override + void run() { + try { + after.set(once.stream().collect(Collectors.toList())) + } finally { + afterDone.countDown() + } + } + }) + afterReader.setDaemon(true) + afterReader.start() + assert afterDone.await(5, TimeUnit.SECONDS) : 'read lock still held after the action threw' + assert after.get() == expected + + List throwingRest = new ArrayList<>() + throwing.forEachRemaining(new Consumer() { + @Override + void accept(Integer item) { + throwingRest.add(item) + } + }) + assert throwingRest == [30, 40] + + List writerRest = new ArrayList<>() + writer.forEachRemaining(new Consumer() { + @Override + void accept(Integer item) { + writerRest.add(item) + } + }) + assert writerRest == [30, 40] + + List otherSeen = new ArrayList<>() + other.forEachRemaining(new Consumer() { + @Override + void accept(Integer item) { + otherSeen.add(item) + } + }) + assert otherSeen == expected + } + + + @Test + void iteratorThenStreamReplaysAOneShotSource() { + Queryable once = from(Stream.of(1, 2, 3)) + assert collect(once.iterator()) == [1, 2, 3] + assert once.stream().toList() == [1, 2, 3] + } + + @Test + void streamThenIteratorReplaysAOneShotSource() { + Queryable once = from(Stream.of(1, 2, 3)) + assert once.stream().toList() == [1, 2, 3] + assert collect(once.iterator()) == [1, 2, 3] + } + + @Test + @CompileDynamic + void asIteratorFollowsTheSameReplayRulesAsStream() { + Queryable once = from(Stream.of(1, 2, 3)) + Iterator first = once as Iterator + assert first.toList() == [1, 2, 3] + assert once.toList() == [1, 2, 3] + Iterator second = once as Iterator + assert second.toList() == [1, 2, 3] + } + + @Test + @CompileDynamic + void groovyForThenASecondTerminalReplaysAOneShotSource() { + Queryable once = from(Stream.of(1, 2, 3)) + List seen = new ArrayList<>() + for (n in once) { + seen.add(n) + } + assert seen == [1, 2, 3] + assert once.toList() == [1, 2, 3] + } + + @Test + void iteratorRereadsANonListIterableMutatedBetweenCalls() { + List data = new ArrayList<>([1, 2, 3]) + Iterable source = new Iterable() { + @Override + Iterator iterator() { + return data.iterator() + } + } + Queryable query = from(source) + assert collect(query.iterator()) == [1, 2, 3] + data.add(4) + assert collect(query.iterator()) == [1, 2, 3, 4] + } + + @Test + void asTypeNullThrowsGroovyCastException() { + Queryable query = from([1, 2, 3]) + def thrown = shouldFail(GroovyCastException) { + query.asType(null) + } + assert thrown.message.contains('to null') + } + + @Test + void toListDoesNotReturnTheLiveInternalReplayBuffer() { + Queryable once = from(Stream.of(1, 2, 3)) + assert once.stream().toList() == [1, 2, 3] + List first = once.toList() + first.add(99) + assert once.toList() == [1, 2, 3] + assert once.asType(ArrayList) == [1, 2, 3] + } + + @Test + void toListDoesNotReturnAListThisQueryableInstalled() { + Queryable once = from(Stream.of(1, 2, 3)) + List first = once.toList() + first.add(99) + List second = once.toList() + assert second == [1, 2, 3] + second.add(88) + assert once.toList() == [1, 2, 3] + } + + @Test + void toListAfterAPartialOneShotBindDoesNotReturnTheLiveReplayBuffer() { + Queryable once = from(Stream.of(1, 2, 3)) + Iterator first = once.iterator() + assert first.next() == 1 + List list = once.toList() + list.add(99) + assert once.toList() == [1, 2, 3] + assert once.asType(ArrayList) == [1, 2, 3] + } + + @Test + void asTypeArrayListCopiesAUserSuppliedLinkedList() { + LinkedList source = new LinkedList<>([1, 2, 3]) + Queryable query = from(source) + assert query.toList().is(source) + ArrayList copy = (ArrayList) query.asType(ArrayList) + assert copy instanceof ArrayList + assert !copy.is(source) + copy.add(99) + assert query.toList() == [1, 2, 3] + assert source == [1, 2, 3] + } + + @Test + void toListCopiesAnOwnedList() { + List owned = new ArrayList<>([1, 2, 3]) + Queryable query = Queryable.fromOwned(owned) + List first = query.toList() + assert !first.is(owned) + first.add(99) + assert query.toList() == [1, 2, 3] + assert owned == [1, 2, 3] + } + + @Test + void toListReturnsAUserSuppliedListWithoutCopying() { + List source = new ArrayList<>([1, 2, 3]) + Queryable query = from(source) + assert query.toList().is(source) + source.add(4) + assert query.toList() == [1, 2, 3, 4] + assert query.asType(ArrayList).is(source) + } + + @Test + void whereAfterAPublicStreamStillSeesTheOneShotSource() { + Queryable once = from(Stream.of(1, 2, 3, 4)) + Iterator first = once.stream().iterator() + assert first.next() == 1 + assert once.where(n -> n > 1).toList() == [2, 3, 4] + assert once.select((n, rows) -> n).toList() == [1, 2, 3, 4] + assert once.limit(2).toList() == [1, 2] + } + + @Test + void whereAfterIteratorHasConsumedOneElementStillSeesTheOneShotSource() { + Queryable once = from(Stream.of(1, 2, 3, 4)) + Iterator first = once.iterator() + assert first.next() == 1 + assert once.where(n -> true).toList() == [1, 2, 3, 4] + } + + @Test + void whereAfterTheOneShotSourceIsFullyConsumedStillWorks() { + Queryable once = from(Stream.of(1, 2, 3)) + assert once.stream().toList() == [1, 2, 3] + assert once.where(n -> n > 1).toList() == [2, 3] + } + + + + private static List collect(Iterator iterator) { + List result = new ArrayList<>() + iterator.forEachRemaining(result::add) + return result + } + @ToString @EqualsAndHashCode static class Person { diff --git a/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImplTest.groovy b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImplTest.groovy new file mode 100644 index 00000000000..a0e62539938 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/groovy/org/apache/groovy/ginq/provider/collection/runtime/WindowImplTest.groovy @@ -0,0 +1,271 @@ +/* + * 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.collection.runtime + +import groovy.lang.Tuple2 +import groovy.transform.CompileDynamic +import org.junit.jupiter.api.Test + +import static groovy.test.GroovyAssert.shouldFail +import static org.apache.groovy.ginq.provider.collection.runtime.Queryable.from + +final class WindowImplTest { + + @Test + void testNullPartitionKeyGroupsTogether() { + assert [[1, 2], [2, 2], [3, 1]] == GQ { + from r in [[k: null, n: 1], [k: null, n: 2], [k: 1, n: 3]] + select r.n, (count() over(partitionby r.k)) + }.toList() + } + + @Test + void testRankUsesEveryOrderKey() { + assert [[1, 2, 3, 2], [1, 1, 1, 1], [1, 1, 1, 1], [2, 0, 4, 3]] == GQ { + from r in [[a: 1, b: 2], [a: 1, b: 1], [a: 1, b: 1], [a: 2, b: 0]] + select r.a, r.b, + (rank() over(orderby r.a, r.b)), + (denseRank() over(orderby r.a, r.b)) + }.toList() + + assert [[1, null, null, null, null], [2, null, null, null, null]] == GQ { + from n in [1, 2] + select n, (rank() over()), (denseRank() over()), (percentRank() over()), (cumeDist() over()) + }.toList() + + assert [1] == GQ { + from n in [7] + select (percentRank() over(orderby n)) + }.toList() + } + + @Test + void testOneRowNumberingIsZeroBased() { + assert [[0L, 7]] == GQ { + from n in [7] + select (rowNumber() over(orderby n)), (nthValue(n, 0) over(orderby n)) + }.toList() + } + + @Test + void testNtileZeroIsBucketZero() { + assert [0L, 0L, 0L] == GQ { + from n in [1, 2, 3] + select (ntile(0) over(orderby n)) + }.toList() + } + + @Test + void testAllNullWindowSumIsZero() { + assert [0, 0] == GQ { + from n in [null, null] + select (sum(n) over()) + }.toList() + } + + @Test + void testRankWithAFrameHonorsTheFrame() { + assert [1L, 1L, 1L] == GQ { + from n in [10, 20, 30] + select (rank() over(orderby n rows 0, 0)) + }.toList() + } + + @Test + void testLeadAndNtileUseThePartition() { + assert [[1, 2], [2, 3], [3, 4], [4, null]] == GQ { + from n in [1, 2, 3, 4] + select n, (lead(n) over(orderby n rows -1, 1)) + }.toList() + + assert [[1, 0], [2, 0], [3, 1], [4, 1]] == GQ { + from n in [1, 2, 3, 4] + select n, (ntile(2) over(orderby n rows 0, 0)) + }.toList() + + assert [[1, 1], [2, 2]] == GQ { + from n in [1, 2] + select n, (lead(n, 0) over(orderby n)) + }.toList() + } + + @Test + void testNthValueRejectsANegativeIndex() { + def err = shouldFail(IllegalArgumentException) { + GQ { + from n in [1, 2] + select (nthValue(n, -1) over(orderby n)) + }.toList() + } + assert err.message.contains('index cannot be less than 0') + } + + @Test + void testDirectBoundsForEmptyPeersAndMissedIntervals() { + def order = new Queryable.Order({ Integer n -> n }, true) + def finite = new WindowDefinitionImpl([order], new ValueBound(-1, 1)) + def numbers = [Tuple.tuple(1, 0L), Tuple.tuple(2, 1L)] + assert null == WindowImpl.getValidRowBound(finite, 0, null, numbers) + + def nulls = [Tuple.tuple(null, 0L), Tuple.tuple(null, 1L)] + RowBound peers = WindowImpl.getValidRowBound(finite, 0, 5, nulls) + assert 0L == peers.lower + assert 1L == peers.upper + + def backwards = new WindowDefinitionImpl([order], new ValueBound(2, -1)) + def mixed = [Tuple.tuple(1, 0L), Tuple.tuple(3, 1L), Tuple.tuple(null, 2L)] + assert null == WindowImpl.getValidRowBound(backwards, 0, 2, mixed) + + Comparator ordering = { Integer a, Integer b -> a <=> b } + def empty = new WindowImpl(Tuple.tuple(1, 0L), 0, [], ordering, []) + assert 0L == empty.ntile(4) + assert null == empty.percentRank() + assert null == empty.cumeDist() + def one = new WindowImpl(Tuple.tuple(1, 0L), 0, [1], ordering, [1]) + assert BigDecimal.ONE == one.percentRank() + assert 1 == one.lead({ Integer n -> n }, 0L, null) + } + + @Test + void testEmptyFrameAggregatesAreNull() { + assert [null, null, null] == GQ { + from n in [1, 2, 3] + select (avg(n) over(orderby n rows 5, 6)) + }.toList() + + assert [null, null, null] == GQ { + from n in [1, 2, 3] + select (stdevp(n) over(orderby n rows 0, 0)) + }.toList() + + assert [null, null, null] == GQ { + from n in [1, 2, 3] + select (percentRank() over(orderby n rows 5, 6)) + }.toList() + + assert [null, null] == GQ { + from n in [null, null] + select (avg(n) over()) + }.toList() + + assert [0, 0, 0] == GQ { + from n in [1, 2, 3] + select (count() over(orderby n rows 5, 3)) + }.toList() + } + + @Test + void testRangeFramesAroundNullsAndLargeValues() { + assert [0L, 1L] == GQ { + from n in [1, null] + orderby n + select (count() over(orderby n range 100, 200)) + }.toList() + + assert [[1.0d, 2L], [1.0e20d, 1L]] == GQ { + from n in [1.0d, 1.0e20d] + select n, (count() over(orderby n range 0, null)) + }.toList() + + assert [[null, 2L], [null, 2L]] == GQ { + from n in [null, null] + select n, (count() over(orderby n range -1, 1)) + }.toList() + + // Descending order keeps the value interval. An unbounded low bound + // reaches the nulls that sort after the small values. + assert [[1, 2L, 1], [null, 1L, 0], [3, 3L, 4]] == GQ { + from n in [1, null, 3] + select n, + (count() over(orderby n in desc range null, 0)), + (sum(n) over(orderby n in desc range null, 0)) + }.toList() + + assert [[1, 2L, 4], [null, 3L, 4], [3, 1L, 3]] == GQ { + from n in [1, null, 3] + select n, + (count() over(orderby n in desc range 0, null)), + (sum(n) over(orderby n in desc range 0, null)) + }.toList() + + assert [[1, 3L, 4], [null, 1L, 0], [3, 2L, 3]] == GQ { + from n in [1, null, 3] + select n, + (count() over(orderby n in desc(nullsfirst) range 0, null)), + (sum(n) over(orderby n in desc(nullsfirst) range 0, null)) + }.toList() + } + + @Test + void testNonNumericRangeIsRejected() { + def err = shouldFail(IllegalArgumentException) { + GQ { + from s in ['a', 'b'] + select (count() over(orderby s range 1, 2)) + }.toList() + } + assert err.message.contains('numeric order key') + + assert [2, 2] == GQ { + from s in ['a', 'b'] + select (count() over(orderby s range null, null)) + }.toList() + } + + @Test + void testEmptyPartitionHasNoRowBound() { + WindowDefinition definition = new WindowDefinitionImpl<>( + [new Queryable.Order<>({ Integer n -> n }, true)], + new ValueBound<>(0, null)) + List> empty = Collections.>emptyList() + assert null == WindowImpl.getValidRowBound(definition, 0, Integer.valueOf(1), empty) + } + + @Test + @CompileDynamic + void testNullGroupKeyInSequentialAndParallelGrouping() { + assert grouped([null, 'a', null]) == [[null, 2L], ['a', 1L]] as Set + + def previous = QueryableHelper.getVar('parallel') + QueryableHelper.setVar('parallel', 'true') + def parallelGroups + def into + try { + assert QueryableHelper.isParallel() + // Grouping itself honors parallel mode. select() does not: it expects + // the macro's future protocol, so turn parallel off before reading. + parallelGroups = from([null, 'a', null]).groupBy(e -> e) + into = from([null, 'b', null]).groupByInto(e -> e) + } finally { + QueryableHelper.setVar('parallel', previous) + } + assert parallelGroups.select((e, q) -> Tuple.tuple(e.v1, e.v2.count())).toList() as Set == [[null, 2L], ['a', 1L]] as Set + def intoRows = into.toList() + assert 2 == intoRows.size() + assert 2L == intoRows.find { it.key == null }.count() + assert 1L == intoRows.find { it.key == 'b' }.count() + } + + @CompileDynamic + private static Set grouped(List values) { + from(values).groupBy(e -> e) + .select((e, q) -> Tuple.tuple(e.v1, e.v2.count())) + .toList() as Set + } +} diff --git a/subprojects/groovy-ginq/src/test/resources/META-INF/services/org.apache.groovy.ginq.provider.GinqAggregate b/subprojects/groovy-ginq/src/test/resources/META-INF/services/org.apache.groovy.ginq.provider.GinqAggregate new file mode 100644 index 00000000000..c2f76adbb07 --- /dev/null +++ b/subprojects/groovy-ginq/src/test/resources/META-INF/services/org.apache.groovy.ginq.provider.GinqAggregate @@ -0,0 +1,15 @@ +# 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.TotalAggregate diff --git a/versions.properties b/versions.properties index f6131b134d0..13a2c9ffbbd 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.7.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