Search in sources :

Example 6 with SqlLiteral

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);
    }
}
Also used : ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlLiteral(org.apache.calcite.sql.SqlLiteral) RexNode(org.apache.calcite.rex.RexNode)

Example 7 with SqlLiteral

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;
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) NlsString(org.apache.calcite.util.NlsString) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlLiteral(org.apache.calcite.sql.SqlLiteral) BigDecimal(java.math.BigDecimal) RexNode(org.apache.calcite.rex.RexNode)

Example 8 with SqlLiteral

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();
}
Also used : BasicSqlType(org.apache.calcite.sql.type.BasicSqlType) Calendar(java.util.Calendar) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) SqlLiteral(org.apache.calcite.sql.SqlLiteral)

Example 9 with SqlLiteral

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));
}
Also used : OptionScope(org.apache.drill.exec.server.options.OptionValue.OptionScope) QueryOptionManager(org.apache.drill.exec.server.options.QueryOptionManager) OptionValue(org.apache.drill.exec.server.options.OptionValue) SqlSetOption(org.apache.calcite.sql.SqlSetOption) NlsString(org.apache.calcite.util.NlsString) SqlLiteral(org.apache.calcite.sql.SqlLiteral) OptionManager(org.apache.drill.exec.server.options.OptionManager) QueryOptionManager(org.apache.drill.exec.server.options.QueryOptionManager) SqlNode(org.apache.calcite.sql.SqlNode)

Example 10 with SqlLiteral

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));
}
Also used : AliasRegistry(org.apache.drill.exec.alias.AliasRegistry) SqlCreateAlias(org.apache.drill.exec.planner.sql.parser.SqlCreateAlias) Aliases(org.apache.drill.exec.alias.Aliases) SqlLiteral(org.apache.calcite.sql.SqlLiteral)

Aggregations

SqlLiteral (org.apache.calcite.sql.SqlLiteral)42 SqlNode (org.apache.calcite.sql.SqlNode)19 RelDataType (org.apache.calcite.rel.type.RelDataType)12 SqlCall (org.apache.calcite.sql.SqlCall)8 SqlNodeList (org.apache.calcite.sql.SqlNodeList)7 RexNode (org.apache.calcite.rex.RexNode)6 ArrayList (java.util.ArrayList)5 TimeUnitRange (org.apache.calcite.avatica.util.TimeUnitRange)5 NlsString (org.apache.calcite.util.NlsString)5 SqlBasicCall (org.apache.calcite.sql.SqlBasicCall)4 SqlIdentifier (org.apache.calcite.sql.SqlIdentifier)4 SqlMatchRecognize (org.apache.calcite.sql.SqlMatchRecognize)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 Map (java.util.Map)3 RelDataTypeFactory (org.apache.calcite.rel.type.RelDataTypeFactory)3 RelDataTypeField (org.apache.calcite.rel.type.RelDataTypeField)3 RexLiteral (org.apache.calcite.rex.RexLiteral)3 SqlCallBinding (org.apache.calcite.sql.SqlCallBinding)3 BitString (org.apache.calcite.util.BitString)3 HashMap (java.util.HashMap)2