use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.
the class SqlToRelConverter method convertOrder.
/**
* Converts a query's ORDER BY clause, if any.
*
* @param select Query
* @param bb Blackboard
* @param collation Collation list
* @param orderExprList Method populates this list with orderBy expressions
* not present in selectList
* @param offset Expression for number of rows to discard before
* returning first row
* @param fetch Expression for number of rows to fetch
*/
protected void convertOrder(SqlSelect select, Blackboard bb, RelCollation collation, List<SqlNode> orderExprList, SqlNode offset, SqlNode fetch) {
if (select.getOrderList() == null || select.getOrderList().getList().isEmpty()) {
assert collation.getFieldCollations().isEmpty();
if ((offset == null || (offset instanceof SqlLiteral && ((SqlLiteral) offset).bigDecimalValue().equals(BigDecimal.ZERO))) && fetch == null) {
return;
}
}
// Create a sorter using the previously constructed collations.
bb.setRoot(LogicalSort.create(bb.root, collation, offset == null ? null : convertExpression(offset), fetch == null ? null : convertExpression(fetch)), false);
// If it is the top node, use the real collation, but don't trim fields.
if (orderExprList.size() > 0 && !bb.top) {
final List<RexNode> exprs = new ArrayList<>();
final RelDataType rowType = bb.root.getRowType();
final int fieldCount = rowType.getFieldCount() - orderExprList.size();
for (int i = 0; i < fieldCount; i++) {
exprs.add(rexBuilder.makeInputRef(bb.root, i));
}
bb.setRoot(LogicalProject.create(bb.root, exprs, rowType.getFieldNames().subList(0, fieldCount)), false);
}
}
use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.
the class SqlToRelConverter method convertLiteralInValuesList.
private RexLiteral convertLiteralInValuesList(SqlNode sqlNode, Blackboard bb, RelDataType rowType, int iField) {
if (!(sqlNode instanceof SqlLiteral)) {
return null;
}
RelDataTypeField field = rowType.getFieldList().get(iField);
RelDataType type = field.getType();
if (type.isStruct()) {
// don't use LogicalValues for those
return null;
}
RexNode literalExpr = exprConverter.convertLiteral(bb, (SqlLiteral) sqlNode);
if (!(literalExpr instanceof RexLiteral)) {
assert literalExpr.isA(SqlKind.CAST);
RexNode child = ((RexCall) literalExpr).getOperands().get(0);
assert RexLiteral.isNullLiteral(child);
// in LogicalValues digest, so it's OK to lose it here
return (RexLiteral) child;
}
RexLiteral literal = (RexLiteral) literalExpr;
Comparable value = literal.getValue();
if (SqlTypeUtil.isExactNumeric(type) && SqlTypeUtil.hasScale(type)) {
BigDecimal roundedValue = NumberUtil.rescaleBigDecimal((BigDecimal) value, type.getScale());
return rexBuilder.makeExactLiteral(roundedValue, type);
}
if ((value instanceof NlsString) && (type.getSqlTypeName() == SqlTypeName.CHAR)) {
// pad fixed character type
NlsString unpadded = (NlsString) value;
return rexBuilder.makeCharLiteral(new NlsString(Spaces.padRight(unpadded.getValue(), type.getPrecision()), unpadded.getCharsetName(), unpadded.getCollation()));
}
return literal;
}
use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.
the class SqlLimitsTest method printLimit.
private void printLimit(PrintWriter pw, String desc, RelDataType type, boolean sign, SqlTypeName.Limit limit, boolean beyond) {
Object o = ((BasicSqlType) type).getLimit(sign, limit, beyond);
if (o == null) {
return;
}
pw.print(desc);
String s;
if (o instanceof byte[]) {
int k = 0;
StringBuilder buf = new StringBuilder("{");
for (byte b : (byte[]) o) {
if (k++ > 0) {
buf.append(", ");
}
buf.append(Integer.toHexString(b & 0xff));
}
buf.append("}");
s = buf.toString();
} else if (o instanceof Calendar) {
Calendar calendar = (Calendar) o;
DateFormat dateFormat = getDateFormat(type.getSqlTypeName());
dateFormat.setTimeZone(DateTimeUtils.UTC_ZONE);
s = dateFormat.format(calendar.getTime());
} else {
s = o.toString();
}
pw.print(s);
SqlLiteral literal = type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
pw.print("; as SQL: ");
pw.print(literal.toSqlString(AnsiSqlDialect.DEFAULT));
pw.println();
}
use of org.apache.calcite.sql.SqlLiteral in project drill by axbaretto.
the class SetOptionHandler method getPlan.
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ValidationException, ForemanSetupException {
final SqlSetOption option = unwrap(sqlNode, SqlSetOption.class);
final SqlNode value = option.getValue();
if (value != null && !(value instanceof SqlLiteral)) {
throw UserException.validationError().message("Drill does not support assigning non-literal values in SET statements.").build(logger);
}
final String scope = option.getScope();
final OptionValue.OptionScope optionScope;
if (scope == null) {
// No scope mentioned assumed SESSION
optionScope = OptionScope.SESSION;
} else {
switch(scope.toLowerCase()) {
case "session":
optionScope = OptionScope.SESSION;
break;
case "system":
optionScope = OptionScope.SYSTEM;
break;
default:
throw UserException.validationError().message("Invalid OPTION scope %s. Scope must be SESSION or SYSTEM.", scope).build(logger);
}
}
final QueryOptionManager options = context.getOptions();
if (optionScope == OptionScope.SYSTEM) {
// administrative privileges.
if (context.isUserAuthenticationEnabled() && !ImpersonationUtil.hasAdminPrivileges(context.getQueryUserName(), ExecConstants.ADMIN_USERS_VALIDATOR.getAdminUsers(options), ExecConstants.ADMIN_USER_GROUPS_VALIDATOR.getAdminUserGroups(options))) {
throw UserException.permissionError().message("Not authorized to change SYSTEM options.").build(logger);
}
}
final String optionName = option.getName().toString();
// Currently, we convert multi-part identifier to a string.
final OptionManager chosenOptions = options.getOptionManager(optionScope);
if (value != null) {
// SET option
final Object literalObj = sqlLiteralToObject((SqlLiteral) value);
chosenOptions.setLocalOption(optionName, literalObj);
} else {
// RESET option
if ("ALL".equalsIgnoreCase(optionName)) {
chosenOptions.deleteAllLocalOptions();
} else {
chosenOptions.deleteLocalOption(optionName);
}
}
return DirectPlan.createDirectPlan(context, true, String.format("%s updated.", optionName));
}
use of org.apache.calcite.sql.SqlLiteral in project drill by apache.
the class CreateAliasHandler method getPlan.
@Override
public PhysicalPlan getPlan(SqlNode sqlNode) throws ForemanSetupException, IOException {
checkAliasesEnabled();
SqlCreateAlias node = unwrap(sqlNode, SqlCreateAlias.class);
String alias = SchemaPath.getCompoundPath(node.getAlias().names.toArray(new String[0])).toExpr();
String aliasTarget = ((SqlLiteral) node.getAliasKind()).toValue();
AliasRegistry aliasRegistry = getAliasRegistry(aliasTarget);
String value = getValue(node, aliasTarget);
boolean replace = ((SqlLiteral) node.getReplace()).booleanValue();
Aliases aliases = getAliases(node, aliasRegistry);
if (!aliases.put(alias, value, replace)) {
throw UserException.validationError().message("Alias with given name [%s] already exists", alias).build(logger);
}
return DirectPlan.createDirectPlan(context, true, String.format("%s alias '%s' for '%s' created successfully", StringUtils.capitalize(aliasTarget.toLowerCase(Locale.ROOT)), alias, value));
}
Aggregations