From e724e64f352ba5852a5b507d425a730cca9b2ca1 Mon Sep 17 00:00:00 2001 From: Aastha Agrrawal Date: Wed, 12 Apr 2023 15:45:37 -0700 Subject: [PATCH] Backport [CALCITE-4145]: Select nested field from aliased subquery (#86) * Backport [CALCITE-4145] select nested field from subquery * modify UT --- .../org/apache/calcite/sql/type/SqlTypeUtil.java | 8 ++++++++ .../apache/calcite/test/SqlToRelConverterTest.java | 11 +++++++++++ .../apache/calcite/test/SqlToRelConverterTest.xml | 12 ++++++++++++ 3 files changed, 31 insertions(+) diff --git a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java index dcfcdd107..e184b9685 100644 --- a/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java +++ b/core/src/main/java/org/apache/calcite/sql/type/SqlTypeUtil.java @@ -1209,6 +1209,10 @@ public static boolean equalAsStructSansNullability( * Returns the ordinal of a given field in a record type, or -1 if the field * is not found. * + *

The {@code fieldName} is always simple, if the field is nested within a record field, + * returns index of the outer field instead. i.g. for row type + * (a int, b (b1 bigint, b2 varchar(20) not null)), returns 1 for both simple name "b1" and "b2". + * * @param type Record type * @param fieldName Name of field * @return Ordinal of field @@ -1220,6 +1224,10 @@ public static int findField(RelDataType type, String fieldName) { if (field.getName().equals(fieldName)) { return i; } + final RelDataType fieldType = field.getType(); + if (fieldType.isStruct() && findField(fieldType, fieldName) != -1) { + return i; + } } return -1; } diff --git a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java index ad05e88ff..3d03bd1ab 100644 --- a/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java +++ b/core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java @@ -3554,6 +3554,17 @@ private Tester getExtendedTester() { sql(sql).ok(); } + /** + * Test case for + * [CALCITE-4145] + * Exception when nested field queried from subquery. + */ + @Test public void testSelectNestedFromSubquery() { + final String sql = "select tmp.nested.\"EXPR$0\" as id from (" + + " select (1, 2) as nested) tmp"; + sql(sql).ok(); + } + /** * Visitor that checks that every {@link RelNode} in a tree is valid. * diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml index a473e637b..5acf7be75 100644 --- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml +++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml @@ -6269,6 +6269,18 @@ from emp window w as (order by empno)]]> + + + + + + + +