Java Code Examples for org.apache.calcite.sql.SqlLiteral#getTypeName()

The following examples show how to use org.apache.calcite.sql.SqlLiteral#getTypeName() . 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: 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 2
Source File: SqlValidatorImpl.java    From flink 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 3
Source File: SetOptionHandler.java    From Bats with Apache License 2.0 5 votes vote down vote up
private static Object sqlLiteralToObject(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 bigDecimal.longValue();
    } else {
      return bigDecimal.doubleValue();
    }
  }

  case DOUBLE:
  case FLOAT:
    return ((BigDecimal) object).doubleValue();

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

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

  case BOOLEAN:
    return object;

  default:
    throw UserException.validationError()
      .message("Drill doesn't support assigning literals of type %s in SET statements.", typeName)
      .build(logger);
  }
}
 
Example 4
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 5
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 6
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 7
Source File: SqlNodeToRexConverterImpl.java    From Bats with Apache License 2.0 4 votes vote down vote up
public RexNode convertLiteral(
    SqlRexContext cx,
    SqlLiteral literal) {
  RexBuilder rexBuilder = cx.getRexBuilder();
  RelDataTypeFactory typeFactory = cx.getTypeFactory();
  SqlValidator validator = cx.getValidator();
  if (literal.getValue() == null) {
    // Since there is no eq. RexLiteral of SqlLiteral.Unknown we
    // treat it as a cast(null as boolean)
    RelDataType type;
    if (literal.getTypeName() == SqlTypeName.BOOLEAN) {
      type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
      type = typeFactory.createTypeWithNullability(type, true);
    } else {
      type = validator.getValidatedNodeType(literal);
    }
    return rexBuilder.makeCast(
        type,
        rexBuilder.constantNull());
  }

  BitString bitString;
  SqlIntervalLiteral.IntervalValue intervalValue;
  long l;

  switch (literal.getTypeName()) {
  case DECIMAL:
    // exact number
    BigDecimal bd = literal.getValueAs(BigDecimal.class);
    return rexBuilder.makeExactLiteral(
        bd,
        literal.createSqlType(typeFactory));

  case DOUBLE:
    // approximate type
    // TODO:  preserve fixed-point precision and large integers
    return rexBuilder.makeApproxLiteral(literal.getValueAs(BigDecimal.class));

  case CHAR:
    return rexBuilder.makeCharLiteral(literal.getValueAs(NlsString.class));
  case BOOLEAN:
    return rexBuilder.makeLiteral(literal.getValueAs(Boolean.class));
  case BINARY:
    bitString = literal.getValueAs(BitString.class);
    Preconditions.checkArgument((bitString.getBitCount() % 8) == 0,
        "incomplete octet");

    // An even number of hexits (e.g. X'ABCD') makes whole number
    // of bytes.
    ByteString byteString = new ByteString(bitString.getAsByteArray());
    return rexBuilder.makeBinaryLiteral(byteString);
  case SYMBOL:
    return rexBuilder.makeFlag(literal.getValueAs(Enum.class));
  case TIMESTAMP:
    return rexBuilder.makeTimestampLiteral(
        literal.getValueAs(TimestampString.class),
        ((SqlTimestampLiteral) literal).getPrec());
  case TIME:
    return rexBuilder.makeTimeLiteral(
        literal.getValueAs(TimeString.class),
        ((SqlTimeLiteral) literal).getPrec());
  case DATE:
    return rexBuilder.makeDateLiteral(literal.getValueAs(DateString.class));

  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
  case INTERVAL_DAY:
  case INTERVAL_DAY_HOUR:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    SqlIntervalQualifier sqlIntervalQualifier =
        literal.getValueAs(SqlIntervalLiteral.IntervalValue.class)
            .getIntervalQualifier();
    return rexBuilder.makeIntervalLiteral(
        literal.getValueAs(BigDecimal.class),
        sqlIntervalQualifier);
  default:
    throw Util.unexpected(literal.getTypeName());
  }
}
 
Example 8
Source File: SqlLiteralChainOperator.java    From Bats with Apache License 2.0 4 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startList("", "");
  SqlCollation collation = null;
  for (Ord<SqlNode> operand : Ord.zip(call.getOperandList())) {
    SqlLiteral rand = (SqlLiteral) operand.e;
    if (operand.i > 0) {
      // SQL:2003 says there must be a newline between string
      // fragments.
      writer.newlineAndIndent();
    }
    if (rand instanceof SqlCharStringLiteral) {
      NlsString nls = ((SqlCharStringLiteral) rand).getNlsString();
      if (operand.i == 0) {
        collation = nls.getCollation();

        // print with prefix
        writer.literal(nls.asSql(true, false));
      } else {
        // print without prefix
        writer.literal(nls.asSql(false, false));
      }
    } else if (operand.i == 0) {
      // print with prefix
      rand.unparse(writer, leftPrec, rightPrec);
    } else {
      // print without prefix
      if (rand.getTypeName() == SqlTypeName.BINARY) {
        BitString bs = (BitString) rand.getValue();
        writer.literal("'" + bs.toHexString() + "'");
      } else {
        writer.literal("'" + rand.toValue() + "'");
      }
    }
  }
  if (collation != null) {
    collation.unparse(writer, 0, 0);
  }
  writer.endList(frame);
}
 
Example 9
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
public void validateLiteral(SqlLiteral literal) {
	switch (literal.getTypeName()) {
		case DECIMAL:
			// Decimal and long have the same precision (as 64-bit integers), so
			// the unscaled value of a decimal must fit into a long.

			// REVIEW jvs 4-Aug-2004:  This should probably be calling over to
			// the available calculator implementations to see what they
			// support.  For now use ESP instead.
			//
			// jhyde 2006/12/21: I think the limits should be baked into the
			// type system, not dependent on the calculator implementation.
			BigDecimal bd = (BigDecimal) literal.getValue();
			BigInteger unscaled = bd.unscaledValue();
			long longValue = unscaled.longValue();
			if (!BigInteger.valueOf(longValue).equals(unscaled)) {
				// overflow
				throw newValidationError(literal,
					RESOURCE.numberLiteralOutOfRange(bd.toString()));
			}
			break;

		case DOUBLE:
			validateLiteralAsDouble(literal);
			break;

		case BINARY:
			final BitString bitString = (BitString) literal.getValue();
			if ((bitString.getBitCount() % 8) != 0) {
				throw newValidationError(literal, RESOURCE.binaryLiteralOdd());
			}
			break;

		case DATE:
		case TIME:
		case TIMESTAMP:
			Calendar calendar = literal.getValueAs(Calendar.class);
			final int year = calendar.get(Calendar.YEAR);
			final int era = calendar.get(Calendar.ERA);
			if (year < 1 || era == GregorianCalendar.BC || year > 9999) {
				throw newValidationError(literal,
					RESOURCE.dateLiteralOutOfRange(literal.toString()));
			}
			break;

		case INTERVAL_YEAR:
		case INTERVAL_YEAR_MONTH:
		case INTERVAL_MONTH:
		case INTERVAL_DAY:
		case INTERVAL_DAY_HOUR:
		case INTERVAL_DAY_MINUTE:
		case INTERVAL_DAY_SECOND:
		case INTERVAL_HOUR:
		case INTERVAL_HOUR_MINUTE:
		case INTERVAL_HOUR_SECOND:
		case INTERVAL_MINUTE:
		case INTERVAL_MINUTE_SECOND:
		case INTERVAL_SECOND:
			if (literal instanceof SqlIntervalLiteral) {
				SqlIntervalLiteral.IntervalValue interval =
					(SqlIntervalLiteral.IntervalValue)
						literal.getValue();
				SqlIntervalQualifier intervalQualifier =
					interval.getIntervalQualifier();

				// ensure qualifier is good before attempting to validate literal
				validateIntervalQualifier(intervalQualifier);
				String intervalStr = interval.getIntervalLiteral();
				// throws CalciteContextException if string is invalid
				int[] values = intervalQualifier.evaluateIntervalLiteral(intervalStr,
					literal.getParserPosition(), typeFactory.getTypeSystem());
				Util.discard(values);
			}
			break;
		default:
			// default is to do nothing
	}
}
 
Example 10
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
public SqlNode visit(SqlLiteral literal) {
	if (havingExpr || !validator.getConformance().isGroupByOrdinal()) {
		return super.visit(literal);
	}
	boolean isOrdinalLiteral = literal == root;
	switch (root.getKind()) {
		case GROUPING_SETS:
		case ROLLUP:
		case CUBE:
			if (root instanceof SqlBasicCall) {
				List<SqlNode> operandList = ((SqlBasicCall) root).getOperandList();
				for (SqlNode node : operandList) {
					if (node.equals(literal)) {
						isOrdinalLiteral = true;
						break;
					}
				}
			}
			break;
	}
	if (isOrdinalLiteral) {
		switch (literal.getTypeName()) {
			case DECIMAL:
			case DOUBLE:
				final int intValue = literal.intValue(false);
				if (intValue >= 0) {
					if (intValue < 1 || intValue > select.getSelectList().size()) {
						throw validator.newValidationError(literal,
							RESOURCE.orderByOrdinalOutOfRange());
					}

					// SQL ordinals are 1-based, but Sort's are 0-based
					int ordinal = intValue - 1;
					return SqlUtil.stripAs(select.getSelectList().get(ordinal));
				}
				break;
		}
	}

	return super.visit(literal);
}
 
Example 11
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
public void validateLiteral(SqlLiteral literal) {
	switch (literal.getTypeName()) {
		case DECIMAL:
			// Decimal and long have the same precision (as 64-bit integers), so
			// the unscaled value of a decimal must fit into a long.

			// REVIEW jvs 4-Aug-2004:  This should probably be calling over to
			// the available calculator implementations to see what they
			// support.  For now use ESP instead.
			//
			// jhyde 2006/12/21: I think the limits should be baked into the
			// type system, not dependent on the calculator implementation.
			BigDecimal bd = (BigDecimal) literal.getValue();
			BigInteger unscaled = bd.unscaledValue();
			long longValue = unscaled.longValue();
			if (!BigInteger.valueOf(longValue).equals(unscaled)) {
				// overflow
				throw newValidationError(literal,
					RESOURCE.numberLiteralOutOfRange(bd.toString()));
			}
			break;

		case DOUBLE:
			validateLiteralAsDouble(literal);
			break;

		case BINARY:
			final BitString bitString = (BitString) literal.getValue();
			if ((bitString.getBitCount() % 8) != 0) {
				throw newValidationError(literal, RESOURCE.binaryLiteralOdd());
			}
			break;

		case DATE:
		case TIME:
		case TIMESTAMP:
			Calendar calendar = literal.getValueAs(Calendar.class);
			final int year = calendar.get(Calendar.YEAR);
			final int era = calendar.get(Calendar.ERA);
			if (year < 1 || era == GregorianCalendar.BC || year > 9999) {
				throw newValidationError(literal,
					RESOURCE.dateLiteralOutOfRange(literal.toString()));
			}
			break;

		case INTERVAL_YEAR:
		case INTERVAL_YEAR_MONTH:
		case INTERVAL_MONTH:
		case INTERVAL_DAY:
		case INTERVAL_DAY_HOUR:
		case INTERVAL_DAY_MINUTE:
		case INTERVAL_DAY_SECOND:
		case INTERVAL_HOUR:
		case INTERVAL_HOUR_MINUTE:
		case INTERVAL_HOUR_SECOND:
		case INTERVAL_MINUTE:
		case INTERVAL_MINUTE_SECOND:
		case INTERVAL_SECOND:
			if (literal instanceof SqlIntervalLiteral) {
				SqlIntervalLiteral.IntervalValue interval =
					(SqlIntervalLiteral.IntervalValue)
						literal.getValue();
				SqlIntervalQualifier intervalQualifier =
					interval.getIntervalQualifier();

				// ensure qualifier is good before attempting to validate literal
				validateIntervalQualifier(intervalQualifier);
				String intervalStr = interval.getIntervalLiteral();
				// throws CalciteContextException if string is invalid
				int[] values = intervalQualifier.evaluateIntervalLiteral(intervalStr,
					literal.getParserPosition(), typeFactory.getTypeSystem());
				Util.discard(values);
			}
			break;
		default:
			// default is to do nothing
	}
}
 
Example 12
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
public SqlNode visit(SqlLiteral literal) {
	if (havingExpr || !validator.getConformance().isGroupByOrdinal()) {
		return super.visit(literal);
	}
	boolean isOrdinalLiteral = literal == root;
	switch (root.getKind()) {
		case GROUPING_SETS:
		case ROLLUP:
		case CUBE:
			if (root instanceof SqlBasicCall) {
				List<SqlNode> operandList = ((SqlBasicCall) root).getOperandList();
				for (SqlNode node : operandList) {
					if (node.equals(literal)) {
						isOrdinalLiteral = true;
						break;
					}
				}
			}
			break;
	}
	if (isOrdinalLiteral) {
		switch (literal.getTypeName()) {
			case DECIMAL:
			case DOUBLE:
				final int intValue = literal.intValue(false);
				if (intValue >= 0) {
					if (intValue < 1 || intValue > select.getSelectList().size()) {
						throw validator.newValidationError(literal,
							RESOURCE.orderByOrdinalOutOfRange());
					}

					// SQL ordinals are 1-based, but Sort's are 0-based
					int ordinal = intValue - 1;
					return SqlUtil.stripAs(select.getSelectList().get(ordinal));
				}
				break;
		}
	}

	return super.visit(literal);
}
 
Example 13
Source File: SqlNodeToRexConverterImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RexNode convertLiteral(
    SqlRexContext cx,
    SqlLiteral literal) {
  RexBuilder rexBuilder = cx.getRexBuilder();
  RelDataTypeFactory typeFactory = cx.getTypeFactory();
  SqlValidator validator = cx.getValidator();
  if (literal.getValue() == null) {
    // Since there is no eq. RexLiteral of SqlLiteral.Unknown we
    // treat it as a cast(null as boolean)
    RelDataType type;
    if (literal.getTypeName() == SqlTypeName.BOOLEAN) {
      type = typeFactory.createSqlType(SqlTypeName.BOOLEAN);
      type = typeFactory.createTypeWithNullability(type, true);
    } else {
      type = validator.getValidatedNodeType(literal);
    }
    return rexBuilder.makeNullLiteral(type);
  }

  BitString bitString;
  SqlIntervalLiteral.IntervalValue intervalValue;
  long l;

  switch (literal.getTypeName()) {
  case DECIMAL:
    // exact number
    BigDecimal bd = literal.getValueAs(BigDecimal.class);
    return rexBuilder.makeExactLiteral(
        bd,
        literal.createSqlType(typeFactory));

  case DOUBLE:
    // approximate type
    // TODO:  preserve fixed-point precision and large integers
    return rexBuilder.makeApproxLiteral(literal.getValueAs(BigDecimal.class));

  case CHAR:
    return rexBuilder.makeCharLiteral(literal.getValueAs(NlsString.class));
  case BOOLEAN:
    return rexBuilder.makeLiteral(literal.getValueAs(Boolean.class));
  case BINARY:
    bitString = literal.getValueAs(BitString.class);
    Preconditions.checkArgument((bitString.getBitCount() % 8) == 0,
        "incomplete octet");

    // An even number of hexits (e.g. X'ABCD') makes whole number
    // of bytes.
    ByteString byteString = new ByteString(bitString.getAsByteArray());
    return rexBuilder.makeBinaryLiteral(byteString);
  case SYMBOL:
    return rexBuilder.makeFlag(literal.getValueAs(Enum.class));
  case TIMESTAMP:
    return rexBuilder.makeTimestampLiteral(
        literal.getValueAs(TimestampString.class),
        ((SqlTimestampLiteral) literal).getPrec());
  case TIME:
    return rexBuilder.makeTimeLiteral(
        literal.getValueAs(TimeString.class),
        ((SqlTimeLiteral) literal).getPrec());
  case DATE:
    return rexBuilder.makeDateLiteral(literal.getValueAs(DateString.class));

  case INTERVAL_YEAR:
  case INTERVAL_YEAR_MONTH:
  case INTERVAL_MONTH:
  case INTERVAL_DAY:
  case INTERVAL_DAY_HOUR:
  case INTERVAL_DAY_MINUTE:
  case INTERVAL_DAY_SECOND:
  case INTERVAL_HOUR:
  case INTERVAL_HOUR_MINUTE:
  case INTERVAL_HOUR_SECOND:
  case INTERVAL_MINUTE:
  case INTERVAL_MINUTE_SECOND:
  case INTERVAL_SECOND:
    SqlIntervalQualifier sqlIntervalQualifier =
        literal.getValueAs(SqlIntervalLiteral.IntervalValue.class)
            .getIntervalQualifier();
    return rexBuilder.makeIntervalLiteral(
        literal.getValueAs(BigDecimal.class),
        sqlIntervalQualifier);
  default:
    throw Util.unexpected(literal.getTypeName());
  }
}
 
Example 14
Source File: SqlLiteralChainOperator.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startList("", "");
  SqlCollation collation = null;
  for (Ord<SqlNode> operand : Ord.zip(call.getOperandList())) {
    SqlLiteral rand = (SqlLiteral) operand.e;
    if (operand.i > 0) {
      // SQL:2003 says there must be a newline between string
      // fragments.
      writer.newlineAndIndent();
    }
    if (rand instanceof SqlCharStringLiteral) {
      NlsString nls = ((SqlCharStringLiteral) rand).getNlsString();
      if (operand.i == 0) {
        collation = nls.getCollation();

        // print with prefix
        writer.literal(nls.asSql(true, false, writer.getDialect()));
      } else {
        // print without prefix
        writer.literal(nls.asSql(false, false, writer.getDialect()));
      }
    } else if (operand.i == 0) {
      // print with prefix
      rand.unparse(writer, leftPrec, rightPrec);
    } else {
      // print without prefix
      if (rand.getTypeName() == SqlTypeName.BINARY) {
        BitString bs = (BitString) rand.getValue();
        writer.literal("'" + bs.toHexString() + "'");
      } else {
        writer.literal("'" + rand.toValue() + "'");
      }
    }
  }
  if (collation != null) {
    collation.unparse(writer);
  }
  writer.endList(frame);
}