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

The following examples show how to use org.apache.calcite.sql.SqlCall#getOperator() . 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: OracleSqlDialect.java    From calcite with 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(SqlLibraryOperators.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 File: SqlNodeConverter.java    From kylin with Apache License 2.0 6 votes vote down vote up
private SqlNode convertSqlCall(SqlCall sqlCall) {
    SqlOperator operator = sqlCall.getOperator();
    if (operator != null) {
        Pair<SqlNode, SqlNode> matched = convMaster.matchSqlFunc(sqlCall);

        if (matched != null) {
            Preconditions.checkState(matched.getFirst() instanceof SqlCall);
            SqlCall sourceTmpl = (SqlCall) matched.getFirst();

            Preconditions.checkState(sourceTmpl.operandCount() == sqlCall.operandCount());
            SqlNode targetTmpl = matched.getSecond();

            boolean isWindowCall = sourceTmpl.getOperator() instanceof SqlOverOperator;
            SqlParamsFinder sqlParamsFinder = SqlParamsFinder.newInstance(sourceTmpl, sqlCall, isWindowCall);
            return targetTmpl.accept(new SqlFuncFiller(sqlParamsFinder.getParamNodes(), isWindowCall));
        }
    }
    return null;
}
 
Example 3
Source File: SqlNodeConverter.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
private SqlNode convertSqlCall(SqlCall sqlCall) {
    SqlOperator operator = sqlCall.getOperator();
    if (operator != null) {
        Pair<SqlNode, SqlNode> matched = convMaster.matchSqlFunc(sqlCall);

        if (matched != null) {
            Preconditions.checkState(matched.getFirst() instanceof SqlCall);
            SqlCall sourceTmpl = (SqlCall) matched.getFirst();

            Preconditions.checkState(sourceTmpl.operandCount() == sqlCall.operandCount());
            SqlNode targetTmpl = matched.getSecond();

            boolean isWindowCall = sourceTmpl.getOperator() instanceof SqlOverOperator;
            SqlParamsFinder sqlParamsFinder = SqlParamsFinder.newInstance(sourceTmpl, sqlCall, isWindowCall);
            return targetTmpl.accept(new SqlFuncFiller(sqlParamsFinder.getParamNodes(), isWindowCall));
        }
    }
    return null;
}
 
Example 4
Source File: SqlStdOperatorTable.java    From Bats with 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 5
Source File: DrillConvertletTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override
public SqlRexConvertlet get(SqlCall call) {
  SqlRexConvertlet convertlet;
  if(call.getOperator() instanceof DrillCalciteSqlWrapper) {
    final SqlOperator wrapper = call.getOperator();
    final SqlOperator wrapped = DrillCalciteWrapperUtility.extractSqlOperatorFromWrapper(call.getOperator());
    if ((convertlet = map.get(wrapped)) != null) {
      return convertlet;
    }

    ((SqlBasicCall) call).setOperator(wrapped);
    SqlRexConvertlet sqlRexConvertlet = StandardConvertletTable.INSTANCE.get(call);
    ((SqlBasicCall) call).setOperator(wrapper);
    return sqlRexConvertlet;
  }

  if ((convertlet = map.get(call.getOperator())) != null) {
    return convertlet;
  }

  return StandardConvertletTable.INSTANCE.get(call);
}
 
Example 6
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a BETWEEN expression.
 *
 * <p>Called automatically via reflection.
 */
public RexNode convertBetween(
    SqlRexContext cx,
    SqlBetweenOperator op,
    SqlCall call) {
  final List<RexNode> list =
      convertExpressionList(cx, call.getOperandList(),
          op.getOperandTypeChecker().getConsistency());
  final RexNode x = list.get(SqlBetweenOperator.VALUE_OPERAND);
  final RexNode y = list.get(SqlBetweenOperator.LOWER_OPERAND);
  final RexNode z = list.get(SqlBetweenOperator.UPPER_OPERAND);

  final RexBuilder rexBuilder = cx.getRexBuilder();
  RexNode ge1 = ge(rexBuilder, x, y);
  RexNode le1 = le(rexBuilder, x, z);
  RexNode and1 = and(rexBuilder, ge1, le1);

  RexNode res;
  final SqlBetweenOperator.Flag symmetric = op.flag;
  switch (symmetric) {
  case ASYMMETRIC:
    res = and1;
    break;
  case SYMMETRIC:
    RexNode ge2 = ge(rexBuilder, x, z);
    RexNode le2 = le(rexBuilder, x, y);
    RexNode and2 = and(rexBuilder, ge2, le2);
    res = or(rexBuilder, and1, and2);
    break;
  default:
    throw Util.unexpected(symmetric);
  }
  final SqlBetweenOperator betweenOp =
      (SqlBetweenOperator) call.getOperator();
  if (betweenOp.isNegated()) {
    res = rexBuilder.makeCall(SqlStdOperatorTable.NOT, res);
  }
  return res;
}
 
Example 7
Source File: ReflectionAllowedMonitoringConvertletTable.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public SqlRexConvertlet get(SqlCall call) {
  SqlOperator operator = call.getOperator();
  if(operator.isDynamicFunction() && !WHITELIST.contains(operator)) {
    contextSensitive = true;
  }
  return delegate.get(call);
}
 
Example 8
Source File: SqlStdOperatorTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Converts a call to a grouped auxiliary function
 * to a call to the grouped window function. 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 SqlCall convertAuxiliaryToGroupCall(SqlCall call) {
  final SqlOperator op = call.getOperator();
  if (op instanceof SqlGroupedWindowFunction
      && op.isGroupAuxiliary()) {
    return copy(call, ((SqlGroupedWindowFunction) op).groupFunction);
  }
  return null;
}
 
Example 9
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
public void validateCall(
	SqlCall call,
	SqlValidatorScope scope) {
	final SqlOperator operator = call.getOperator();
	if ((call.operandCount() == 0)
		&& (operator.getSyntax() == SqlSyntax.FUNCTION_ID)
		&& !call.isExpanded()
		&& !conformance.allowNiladicParentheses()) {
		// For example, "LOCALTIME()" is illegal. (It should be
		// "LOCALTIME", which would have been handled as a
		// SqlIdentifier.)
		throw handleUnresolvedFunction(call, (SqlFunction) operator,
			ImmutableList.of(), null);
	}

	SqlValidatorScope operandScope = scope.getOperandScope(call);

	if (operator instanceof SqlFunction
		&& ((SqlFunction) operator).getFunctionType()
		== SqlFunctionCategory.MATCH_RECOGNIZE
		&& !(operandScope instanceof MatchRecognizeScope)) {
		throw newValidationError(call,
			Static.RESOURCE.functionMatchRecognizeOnly(call.toString()));
	}
	// Delegate validation to the operator.
	operator.validateCall(call, this, scope, operandScope);
}
 
Example 10
Source File: HiveSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseCall(final SqlWriter writer, final SqlCall call,
    final int leftPrec, final int rightPrec) {
  switch (call.getKind()) {
  case POSITION:
    final SqlWriter.Frame frame = writer.startFunCall("INSTR");
    writer.sep(",");
    call.operand(1).unparse(writer, leftPrec, rightPrec);
    writer.sep(",");
    call.operand(0).unparse(writer, leftPrec, rightPrec);
    if (3 == call.operandCount()) {
      throw new RuntimeException("3rd operand Not Supported for Function INSTR in Hive");
    }
    writer.endFunCall(frame);
    break;
  case MOD:
    SqlOperator op = SqlStdOperatorTable.PERCENT_REMAINDER;
    SqlSyntax.BINARY.unparse(writer, op, call, leftPrec, rightPrec);
    break;
  case TRIM:
    RelToSqlConverterUtil.unparseHiveTrim(writer, call, leftPrec, rightPrec);
    break;
  case OTHER_FUNCTION:
    if (call.getOperator() instanceof SqlSubstringFunction) {
      final SqlWriter.Frame funCallFrame = writer.startFunCall(call.getOperator().getName());
      call.operand(0).unparse(writer, leftPrec, rightPrec);
      writer.sep(",", true);
      call.operand(1).unparse(writer, leftPrec, rightPrec);
      if (3 == call.operandCount()) {
        writer.sep(",", true);
        call.operand(2).unparse(writer, leftPrec, rightPrec);
      }
      writer.endFunCall(funCallFrame);
    } else {
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
    break;
  default:
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example 11
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public void validateCall(
	SqlCall call,
	SqlValidatorScope scope) {
	final SqlOperator operator = call.getOperator();
	if ((call.operandCount() == 0)
		&& (operator.getSyntax() == SqlSyntax.FUNCTION_ID)
		&& !call.isExpanded()
		&& !conformance.allowNiladicParentheses()) {
		// For example, "LOCALTIME()" is illegal. (It should be
		// "LOCALTIME", which would have been handled as a
		// SqlIdentifier.)
		throw handleUnresolvedFunction(call, (SqlFunction) operator,
			ImmutableList.of(), null);
	}

	SqlValidatorScope operandScope = scope.getOperandScope(call);

	if (operator instanceof SqlFunction
		&& ((SqlFunction) operator).getFunctionType()
		== SqlFunctionCategory.MATCH_RECOGNIZE
		&& !(operandScope instanceof MatchRecognizeScope)) {
		throw newValidationError(call,
			Static.RESOURCE.functionMatchRecognizeOnly(call.toString()));
	}
	// Delegate validation to the operator.
	operator.validateCall(call, this, scope, operandScope);
}
 
Example 12
Source File: ReflectiveConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlRexConvertlet get(SqlCall call) {
  SqlRexConvertlet convertlet;
  final SqlOperator op = call.getOperator();

  // Is there a convertlet for this operator
  // (e.g. SqlStdOperatorTable.plusOperator)?
  convertlet = (SqlRexConvertlet) map.get(op);
  if (convertlet != null) {
    return convertlet;
  }

  // Is there a convertlet for this class of operator
  // (e.g. SqlBinaryOperator)?
  Class<?> clazz = op.getClass();
  while (clazz != null) {
    convertlet = (SqlRexConvertlet) map.get(clazz);
    if (convertlet != null) {
      return convertlet;
    }
    clazz = clazz.getSuperclass();
  }

  // Is there a convertlet for this class of expression
  // (e.g. SqlCall)?
  clazz = call.getClass();
  while (clazz != null) {
    convertlet = (SqlRexConvertlet) map.get(clazz);
    if (convertlet != null) {
      return convertlet;
    }
    clazz = clazz.getSuperclass();
  }
  return null;
}
 
Example 13
Source File: ClickHouseSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    RelToSqlConverterUtil.specialOperatorByName("substring")
        .unparse(writer, call, 0, 0);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      unparseFloor(writer, call);
      break;

    case COUNT:
      // CH returns NULL rather than 0 for COUNT(DISTINCT) of NULL values.
      // https://github.com/yandex/ClickHouse/issues/2494
      // Wrap the call in a CH specific coalesce (assumeNotNull).
      if (call.getFunctionQuantifier() != null
          && call.getFunctionQuantifier().toString().equals("DISTINCT")) {
        writer.print("assumeNotNull");
        SqlWriter.Frame frame = writer.startList("(", ")");
        super.unparseCall(writer, call, leftPrec, rightPrec);
        writer.endList(frame);
      } else {
        super.unparseCall(writer, call, leftPrec, rightPrec);
      }
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 14
Source File: SqlStdOperatorTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Converts a call to a grouped auxiliary function
 * to a call to the grouped window function. 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 SqlCall convertAuxiliaryToGroupCall(SqlCall call) {
  final SqlOperator op = call.getOperator();
  if (op instanceof SqlGroupedWindowFunction
      && op.isGroupAuxiliary()) {
    return copy(call, ((SqlGroupedWindowFunction) op).groupFunction);
  }
  return null;
}
 
Example 15
Source File: SqlBetweenOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
public Void visit(SqlCall call) {
  final SqlOperator operator = call.getOperator();
  if (operator == SqlStdOperatorTable.AND) {
    throw Util.FoundOne.NULL;
  }
  return super.visit(call);
}
 
Example 16
Source File: ExpressionGenerator.java    From streamline with Apache License 2.0 5 votes vote down vote up
@Override
public Expression visit(SqlCall call) {
    SqlOperator sqlOperator = call.getOperator();
    if (sqlOperator instanceof SqlBinaryOperator) {
        return visitBinaryOperator((SqlBinaryOperator) sqlOperator, call.getOperandList().get(0),
                call.getOperandList().get(1));
    } else if (sqlOperator instanceof SqlSpecialOperator) {
        return visitSqlSpecialOperator((SqlSpecialOperator) sqlOperator, call.getOperandList());
    } else if (sqlOperator instanceof SqlFunction) {
        SqlFunction sqlFunction = (SqlFunction) sqlOperator;
        if (sqlFunction instanceof SqlAggFunction) {
            return visitAggregateFunction(sqlFunction.getName(), call.getOperandList());
        } else if (sqlFunction instanceof SqlUnresolvedFunction) {
            String udfName = sqlFunction.getName().toUpperCase();
            if (catalogUdfs.containsKey(udfName)) {
                Udf udfInfo = catalogUdfs.get(udfName);
                if (udfInfo.isAggregate()) {
                    return visitUserDefinedAggregateFunction(udfInfo, call.getOperandList());
                } else {
                    return visitUserDefinedFunction(udfInfo, call.getOperandList());
                }
            } else {
                throw new UnsupportedOperationException("Unknown built-in or User defined function '" + udfName + "'");
            }
        } else {
            return visitFunction(sqlFunction.getName(), call.getOperandList());
        }
    } else {
        throw new UnsupportedOperationException("Operator " + sqlOperator.getName() + " is not supported");
    }
}
 
Example 17
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a BETWEEN expression.
 *
 * <p>Called automatically via reflection.
 */
public RexNode convertBetween(
    SqlRexContext cx,
    SqlBetweenOperator op,
    SqlCall call) {
  final List<RexNode> list =
      convertExpressionList(cx, call.getOperandList(),
          op.getOperandTypeChecker().getConsistency());
  final RexNode x = list.get(SqlBetweenOperator.VALUE_OPERAND);
  final RexNode y = list.get(SqlBetweenOperator.LOWER_OPERAND);
  final RexNode z = list.get(SqlBetweenOperator.UPPER_OPERAND);

  final RexBuilder rexBuilder = cx.getRexBuilder();
  RexNode ge1 = ge(rexBuilder, x, y);
  RexNode le1 = le(rexBuilder, x, z);
  RexNode and1 = and(rexBuilder, ge1, le1);

  RexNode res;
  final SqlBetweenOperator.Flag symmetric = op.flag;
  switch (symmetric) {
  case ASYMMETRIC:
    res = and1;
    break;
  case SYMMETRIC:
    RexNode ge2 = ge(rexBuilder, x, z);
    RexNode le2 = le(rexBuilder, x, y);
    RexNode and2 = and(rexBuilder, ge2, le2);
    res = or(rexBuilder, and1, and2);
    break;
  default:
    throw Util.unexpected(symmetric);
  }
  final SqlBetweenOperator betweenOp =
      (SqlBetweenOperator) call.getOperator();
  if (betweenOp.isNegated()) {
    res = rexBuilder.makeCall(SqlStdOperatorTable.NOT, res);
  }
  return res;
}
 
Example 18
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
public RelDataType visit(SqlCall call) {
	final SqlOperator operator = call.getOperator();
	return operator.deriveType(SqlValidatorImpl.this, scope, call);
}
 
Example 19
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
public RelDataType visit(SqlCall call) {
	final SqlOperator operator = call.getOperator();
	return operator.deriveType(SqlValidatorImpl.this, scope, call);
}
 
Example 20
Source File: AbstractTypeCoercion.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Cast column at index {@code index} to target type.
 *
 * @param scope      Validator scope for the node list
 * @param nodeList   Column node list
 * @param index      Index of column
 * @param targetType Target type to cast to
 */
protected boolean coerceColumnType(
    SqlValidatorScope scope,
    SqlNodeList nodeList,
    int index,
    RelDataType targetType) {
  // Transform the JavaType to SQL type because the SqlDataTypeSpec
  // does not support deriving JavaType yet.
  if (RelDataTypeFactoryImpl.isJavaType(targetType)) {
    targetType = ((JavaTypeFactory) factory).toSql(targetType);
  }

  // This will happen when there is a star/dynamic-star column in the select list,
  // and the source is values expression, i.e. `select * from (values(1, 2, 3))`.
  // There is no need to coerce the column type, only remark
  // the inferred row type has changed, we will then add in type coercion
  // when expanding star/dynamic-star.

  // See SqlToRelConverter#convertSelectList for details.
  if (index >= nodeList.getList().size()) {
    // Can only happen when there is a star(*) in the column,
    // just return true.
    return true;
  }

  final SqlNode node = nodeList.get(index);
  if (node instanceof SqlDynamicParam) {
    // Do not support implicit type coercion for dynamic param.
    return false;
  }
  if (node instanceof SqlIdentifier) {
    // Do not expand a star/dynamic table col.
    SqlIdentifier node1 = (SqlIdentifier) node;
    if (node1.isStar()) {
      return true;
    } else if (DynamicRecordType.isDynamicStarColName(Util.last(node1.names))) {
      // Should support implicit cast for dynamic table.
      return false;
    }
  }

  if (node instanceof SqlCall) {
    SqlCall node2 = (SqlCall) node;
    if (node2.getOperator().kind == SqlKind.AS) {
      final SqlNode operand = node2.operand(0);
      if (!needToCast(scope, operand, targetType)) {
        return false;
      }
      RelDataType targetType2 = syncAttributes(validator.deriveType(scope, operand), targetType);
      final SqlNode casted = castTo(operand, targetType2);
      node2.setOperand(0, casted);
      updateInferredType(casted, targetType2);
      return true;
    }
  }
  if (!needToCast(scope, node, targetType)) {
    return false;
  }
  RelDataType targetType3 = syncAttributes(validator.deriveType(scope, node), targetType);
  final SqlNode node3 = castTo(node, targetType3);
  nodeList.set(index, node3);
  updateInferredType(node3, targetType3);
  return true;
}