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

The following examples show how to use org.apache.calcite.sql.SqlCall#operand() . 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: HsqldbSqlDialect.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) {
  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);

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

  default:
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example 2
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Registers any sub-queries inside a given call operand, and converts the
 * operand to a scalar sub-query if the operator requires it.
 *
 * @param parentScope    Parent scope
 * @param call           Call
 * @param operandOrdinal Ordinal of operand within call
 * @see SqlOperator#argumentMustBeScalar(int)
 */
private void registerOperandSubQueries(
	SqlValidatorScope parentScope,
	SqlCall call,
	int operandOrdinal) {
	SqlNode operand = call.operand(operandOrdinal);
	if (operand == null) {
		return;
	}
	if (operand.getKind().belongsTo(SqlKind.QUERY)
		&& call.getOperator().argumentMustBeScalar(operandOrdinal)) {
		operand =
			SqlStdOperatorTable.SCALAR_QUERY.createCall(
				operand.getParserPosition(),
				operand);
		call.setOperand(operandOrdinal, operand);
	}
	registerSubQueries(parentScope, operand);
}
 
Example 3
Source File: MssqlSqlDialect.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void unparseSqlDatetimeArithmetic(SqlWriter writer,
    SqlCall call, SqlKind sqlKind, int leftPrec, int rightPrec) {

  final SqlWriter.Frame frame = writer.startFunCall("DATEADD");
  SqlNode operand = call.operand(1);
  if (operand instanceof SqlIntervalLiteral) {
    //There is no DATESUB method available, so change the sign.
    unparseSqlIntervalLiteralMssql(
        writer, (SqlIntervalLiteral) operand, sqlKind == SqlKind.MINUS ? -1 : 1);
  } else {
    operand.unparse(writer, leftPrec, rightPrec);
  }
  writer.sep(",", true);

  call.operand(0).unparse(writer, leftPrec, rightPrec);
  writer.endList(frame);
}
 
Example 4
Source File: RelToSqlConverterUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Unparses TRIM function with value as space.
 *
 * <p>For example :
 *
 * <blockquote><pre>
 * SELECT TRIM(both ' ' from "ABC") &rarr; SELECT TRIM(ABC)
 * </pre></blockquote>
 *
 * @param writer writer
 * @param call the call
 */
private static void unparseTrimWithSpace(
    SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
  final String operatorName;
  final SqlLiteral trimFlag = call.operand(0);
  switch (trimFlag.getValueAs(SqlTrimFunction.Flag.class)) {
  case LEADING:
    operatorName = "LTRIM";
    break;
  case TRAILING:
    operatorName = "RTRIM";
    break;
  default:
    operatorName = call.getOperator().getName();
    break;
  }
  final SqlWriter.Frame trimFrame = writer.startFunCall(operatorName);
  call.operand(2).unparse(writer, leftPrec, rightPrec);
  writer.endFunCall(trimFrame);
}
 
Example 5
Source File: PostgresqlSqlDialect.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  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, "DATE_TRUNC", false);
    break;

  default:
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example 6
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 7
Source File: RelToSqlConverterUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * For usage of TRIM, LTRIM and RTRIM in Hive, see
 * <a href="https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF">Hive UDF usage</a>.
 */
public static void unparseHiveTrim(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlLiteral valueToTrim = call.operand(1);
  if (valueToTrim.toValue().matches("\\s+")) {
    unparseTrimWithSpace(writer, call, leftPrec, rightPrec);
  } else {
    // SELECT TRIM(both 'A' from "ABC") -> SELECT REGEXP_REPLACE("ABC", '^(A)*', '')
    final SqlLiteral trimFlag = call.operand(0);
    final SqlCharStringLiteral regexNode =
        createRegexPatternLiteral(call.operand(1), trimFlag);
    final SqlCharStringLiteral blankLiteral =
        SqlLiteral.createCharString("", call.getParserPosition());
    final SqlNode[] trimOperands = new SqlNode[] { call.operand(2), regexNode, blankLiteral };
    final SqlCall regexReplaceCall = REGEXP_REPLACE.createCall(SqlParserPos.ZERO, trimOperands);
    regexReplaceCall.unparse(writer, leftPrec, rightPrec);
  }
}
 
Example 8
Source File: SqlAdvisorValidator.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected void validateOver(SqlCall call, SqlValidatorScope scope) {
  try {
    final OverScope overScope = (OverScope) getOverScope(call);
    final SqlNode relation = call.operand(0);
    validateFrom(relation, unknownType, scope);
    final SqlNode window = call.operand(1);
    SqlValidatorScope opScope = scopes.get(relation);
    if (opScope == null) {
      opScope = overScope;
    }
    validateWindow(window, opScope, null);
  } catch (CalciteException e) {
    Util.swallow(e, TRACER);
  }
}
 
Example 9
Source File: SqlCursorConstructor.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  SqlSelect subSelect = call.operand(0);
  validator.declareCursor(subSelect, scope);
  subSelect.validateExpr(validator, scope);
  return super.deriveType(validator, scope, call);
}
 
Example 10
Source File: BigQuerySqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * For usage of TRIM, LTRIM and RTRIM in BQ see
 * <a href="https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#trim">
 *  BQ Trim Function</a>.
 */
private void unparseTrim(SqlWriter writer, SqlCall call, int leftPrec,
    int rightPrec) {
  final String operatorName;
  SqlLiteral trimFlag = call.operand(0);
  SqlLiteral valueToTrim = call.operand(1);
  switch (trimFlag.getValueAs(SqlTrimFunction.Flag.class)) {
  case LEADING:
    operatorName = "LTRIM";
    break;
  case TRAILING:
    operatorName = "RTRIM";
    break;
  default:
    operatorName = call.getOperator().getName();
    break;
  }
  final SqlWriter.Frame trimFrame = writer.startFunCall(operatorName);
  call.operand(2).unparse(writer, leftPrec, rightPrec);

  // If the trimmed character is a non-space character, add it to the target SQL.
  // eg: TRIM(BOTH 'A' from 'ABCD'
  // Output Query: TRIM('ABC', 'A')
  if (!valueToTrim.toValue().matches("\\s+")) {
    writer.literal(",");
    call.operand(1).unparse(writer, leftPrec, rightPrec);
  }
  writer.endFunCall(trimFrame);
}
 
Example 11
Source File: SqlStdOperatorTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  call.operand(0).unparse(writer, this.getLeftPrec(), this.getRightPrec());
  int startNum = ((SqlNumericLiteral) call.operand(1)).intValue(true);
  SqlNumericLiteral endRepNum = call.operand(2);
  boolean isReluctant = ((SqlLiteral) call.operand(3)).booleanValue();
  int endNum = endRepNum.intValue(true);
  if (startNum == endNum) {
    writer.keyword("{ " + startNum + " }");
  } else {
    if (endNum == -1) {
      if (startNum == 0) {
        writer.keyword("*");
      } else if (startNum == 1) {
        writer.keyword("+");
      } else {
        writer.keyword("{ " + startNum + ", }");
      }
    } else {
      if (startNum == 0 && endNum == 1) {
        writer.keyword("?");
      } else if (startNum == -1) {
        writer.keyword("{ , " + endNum + " }");
      } else {
        writer.keyword("{ " + startNum + ", " + endNum + " }");
      }
    }
    if (isReluctant) {
      writer.keyword("?");
    }
  }
}
 
Example 12
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPADD(unit, count, timestamp)
  //  => timestamp + count * INTERVAL '1' UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  RexNode interval2Add;
  SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
  RexNode op1 = cx.convertExpression(call.operand(1));
  switch (unit) {
  case MICROSECOND:
  case NANOSECOND:
    interval2Add =
        divide(rexBuilder,
            multiply(rexBuilder,
                rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
            BigDecimal.ONE.divide(unit.multiplier,
                RoundingMode.UNNECESSARY));
    break;
  default:
    interval2Add = multiply(rexBuilder,
        rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
  }

  return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
      cx.convertExpression(call.operand(2)), interval2Add);
}
 
Example 13
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected RexNode convertFloorCeil(SqlRexContext cx, SqlCall call) {
  final boolean floor = call.getKind() == SqlKind.FLOOR;
  // Rewrite floor, ceil of interval
  if (call.operandCount() == 1
      && call.operand(0) instanceof SqlIntervalLiteral) {
    final SqlIntervalLiteral literal = call.operand(0);
    SqlIntervalLiteral.IntervalValue interval =
        (SqlIntervalLiteral.IntervalValue) literal.getValue();
    BigDecimal val =
        interval.getIntervalQualifier().getStartUnit().multiplier;
    RexNode rexInterval = cx.convertExpression(literal);

    final RexBuilder rexBuilder = cx.getRexBuilder();
    RexNode zero = rexBuilder.makeExactLiteral(BigDecimal.valueOf(0));
    RexNode cond = ge(rexBuilder, rexInterval, zero);

    RexNode pad =
        rexBuilder.makeExactLiteral(val.subtract(BigDecimal.ONE));
    RexNode cast = rexBuilder.makeReinterpretCast(
        rexInterval.getType(), pad, rexBuilder.makeLiteral(false));
    RexNode sum = floor
        ? minus(rexBuilder, rexInterval, cast)
        : plus(rexBuilder, rexInterval, cast);

    RexNode kase = floor
        ? case_(rexBuilder, rexInterval, cond, sum)
        : case_(rexBuilder, sum, cond, rexInterval);

    RexNode factor = rexBuilder.makeExactLiteral(val);
    RexNode div = divideInt(rexBuilder, kase, factor);
    return multiply(rexBuilder, div, factor);
  }

  // normal floor, ceil function
  return convertFunction(cx, (SqlFunction) call.getOperator(), call);
}
 
Example 14
Source File: SparkSqlDialect.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) {
    SqlUtil.unparseFunctionSyntax(SPARKSQL_SUBSTRING, 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, "DATE_TRUNC", false);
      break;
    case TRIM:
      unparseHiveTrim(writer, call, leftPrec, rightPrec);
      break;
    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 15
Source File: SqlOverlapsOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
void arg(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec, int i) {
  if (SqlUtil.isCallTo(call.operand(i), SqlStdOperatorTable.ROW)) {
    SqlCall row = call.operand(i);
    writer.keyword("PERIOD");
    writer.sep("(", true);
    row.operand(0).unparse(writer, leftPrec, rightPrec);
    writer.sep(",", true);
    row.operand(1).unparse(writer, leftPrec, rightPrec);
    writer.sep(")", true);
  } else {
    call.operand(i).unparse(writer, leftPrec, rightPrec);
  }
}
 
Example 16
Source File: SqlAdvisorValidator.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected void validateOver(SqlCall call, SqlValidatorScope scope) {
  try {
    final OverScope overScope = (OverScope) getOverScope(call);
    final SqlNode relation = call.operand(0);
    validateFrom(relation, unknownType, scope);
    final SqlNode window = call.operand(1);
    SqlValidatorScope opScope = scopes.get(relation);
    if (opScope == null) {
      opScope = overScope;
    }
    validateWindow(window, opScope, null);
  } catch (CalciteException e) {
    Util.swallow(e, TRACER);
  }
}
 
Example 17
Source File: ClickHouseSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Unparses datetime floor for ClickHouse.
 *
 * @param writer Writer
 * @param call Call
 */
private void unparseFloor(SqlWriter writer, SqlCall call) {
  final SqlLiteral timeUnitNode = call.operand(1);
  TimeUnitRange unit = (TimeUnitRange) timeUnitNode.getValue();

  String funName;
  switch (unit) {
  case YEAR:
    funName = "toStartOfYear";
    break;
  case MONTH:
    funName = "toStartOfMonth";
    break;
  case WEEK:
    funName = "toMonday";
    break;
  case DAY:
    funName = "toDate";
    break;
  case HOUR:
    funName = "toStartOfHour";
    break;
  case MINUTE:
    funName = "toStartOfMinute";
    break;
  default:
    throw new RuntimeException("ClickHouse does not support FLOOR for time unit: "
        + unit);
  }

  writer.print(funName);
  SqlWriter.Frame frame = writer.startList("(", ")");
  call.operand(0).unparse(writer, 0, 0);
  writer.endList(frame);
}
 
Example 18
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPADD(unit, count, timestamp)
  //  => timestamp + count * INTERVAL '1' UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  final TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  RexNode interval2Add;
  SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, unitLiteral.getParserPosition());
  RexNode op1 = cx.convertExpression(call.operand(1));
  switch (unit) {
  case MICROSECOND:
  case NANOSECOND:
    interval2Add =
        divide(rexBuilder,
            multiply(rexBuilder,
                rexBuilder.makeIntervalLiteral(BigDecimal.ONE, qualifier), op1),
            BigDecimal.ONE.divide(unit.multiplier,
                RoundingMode.UNNECESSARY));
    break;
  default:
    interval2Add = multiply(rexBuilder,
        rexBuilder.makeIntervalLiteral(unit.multiplier, qualifier), op1);
  }

  return rexBuilder.makeCall(SqlStdOperatorTable.DATETIME_PLUS,
      cx.convertExpression(call.operand(2)), interval2Add);
}
 
Example 19
Source File: SqlNewOperator.java    From Bats with Apache License 2.0 4 votes vote down vote up
public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  // New specification is purely syntactic, so we rewrite it as a
  // direct call to the constructor method.
  return call.operand(0);
}
 
Example 20
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  // TIMESTAMPDIFF(unit, t1, t2)
  //    => (t2 - t1) UNIT
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlLiteral unitLiteral = call.operand(0);
  TimeUnit unit = unitLiteral.symbolValue(TimeUnit.class);
  BigDecimal multiplier = BigDecimal.ONE;
  BigDecimal divider = BigDecimal.ONE;
  SqlTypeName sqlTypeName = unit == TimeUnit.NANOSECOND
      ? SqlTypeName.BIGINT
      : SqlTypeName.INTEGER;
  switch (unit) {
  case MICROSECOND:
  case MILLISECOND:
  case NANOSECOND:
  case WEEK:
    multiplier = BigDecimal.valueOf(DateTimeUtils.MILLIS_PER_SECOND);
    divider = unit.multiplier;
    unit = TimeUnit.SECOND;
    break;
  case QUARTER:
    divider = unit.multiplier;
    unit = TimeUnit.MONTH;
    break;
  }
  final SqlIntervalQualifier qualifier =
      new SqlIntervalQualifier(unit, null, SqlParserPos.ZERO);
  final RexNode op2 = cx.convertExpression(call.operand(2));
  final RexNode op1 = cx.convertExpression(call.operand(1));
  final RelDataType intervalType =
      cx.getTypeFactory().createTypeWithNullability(
          cx.getTypeFactory().createSqlIntervalType(qualifier),
          op1.getType().isNullable() || op2.getType().isNullable());
  final RexCall rexCall = (RexCall) rexBuilder.makeCall(
      intervalType, SqlStdOperatorTable.MINUS_DATE,
      ImmutableList.of(op2, op1));
  final RelDataType intType =
      cx.getTypeFactory().createTypeWithNullability(
          cx.getTypeFactory().createSqlType(sqlTypeName),
          SqlTypeUtil.containsNullable(rexCall.getType()));
  RexNode e = rexBuilder.makeCast(intType, rexCall);
  return rexBuilder.multiplyDivide(e, multiplier, divider);
}