org.apache.calcite.sql.SqlLiteral Java Examples

The following examples show how to use org.apache.calcite.sql.SqlLiteral. 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: RelToSqlConverter.java    From quark with 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 File: RelToSqlConverter.java    From calcite with 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 #3
Source File: SqlRefreshTable.java    From dremio-oss with 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 #4
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 #5
Source File: SqlOperatorBindingTest.java    From calcite with 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 File: SqlValidatorImpl.java    From Flink-CEPplus with 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 #7
Source File: SqlCreateHiveDatabase.java    From flink with 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 #8
Source File: RequestUtils.java    From incubator-pinot with 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 #9
Source File: SqlParserUtil.java    From calcite with 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 #10
Source File: SqlCase.java    From calcite with 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 #11
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void validateLiteral(SqlLiteral literal) {
	if (literal.getTypeName() == DECIMAL) {
		final BigDecimal decimal = literal.getValueAs(BigDecimal.class);
		if (decimal.precision() > DecimalType.MAX_PRECISION) {
			throw newValidationError(
				literal,
				Static.RESOURCE.numberLiteralOutOfRange(decimal.toString()));
		}
	}
	super.validateLiteral(literal);
}
 
Example #12
Source File: SqlAlterHiveDatabaseLocation.java    From flink with Apache License 2.0 5 votes vote down vote up
public SqlAlterHiveDatabaseLocation(SqlParserPos pos, SqlIdentifier databaseName, SqlCharStringLiteral location) {
	super(pos, databaseName, new SqlNodeList(pos));
	getPropertyList().add(new SqlTableOption(
			SqlLiteral.createCharString(DATABASE_LOCATION_URI, location.getParserPosition()),
			location,
			location.getParserPosition()));
	this.location = location;
}
 
Example #13
Source File: SqlAlterTableAddColumns.java    From dremio-oss with 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, "SqlAlterTableAddColumns.createCall() " +
      "has to get 2 operands!");

  if (((SqlNodeList) operands[1]).getList().size() == 0) {
    throw UserException.parseError().message("Columns not specified.").buildSilently();
  }

  return new SqlAlterTableAddColumns(
      pos,
      (SqlIdentifier) operands[0],
      (SqlNodeList) operands[1]);
}
 
Example #14
Source File: SqlAnalyzeTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlAnalyzeTable(SqlParserPos pos, SqlIdentifier tblName, SqlLiteral estimate,
    SqlNodeList fieldList, SqlNumericLiteral samplePercent) {
  super(pos);
  this.tblName = tblName;
  this.estimate = estimate;
  this.fieldList = fieldList;
  this.samplePercent = samplePercent;
}
 
Example #15
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 #16
Source File: SqlJsonValueFunction.java    From Bats with 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 #17
Source File: RelToSqlConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlNode createAlwaysFalseCondition() {
  // Building the select query in the form:
  // select * from VALUES(NULL,NULL ...) where 1=0
  // Use condition 1=0 since "where false" does not seem to be supported
  // on some DB vendors.
  return SqlStdOperatorTable.EQUALS.createCall(POS,
          ImmutableList.of(SqlLiteral.createExactNumeric("1", POS),
                  SqlLiteral.createExactNumeric("0", POS)));
}
 
Example #18
Source File: SqlImplementor.java    From Bats with 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 #19
Source File: SqlCreateView.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public List<SqlNode> getOperandList() {
	List<SqlNode> ops = new ArrayList<>();
	ops.add(viewName);
	ops.add(fieldList);
	ops.add(query);
	ops.add(SqlLiteral.createBoolean(getReplace(), SqlParserPos.ZERO));
	return ops;
}
 
Example #20
Source File: SetOptionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static OptionValue createOptionValue(final String name, final OptionValue.OptionType type,
                                             final SqlLiteral literal) {
  final Object object = literal.getValue();
  final SqlTypeName typeName = literal.getTypeName();
  switch (typeName) {
  case DECIMAL: {
    final BigDecimal bigDecimal = (BigDecimal) object;
    if (bigDecimal.scale() == 0) {
      return OptionValue.createLong(type, name, bigDecimal.longValue());
    } else {
      return OptionValue.createDouble(type, name, bigDecimal.doubleValue());
    }
  }

  case DOUBLE:
  case FLOAT:
    return OptionValue.createDouble(type, name, ((BigDecimal) object).doubleValue());

  case SMALLINT:
  case TINYINT:
  case BIGINT:
  case INTEGER:
    return OptionValue.createLong(type, name, ((BigDecimal) object).longValue());

  case VARBINARY:
  case VARCHAR:
  case CHAR:
    return OptionValue.createString(type, name, ((NlsString) object).getValue());

  case BOOLEAN:
    return OptionValue.createBoolean(type, name, (Boolean) object);

  default:
    throw UserException.validationError()
      .message("Dremio doesn't support assigning literals of type %s in SET statements.", typeName)
      .build(logger);
  }
}
 
Example #21
Source File: AlterTableSetOptionHandler.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static AttributeValue createAttributeValue(final SqlLiteral literal) {
  final Object object = literal.getValue();
  final SqlTypeName typeName = literal.getTypeName();
  switch (typeName) {
    case DOUBLE:
    case FLOAT:
      return AttributeValue.of(((BigDecimal) object).doubleValue());

    case SMALLINT:
    case TINYINT:
    case BIGINT:
    case INTEGER:
      return AttributeValue.of(((BigDecimal) object).longValue());

    case VARBINARY:
    case VARCHAR:
    case CHAR:
      return AttributeValue.of(((NlsString) object).getValue());

    case BOOLEAN:
      return AttributeValue.of((Boolean) object);

    default:
      throw UserException.validationError()
          .message("Dremio doesn't support assigning literals of type %s in SET statements.", typeName)
          .buildSilently();
  }
}
 
Example #22
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 #23
Source File: TypeInferenceUtils.java    From Bats with 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;
}
 
Example #24
Source File: ConvSqlWriter.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private void doWriteFetchNext(SqlNode fetch, SqlNode offset) {
    if (offset == null && !configurer.allowNoOffset())
        offset = SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO);

    if (fetch != null && !configurer.allowNoOrderByWithFetch() && lastFrame != null
            && lastFrame.getFrameType() != FrameTypeEnum.ORDER_BY_LIST) { // MSSQL requires ORDER_BY list for FETCH clause, so must append one here.
        DUMMY_ORDER_BY_NODE.unparse(this, 0, 0);
    }

    if (offset != null) {
        this.newlineAndIndent();
        final Frame offsetFrame = this.startList(FrameTypeEnum.OFFSET);
        this.keyword("OFFSET");
        offset.unparse(this, -1, -1);
        this.keyword("ROWS");
        this.endList(offsetFrame);
    }
    if (fetch != null) {
        if (!configurer.allowFetchNoRows() && fetch instanceof SqlNumericLiteral)
            if (((SqlNumericLiteral) fetch).toValue().equals("0"))
                fetch = SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO);

        this.newlineAndIndent();
        final Frame fetchFrame = this.startList(FrameTypeEnum.FETCH);
        this.keyword("FETCH");
        this.keyword("NEXT");
        fetch.unparse(this, -1, -1);
        this.keyword("ROWS");
        this.keyword("ONLY");
        this.endList(fetchFrame);
    }
}
 
Example #25
Source File: SqlCreateReflection.java    From dremio-oss with 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 #26
Source File: SqlValidatorImpl.java    From Flink-CEPplus with 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 #27
Source File: SqlParserUtil.java    From calcite with 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 #28
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 #29
Source File: SqlAlterTableChangeColumn.java    From dremio-oss with 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 #30
Source File: SqlParserUtil.java    From calcite with 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);
}