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

The following examples show how to use org.apache.calcite.sql.SqlLiteral. 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: quark   Source File: RelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
public Result visitJoin(Join e) {
  final Result leftResult = visitChild(0, e.getLeft());
  final Result rightResult = visitChild(1, e.getRight());
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext =
      rightResult.qualifiedContext();
  SqlNode sqlCondition = convertConditionToSqlNode(e.getCondition(),
      leftContext,
      rightContext,
      e.getLeft().getRowType().getFieldCount());
  SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          joinType(e.getJoinType()).symbol(POS),
          rightResult.asFrom(),
          JoinConditionType.ON.symbol(POS),
          sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example 2
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNode visit(SqlLiteral literal) {
	// Ordinal markers, e.g. 'select a, b from t order by 2'.
	// Only recognize them if they are the whole expression,
	// and if the dialect permits.
	if (literal == root && getConformance().isSortByOrdinal()) {
		switch (literal.getTypeName()) {
			case DECIMAL:
			case DOUBLE:
				final int intValue = literal.intValue(false);
				if (intValue >= 0) {
					if (intValue < 1 || intValue > aliasList.size()) {
						throw newValidationError(
							literal, RESOURCE.orderByOrdinalOutOfRange());
					}

					// SQL ordinals are 1-based, but Sort's are 0-based
					int ordinal = intValue - 1;
					return nthSelectItem(ordinal, literal.getParserPosition());
				}
				break;
		}
	}

	return super.visit(literal);
}
 
Example 3
Source Project: calcite   Source File: SqlCase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a call to the switched form of the case operator, viz:
 *
 * <blockquote><code>CASE value<br>
 * WHEN whenList[0] THEN thenList[0]<br>
 * WHEN whenList[1] THEN thenList[1]<br>
 * ...<br>
 * ELSE elseClause<br>
 * END</code></blockquote>
 */
public static SqlCase createSwitched(SqlParserPos pos, SqlNode value,
    SqlNodeList whenList, SqlNodeList thenList, SqlNode elseClause) {
  if (null != value) {
    List<SqlNode> list = whenList.getList();
    for (int i = 0; i < list.size(); i++) {
      SqlNode e = list.get(i);
      final SqlCall call;
      if (e instanceof SqlNodeList) {
        call = SqlStdOperatorTable.IN.createCall(pos, value, e);
      } else {
        call = SqlStdOperatorTable.EQUALS.createCall(pos, value, e);
      }
      list.set(i, call);
    }
  }

  if (null == elseClause) {
    elseClause = SqlLiteral.createNull(pos);
  }

  return new SqlCase(pos, null, whenList, thenList, elseClause);
}
 
Example 4
Source Project: calcite   Source File: SqlParserUtil.java    License: Apache License 2.0 6 votes vote down vote up
public static SqlTimestampLiteral parseTimestampLiteral(String s,
    SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Format format = Format.PER_THREAD.get();
  DateTimeUtils.PrecisionTime pt = null;
  // Allow timestamp literals with and without time fields (as does
  // PostgreSQL); TODO: require time fields except in Babel's lenient mode
  final DateFormat[] dateFormats = {format.timestamp, format.date};
  for (DateFormat dateFormat : dateFormats) {
    pt = DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
        dateFormat, DateTimeUtils.UTC_ZONE, -1);
    if (pt != null) {
      break;
    }
  }
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIMESTAMP", s,
            RESOURCE.badFormat(DateTimeUtils.TIMESTAMP_FORMAT_STRING).str()));
  }
  final TimestampString ts =
      TimestampString.fromCalendarFields(pt.getCalendar())
          .withFraction(pt.getFraction());
  return SqlLiteral.createTimestamp(ts, pt.getPrecision(), pos);
}
 
Example 5
Source Project: calcite   Source File: SqlOperatorBindingTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Tests {@link org.apache.calcite.sql.SqlUtil#isLiteral(SqlNode, boolean)},
 * which was added to enhance Calcite's public API
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1219">[CALCITE-1219]
 * Add a method to SqlOperatorBinding to determine whether operand is a
 * literal</a>.
 */
@Test void testSqlNodeLiteral() {
  final SqlNode literal = SqlLiteral.createExactNumeric(
      "0",
      SqlParserPos.ZERO);
  final SqlNode castLiteral = SqlStdOperatorTable.CAST.createCall(
      SqlParserPos.ZERO,
      literal,
      integerType);
  final SqlNode castCastLiteral = SqlStdOperatorTable.CAST.createCall(
      SqlParserPos.ZERO,
      castLiteral,
      integerType);

  // SqlLiteral is considered as a Literal
  assertSame(true, SqlUtil.isLiteral(literal, true));
  // CAST(SqlLiteral as type) is considered as a Literal
  assertSame(true, SqlUtil.isLiteral(castLiteral, true));
  // CAST(CAST(SqlLiteral as type) as type) is NOT considered as a Literal
  assertSame(false, SqlUtil.isLiteral(castCastLiteral, true));
}
 
Example 6
Source Project: dremio-oss   Source File: SqlRefreshTable.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void setOperand(int i, SqlNode operand) {
  switch (i) {
    case 0:
      table = (SqlIdentifier) operand;
      break;
    case 1:
      deleteUnavail = (SqlLiteral) operand;
      break;
    case 2:
      forceUp = (SqlLiteral) operand;
      break;
    case 3:
      promotion = (SqlLiteral) operand;
      break;
    default:
      throw new AssertionError(i);
  }
}
 
Example 7
Source Project: incubator-pinot   Source File: RequestUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Expression getLiteralExpression(Object object) {
  if (object instanceof Integer) {
    return RequestUtils.getLiteralExpression((Integer) object);
  }
  if (object instanceof Long) {
    return RequestUtils.getLiteralExpression((Long) object);
  }
  if (object instanceof Float) {
    return RequestUtils.getLiteralExpression((Float) object);
  }
  if (object instanceof Double) {
    return RequestUtils.getLiteralExpression((Double) object);
  }
  if (object instanceof String) {
    return RequestUtils.getLiteralExpression((String) object);
  }
  if (object instanceof SqlLiteral) {
    return RequestUtils.getLiteralExpression((SqlLiteral) object);
  }
  throw new SqlCompilationException(
      new IllegalArgumentException("Unsupported Literal value type - " + object.getClass()));
}
 
Example 8
Source Project: flink   Source File: SqlCreateHiveDatabase.java    License: Apache License 2.0 6 votes vote down vote up
public SqlCreateHiveDatabase(SqlParserPos pos, SqlIdentifier databaseName, SqlNodeList propertyList,
		SqlCharStringLiteral comment, SqlCharStringLiteral location, boolean ifNotExists) throws ParseException {
	super(
			pos,
			databaseName,
			HiveDDLUtils.checkReservedDBProperties(propertyList),
			HiveDDLUtils.unescapeStringLiteral(comment),
			ifNotExists
	);
	HiveDDLUtils.ensureNonGeneric(propertyList);
	originPropList = new SqlNodeList(propertyList.getList(), propertyList.getParserPosition());
	// mark it as a hive database
	propertyList.add(HiveDDLUtils.toTableOption(CatalogConfig.IS_GENERIC, "false", pos));
	if (location != null) {
		propertyList.add(new SqlTableOption(
				SqlLiteral.createCharString(DATABASE_LOCATION_URI, location.getParserPosition()),
				location,
				location.getParserPosition()));
	}
	this.location = location;
}
 
Example 9
Source Project: calcite   Source File: RelToSqlConverterUtil.java    License: 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 10
Source Project: calcite   Source File: RelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
/** @see #dispatch */
public Result visit(Correlate e) {
  final Result leftResult =
      visitChild(0, e.getLeft())
          .resetAlias(e.getCorrelVariable(), e.getRowType());
  parseCorrelTable(e, leftResult);
  final Result rightResult = visitChild(1, e.getRight());
  final SqlNode rightLateral =
      SqlStdOperatorTable.LATERAL.createCall(POS, rightResult.node);
  final SqlNode rightLateralAs =
      SqlStdOperatorTable.AS.createCall(POS, rightLateral,
          new SqlIdentifier(rightResult.neededAlias, POS));

  final SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          JoinType.COMMA.symbol(POS),
          rightLateralAs,
          JoinConditionType.NONE.symbol(POS),
          null);
  return result(join, leftResult, rightResult);
}
 
Example 11
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 5 votes vote down vote up
private SqlCall toSql(RexProgram program, RexOver rexOver) {
    final RexWindow rexWindow = rexOver.getWindow();
    final SqlNodeList partitionList = new SqlNodeList(toSql(program, rexWindow.partitionKeys), POS);

    ImmutableList.Builder<SqlNode> orderNodes = ImmutableList.builder();
    if (rexWindow.orderKeys != null) {
        for (RexFieldCollation rfc : rexWindow.orderKeys) {
            orderNodes.add(toSql(program, rfc));
        }
    }
    final SqlNodeList orderList = new SqlNodeList(orderNodes.build(), POS);

    final SqlLiteral isRows = SqlLiteral.createBoolean(rexWindow.isRows(), POS);

    // null defaults to true.
    // During parsing the allowPartial == false (e.g. disallow partial)
    // is expand into CASE expression and is handled as a such.
    // Not sure if we can collapse this CASE expression back into
    // "disallow partial" and set the allowPartial = false.
    final SqlLiteral allowPartial = null;

    SqlAggFunction sqlAggregateFunction = rexOver.getAggOperator();

    SqlNode lowerBound = null;
    SqlNode upperBound = null;

    if (sqlAggregateFunction.allowsFraming()) {
        lowerBound = createSqlWindowBound(rexWindow.getLowerBound());
        upperBound = createSqlWindowBound(rexWindow.getUpperBound());
    }

    final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList, orderList, isRows, lowerBound,
            upperBound, allowPartial, POS);

    final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
    return createOverCall(sqlAggregateFunction, nodeList, sqlWindow);
}
 
Example 12
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 5 votes vote down vote up
private SqlCall createOverCall(SqlAggFunction op, List<SqlNode> operands, SqlWindow window) {
    if (op instanceof SqlSumEmptyIsZeroAggFunction) {
        // Rewrite "SUM0(x) OVER w" to "COALESCE(SUM(x) OVER w, 0)"
        final SqlCall node = createOverCall(SqlStdOperatorTable.SUM, operands, window);
        return SqlStdOperatorTable.COALESCE.createCall(POS, node, SqlLiteral.createExactNumeric("0", POS));
    }
    final SqlCall aggFunctionCall = op.createCall(POS, operands);
    return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall, window);
}
 
Example 13
Source Project: Bats   Source File: RelToSqlConverter.java    License: Apache License 2.0 5 votes vote down vote up
/** @see #dispatch */
public Result visit(Join e) {
  final Result leftResult = visitChild(0, e.getLeft()).resetAlias();
  final Result rightResult = visitChild(1, e.getRight()).resetAlias();
  final Context leftContext = leftResult.qualifiedContext();
  final Context rightContext = rightResult.qualifiedContext();
  SqlNode sqlCondition = null;
  SqlLiteral condType = JoinConditionType.ON.symbol(POS);
  JoinType joinType = joinType(e.getJoinType());
  if (isCrossJoin(e)) {
    joinType = dialect.emulateJoinTypeForCrossJoin();
    condType = JoinConditionType.NONE.symbol(POS);
  } else {
    sqlCondition = convertConditionToSqlNode(e.getCondition(),
        leftContext,
        rightContext,
        e.getLeft().getRowType().getFieldCount());
  }
  SqlNode join =
      new SqlJoin(POS,
          leftResult.asFrom(),
          SqlLiteral.createBoolean(false, POS),
          joinType.symbol(POS),
          rightResult.asFrom(),
          condType,
          sqlCondition);
  return result(join, leftResult, rightResult);
}
 
Example 14
Source Project: Bats   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlDateLiteral parseDateLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Calendar cal =
      DateTimeUtils.parseDateFormat(dateStr, Format.PER_THREAD.get().date,
          DateTimeUtils.UTC_ZONE);
  if (cal == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("DATE", s,
            RESOURCE.badFormat(DateTimeUtils.DATE_FORMAT_STRING).str()));
  }
  final DateString d = DateString.fromCalendarFields(cal);
  return SqlLiteral.createDate(d, pos);
}
 
Example 15
Source Project: flink   Source File: CallBindingCallContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T> Optional<T> getArgumentValue(int pos, Class<T> clazz) {
	if (isArgumentNull(pos)) {
		return Optional.empty();
	}
	try {
		final SqlLiteral literal = SqlLiteral.unchain(adaptedArguments.get(pos));
		return Optional.ofNullable(getLiteralValueAs(literal::getValueAs, clazz));
	} catch (IllegalArgumentException e) {
		return Optional.empty();
	}
}
 
Example 16
Source Project: calcite   Source File: SqlUserDefinedTableMacro.java    License: Apache License 2.0 5 votes vote down vote up
private static Object getValue(SqlNode right) throws NonLiteralException {
  switch (right.getKind()) {
  case ARRAY_VALUE_CONSTRUCTOR:
    final List<Object> list = new ArrayList<>();
    for (SqlNode o : ((SqlCall) right).getOperandList()) {
      list.add(getValue(o));
    }
    return ImmutableNullableList.copyOf(list);
  case MAP_VALUE_CONSTRUCTOR:
    final ImmutableMap.Builder<Object, Object> builder2 =
        ImmutableMap.builder();
    final List<SqlNode> operands = ((SqlCall) right).getOperandList();
    for (int i = 0; i < operands.size(); i += 2) {
      final SqlNode key = operands.get(i);
      final SqlNode value = operands.get(i + 1);
      builder2.put(getValue(key), getValue(value));
    }
    return builder2.build();
  case CAST:
    return getValue(((SqlCall) right).operand(0));
  default:
    if (SqlUtil.isNullLiteral(right, true)) {
      return null;
    }
    if (SqlUtil.isLiteral(right)) {
      return ((SqlLiteral) right).getValue();
    }
    if (right.getKind() == SqlKind.DEFAULT) {
      return null; // currently NULL is the only default value
    }
    throw new NonLiteralException();
  }
}
 
Example 17
Source Project: Bats   Source File: EmptyScope.java    License: Apache License 2.0 5 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlNode expr) {
  return
      ((expr instanceof SqlLiteral)
          || (expr instanceof SqlDynamicParam)
          || (expr instanceof SqlDataTypeSpec)) ? SqlMonotonicity.CONSTANT
          : SqlMonotonicity.NOT_MONOTONIC;
}
 
Example 18
Source Project: calcite   Source File: MssqlSqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc}
 *
 * <p>MSSQL does not support NULLS FIRST, so we emulate using CASE
 * expressions. For example,
 *
 * <blockquote>{@code ORDER BY x NULLS FIRST}</blockquote>
 *
 * <p>becomes
 *
 * <blockquote>
 *   {@code ORDER BY CASE WHEN x IS NULL THEN 0 ELSE 1 END, x}
 * </blockquote>
 */
@Override public SqlNode emulateNullDirection(SqlNode node,
    boolean nullsFirst, boolean desc) {
  // Default ordering preserved
  if (nullCollation.isDefaultOrder(nullsFirst, desc)) {
    return null;
  }

  // Grouping node should preserve grouping, no emulation needed
  if (node.getKind() == SqlKind.GROUPING) {
    return node;
  }

  // Emulate nulls first/last with case ordering
  final SqlParserPos pos = SqlParserPos.ZERO;
  final SqlNodeList whenList =
      SqlNodeList.of(SqlStdOperatorTable.IS_NULL.createCall(pos, node));

  final SqlNode oneLiteral = SqlLiteral.createExactNumeric("1", pos);
  final SqlNode zeroLiteral = SqlLiteral.createExactNumeric("0", pos);

  if (nullsFirst) {
    // IS NULL THEN 0 ELSE 1 END
    return SqlStdOperatorTable.CASE.createCall(null, pos,
        null, whenList, SqlNodeList.of(zeroLiteral), oneLiteral);
  } else {
    // IS NULL THEN 1 ELSE 0 END
    return SqlStdOperatorTable.CASE.createCall(null, pos,
        null, whenList, SqlNodeList.of(oneLiteral), zeroLiteral);
  }
}
 
Example 19
Source Project: calcite   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlTimeLiteral parseTimeLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final DateTimeUtils.PrecisionTime pt =
      DateTimeUtils.parsePrecisionDateTimeLiteral(dateStr,
          Format.PER_THREAD.get().time, DateTimeUtils.UTC_ZONE, -1);
  if (pt == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("TIME", s,
            RESOURCE.badFormat(DateTimeUtils.TIME_FORMAT_STRING).str()));
  }
  final TimeString t = TimeString.fromCalendarFields(pt.getCalendar())
      .withFraction(pt.getFraction());
  return SqlLiteral.createTime(t, pt.getPrecision(), pos);
}
 
Example 20
Source Project: calcite   Source File: MssqlSqlDialect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unparses datetime floor for Microsoft SQL Server.
 * There is no TRUNC function, so simulate this using calls to CONVERT.
 *
 * @param writer Writer
 * @param call Call
 */
private void unparseFloor(SqlWriter writer, SqlCall call) {
  SqlLiteral node = call.operand(1);
  TimeUnitRange unit = (TimeUnitRange) node.getValue();

  switch (unit) {
  case YEAR:
    unparseFloorWithUnit(writer, call, 4, "-01-01");
    break;
  case MONTH:
    unparseFloorWithUnit(writer, call, 7, "-01");
    break;
  case WEEK:
    writer.print("CONVERT(DATETIME, CONVERT(VARCHAR(10), "
        + "DATEADD(day, - (6 + DATEPART(weekday, ");
    call.operand(0).unparse(writer, 0, 0);
    writer.print(")) % 7, ");
    call.operand(0).unparse(writer, 0, 0);
    writer.print("), 126))");
    break;
  case DAY:
    unparseFloorWithUnit(writer, call, 10, "");
    break;
  case HOUR:
    unparseFloorWithUnit(writer, call, 13, ":00:00");
    break;
  case MINUTE:
    unparseFloorWithUnit(writer, call, 16, ":00");
    break;
  case SECOND:
    unparseFloorWithUnit(writer, call, 19, ":00");
    break;
  default:
    throw new IllegalArgumentException("MSSQL does not support FLOOR for time unit: "
        + unit);
  }
}
 
Example 21
Source Project: Bats   Source File: SqlLiteralChainOperator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Concatenates the operands of a call to this operator.
 */
public static SqlLiteral concatenateOperands(SqlCall call) {
  final List<SqlNode> operandList = call.getOperandList();
  assert operandList.size() > 0;
  assert operandList.get(0) instanceof SqlLiteral
      : operandList.get(0).getClass();
  return SqlUtil.concatenateLiterals(
      Util.cast(operandList, SqlLiteral.class));
}
 
Example 22
Source Project: calcite   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a LiteralChain expression: that is, concatenates the operands
 * immediately, to produce a single literal string.
 *
 * <p>Called automatically via reflection.
 */
public RexNode convertLiteralChain(
    SqlRexContext cx,
    SqlLiteralChainOperator op,
    SqlCall call) {
  Util.discard(cx);

  SqlLiteral sum = SqlLiteralChainOperator.concatenateOperands(call);
  return cx.convertLiteral(sum);
}
 
Example 23
Source Project: calcite   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlIntervalLiteral parseIntervalLiteral(SqlParserPos pos,
    int sign, String s, SqlIntervalQualifier intervalQualifier) {
  final String intervalStr = parseString(s);
  if (intervalStr.equals("")) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalIntervalLiteral(s + " "
            + intervalQualifier.toString(), pos.toString()));
  }
  return SqlLiteral.createInterval(sign, intervalStr, intervalQualifier, pos);
}
 
Example 24
Source Project: dremio-oss   Source File: SqlAlterTableChangeColumn.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 == 3, "SqlAlterTableChangeColumn.createCall() " +
      "has to get 3 operands!");

  return new SqlAlterTableChangeColumn(
      pos,
      (SqlIdentifier) operands[0],
      (SqlIdentifier) operands[1],
      (SqlColumnDeclaration) operands[2]);
}
 
Example 25
Source Project: calcite   Source File: StandardConvertletTable.java    License: 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 26
Source Project: calcite   Source File: SqlParserUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlDateLiteral parseDateLiteral(String s, SqlParserPos pos) {
  final String dateStr = parseString(s);
  final Calendar cal =
      DateTimeUtils.parseDateFormat(dateStr, Format.PER_THREAD.get().date,
          DateTimeUtils.UTC_ZONE);
  if (cal == null) {
    throw SqlUtil.newContextException(pos,
        RESOURCE.illegalLiteral("DATE", s,
            RESOURCE.badFormat(DateTimeUtils.DATE_FORMAT_STRING).str()));
  }
  final DateString d = DateString.fromCalendarFields(cal);
  return SqlLiteral.createDate(d, pos);
}
 
Example 27
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode visit(SqlIdentifier id) {
	if (id.isSimple()) {
		return id;
	}
	SqlOperator operator = id.names.get(0).equals(alpha)
		? SqlStdOperatorTable.PREV : SqlStdOperatorTable.LAST;

	return operator.createCall(SqlParserPos.ZERO, id,
		SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO));
}
 
Example 28
Source Project: dremio-oss   Source File: SqlCreateReflection.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlCreateReflection createRaw(SqlParserPos pos, SqlIdentifier tblName, SqlNodeList displayList,
                                            SqlNodeList distributionList, SqlNodeList partitionList,
                                            SqlNodeList sortList,
                                            PartitionDistributionStrategy partitionDistributionStrategy,
                                            SqlIdentifier name) {
  return new SqlCreateReflection(pos, tblName, SqlLiteral.createBoolean(true, SqlParserPos.ZERO), displayList, null, null,
      distributionList, partitionList, sortList, partitionDistributionStrategy, name);
}
 
Example 29
Source Project: Bats   Source File: SqlJsonValueFunction.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlCall createCall(SqlLiteral functionQualifier,
    SqlParserPos pos, SqlNode... operands) {
  List<SqlNode> operandList = new ArrayList<>();
  operandList.add(operands[0]);
  if (operands[1] == null) {
    operandList.add(
        SqlLiteral.createSymbol(SqlJsonValueEmptyOrErrorBehavior.NULL, pos));
    operandList.add(SqlLiteral.createNull(pos));
  } else {
    operandList.add(operands[1]);
    operandList.add(operands[2]);
  }
  if (operands[3] == null) {
    operandList.add(
        SqlLiteral.createSymbol(SqlJsonValueEmptyOrErrorBehavior.NULL, pos));
    operandList.add(SqlLiteral.createNull(pos));
  } else {
    operandList.add(operands[3]);
    operandList.add(operands[4]);
  }
  if (operands.length == 6 && operands[5] != null) {
    if (returnAny) {
      throw new IllegalArgumentException(
          "illegal returning clause in json_value_any function");
    }
    operandList.add(operands[5]);
  } else if (!returnAny) {
    SqlDataTypeSpec defaultTypeSpec =
        new SqlDataTypeSpec(new SqlIdentifier("VARCHAR", pos), 2000, -1,
            null, null, pos);
    operandList.add(defaultTypeSpec);
  }
  return super.createCall(functionQualifier, pos,
      operandList.toArray(SqlNode.EMPTY_ARRAY));
}
 
Example 30
Source Project: Bats   Source File: TypeInferenceUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
  final RelDataTypeFactory factory = opBinding.getTypeFactory();
  final boolean isNullable = opBinding
      .getOperandType(0)
      .isNullable();

  RelDataType ret = factory.createTypeWithNullability(
      opBinding.getOperandType(1),
      isNullable);
  if (opBinding instanceof SqlCallBinding) {
    SqlCallBinding callBinding = (SqlCallBinding) opBinding;
    SqlNode operand0 = callBinding.operand(0);

    // dynamic parameters and null constants need their types assigned
    // to them using the type they are casted to.
    if(((operand0 instanceof SqlLiteral)
        && (((SqlLiteral) operand0).getValue() == null))
            || (operand0 instanceof SqlDynamicParam)) {
      callBinding.getValidator().setValidatedNodeType(
          operand0,
          ret);
    }
  }

  return ret;
}