Skip to content
Open
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,13 @@ private RelDataType copyRecordType(
final boolean nullable) {
requireNonNull(type, "type");
RelDataType newType;
if (type.isNullable() == nullable) {
if (type instanceof SingleColumnAliasRelDataType) {
// Preserve the alias wrapper, applying nullability to both wrapped types.
final SingleColumnAliasRelDataType aliasType = (SingleColumnAliasRelDataType) type;
return new SingleColumnAliasRelDataType(
createTypeWithNullability(aliasType.getOriginal(), nullable),
createTypeWithNullability(aliasType.getAlias(), nullable));
} else if (type.isNullable() == nullable) {
newType = type;
} else if (type instanceof RelRecordType) {
// REVIEW: angel 18-Aug-2005 dtbug 336 workaround
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,26 +26,57 @@
import java.nio.charset.Charset;
import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;

/**
* Specific type of RelDataType that corresponds to a single column table,
* where column can have alias.
* Specific type of RelDataType where the first column can also be
* referenced by an alias.
*
* <p>For instance:
* <blockquote><pre>select rmp, rmp.i from table(ramp(3)) as rmp;</pre></blockquote>
*
* <p>The wrapped type may have more than one field, for example
* UNNEST WITH ORDINALITY of a collection of single-field ROW values, whose
* second field is ORDINALITY; only the first field gets the extra alias name.
* If the alias equals the name of another field, that field wins (see
* {@link #getField}).
*
* @see org.apache.calcite.sql.validate.AliasNamespace
*/
public class SingleColumnAliasRelDataType implements RelDataType {
private final RelDataType original;
private final RelDataType alias;

/**
* Creates a SingleColumnAliasRelDataType.
*
* @param original Row type whose fields are exposed; a struct with at
* least one field
* @param alias Struct with exactly one field, named after the alias, whose
* type is that of the first field of {@code original}
*
* @throws IllegalArgumentException if either type does not have the
* required shape
*/
public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) {
assert original.isStruct() && original.getFieldCount() == 1;
assert alias.isStruct() && alias.getFieldCount() == 1;
checkArgument(original.isStruct() && original.getFieldCount() >= 1,
"original must be a struct with at least one field: %s", original);
checkArgument(alias.isStruct() && alias.getFieldCount() == 1,
"alias must be a struct with exactly one field: %s", alias);
this.original = original;
this.alias = alias;
}

/** Returns the wrapped type whose fields are exposed. */
public RelDataType getOriginal() {
return original;
}

/** Returns the single-field type that supplies the extra alias name. */
public RelDataType getAlias() {
return alias;
}

@Override public boolean isStruct() {
return true;
}
Expand All @@ -59,13 +90,18 @@ public SingleColumnAliasRelDataType(RelDataType original, RelDataType alias) {
}

@Override public int getFieldCount() {
return 1;
return original.getFieldCount();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

F5 minor No test observes SingleColumnAliasRelDataType.getFieldCount(): the mutant that returns 0 survives, though a wrong count binds a correlated reference to the wrong column.

Problem: The change makes getFieldCount() report the wrapped type's count so that WITH ORDINALITY works through the wrapper. SqlToRelConverter adds each namespace's field count to the offset of the correlation fields after it, so a FROM item to the right of an aliased ROW-element UNNEST WITH ORDINALITY that a correlated sub-query references is where the count shows.

@Test void testUnnestSingleFieldRowAliasWithOrdinalityCorrelatedOffset() {
  final String sql = "select t.name\n"
      + "from unnest(cast(array[row(1)] as row(a integer) array))\n"
      + "  with ordinality as d, dept as t\n"
      + "where exists (select 1 from emp e\n"
      + "  where e.deptno = t.deptno and e.empno = d.ordinality)";
  // head: LogicalFilter(condition=[AND(=($7, $cor0.DEPTNO), =($0, $cor0.ORDINALITY))])
  // getFieldCount() mutated to `return 0;`: =($7, $cor0.A)
  sql(sql).withDecorrelate(false).withExpand(false).ok();
}

Proposed solution: Add a SqlToRelConverterTest case with an aliased ROW-element UNNEST WITH ORDINALITY followed by another table in the same FROM, and a correlated sub-query that references that table, so the plan pins the correlation field.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed in c0aac83

}

@Override public StructKind getStructKind() {
return original.getStructKind();
}

/**
* Looks up {@code fieldName} in the wrapped type first, then in the alias.
* A name that matches a wrapped field resolves to that field; the alias is
* a fallback for names that match none.
*/
@Override public @Nullable RelDataTypeField getField(final String fieldName,
final boolean caseSensitive, final boolean elideRecord) {
RelDataTypeField originalField = original.getField(fieldName, caseSensitive, elideRecord);
Expand Down
38 changes: 31 additions & 7 deletions core/src/main/java/org/apache/calcite/sql/SqlUnnestOperator.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,11 @@
import org.apache.calcite.sql.type.OperandTypes;
import org.apache.calcite.sql.type.SqlOperandCountRanges;
import org.apache.calcite.sql.type.SqlTypeName;
import org.apache.calcite.sql.validate.SqlConformance;
import org.apache.calcite.util.Util;

import org.apiguardian.api.API;

import static java.util.Objects.requireNonNull;

/**
Expand Down Expand Up @@ -77,9 +80,7 @@ public SqlUnnestOperator(boolean withOrdinality) {
return builder.build();
}

if (type.isStruct()) {
type = type.getFieldList().get(0).getType();
}
type = unwrapOperandType(type);

assert type instanceof ArraySqlType || type instanceof MultisetSqlType
|| type instanceof MapSqlType;
Expand All @@ -100,10 +101,7 @@ public SqlUnnestOperator(boolean withOrdinality) {
} else {
RelDataType componentType = requireNonNull(type.getComponentType(), "componentType");
boolean isNullable = componentType.isNullable() || padNullable;
// Whether a struct element expands into one column per field depends
// on the SQL conformance; allowAliasUnnestItems describes how
// collections of ROW values are expanded.
if (!allowAliasUnnestItems(opBinding) && componentType.isStruct()) {
if (expandsStructIntoColumns(componentType, allowAliasUnnestItems(opBinding))) {
for (RelDataTypeField field : componentType.getFieldList()) {
RelDataType fieldType = field.getType();
if (isNullable) {
Expand Down Expand Up @@ -131,6 +129,32 @@ public SqlUnnestOperator(boolean withOrdinality) {
return builder.build();
}

/**
* Returns the collection type that {@code operandType} denotes.
*
* <p>For a sub-query operand, {@code operandType} is a single-field
* struct; this returns the type of that field.
*/
@API(since = "1.43", status = API.Status.INTERNAL)
public static RelDataType unwrapOperandType(RelDataType operandType) {
return operandType.isStruct() ? operandType.getFieldList().get(0).getType() : operandType;
}

/**
* Returns whether UNNEST expands an element of type {@code componentType}
* into one column per field.
*
* @param componentType element type of the collection
* @param allowAliasUnnestItems value of
* {@link SqlConformance#allowAliasUnnestItems()}; when true, a ROW
* element becomes a single column of the ROW type
*/
@API(since = "1.43", status = API.Status.INTERNAL)
public static boolean expandsStructIntoColumns(RelDataType componentType,
boolean allowAliasUnnestItems) {
return componentType.isStruct() && !allowAliasUnnestItems;
}

private static boolean allowAliasUnnestItems(SqlOperatorBinding operatorBinding) {
return (operatorBinding instanceof SqlCallBinding)
&& ((SqlCallBinding) operatorBinding)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlNodeList;
import org.apache.calcite.sql.SqlUnnestOperator;
import org.apache.calcite.sql.SqlUtil;
import org.apache.calcite.sql.fun.SqlStdOperatorTable;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.util.Pair;
Expand Down Expand Up @@ -103,29 +104,30 @@ protected AliasNamespace(
final RelDataType aliasedType;
if (operands.size() == 2) {
final SqlNode node = operands.get(0);
// Alias is 'AS t' (no column list).
// If the sub-query is UNNEST or VALUES,
// and the sub-query has one column,
// then the namespace's sole column is named after the alias.
// 'AS t' on a single-column result, or on UNNEST WITH ORDINALITY with one
// data column: the data column is named after the alias. A ROW element's
// field keeps its own name for star expansion, and the alias names it as
// well. COLLECTION_TABLE handles its column the same way.
final boolean keepsElementFieldName = node.getKind() == SqlKind.UNNEST
&& keepsElementFieldName((SqlCall) node);
if (rowType.getFieldCount() == 1) {
final RelDataType singleColumnAlias = validator.getTypeFactory().builder()
.kind(rowType.getStructKind())
.add(((SqlIdentifier) operands.get(1)).getSimple(),
rowType.getFieldList().get(0).getType())
.build();
aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE
? new SingleColumnAliasRelDataType(rowType, singleColumnAlias) : singleColumnAlias;
// If the sub-query is UNNEST with ordinality
// and the sub-query has two columns: data column, ordinality column
// then the namespace's sole column is named after the alias.
final RelDataType dataColumnAlias =
aliasDataColumn(rowType, (SqlIdentifier) operands.get(1));
aliasedType = node.getKind() == SqlKind.COLLECTION_TABLE || keepsElementFieldName
? new SingleColumnAliasRelDataType(rowType, dataColumnAlias) : dataColumnAlias;
} else if (node.getKind() == SqlKind.UNNEST && rowType.getFieldCount() == 2
&& ((SqlUnnestOperator) ((SqlBasicCall) node).getOperator()).withOrdinality) {
aliasedType = validator.getTypeFactory().builder()
.kind(rowType.getStructKind())
.add(((SqlIdentifier) operands.get(1)).getSimple(),
rowType.getFieldList().get(0).getType())
.add(rowType.getFieldList().get(1))
.build();
// WITH ORDINALITY: data column, ordinality column. The data
// column is named after the alias, same as the single-column case.
final RelDataType dataColumnAlias =
aliasDataColumn(rowType, (SqlIdentifier) operands.get(1));
aliasedType = keepsElementFieldName
? new SingleColumnAliasRelDataType(rowType, dataColumnAlias)
Comment on lines +116 to +125

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

F1 major An aliased UNNEST of a single-field ROW array on the null-generating side of a LEFT or RIGHT JOIN now validates its column as NOT NULL, and SqlToRelConverter rejects the query, which converted on the base.

Problem: The validator's outer-join nullability does not reach a SingleColumnAliasRelDataType, so a column reference through it (d, d.a, d + 1, d.ordinality) keeps NOT NULL while the converted plan makes it nullable, and conversion throws AssertionError: Conversion to relational algebra failed to preserve datatypes. The throw is unconditional, so it does not depend on -ea. Plain UNNEST and WITH ORDINALITY fail alike; only select * converts. TABLE(...) AS alias, which the base already wraps, fails the same way at the base, so a fix inside the UNNEST branch alone leaves it.

Reproducer
// SqlToRelConverterTest
@Test void testUnnestSingleFieldRowAliasOnNullableSide() {
  sql("select d, d.a from (values 1) as t (x)\n"
      + "left join unnest(cast(array[row(1)] as row(a integer) array)) as d on true").ok();
  sql("select d, d.ordinality from (values 1) as t (x)\n"
      + "left join unnest(cast(array[row(1)] as row(a integer) array))\n"
      + "  with ordinality as d on true").ok();
  sql("select d from unnest(cast(array[row(1)] as row(a integer) array)) as d\n"
      + "right join (values 1) as t (x) on true").ok();
  // head: AssertionError: Conversion to relational algebra failed to preserve datatypes
  //   validated type: RecordType(INTEGER NOT NULL D) NOT NULL
  //   converted type: RecordType(INTEGER D) NOT NULL
  // expected (base 9634752f for `d`): validated RecordType(INTEGER D) NOT NULL, plan converts
}

Proposed solution: Make the nullable copy of a SingleColumnAliasRelDataType a SingleColumnAliasRelDataType over nullable copies of both wrapped types, for example in RelDataTypeFactoryImpl.createTypeWithNullability, which fixes TABLE(...) AS alias with it. Add SqlToRelConverterTest cases, with their validator types in testUnnestAlias, for the aliased UNNEST on the null-generating side of a LEFT and a RIGHT JOIN, plain and WITH ORDINALITY, selecting the alias and the field name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch. fixed in c0aac83

: validator.getTypeFactory().builder()
.kind(rowType.getStructKind())
.addAll(dataColumnAlias.getFieldList())
.add(rowType.getFieldList().get(1))
.build();
} else {
aliasedType = rowType;
}
Expand Down Expand Up @@ -165,6 +167,39 @@ protected AliasNamespace(
}
}

/** Returns a single-field struct holding the first column of
* {@code rowType}, named after the alias. */
private RelDataType aliasDataColumn(RelDataType rowType, SqlIdentifier alias) {
return validator.getTypeFactory().builder()
.kind(rowType.getStructKind())
.add(alias.getSimple(), rowType.getFieldList().get(0).getType())
.build();
}

/**
* Returns whether UNNEST expands the collection's ROW element into one
* column per field. Such a column keeps its field name, and the alias
* names it as well; any other data column takes the alias as its name.
*/
private boolean keepsElementFieldName(SqlCall unnestCall) {
final RelDataType operandType =
SqlUnnestOperator.unwrapOperandType(
validator.getValidatedNodeType(unnestCall.operand(0)));
final RelDataType componentType = operandType.getComponentType();
return componentType != null
&& SqlUnnestOperator.expandsStructIntoColumns(componentType,
validator.config().conformance().allowAliasUnnestItems())
&& !hasGeneratedFirstFieldName(componentType);
}

/** Returns whether the first field of a ROW element has a generated name,
* such as {@code EXPR$0} for {@code ROW(1)}. The alias then names the
* column, because a generated name is not worth keeping. */
private static boolean hasGeneratedFirstFieldName(RelDataType componentType) {
final List<RelDataTypeField> fields = componentType.getFieldList();
return !fields.isEmpty() && SqlUtil.isGeneratedAlias(fields.get(0).getName());
}
Comment on lines +184 to +201

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

F2 major An aliased UNNEST of an anonymous single-field ROW array now exposes the generated field name EXPR$0 instead of the alias, so select * loses the alias and NATURAL JOIN of two such UNNESTs becomes an equi-join.

Problem: keepsElementFieldName is true for every single-field ROW element, including ROW(1), whose field name is generated. Two aliased UNNESTs in one FROM clause give EXPR$0, EXPR$00 instead of A, B, and a NATURAL JOIN between them now filters rows where the base did a cross join, without an error. WITH ORDINALITY and a sub-query operand behave the same. The thread that settled the field name as canonical ("the field name is what star-expansion and NATURAL JOIN use") considered a declared name such as A, not a generated one.

select * from unnest(array[row(1)]) as d;
-- head: RecordType(INTEGER NOT NULL EXPR$0)   base: RecordType(INTEGER NOT NULL D)

select * from unnest(array[row(1)]) as a natural join unnest(array[row(2)]) as b;
-- head: (EXPR$0), LogicalJoin(condition=[=($0, $1)]), no rows
-- base: (A, B), LogicalJoin(condition=[true])

select * from unnest(array[row(1)]) with ordinality as d;
-- head: (EXPR$0, ORDINALITY)   base: (D, ORDINALITY)

Proposed solution: Keep the base behavior, the alias as the column name, when the element's single field name is generated, for example by also requiring !SqlUtil.isGeneratedAlias(...) of that name in keepsElementFieldName, and add a testUnnestAlias case for unnest(array[row(1)]) as d. If the generated name is meant to win, state it in the PR description and the JIRA release note and pin it with a test.

@sbroeder sbroeder Nov 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch. Fixed in c0aac83


private static String getString(RelDataType rowType) {
StringBuilder buf = new StringBuilder();
buf.append("(");
Expand Down
Loading
Loading