Java Code Examples for org.apache.calcite.sql.SqlCall

The following examples show how to use org.apache.calcite.sql.SqlCall. These examples are extracted from open source projects. 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 Project: Bats   Source File: OracleSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    SqlUtil.unparseFunctionSyntax(OracleSqlOperatorTable.SUBSTR, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 2
Source Project: Bats   Source File: SqlStdOperatorTable.java    License: Apache License 2.0 6 votes vote down vote up
/** Converts a call to a grouped window function to a call to its auxiliary
 * window function(s). For other calls returns null.
 *
 * <p>For example, converts {@code TUMBLE_START(rowtime, INTERVAL '1' HOUR))}
 * to {@code TUMBLE(rowtime, INTERVAL '1' HOUR))}. */
public static List<Pair<SqlNode, AuxiliaryConverter>> convertGroupToAuxiliaryCalls(
    SqlCall call) {
  final SqlOperator op = call.getOperator();
  if (op instanceof SqlGroupedWindowFunction
      && op.isGroup()) {
    ImmutableList.Builder<Pair<SqlNode, AuxiliaryConverter>> builder =
        ImmutableList.builder();
    for (final SqlGroupedWindowFunction f
        : ((SqlGroupedWindowFunction) op).getAuxiliaryFunctions()) {
      builder.add(
          Pair.of(copy(call, f),
              new AuxiliaryConverter.Impl(f)));
    }
    return builder.build();
  }
  return ImmutableList.of();
}
 
Example 3
Source Project: dremio-oss   Source File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean hasNestedAggregations(LogicalAggregate rel) {
  List<AggregateCall> aggCallList = rel.getAggCallList();
  HashSet<Integer> aggregatesArgs = new HashSet<>();
  for (AggregateCall aggregateCall : aggCallList) {
    aggregatesArgs.addAll(aggregateCall.getArgList());
  }
  for (Integer aggregatesArg : aggregatesArgs) {
    SqlNode selectNode = ((SqlSelect) node).getSelectList().get(aggregatesArg);
    if (!(selectNode instanceof SqlBasicCall)) {
      continue;
    }
    for (SqlNode operand : ((SqlBasicCall) selectNode).getOperands()) {
      if (operand instanceof SqlCall) {
        final SqlOperator operator = ((SqlCall) operand).getOperator();
        if (operator instanceof SqlAggFunction) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example 4
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validates an expression.
 *
 * @param expr  Expression
 * @param scope Scope in which expression occurs
 */
private void validateExpr(SqlNode expr, SqlValidatorScope scope) {
	if (expr instanceof SqlCall) {
		final SqlOperator op = ((SqlCall) expr).getOperator();
		if (op.isAggregator() && op.requiresOver()) {
			throw newValidationError(expr,
				RESOURCE.absentOverClause());
		}
	}

	// Call on the expression to validate itself.
	expr.validateExpr(this, scope);

	// Perform any validation specific to the scope. For example, an
	// aggregating scope requires that expressions are valid aggregations.
	scope.validateExpr(expr);
}
 
Example 5
Source Project: dremio-oss   Source File: FlattenConvertlet.java    License: 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 6
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 6 votes vote down vote up
/** Converts a {@link SqlCall} to a {@link RexCall} with a perhaps different
 * operator. */
private RexNode convertCall(
    SqlRexContext cx,
    SqlCall call,
    SqlOperator op) {
  final List<SqlNode> operands = call.getOperandList();
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlOperandTypeChecker.Consistency consistency =
      op.getOperandTypeChecker() == null
          ? SqlOperandTypeChecker.Consistency.NONE
          : op.getOperandTypeChecker().getConsistency();
  final List<RexNode> exprs =
      convertExpressionList(cx, operands, consistency);
  RelDataType type = rexBuilder.deriveReturnType(op, exprs);
  return rexBuilder.makeCall(type, op, RexUtil.flatten(exprs, op));
}
 
Example 7
Source Project: Bats   Source File: SelectScope.java    License: Apache License 2.0 6 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlNode expr) {
  SqlMonotonicity monotonicity = expr.getMonotonicity(this);
  if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
    return monotonicity;
  }

  // TODO: compare fully qualified names
  final SqlNodeList orderList = getOrderList();
  if (orderList.size() > 0) {
    SqlNode order0 = orderList.get(0);
    monotonicity = SqlMonotonicity.INCREASING;
    if ((order0 instanceof SqlCall)
        && (((SqlCall) order0).getOperator()
        == SqlStdOperatorTable.DESC)) {
      monotonicity = monotonicity.reverse();
      order0 = ((SqlCall) order0).operand(0);
    }
    if (expr.equalsDeep(order0, Litmus.IGNORE)) {
      return monotonicity;
    }
  }

  return SqlMonotonicity.NOT_MONOTONIC;
}
 
Example 8
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable public SqlCall makeNullaryCall(SqlIdentifier id) {
	if (id.names.size() == 1 && !id.isComponentQuoted(0)) {
		final List<SqlOperator> list = new ArrayList<>();
		opTab.lookupOperatorOverloads(id, null, SqlSyntax.FUNCTION, list,
				catalogReader.nameMatcher());
		for (SqlOperator operator : list) {
			if (operator.getSyntax() == SqlSyntax.FUNCTION_ID) {
				// Even though this looks like an identifier, it is a
				// actually a call to a function. Construct a fake
				// call to this function, so we can use the regular
				// operator validation.
				return new SqlBasicCall(operator, SqlNode.EMPTY_ARRAY,
						id.getParserPosition(), true, null);
			}
		}
	}
	return null;
}
 
Example 9
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void checkRollUp(SqlNode grandParent, SqlNode parent,
	SqlNode current, SqlValidatorScope scope, String optionalClause) {
	current = stripAs(current);
	if (current instanceof SqlCall && !(current instanceof SqlSelect)) {
		// Validate OVER separately
		checkRollUpInWindow(getWindowInOver(current), scope);
		current = stripOver(current);

		List<SqlNode> children = ((SqlCall) stripDot(current)).getOperandList();
		for (SqlNode child : children) {
			checkRollUp(parent, current, child, scope, optionalClause);
		}
	} else if (current instanceof SqlIdentifier) {
		SqlIdentifier id = (SqlIdentifier) current;
		if (!id.isStar() && isRolledUpColumn(id, scope)) {
			if (!isAggregation(parent.getKind())
				|| !isRolledUpColumnAllowedInAgg(id, scope, (SqlCall) parent, grandParent)) {
				String context = optionalClause != null ? optionalClause : parent.getKind().toString();
				throw newValidationError(id,
					RESOURCE.rolledUpNotAllowed(deriveAlias(id, 0), context));
			}
		}
	}
}
 
Example 10
Source Project: calcite   Source File: SqlSubstringFunction.java    License: Apache License 2.0 6 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startFunCall(getName());
  call.operand(0).unparse(writer, leftPrec, rightPrec);
  writer.sep("FROM");
  call.operand(1).unparse(writer, leftPrec, rightPrec);

  if (3 == call.operandCount()) {
    writer.sep("FOR");
    call.operand(2).unparse(writer, leftPrec, rightPrec);
  }

  writer.endFunCall(frame);
}
 
Example 11
Source Project: dremio-oss   Source File: DremioSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
  // Translate the PI function call to PI()
  if (call.getOperator() == SqlStdOperatorTable.PI) {
    super.unparseCall(
      writer,
      PI_FUNCTION.createCall(new SqlNodeList(call.getOperandList(), SqlParserPos.ZERO)),
      leftPrec, rightPrec);
  } else if (call.getOperator().equals(FunctionRegistry.E_FUNCTION)) {
    // Translate the E() function call to EXP(1)
    final SqlCall newCall = SqlStdOperatorTable.EXP.createCall(
      SqlParserPos.ZERO, SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO));
    super.unparseCall(writer, newCall, leftPrec, rightPrec);
  } else if (call.getKind() == SqlKind.JOIN) {
    this.unparseJoin(writer, (SqlJoin) call, leftPrec, rightPrec);
  } else {
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example 12
Source Project: calcite   Source File: ServerDdlExecutor.java    License: Apache License 2.0 6 votes vote down vote up
/** Wraps a query to rename its columns. Used by CREATE VIEW and CREATE
 * MATERIALIZED VIEW. */
static SqlNode renameColumns(SqlNodeList columnList, SqlNode query) {
  if (columnList == null) {
    return query;
  }
  final SqlParserPos p = query.getParserPosition();
  final SqlNodeList selectList = SqlNodeList.SINGLETON_STAR;
  final SqlCall from =
      SqlStdOperatorTable.AS.createCall(p,
          ImmutableList.<SqlNode>builder()
              .add(query)
              .add(new SqlIdentifier("_", p))
              .addAll(columnList)
              .build());
  return new SqlSelect(p, null, selectList, from, null, null, null, null,
      null, null, null, null);
}
 
Example 13
Source Project: Bats   Source File: MssqlSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    if (call.operandCount() != 3) {
      throw new IllegalArgumentException("MSSQL SUBSTRING requires FROM and FOR arguments");
    }
    SqlUtil.unparseFunctionSyntax(MSSQL_SUBSTRING, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }
      unparseFloor(writer, call);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 14
Source Project: calcite   Source File: SqlJsonValueFunction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns new operand list with type specification removed.
 */
public static List<SqlNode> removeTypeSpecOperands(SqlCall call) {
  SqlNode[] operands = call.getOperandList().toArray(SqlNode.EMPTY_ARRAY);
  if (hasExplicitTypeSpec(operands)) {
    operands[2] = null;
    operands[3] = null;
  }
  return Arrays.stream(operands)
      .filter(Objects::nonNull)
      .collect(Collectors.toList());
}
 
Example 15
Source Project: calcite   Source File: SqlCastFunction.java    License: Apache License 2.0 5 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  assert call.operandCount() == 2;
  final SqlWriter.Frame frame = writer.startFunCall(getName());
  call.operand(0).unparse(writer, 0, 0);
  writer.sep("AS");
  if (call.operand(1) instanceof SqlIntervalQualifier) {
    writer.sep("INTERVAL");
  }
  call.operand(1).unparse(writer, 0, 0);
  writer.endFunCall(frame);
}
 
Example 16
Source Project: Bats   Source File: SqlJsonArrayAggAggFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call, int leftPrec,
    int rightPrec) {
  assert call.operandCount() == 1;
  final SqlWriter.Frame frame = writer.startFunCall("JSON_ARRAYAGG");
  call.operand(0).unparse(writer, leftPrec, rightPrec);
  writer.keyword(nullClause.sql);
  writer.endFunCall(frame);
}
 
Example 17
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns null if there is no common type. E.g. if the rows have a
 * different number of columns.
 */
RelDataType getTableConstructorRowType(
	SqlCall values,
	SqlValidatorScope scope) {
	final List<SqlNode> rows = values.getOperandList();
	assert rows.size() >= 1;
	final List<RelDataType> rowTypes = new ArrayList<>();
	for (final SqlNode row : rows) {
		assert row.getKind() == SqlKind.ROW;
		SqlCall rowConstructor = (SqlCall) row;

		// REVIEW jvs 10-Sept-2003: Once we support single-row queries as
		// rows, need to infer aliases from there.
		final List<String> aliasList = new ArrayList<>();
		final List<RelDataType> typeList = new ArrayList<>();
		for (Ord<SqlNode> column : Ord.zip(rowConstructor.getOperandList())) {
			final String alias = deriveAlias(column.e, column.i);
			aliasList.add(alias);
			final RelDataType type = deriveType(scope, column.e);
			typeList.add(type);
		}
		rowTypes.add(typeFactory.createStructType(typeList, aliasList));
	}
	if (rows.size() == 1) {
		// TODO jvs 10-Oct-2005:  get rid of this workaround once
		// leastRestrictive can handle all cases
		return rowTypes.get(0);
	}
	return typeFactory.leastRestrictive(rowTypes);
}
 
Example 18
Source Project: calcite   Source File: StandardConvertletTable.java    License: 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 19
Source Project: Bats   Source File: SqlNodeToRexConverterImpl.java    License: Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  final SqlRexConvertlet convertlet = convertletTable.get(call);
  if (convertlet != null) {
    return convertlet.convertCall(cx, call);
  }

  // No convertlet was suitable. (Unlikely, because the standard
  // convertlet table has a fall-back for all possible calls.)
  throw Util.needToImplement(call);
}
 
Example 20
Source Project: flink   Source File: ProcedureNamespace.java    License: Apache License 2.0 5 votes vote down vote up
ProcedureNamespace(
	SqlValidatorImpl validator,
	SqlValidatorScope scope,
	SqlCall call,
	SqlNode enclosingNode) {
	super(validator, enclosingNode);
	this.scope = scope;
	this.call = call;
}
 
Example 21
Source Project: calcite   Source File: SqlCaseOperator.java    License: Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Do not try to derive the types of the operands. We will do that
  // later, top down.
  return validateOperands(validator, scope, call);
}
 
Example 22
Source Project: calcite   Source File: SqlOverlapsOperator.java    License: 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.startList(SqlWriter.FrameTypeEnum.SIMPLE);
  arg(writer, call, leftPrec, rightPrec, 0);
  writer.sep(getName());
  arg(writer, call, leftPrec, rightPrec, 1);
  writer.endList(frame);
}
 
Example 23
Source Project: Bats   Source File: SqlShuttle.java    License: Apache License 2.0 5 votes vote down vote up
public SqlNode visit(final SqlCall call) {
  // Handler creates a new copy of 'call' only if one or more operands
  // change.
  ArgHandler<SqlNode> argHandler = new CallCopyingArgHandler(call, false);
  call.getOperator().acceptCall(this, call, false, argHandler);
  return argHandler.result();
}
 
Example 24
Source Project: calcite   Source File: SqlJsonQueryFunction.java    License: 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(getName());
  call.operand(0).unparse(writer, 0, 0);
  writer.sep(",", true);
  call.operand(1).unparse(writer, 0, 0);
  final SqlJsonQueryWrapperBehavior wrapperBehavior =
      getEnumValue(call.operand(2));
  switch (wrapperBehavior) {
  case WITHOUT_ARRAY:
    writer.keyword("WITHOUT ARRAY");
    break;
  case WITH_CONDITIONAL_ARRAY:
    writer.keyword("WITH CONDITIONAL ARRAY");
    break;
  case WITH_UNCONDITIONAL_ARRAY:
    writer.keyword("WITH UNCONDITIONAL ARRAY");
    break;
  default:
    throw new IllegalStateException("unreachable code");
  }
  writer.keyword("WRAPPER");
  unparseEmptyOrErrorBehavior(writer, getEnumValue(call.operand(3)));
  writer.keyword("ON EMPTY");
  unparseEmptyOrErrorBehavior(writer, getEnumValue(call.operand(4)));
  writer.keyword("ON ERROR");
  writer.endFunCall(frame);
}
 
Example 25
Source Project: calcite   Source File: SqlJsonValueFunction.java    License: 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(getName());
  call.operand(0).unparse(writer, leftPrec, rightPrec);
  writer.sep(",", true);
  for (int i = 1; i < call.operandCount(); i++) {
    call.operand(i).unparse(writer, leftPrec, rightPrec);
  }
  writer.endFunCall(frame);
}
 
Example 26
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode visit(SqlIdentifier id) {
	// First check for builtin functions which don't have
	// parentheses, like "LOCALTIME".
	final SqlCall call = validator.makeNullaryCall(id);
	if (call != null) {
		return call.accept(this);
	}
	final SqlIdentifier fqId = getScope().fullyQualify(id).identifier;
	SqlNode expandedExpr = expandDynamicStar(id, fqId);
	validator.setOriginal(expandedExpr, id);
	return expandedExpr;
}
 
Example 27
Source Project: Bats   Source File: SqlDotOperator.java    License: Apache License 2.0 5 votes vote down vote up
@Override public RelDataType deriveType(SqlValidator validator,
    SqlValidatorScope scope, SqlCall call) {
  final SqlNode operand = call.getOperandList().get(0);
  final RelDataType nodeType =
      validator.deriveType(scope, operand);
  assert nodeType != null;
  if (!nodeType.isStruct()) {
    throw SqlUtil.newContextException(operand.getParserPosition(),
        Static.RESOURCE.incompatibleTypes());
  }

  final SqlNode fieldId = call.operand(1);
  final String fieldName = fieldId.toString();
  final RelDataTypeField field =
      nodeType.getField(fieldName, false, false);
  if (field == null) {
    throw SqlUtil.newContextException(fieldId.getParserPosition(),
        Static.RESOURCE.unknownField(fieldName));
  }
  RelDataType type = field.getType();

  // Validate and determine coercibility and resulting collation
  // name of binary operator if needed.
  type = adjustType(validator, call, type);
  SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
  return type;
}
 
Example 28
Source Project: Bats   Source File: SetopNamespace.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a <code>SetopNamespace</code>.
 *
 * @param validator     Validator
 * @param call          Call to set operator
 * @param enclosingNode Enclosing node
 */
protected SetopNamespace(
    SqlValidatorImpl validator,
    SqlCall call,
    SqlNode enclosingNode) {
  super(validator, enclosingNode);
  this.call = call;
}
 
Example 29
Source Project: Bats   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
public RexNode convertSequenceValue(
    SqlRexContext cx,
    SqlSequenceValueOperator fun,
    SqlCall call) {
  final List<SqlNode> operands = call.getOperandList();
  assert operands.size() == 1;
  assert operands.get(0) instanceof SqlIdentifier;
  final SqlIdentifier id = (SqlIdentifier) operands.get(0);
  final String key = Util.listToString(id.names);
  RelDataType returnType =
      cx.getValidator().getValidatedNodeType(call);
  return cx.getRexBuilder().makeCall(returnType, fun,
      ImmutableList.of(cx.getRexBuilder().makeLiteral(key)));
}
 
Example 30
Source Project: dremio-oss   Source File: SqlRefreshReflection.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SqlCall createCall(SqlLiteral functionQualifier, SqlParserPos pos, SqlNode... operands) {
  Preconditions.checkArgument(operands.length == 2, "SqlRefreshReflection.createCall() has to get 3 operands!");
  return new SqlRefreshReflection(
      pos,
      (SqlLiteral) operands[0],
      (SqlLiteral) operands[1]
          );
}