Java Code Examples for org.apache.calcite.sql.SqlCall#getOperandList()

The following examples show how to use org.apache.calcite.sql.SqlCall#getOperandList() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override public SqlNode visit(SqlCall call) {
	SqlKind kind = call.getKind();
	if (isLogicalNavigation(kind)
		|| isAggregation(kind)
		|| isRunningOrFinal(kind)) {
		return call;
	}

	switch (kind) {
		case PREV:
			final List<SqlNode> operands = call.getOperandList();
			if (operands.get(0) instanceof SqlIdentifier) {
				String name = ((SqlIdentifier) operands.get(0)).names.get(0);
				return name.equals(alpha) ? call
					: SqlStdOperatorTable.LAST.createCall(SqlParserPos.ZERO, operands);
			}
	}
	return super.visit(call);
}
 
Example 2
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
public RexNode convertFunction(
    SqlRexContext cx,
    SqlFunction fun,
    SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = convertExpressionList(cx, operands,
      SqlOperandTypeChecker.Consistency.NONE);
  if (fun.getFunctionType() == SqlFunctionCategory.USER_DEFINED_CONSTRUCTOR) {
    return makeConstructorCall(cx, fun, exprs);
  }
  RelDataType returnType =
      cx.getValidator().getValidatedNodeTypeIfKnown(call);
  if (returnType == null) {
    returnType = cx.getRexBuilder().deriveReturnType(fun, exprs);
  }
  return cx.getRexBuilder().makeCall(returnType, fun, exprs);
}
 
Example 3
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a ROW.
 *
 * <p>Called automatically via reflection.
 */
public RexNode convertRow(
    SqlRexContext cx,
    SqlRowOperator op,
    SqlCall call) {
  if (cx.getValidator().getValidatedNodeType(call).getSqlTypeName()
      != SqlTypeName.COLUMN_LIST) {
    return convertCall(cx, call);
  }
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final List<RexNode> columns = new ArrayList<>();
  for (SqlNode operand : call.getOperandList()) {
    columns.add(
        rexBuilder.makeLiteral(
            ((SqlIdentifier) operand).getSimple()));
  }
  final RelDataType type =
      rexBuilder.deriveReturnType(SqlStdOperatorTable.COLUMN_LIST, columns);
  return rexBuilder.makeCall(type, SqlStdOperatorTable.COLUMN_LIST, columns);
}
 
Example 4
Source File: SqlLiteralChainOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  // per the SQL std, each string fragment must be on a different line
  final List<SqlNode> operandList = call.getOperandList();
  for (int i = 1; i < operandList.size(); i++) {
    SqlParserPos prevPos = operandList.get(i - 1).getParserPosition();
    final SqlNode operand = operandList.get(i);
    SqlParserPos pos = operand.getParserPosition();
    if (pos.getLineNum() <= prevPos.getLineNum()) {
      throw validator.newValidationError(operand,
          RESOURCE.stringFragsOnSameLine());
    }
  }
}
 
Example 5
Source File: SqlTypeUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Recreates a given RelDataType with nullability iff any of the operands
 * of a call are nullable.
 */
public static RelDataType makeNullableIfOperandsAre(
    final SqlValidator validator,
    final SqlValidatorScope scope,
    final SqlCall call,
    RelDataType type) {
  for (SqlNode operand : call.getOperandList()) {
    RelDataType operandType = validator.deriveType(scope, operand);

    if (containsNullable(operandType)) {
      RelDataTypeFactory typeFactory = validator.getTypeFactory();
      type = typeFactory.createTypeWithNullability(type, true);
      break;
    }
  }
  return type;
}
 
Example 6
Source File: SqlRollupOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
private static void unparseCube(SqlWriter writer, SqlCall call) {
  writer.keyword(call.getOperator().getName());
  final SqlWriter.Frame frame =
      writer.startList(SqlWriter.FrameTypeEnum.FUN_CALL, "(", ")");
  for (SqlNode operand : call.getOperandList()) {
    writer.sep(",");
    if (operand.getKind() == SqlKind.ROW) {
      final SqlWriter.Frame frame2 =
          writer.startList(SqlWriter.FrameTypeEnum.SIMPLE, "(", ")");
      for (SqlNode operand2 : ((SqlCall) operand).getOperandList()) {
        writer.sep(",");
        operand2.unparse(writer, 0, 0);
      }
      writer.endList(frame2);
    } else if (operand instanceof SqlNodeList
        && ((SqlNodeList) operand).size() == 0) {
      writer.keyword("()");
    } else {
      operand.unparse(writer, 0, 0);
    }
  }
  writer.endList(frame);
}
 
Example 7
Source File: SqlTypeUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Recreates a given RelDataType with nullability iff any of the operands
 * of a call are nullable.
 */
public static RelDataType makeNullableIfOperandsAre(
    final SqlValidator validator,
    final SqlValidatorScope scope,
    final SqlCall call,
    RelDataType type) {
  for (SqlNode operand : call.getOperandList()) {
    RelDataType operandType = validator.deriveType(scope, operand);

    if (containsNullable(operandType)) {
      RelDataTypeFactory typeFactory = validator.getTypeFactory();
      type = typeFactory.createTypeWithNullability(type, true);
      break;
    }
  }
  return type;
}
 
Example 8
Source File: FlattenConvertlet.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  SqlFlattenOperator operator = (SqlFlattenOperator) call.getOperator();
  final List<RexNode> exprs = new LinkedList<>();

  for (SqlNode node : call.getOperandList()) {
    exprs.add(cx.convertExpression(node));
  }

  SqlFlattenOperator indexedOperator = operator.withIndex(((SqlValidatorImpl)cx.getValidator()).nextFlattenIndex());
  final RexBuilder rexBuilder = cx.getRexBuilder();
  // Since we don't have any way of knowing if the output of the flatten is nullable, we should always assume it is.
  // This is especially important when accelerating a count(column) query, because the normalizer will convert it to
  // a count(1) if it thinks this column is non-nullable, and then remove the flatten altogether. This is actually a
  // problem with the fact that flatten is not really a project operator (because it can output more than one row per input).
  RelDataType type = rexBuilder
    .getTypeFactory()
    .createTypeWithNullability(
      rexBuilder
        .getTypeFactory()
        .createSqlType(SqlTypeName.ANY),
      true
    );
  return rexBuilder.makeCall(type, indexedOperator, exprs);

}
 
Example 9
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RexNode convertAggregateFunction(
    SqlRexContext cx,
    SqlAggFunction fun,
    SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs;
  if (call.isCountStar()) {
    exprs = ImmutableList.of();
  } else {
    exprs = convertExpressionList(cx, operands,
        SqlOperandTypeChecker.Consistency.NONE);
  }
  RelDataType returnType =
      cx.getValidator().getValidatedNodeTypeIfKnown(call);
  final int groupCount = cx.getGroupCount();
  if (returnType == null) {
    RexCallBinding binding =
        new RexCallBinding(cx.getTypeFactory(), fun, exprs,
            ImmutableList.of()) {
          @Override public int getGroupCount() {
            return groupCount;
          }
        };
    returnType = fun.inferReturnType(binding);
  }
  return cx.getRexBuilder().makeCall(returnType, fun, exprs);
}
 
Example 10
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexNode convertDatetimeMinus(
    SqlRexContext cx,
    SqlDatetimeSubtractionOperator op,
    SqlCall call) {
  // Rewrite datetime minus
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = convertExpressionList(cx, operands,
      SqlOperandTypeChecker.Consistency.NONE);

  final RelDataType resType =
      cx.getValidator().getValidatedNodeType(call);
  return rexBuilder.makeCall(resType, op, exprs.subList(0, 2));
}
 
Example 11
Source File: DrillExtractConvertlet.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final List<SqlNode> operands = call.getOperandList();
  final List<RexNode> exprs = new LinkedList<>();

  String timeUnit = ((SqlIntervalQualifier) operands.get(0)).timeUnitRange.toString();

  RelDataTypeFactory typeFactory = cx.getTypeFactory();

  //RelDataType nullableReturnType =

  for (SqlNode node: operands) {
     exprs.add(cx.convertExpression(node));
  }

  final RelDataType returnType;
  if(call.getOperator() == SqlStdOperatorTable.EXTRACT) {
    // Legacy code:
    // The return type is wrong!
    // Legacy code choose SqlTypeName.BIGINT simply to avoid conflicting against Calcite's inference mechanism
    // (, which chose BIGINT in validation phase already)
    // Determine NULL-able using 2nd argument's Null-able.
    returnType = typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT), exprs.get(1).getType().isNullable());
  } else {
    // Determine NULL-able using 2nd argument's Null-able.
    returnType = typeFactory.createTypeWithNullability(
        typeFactory.createSqlType(
            TypeInferenceUtils.getSqlTypeNameForTimeUnit(timeUnit)),
        exprs.get(1).getType().isNullable());
  }

  return rexBuilder.makeCall(returnType, call.getOperator(), exprs);
}
 
Example 12
Source File: SqlShuttle.java    From Bats with Apache License 2.0 5 votes vote down vote up
public CallCopyingArgHandler(SqlCall call, boolean alwaysCopy) {
  this.call = call;
  this.update = false;
  final List<SqlNode> operands = call.getOperandList();
  this.clonedOperands = operands.toArray(new SqlNode[0]);
  this.alwaysCopy = alwaysCopy;
}
 
Example 13
Source File: SqlTranslate3Function.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call, int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startFunCall("TRANSLATE");
  for (SqlNode sqlNode : call.getOperandList()) {
    writer.sep(",");
    sqlNode.unparse(writer, leftPrec, rightPrec);
  }
  writer.endFunCall(frame);
}
 
Example 14
Source File: SqlDatePartFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  final SqlParserPos pos = call.getParserPosition();
  return SqlStdOperatorTable.EXTRACT.createCall(pos,
      new SqlIntervalQualifier(timeUnit, null, SqlParserPos.ZERO),
      operands.get(0));
}
 
Example 15
Source File: SqlJsonArrayAggAggFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType deriveType(SqlValidator validator,
    SqlValidatorScope scope, SqlCall call) {
  // To prevent operator rewriting by SqlFunction#deriveType.
  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    ((SqlValidatorImpl) validator).setValidatedNodeType(operand, nodeType);
  }
  return validateOperands(validator, scope, call);
}
 
Example 16
Source File: SqlMultisetValueConstructor.java    From Bats with Apache License 2.0 5 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  writer.keyword(getName()); // "MULTISET" or "ARRAY"
  final SqlWriter.Frame frame = writer.startList("[", "]");
  for (SqlNode operand : call.getOperandList()) {
    writer.sep(",");
    operand.unparse(writer, leftPrec, rightPrec);
  }
  writer.endList(frame);
}
 
Example 17
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public void validateAggregateParams(SqlCall aggCall, SqlNode filter,
	SqlValidatorScope scope) {
	// For "agg(expr)", expr cannot itself contain aggregate function
	// invocations.  For example, "SUM(2 * MAX(x))" is illegal; when
	// we see it, we'll report the error for the SUM (not the MAX).
	// For more than one level of nesting, the error which results
	// depends on the traversal order for validation.
	//
	// For a windowed aggregate "agg(expr)", expr can contain an aggregate
	// function. For example,
	//   SELECT AVG(2 * MAX(x)) OVER (PARTITION BY y)
	//   FROM t
	//   GROUP BY y
	// is legal. Only one level of nesting is allowed since non-windowed
	// aggregates cannot nest aggregates.

	// Store nesting level of each aggregate. If an aggregate is found at an invalid
	// nesting level, throw an assert.
	final AggFinder a;
	if (inWindow) {
		a = overFinder;
	} else {
		a = aggOrOverFinder;
	}

	for (SqlNode param : aggCall.getOperandList()) {
		if (a.findAgg(param) != null) {
			throw newValidationError(aggCall, RESOURCE.nestedAggIllegal());
		}
	}
	if (filter != null) {
		if (a.findAgg(filter) != null) {
			throw newValidationError(filter, RESOURCE.aggregateInFilterIllegal());
		}
	}
}
 
Example 18
Source File: SqlJsonArrayAggAggFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType deriveType(SqlValidator validator,
    SqlValidatorScope scope, SqlCall call) {
  // To prevent operator rewriting by SqlFunction#deriveType.
  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    ((SqlValidatorImpl) validator).setValidatedNodeType(operand, nodeType);
  }
  return validateOperands(validator, scope, call);
}
 
Example 19
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override public Set<String> visit(SqlCall call) {
	boolean isSingle = false;
	Set<String> vars = new HashSet<>();
	SqlKind kind = call.getKind();
	List<SqlNode> operands = call.getOperandList();

	if (isSingleVarRequired(kind)) {
		isSingle = true;
		if (isPhysicalNavigation(kind)) {
			if (isMeasure) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionInMeasure(call.toString()));
			}
			if (firstLastCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionOrder(call.toString()));
			}
			prevNextCount++;
		} else if (isLogicalNavigation(kind)) {
			if (firstLastCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternPrevFunctionOrder(call.toString()));
			}
			firstLastCount++;
		} else if (isAggregation(kind)) {
			// cannot apply aggregation in PREV/NEXT, FIRST/LAST
			if (firstLastCount != 0 || prevNextCount != 0) {
				throw newValidationError(call,
					Static.RESOURCE.patternAggregationInNavigation(call.toString()));
			}
			if (kind == SqlKind.COUNT && call.getOperandList().size() > 1) {
				throw newValidationError(call,
					Static.RESOURCE.patternCountFunctionArg());
			}
			aggregateCount++;
		}
	}

	if (isRunningOrFinal(kind) && !isMeasure) {
		throw newValidationError(call,
			Static.RESOURCE.patternRunningFunctionInDefine(call.toString()));
	}

	for (SqlNode node : operands) {
		if (node != null) {
			vars.addAll(
				node.accept(
					new PatternValidator(isMeasure, firstLastCount, prevNextCount,
						aggregateCount)));
		}
	}

	if (isSingle) {
		switch (kind) {
			case COUNT:
				if (vars.size() > 1) {
					throw newValidationError(call,
						Static.RESOURCE.patternCountFunctionArg());
				}
				break;
			default:
				if (operands.size() == 0
					|| !(operands.get(0) instanceof SqlCall)
					|| ((SqlCall) operands.get(0)).getOperator() != SqlStdOperatorTable.CLASSIFIER) {
					if (vars.isEmpty()) {
						throw newValidationError(call,
							Static.RESOURCE.patternFunctionNullCheck(call.toString()));
					}
					if (vars.size() != 1) {
						throw newValidationError(call,
							Static.RESOURCE.patternFunctionVariableCheck(call.toString()));
					}
				}
				break;
		}
	}
	return vars;
}
 
Example 20
Source File: SqlStdOperatorTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Creates a copy of a call with a new operator. */
private static SqlCall copy(SqlCall call, SqlOperator operator) {
  final List<SqlNode> list = call.getOperandList();
  return new SqlBasicCall(operator, list.toArray(new SqlNode[0]),
      call.getParserPosition());
}