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 extends Message> 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 extends T> 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