vlsi commented on code in PR #5300:
URL: https://github.com/apache/calcite/pull/5300#discussion_r4543192395
##########
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScan.java:
##########
@@ -126,16 +134,51 @@ private Result defaultTableFunctionImplement(
final PhysType physType =
PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
false);
+ final List<Expression> cursors = new ArrayList<>();
+ for (int i = 0; i < getInputs().size(); i++) {
+ final EnumerableRel child = (EnumerableRel) getInputs().get(i);
+ final Result result = implementor.visitChild(this, i, child,
Prefer.ARRAY);
+ final Expression rows = bb.append("cursorRows", result.block);
+ cursors.add(
+ bb.append("cursor",
+ Expressions.call(CursorInputs.class, "of",
+ implementor.stash(child.getRowType(), RelDataType.class),
+ result.physType.convertTo(rows, JavaRowFormat.ARRAY))));
+ }
+ final boolean resultSetCursors = !cursors.isEmpty()
+ && ((RexCall) getCall()).getOperator() instanceof
SqlUserDefinedTableFunction
+ && ((SqlUserDefinedTableFunction) ((RexCall) getCall()).getOperator())
+ .getFunction() instanceof TableFunctionImpl;
+ final BlockBuilder callBuilder = resultSetCursors ? new BlockBuilder() :
bb;
+ final ParameterExpression resultSets =
Expressions.parameter(ResultSet[].class, "cursors");
RexToLixTranslator t =
RexToLixTranslator.forAggregation(
(JavaTypeFactory) getCluster().getTypeFactory(),
- bb, null, implementor.getConformance());
+ callBuilder, (list, index, storageType) -> resultSetCursors
+ ? Expressions.arrayIndex(resultSets,
Expressions.constant(index))
+ : cursors.get(index),
+ implementor.getConformance(),
implementor.getRexImplementorTable());
t = t.setCorrelates(implementor.allCorrelateVariables);
Expression expression = t.translate(getCall());
if (arrayRows && format == JavaRowFormat.SCALAR) {
expression = Expressions.call(BuiltInMethod.SLICE0.method, expression);
}
- bb.add(Expressions.return_(null, expression));
+ callBuilder.add(Expressions.return_(null, expression));
+ if (resultSetCursors) {
+ final List<List<ColumnMetaData>> columns = new ArrayList<>();
+ for (RelNode input : getInputs()) {
Review Comment:
**F2 major** A column alias inside `CURSOR(...)` can be lost at run time, so
the function sees different column labels than at validation.
Problem: The run-time metadata comes from `input.getRowType()` of the
physical input, and the `CursorInput` row type from `child.getRowType()`. After
planning, a rename-only projection can be gone, so `CURSOR(SELECT n AS x FROM
(VALUES ...) AS t(n))` reaches the function with a column labelled `N`, while
the validation-time `ResultSet` (built from `getCursorOperand`) says `X`. A
function that reads columns by label fails at run time, and one that names its
output columns after the input emits names that differ from the validated row
type. Whether an alias survives depends on which rules fire: `"empid" AS id,
"deptno" AS dno` from `hr.emps` keeps the aliases, all five `emps` columns
renamed do not.
Proposed solution: Build the metadata and the `CursorInput` row type from
the row type the call's cursor operand carries (or the logical input's row type
captured before planning), and add a test that reads an aliased cursor column
by label.
##########
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScan.java:
##########
@@ -126,16 +134,51 @@ private Result defaultTableFunctionImplement(
final PhysType physType =
PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
false);
+ final List<Expression> cursors = new ArrayList<>();
+ for (int i = 0; i < getInputs().size(); i++) {
+ final EnumerableRel child = (EnumerableRel) getInputs().get(i);
+ final Result result = implementor.visitChild(this, i, child,
Prefer.ARRAY);
+ final Expression rows = bb.append("cursorRows", result.block);
+ cursors.add(
+ bb.append("cursor",
+ Expressions.call(CursorInputs.class, "of",
+ implementor.stash(child.getRowType(), RelDataType.class),
+ result.physType.convertTo(rows, JavaRowFormat.ARRAY))));
+ }
+ final boolean resultSetCursors = !cursors.isEmpty()
+ && ((RexCall) getCall()).getOperator() instanceof
SqlUserDefinedTableFunction
+ && ((SqlUserDefinedTableFunction) ((RexCall) getCall()).getOperator())
+ .getFunction() instanceof TableFunctionImpl;
+ final BlockBuilder callBuilder = resultSetCursors ? new BlockBuilder() :
bb;
+ final ParameterExpression resultSets =
Expressions.parameter(ResultSet[].class, "cursors");
RexToLixTranslator t =
Review Comment:
**F3 major** A cursor argument built with `RelBuilder.cursor` still cannot
be executed: Enumerable code generation fails with `cannot translate call
CURSOR($0)`.
Problem: SqlToRelConverter emits `CAST($0):CURSOR NOT NULL`, while the
public `RelBuilder.cursor(inputCount, ordinal)` emits `CURSOR($0)`. Only the
bare `RexInputRef` is mapped to the cursor (through the `InputGetter` lambda),
and `RexImpTable` has no implementor for `SqlStdOperatorTable.CURSOR`, so a
plan built with `RelBuilder.cursor` fails in code generation with `cannot
translate call CURSOR($0)`. CURSOR support then depends on which front end
built the plan.
Proposed solution: Register an implementor for `SqlStdOperatorTable.CURSOR`
that returns the cursor expression for its input, or unwrap a `CURSOR` call in
the same place as the `RexInputRef`, and add a test that builds the scan with
`RelBuilder.cursor` and executes it.
##########
core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java:
##########
@@ -108,7 +116,15 @@ public TranslatableTable getTable(SqlOperatorBinding
callBinding) {
Ord.forEach(function.getParameters(), (parameter, i) -> {
final RelDataType type = parameter.getType(typeFactory);
final Object value;
- if (callBinding.isOperandLiteral(i, true)) {
+ if (!failOnNonLiteral && type.getSqlTypeName() == SqlTypeName.CURSOR
Review Comment:
**F1 major** `RelBuilder.functionScan` now throws
`UnsupportedOperationException` for a Java table function with a `ResultSet`
parameter, where it used to build the scan.
Problem: `SqlUserDefinedTableFunction.inferRowType` reaches
`convertArguments` with `failOnNonLiteral == false`, and
`RelFactories.TableFunctionScanFactoryImpl` passes a `RexCallBinding`, which
does not override `getCursorOperand`, so `SqlOperatorBinding.getCursorOperand`
throws a bare `UnsupportedOperationException`. Before this change the function
received `null` and returned its row type, so code that builds a table function
scan with `RelBuilder.functionScan` (planner extensions, Rel-level tests,
frameworks that skip SQL) worked and now fails.
Proposed solution: Make the metadata-only branch work for a `RexCallBinding`
(give it a `getCursorOperand` for a `CURSOR(...)` call or a CURSOR-typed
`RexInputRef` operand), or keep passing `null` when the binding cannot supply
the row type. Add a `RelBuilder.functionScan` test with a `ResultSet` parameter.
##########
core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java:
##########
@@ -108,7 +116,15 @@ public TranslatableTable getTable(SqlOperatorBinding
callBinding) {
Ord.forEach(function.getParameters(), (parameter, i) -> {
final RelDataType type = parameter.getType(typeFactory);
final Object value;
- if (callBinding.isOperandLiteral(i, true)) {
+ if (!failOnNonLiteral && type.getSqlTypeName() == SqlTypeName.CURSOR
+ && type instanceof RelDataTypeFactoryImpl.JavaType
+ && ((RelDataTypeFactoryImpl.JavaType) type).getJavaClass() ==
ResultSet.class) {
+ final RelDataType rowType =
Review Comment:
**F7 minor** `NULL` passed to a CURSOR parameter fails with
`NullPointerException: cursor row type` instead of a validation error.
Problem: A `NULL` literal passes the operand type check,
`getCursorOperand(i)` returns `null`, and `requireNonNull` throws
`NullPointerException: cursor row type` during prepare, with no position and no
argument name.
Proposed solution: Reject a non-CURSOR operand for a CURSOR parameter during
operand type checking with a validation error that names the argument, for
example `Argument 1 of ECHO must be CURSOR(query)`, and add the `NULL` case to
the tests.
##########
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScan.java:
##########
@@ -126,16 +134,51 @@ private Result defaultTableFunctionImplement(
final PhysType physType =
PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
false);
+ final List<Expression> cursors = new ArrayList<>();
+ for (int i = 0; i < getInputs().size(); i++) {
+ final EnumerableRel child = (EnumerableRel) getInputs().get(i);
+ final Result result = implementor.visitChild(this, i, child,
Prefer.ARRAY);
+ final Expression rows = bb.append("cursorRows", result.block);
+ cursors.add(
+ bb.append("cursor",
+ Expressions.call(CursorInputs.class, "of",
+ implementor.stash(child.getRowType(), RelDataType.class),
+ result.physType.convertTo(rows, JavaRowFormat.ARRAY))));
+ }
+ final boolean resultSetCursors = !cursors.isEmpty()
+ && ((RexCall) getCall()).getOperator() instanceof
SqlUserDefinedTableFunction
Review Comment:
**F4 minor, medium confidence** Validation and execution use different rules
to choose between `ResultSet` and `CursorInput`.
Problem: `convertArguments` decides by the parameter's Java class
(`ResultSet`), while `EnumerableTableFunctionScan` decides by whether the
function is a `TableFunctionImpl`. A user implementation of
`org.apache.calcite.schema.TableFunction` with a `ResultSet` parameter
therefore receives a metadata-only `ResultSet` during validation and a
`CursorInput` at execution, which can end in a `ClassCastException`. No test
takes the branch that passes a cursor to a non-`TableFunctionImpl` function.
Proposed solution: Decide the cursor's Java representation once, from the
declared parameter type, in a helper both places call; or reject CURSOR
arguments for other `TableFunction` implementations with a clear message. Add a
test with a custom `TableFunction` taking a cursor.
##########
core/src/main/java/org/apache/calcite/sql/validate/SqlUserDefinedTableMacro.java:
##########
@@ -108,7 +116,15 @@ public TranslatableTable getTable(SqlOperatorBinding
callBinding) {
Ord.forEach(function.getParameters(), (parameter, i) -> {
final RelDataType type = parameter.getType(typeFactory);
final Object value;
- if (callBinding.isOperandLiteral(i, true)) {
+ if (!failOnNonLiteral && type.getSqlTypeName() == SqlTypeName.CURSOR
+ && type instanceof RelDataTypeFactoryImpl.JavaType
+ && ((RelDataTypeFactoryImpl.JavaType) type).getJavaClass() ==
ResultSet.class) {
+ final RelDataType rowType =
+ requireNonNull(callBinding.getCursorOperand(i), "cursor row type");
+ value =
Review Comment:
**F9 minor, medium confidence** The validator now casts its type factory to
`JavaTypeFactory` unconditionally.
Problem: `callBinding.getTypeFactory()` is typed `RelDataTypeFactory`, and
`convertArguments` did not assume a `JavaTypeFactory` before. A validator built
on a plain `SqlTypeFactoryImpl` gets a `ClassCastException` here instead of a
validation result, because validation now calls a helper of the JDBC prepare
layer.
Proposed solution: Move the `RelDataType` to `ColumnMetaData` conversion
next to `CursorInputs` and make it take a `RelDataTypeFactory`, or check the
factory type before the cast.
##########
core/src/main/java/org/apache/calcite/sql/util/CursorInput.java:
##########
@@ -14,17 +14,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.calcite.avatica;
+package org.apache.calcite.sql.util;
-import org.checkerframework.checker.nullness.qual.*;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.rel.type.RelDataType;
-import java.sql.*;
+/** A cursor input with a known row type and supplied rows. */
Review Comment:
**F8 minor, medium confidence** `CursorInput` becomes public API in
`org.apache.calcite.sql.util` without `@Experimental`, and the helpers for
generated code are public with no marking.
Problem: `org.apache.calcite.sql.util` holds utilities for the SQL object
model (`SqlShuttle`, `SqlVisitor`, `SqlBuilder`), while `CursorInput` is a
run-time value whose factory `CursorInputs` is in `org.apache.calcite.runtime`.
User functions import it by this name from the first release, and its `rows()`
contract is Calcite's internal representation (DATE as `int` days, TIMESTAMP as
`long` milliseconds), so both are hard to change later. `CursorInputs.of`,
`resultSet`, `enumerable`, `metadataOnly`, and the new
`CalcitePrepareImpl.getColumnMetaDataList(JavaTypeFactory, RelDataType)` exist
for generated code but are public with no marking.
Proposed solution: Move `CursorInput` next to `CursorInputs` (or to
`org.apache.calcite.schema`) and mark it `@Experimental`; mark `CursorInputs`
and the new `getColumnMetaDataList` overload `@API(status =
API.Status.INTERNAL)`.
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
+ return resultSet(new AbstractEnumerable<Object[]>() {
+ @Override public Enumerator<Object[]> enumerator() {
+ throw new UnsupportedOperationException(
+ "Cursor rows are unavailable during type inference");
+ }
+ }, columns, TimeZone.getTimeZone("UTC"));
+ }
+
+ /** Wraps rows and prepared column metadata in a lazy, read-only,
+ * forward-only result set. Closing it closes the input enumerator. */
+ public static ResultSet resultSet(Enumerable<Object[]> input,
+ List<ColumnMetaData> columns, TimeZone timeZone) {
+ final Meta.Signature signature =
+ Meta.Signature.create(columns, "", Collections.emptyList(),
+ Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ try {
+ final AvaticaResultSet resultSet =
+ new AvaticaResultSet(null, null, signature,
+ new AvaticaResultSetMetaData(null, null, signature), timeZone,
null) {
+ @Override public int getType() {
+ return TYPE_FORWARD_ONLY;
+ }
+
+ @Override public int getConcurrency() {
+ return CONCUR_READ_ONLY;
+ }
+
+ @Override public int getHoldability() {
+ return CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override public int getFetchDirection() {
+ return FETCH_FORWARD;
+ }
+ };
+ return resultSet.execute2(
+ new ArrayEnumeratorCursor(new Enumerator<Object[]>() {
+ private @Nullable Enumerator<Object[]> rows;
+
+ @Override public Object[] current() {
+ return requireNonNull(rows, "rows").current();
+ }
+
+ @Override public boolean moveNext() {
+ if (rows == null) {
+ rows = input.enumerator();
+ }
+ return rows.moveNext();
+ }
+
+ @Override public void reset() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override public void close() {
+ if (rows != null) {
+ rows.close();
+ rows = null;
+ }
+ }
+ }), columns);
+ } catch (SQLException e) {
+ throw Util.throwAsRuntime(e);
+ }
+ }
+
+ /** Invokes a table function with fresh result set arguments for each
enumeration.
+ * Closes the arguments when the output is exhausted, closed, or fails. */
+ public static <T> Enumerable<T> enumerable(CursorInput[] inputs,
+ List<? extends List<ColumnMetaData>> columns, TimeZone timeZone,
+ Function1<ResultSet[], Enumerable<T>> function) {
+ return new AbstractEnumerable<T>() {
+ @Override public Enumerator<T> enumerator() {
+ final ResultSet[] resultSets = new ResultSet[inputs.length];
+ final Enumerator<T> output;
+ try {
+ for (int i = 0; i < inputs.length; i++) {
+ resultSets[i] = resultSet(inputs[i].rows(), columns.get(i),
timeZone);
+ }
+ output = function.apply(resultSets).enumerator();
+ } catch (RuntimeException | Error e) {
+ close(resultSets, e);
+ throw e;
+ }
+ return new Enumerator<T>() {
+ private boolean closed;
+
+ @Override public T current() {
+ try {
+ return output.current();
+ } catch (RuntimeException | Error e) {
+ closeOnFailure(e);
+ throw e;
+ }
+ }
+
+ @Override public boolean moveNext() {
Review Comment:
**F12 minor** No test covers the output enumerator throwing from
`moveNext()`.
Problem: The Javadoc of `CursorInputs.enumerable` says it closes the
arguments when the output fails. The only failure test throws from `current()`;
no test makes the output throw from `moveNext()`, which is where a function
that reads its `ResultSet` lazily (as `CursorTable` in `TableFunctionTest`
does) fails.
Proposed solution: Add a `CursorInputsTest` case whose output throws from
`moveNext()`, asserting that the exception propagates and every argument is
closed.
##########
core/src/main/java/org/apache/calcite/sql/util/CursorInput.java:
##########
@@ -14,17 +14,16 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.calcite.avatica;
+package org.apache.calcite.sql.util;
-import org.checkerframework.checker.nullness.qual.*;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.rel.type.RelDataType;
-import java.sql.*;
+/** A cursor input with a known row type and supplied rows. */
Review Comment:
**F10 minor** The `CursorInput` doc comment does not state the row layout,
re-enumeration, or who closes the enumerators.
Problem: "A cursor input with a known row type and supplied rows" restates
the method names, and "Calcite's internal representation" leaves the row layout
open. The reader is the author of an explicit `SqlFunction` table function, who
needs to know that the instance is the value of a `CURSOR(query)` argument,
that `rows()` yields one `Object[]` per row in `getRowType()` field order with
internal Java values, that it can be enumerated again, and who closes each
enumerator.
Proposed solution: State that contract in the interface comment, and link
`JavaRowFormat.ARRAY` for the layout.
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
+ return resultSet(new AbstractEnumerable<Object[]>() {
+ @Override public Enumerator<Object[]> enumerator() {
+ throw new UnsupportedOperationException(
+ "Cursor rows are unavailable during type inference");
+ }
+ }, columns, TimeZone.getTimeZone("UTC"));
+ }
+
+ /** Wraps rows and prepared column metadata in a lazy, read-only,
+ * forward-only result set. Closing it closes the input enumerator. */
+ public static ResultSet resultSet(Enumerable<Object[]> input,
+ List<ColumnMetaData> columns, TimeZone timeZone) {
+ final Meta.Signature signature =
+ Meta.Signature.create(columns, "", Collections.emptyList(),
+ Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ try {
+ final AvaticaResultSet resultSet =
+ new AvaticaResultSet(null, null, signature,
+ new AvaticaResultSetMetaData(null, null, signature), timeZone,
null) {
+ @Override public int getType() {
+ return TYPE_FORWARD_ONLY;
+ }
+
+ @Override public int getConcurrency() {
+ return CONCUR_READ_ONLY;
+ }
+
+ @Override public int getHoldability() {
+ return CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override public int getFetchDirection() {
+ return FETCH_FORWARD;
+ }
+ };
+ return resultSet.execute2(
+ new ArrayEnumeratorCursor(new Enumerator<Object[]>() {
+ private @Nullable Enumerator<Object[]> rows;
+
+ @Override public Object[] current() {
+ return requireNonNull(rows, "rows").current();
+ }
+
+ @Override public boolean moveNext() {
+ if (rows == null) {
+ rows = input.enumerator();
+ }
+ return rows.moveNext();
+ }
+
+ @Override public void reset() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override public void close() {
+ if (rows != null) {
+ rows.close();
+ rows = null;
+ }
+ }
+ }), columns);
+ } catch (SQLException e) {
+ throw Util.throwAsRuntime(e);
+ }
+ }
+
+ /** Invokes a table function with fresh result set arguments for each
enumeration.
+ * Closes the arguments when the output is exhausted, closed, or fails. */
+ public static <T> Enumerable<T> enumerable(CursorInput[] inputs,
+ List<? extends List<ColumnMetaData>> columns, TimeZone timeZone,
+ Function1<ResultSet[], Enumerable<T>> function) {
+ return new AbstractEnumerable<T>() {
+ @Override public Enumerator<T> enumerator() {
+ final ResultSet[] resultSets = new ResultSet[inputs.length];
+ final Enumerator<T> output;
+ try {
+ for (int i = 0; i < inputs.length; i++) {
+ resultSets[i] = resultSet(inputs[i].rows(), columns.get(i),
timeZone);
+ }
+ output = function.apply(resultSets).enumerator();
+ } catch (RuntimeException | Error e) {
+ close(resultSets, e);
+ throw e;
+ }
+ return new Enumerator<T>() {
+ private boolean closed;
+
+ @Override public T current() {
+ try {
+ return output.current();
+ } catch (RuntimeException | Error e) {
+ closeOnFailure(e);
+ throw e;
+ }
+ }
+
+ @Override public boolean moveNext() {
+ if (closed) {
+ return false;
+ }
+ try {
+ if (output.moveNext()) {
+ return true;
+ }
+ close();
+ return false;
+ } catch (RuntimeException | Error e) {
+ closeOnFailure(e);
+ throw e;
+ }
+ }
+
+ @Override public void reset() {
+ throw new UnsupportedOperationException("Cursor arguments cannot
be reset");
+ }
+
+ @Override public void close() {
Review Comment:
**F13 minor** No test checks that closing the cursor enumerator closes the
function's output enumerator.
Problem: Closing the enumerator from `CursorInputs.enumerable` must close
the function's output enumerator as well as the arguments. The tests count
closes of the input enumerators only, so no test fails if `output.close()` is
dropped, called twice, or skipped on an early close.
Proposed solution: Use an output enumerable that counts its `close()` calls
and assert one close on early close and one on exhaustion.
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
+ return resultSet(new AbstractEnumerable<Object[]>() {
+ @Override public Enumerator<Object[]> enumerator() {
+ throw new UnsupportedOperationException(
+ "Cursor rows are unavailable during type inference");
+ }
+ }, columns, TimeZone.getTimeZone("UTC"));
+ }
+
+ /** Wraps rows and prepared column metadata in a lazy, read-only,
+ * forward-only result set. Closing it closes the input enumerator. */
+ public static ResultSet resultSet(Enumerable<Object[]> input,
+ List<ColumnMetaData> columns, TimeZone timeZone) {
+ final Meta.Signature signature =
+ Meta.Signature.create(columns, "", Collections.emptyList(),
+ Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ try {
+ final AvaticaResultSet resultSet =
+ new AvaticaResultSet(null, null, signature,
+ new AvaticaResultSetMetaData(null, null, signature), timeZone,
null) {
+ @Override public int getType() {
+ return TYPE_FORWARD_ONLY;
+ }
+
+ @Override public int getConcurrency() {
+ return CONCUR_READ_ONLY;
+ }
+
+ @Override public int getHoldability() {
+ return CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override public int getFetchDirection() {
+ return FETCH_FORWARD;
+ }
+ };
+ return resultSet.execute2(
+ new ArrayEnumeratorCursor(new Enumerator<Object[]>() {
+ private @Nullable Enumerator<Object[]> rows;
+
+ @Override public Object[] current() {
+ return requireNonNull(rows, "rows").current();
+ }
+
+ @Override public boolean moveNext() {
+ if (rows == null) {
+ rows = input.enumerator();
+ }
+ return rows.moveNext();
+ }
+
+ @Override public void reset() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override public void close() {
+ if (rows != null) {
+ rows.close();
+ rows = null;
+ }
+ }
+ }), columns);
+ } catch (SQLException e) {
+ throw Util.throwAsRuntime(e);
+ }
+ }
+
+ /** Invokes a table function with fresh result set arguments for each
enumeration.
+ * Closes the arguments when the output is exhausted, closed, or fails. */
+ public static <T> Enumerable<T> enumerable(CursorInput[] inputs,
+ List<? extends List<ColumnMetaData>> columns, TimeZone timeZone,
+ Function1<ResultSet[], Enumerable<T>> function) {
+ return new AbstractEnumerable<T>() {
+ @Override public Enumerator<T> enumerator() {
+ final ResultSet[] resultSets = new ResultSet[inputs.length];
+ final Enumerator<T> output;
+ try {
+ for (int i = 0; i < inputs.length; i++) {
+ resultSets[i] = resultSet(inputs[i].rows(), columns.get(i),
timeZone);
+ }
+ output = function.apply(resultSets).enumerator();
+ } catch (RuntimeException | Error e) {
+ close(resultSets, e);
+ throw e;
+ }
+ return new Enumerator<T>() {
+ private boolean closed;
+
+ @Override public T current() {
+ try {
+ return output.current();
+ } catch (RuntimeException | Error e) {
+ closeOnFailure(e);
+ throw e;
+ }
+ }
+
+ @Override public boolean moveNext() {
+ if (closed) {
Review Comment:
**F15 minor** No test calls `moveNext()` after `close()`.
Problem: `moveNext()` returns `false` after `close()` instead of calling
into the closed output enumerator. No test calls `moveNext()` after `close()`.
Proposed solution: Close the enumerator before exhaustion and assert that
`moveNext()` returns `false`, with an output enumerator that fails if it is
touched after close.
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
+ return resultSet(new AbstractEnumerable<Object[]>() {
+ @Override public Enumerator<Object[]> enumerator() {
+ throw new UnsupportedOperationException(
+ "Cursor rows are unavailable during type inference");
+ }
+ }, columns, TimeZone.getTimeZone("UTC"));
+ }
+
+ /** Wraps rows and prepared column metadata in a lazy, read-only,
+ * forward-only result set. Closing it closes the input enumerator. */
+ public static ResultSet resultSet(Enumerable<Object[]> input,
+ List<ColumnMetaData> columns, TimeZone timeZone) {
+ final Meta.Signature signature =
+ Meta.Signature.create(columns, "", Collections.emptyList(),
+ Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ try {
+ final AvaticaResultSet resultSet =
+ new AvaticaResultSet(null, null, signature,
+ new AvaticaResultSetMetaData(null, null, signature), timeZone,
null) {
+ @Override public int getType() {
+ return TYPE_FORWARD_ONLY;
+ }
+
+ @Override public int getConcurrency() {
+ return CONCUR_READ_ONLY;
+ }
+
+ @Override public int getHoldability() {
Review Comment:
**F16 minor** `getHoldability()`, `getFetchDirection()`, and the two
`reset()` overrides have no test.
Problem: `resultSetTypesAndMetadata` asserts `getType()` and
`getConcurrency()` only, and no test calls `reset()` on either enumerator.
Proposed solution: Assert `getHoldability()` and `getFetchDirection()`
beside the existing checks and add an `assertThrows` on `reset()`, or drop the
overrides no caller relies on.
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
Review Comment:
**F5 minor** During validation, `next()` on the cursor `ResultSet` throws an
unchecked `UnsupportedOperationException` whose message gives no remedy, and
the contract is not documented.
Problem: `TableFunctionImpl` calls `eval` while deriving the row type, and a
function that reads rows there (`while (input.next())`, for example to build
the XML document from the use case in the description) fails to prepare. Its
`catch (SQLException e)` does not catch the error, because `next()` throws
`UnsupportedOperationException`. The message `Cursor rows are unavailable
during type inference` does not say what to change, and
`CursorInputs.metadataOnly` has no doc comment that states the two calls (one
at validation, one per enumeration) or that Calcite owns and closes the
`ResultSet`.
Proposed solution: Throw an `SQLException` whose text names the remedy, for
example: call only `getMetaData()` in the function and read rows when the
returned table is scanned. State the same contract in the doc comments of
`CursorInputs.metadataOnly` and `CursorInputs.of`.
##########
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScan.java:
##########
@@ -126,16 +134,51 @@ private Result defaultTableFunctionImplement(
final PhysType physType =
PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
false);
+ final List<Expression> cursors = new ArrayList<>();
+ for (int i = 0; i < getInputs().size(); i++) {
+ final EnumerableRel child = (EnumerableRel) getInputs().get(i);
+ final Result result = implementor.visitChild(this, i, child,
Prefer.ARRAY);
+ final Expression rows = bb.append("cursorRows", result.block);
+ cursors.add(
+ bb.append("cursor",
+ Expressions.call(CursorInputs.class, "of",
+ implementor.stash(child.getRowType(), RelDataType.class),
+ result.physType.convertTo(rows, JavaRowFormat.ARRAY))));
+ }
+ final boolean resultSetCursors = !cursors.isEmpty()
+ && ((RexCall) getCall()).getOperator() instanceof
SqlUserDefinedTableFunction
+ && ((SqlUserDefinedTableFunction) ((RexCall) getCall()).getOperator())
+ .getFunction() instanceof TableFunctionImpl;
+ final BlockBuilder callBuilder = resultSetCursors ? new BlockBuilder() :
bb;
+ final ParameterExpression resultSets =
Expressions.parameter(ResultSet[].class, "cursors");
RexToLixTranslator t =
RexToLixTranslator.forAggregation(
(JavaTypeFactory) getCluster().getTypeFactory(),
- bb, null, implementor.getConformance());
+ callBuilder, (list, index, storageType) -> resultSetCursors
+ ? Expressions.arrayIndex(resultSets,
Expressions.constant(index))
+ : cursors.get(index),
+ implementor.getConformance(),
implementor.getRexImplementorTable());
t = t.setCorrelates(implementor.allCorrelateVariables);
Expression expression = t.translate(getCall());
if (arrayRows && format == JavaRowFormat.SCALAR) {
expression = Expressions.call(BuiltInMethod.SLICE0.method, expression);
}
- bb.add(Expressions.return_(null, expression));
+ callBuilder.add(Expressions.return_(null, expression));
+ if (resultSetCursors) {
Review Comment:
**F18 minor, medium confidence** Temporal columns and a non-UTC time zone
are not tested through a `CURSOR(...)` query.
Problem: The scan passes the connection's time zone to
`CursorInputs.enumerable`, and Avatica uses it to convert DATE, TIME, and
TIMESTAMP values. The query-level tests use INTEGER and VARCHAR columns only,
and `CursorInputsTest` uses UTC only.
Proposed solution: Add a `TableFunctionTest` case with DATE and TIMESTAMP
columns in the cursor under a non-UTC `timeZone`, asserting that the function
reads the values the inner query returns.
##########
core/src/main/java/org/apache/calcite/sql/type/SqlTypeAssignmentRule.java:
##########
@@ -64,6 +64,9 @@ private SqlTypeAssignmentRule(
rules.add(interval, SqlTypeName.DAY_INTERVAL_TYPES);
}
+ // CURSOR is assignable from...
Review Comment:
**F17 minor, medium confidence** No test checks that invalid arguments to
CURSOR and `ResultSet` parameters are rejected.
Problem: The change adds a CURSOR-from-CURSOR rule to
`SqlTypeAssignmentRule` and lets `ResultSet` parameters accept cursors, but
every new test passes a valid cursor. `echo(1)` and a cursor passed to an
`INTEGER` parameter have no case, so a rule that admitted other types, or a
validator that crashed instead of reporting, would pass.
Proposed solution: Add one negative case per direction that asserts the
validation error.
##########
core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableTableFunctionScan.java:
##########
@@ -126,16 +134,51 @@ private Result defaultTableFunctionImplement(
final PhysType physType =
PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), format,
false);
+ final List<Expression> cursors = new ArrayList<>();
+ for (int i = 0; i < getInputs().size(); i++) {
+ final EnumerableRel child = (EnumerableRel) getInputs().get(i);
+ final Result result = implementor.visitChild(this, i, child,
Prefer.ARRAY);
+ final Expression rows = bb.append("cursorRows", result.block);
+ cursors.add(
+ bb.append("cursor",
+ Expressions.call(CursorInputs.class, "of",
+ implementor.stash(child.getRowType(), RelDataType.class),
+ result.physType.convertTo(rows, JavaRowFormat.ARRAY))));
+ }
+ final boolean resultSetCursors = !cursors.isEmpty()
Review Comment:
**F21 nit** The new `resultSetCursors` condition repeats the
`TableFunctionImpl` unwrapping that `isQueryable()` already does.
Problem: `isQueryable()` and the new `resultSetCursors` condition each
unwrap `SqlUserDefinedTableFunction` to `TableFunctionImpl` with their own
casts, and the new copy skips the `getCall() instanceof RexCall` check that
`isQueryable()` has.
Proposed solution: Extract one `@Nullable TableFunctionImpl
tableFunctionImpl()` helper and use it in both.
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
+ return resultSet(new AbstractEnumerable<Object[]>() {
+ @Override public Enumerator<Object[]> enumerator() {
+ throw new UnsupportedOperationException(
+ "Cursor rows are unavailable during type inference");
+ }
+ }, columns, TimeZone.getTimeZone("UTC"));
+ }
+
+ /** Wraps rows and prepared column metadata in a lazy, read-only,
+ * forward-only result set. Closing it closes the input enumerator. */
+ public static ResultSet resultSet(Enumerable<Object[]> input,
+ List<ColumnMetaData> columns, TimeZone timeZone) {
+ final Meta.Signature signature =
+ Meta.Signature.create(columns, "", Collections.emptyList(),
+ Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ try {
+ final AvaticaResultSet resultSet =
Review Comment:
**F22 nit** The four `ResultSet` property overrides have no comment
explaining them.
Problem: Avatica reports 0 for these properties when the statement is
`null`, which is why the overrides exist. Without a comment,
`CLOSE_CURSORS_AT_COMMIT` reads as a claim about transactions, and the
overrides look safe to remove.
Proposed solution: Add one line above them, for example `// With no
statement, AvaticaResultSet reports 0 for these properties.`
##########
core/src/main/java/org/apache/calcite/runtime/CursorInputs.java:
##########
@@ -0,0 +1,222 @@
+/*
+ * 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.calcite.runtime;
+
+import org.apache.calcite.avatica.AvaticaResultSet;
+import org.apache.calcite.avatica.AvaticaResultSetMetaData;
+import org.apache.calcite.avatica.ColumnMetaData;
+import org.apache.calcite.avatica.Meta;
+import org.apache.calcite.linq4j.AbstractEnumerable;
+import org.apache.calcite.linq4j.Enumerable;
+import org.apache.calcite.linq4j.Enumerator;
+import org.apache.calcite.linq4j.function.Function1;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.sql.util.CursorInput;
+import org.apache.calcite.util.Util;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.Collections;
+import java.util.List;
+import java.util.TimeZone;
+
+import static java.util.Objects.requireNonNull;
+
+/** Utilities for working with {@link CursorInput}. */
+public final class CursorInputs {
+ private CursorInputs() {
+ }
+
+ public static CursorInput of(RelDataType rowType, Enumerable<Object[]> rows)
{
+ return new CursorInput() {
+ @Override public RelDataType getRowType() {
+ return rowType;
+ }
+
+ @Override public Enumerable<Object[]> rows() {
+ return rows;
+ }
+ };
+ }
+
+ public static ResultSet metadataOnly(List<ColumnMetaData> columns) {
+ return resultSet(new AbstractEnumerable<Object[]>() {
+ @Override public Enumerator<Object[]> enumerator() {
+ throw new UnsupportedOperationException(
+ "Cursor rows are unavailable during type inference");
+ }
+ }, columns, TimeZone.getTimeZone("UTC"));
+ }
+
+ /** Wraps rows and prepared column metadata in a lazy, read-only,
+ * forward-only result set. Closing it closes the input enumerator. */
+ public static ResultSet resultSet(Enumerable<Object[]> input,
+ List<ColumnMetaData> columns, TimeZone timeZone) {
+ final Meta.Signature signature =
+ Meta.Signature.create(columns, "", Collections.emptyList(),
+ Meta.CursorFactory.ARRAY, Meta.StatementType.SELECT);
+ try {
+ final AvaticaResultSet resultSet =
+ new AvaticaResultSet(null, null, signature,
+ new AvaticaResultSetMetaData(null, null, signature), timeZone,
null) {
+ @Override public int getType() {
+ return TYPE_FORWARD_ONLY;
+ }
+
+ @Override public int getConcurrency() {
+ return CONCUR_READ_ONLY;
+ }
+
+ @Override public int getHoldability() {
+ return CLOSE_CURSORS_AT_COMMIT;
+ }
+
+ @Override public int getFetchDirection() {
+ return FETCH_FORWARD;
+ }
+ };
+ return resultSet.execute2(
+ new ArrayEnumeratorCursor(new Enumerator<Object[]>() {
+ private @Nullable Enumerator<Object[]> rows;
+
+ @Override public Object[] current() {
+ return requireNonNull(rows, "rows").current();
+ }
+
+ @Override public boolean moveNext() {
+ if (rows == null) {
+ rows = input.enumerator();
+ }
+ return rows.moveNext();
+ }
+
+ @Override public void reset() {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override public void close() {
+ if (rows != null) {
+ rows.close();
+ rows = null;
+ }
+ }
+ }), columns);
+ } catch (SQLException e) {
+ throw Util.throwAsRuntime(e);
+ }
+ }
+
+ /** Invokes a table function with fresh result set arguments for each
enumeration.
+ * Closes the arguments when the output is exhausted, closed, or fails. */
+ public static <T> Enumerable<T> enumerable(CursorInput[] inputs,
+ List<? extends List<ColumnMetaData>> columns, TimeZone timeZone,
+ Function1<ResultSet[], Enumerable<T>> function) {
+ return new AbstractEnumerable<T>() {
+ @Override public Enumerator<T> enumerator() {
+ final ResultSet[] resultSets = new ResultSet[inputs.length];
+ final Enumerator<T> output;
+ try {
+ for (int i = 0; i < inputs.length; i++) {
+ resultSets[i] = resultSet(inputs[i].rows(), columns.get(i),
timeZone);
+ }
+ output = function.apply(resultSets).enumerator();
+ } catch (RuntimeException | Error e) {
+ close(resultSets, e);
+ throw e;
+ }
+ return new Enumerator<T>() {
+ private boolean closed;
+
+ @Override public T current() {
+ try {
+ return output.current();
+ } catch (RuntimeException | Error e) {
+ closeOnFailure(e);
+ throw e;
+ }
+ }
+
+ @Override public boolean moveNext() {
+ if (closed) {
+ return false;
+ }
+ try {
+ if (output.moveNext()) {
+ return true;
+ }
+ close();
+ return false;
+ } catch (RuntimeException | Error e) {
+ closeOnFailure(e);
+ throw e;
+ }
+ }
+
+ @Override public void reset() {
+ throw new UnsupportedOperationException("Cursor arguments cannot
be reset");
+ }
+
+ @Override public void close() {
+ if (!closed) {
+ closed = true;
+ Throwable failure = null;
+ try {
+ output.close();
+ } catch (RuntimeException | Error e) {
+ failure = e;
+ throw e;
+ } finally {
+ CursorInputs.close(resultSets, failure);
+ }
+ }
+ }
+
+ private void closeOnFailure(Throwable failure) {
+ try {
+ close();
+ } catch (RuntimeException | Error e) {
+ failure.addSuppressed(e);
+ }
+ }
+ };
+ }
+ };
+ }
+
Review Comment:
**F14 minor** No test covers an argument whose `close()` throws.
Problem: `CursorInputs.close(ResultSet[], Throwable)` rethrows the first
close failure and attaches later ones as suppressed, or attaches them to the
function's failure. No test makes an argument's `close()` throw, so none of
these three cases is checked.
Proposed solution: Let the `tracking()` helper build an input whose
`close()` throws, and assert the thrown and suppressed exceptions with two such
inputs, with and without a failing function.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]