Search in sources :

Example 1 with SqlLiteral

use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.

the class SqlCastFunction method inferReturnType.

// ~ Methods ----------------------------------------------------------------
public RelDataType inferReturnType(SqlOperatorBinding opBinding) {
    assert opBinding.getOperandCount() == 2;
    RelDataType ret = opBinding.getOperandType(1);
    RelDataType firstType = opBinding.getOperandType(0);
    ret = opBinding.getTypeFactory().createTypeWithNullability(ret, firstType.isNullable());
    if (opBinding instanceof SqlCallBinding) {
        SqlCallBinding callBinding = (SqlCallBinding) opBinding;
        SqlNode operand0 = callBinding.operand(0);
        // to them using the type they are casted to.
        if (((operand0 instanceof SqlLiteral) && (((SqlLiteral) operand0).getValue() == null)) || (operand0 instanceof SqlDynamicParam)) {
            final SqlValidatorImpl validator = (SqlValidatorImpl) callBinding.getValidator();
            validator.setValidatedNodeType(operand0, ret);
        }
    }
    return ret;
}
Also used : SqlValidatorImpl(org.apache.calcite.sql.validate.SqlValidatorImpl) SqlDynamicParam(org.apache.calcite.sql.SqlDynamicParam) SqlCallBinding(org.apache.calcite.sql.SqlCallBinding) RelDataType(org.apache.calcite.rel.type.RelDataType) SqlLiteral(org.apache.calcite.sql.SqlLiteral) SqlNode(org.apache.calcite.sql.SqlNode)

Example 2 with SqlLiteral

use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.

the class SqlOperatorBaseTest method testLiteralAtLimit.

/**
 * Tests that CAST fails when given a value just outside the valid range for
 * that type. For example,
 *
 * <ul>
 * <li>CAST(-200 AS TINYINT) fails because the value is less than -128;
 * <li>CAST(1E-999 AS FLOAT) fails because the value underflows;
 * <li>CAST(123.4567891234567 AS FLOAT) fails because the value loses
 * precision.
 * </ul>
 */
@Test
public void testLiteralAtLimit() {
    tester.setFor(SqlStdOperatorTable.CAST);
    if (!enable) {
        return;
    }
    final List<RelDataType> types = SqlLimitsTest.getTypes(tester.getValidator().getTypeFactory());
    for (RelDataType type : types) {
        for (Object o : getValues((BasicSqlType) type, true)) {
            SqlLiteral literal = type.getSqlTypeName().createLiteral(o, SqlParserPos.ZERO);
            SqlString literalString = literal.toSqlString(AnsiSqlDialect.DEFAULT);
            final String expr = "CAST(" + literalString + " AS " + type + ")";
            try {
                tester.checkType(expr, type.getFullTypeString());
                if (type.getSqlTypeName() == SqlTypeName.BINARY) {
                // Casting a string/binary values may change the value.
                // For example, CAST(X'AB' AS BINARY(2)) yields
                // X'AB00'.
                } else {
                    tester.checkScalar(expr + " = " + literalString, true, "BOOLEAN NOT NULL");
                }
            } catch (Error e) {
                System.out.println("Failed for expr=[" + expr + "]");
                throw e;
            } catch (RuntimeException e) {
                System.out.println("Failed for expr=[" + expr + "]");
                throw e;
            }
        }
    }
}
Also used : RelDataType(org.apache.calcite.rel.type.RelDataType) TimestampString(org.apache.calcite.util.TimestampString) SqlString(org.apache.calcite.sql.util.SqlString) SqlLiteral(org.apache.calcite.sql.SqlLiteral) SqlString(org.apache.calcite.sql.util.SqlString) SqlLimitsTest(org.apache.calcite.test.SqlLimitsTest) Test(org.junit.Test)

Example 3 with SqlLiteral

use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.

the class RelToSqlConverter method visit.

/**
 * @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 (e.getJoinType() == JoinRelType.INNER && e.getCondition().isAlwaysTrue()) {
        joinType = JoinType.COMMA;
        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);
}
Also used : SqlJoin(org.apache.calcite.sql.SqlJoin) JoinType(org.apache.calcite.sql.JoinType) SqlLiteral(org.apache.calcite.sql.SqlLiteral) SqlNode(org.apache.calcite.sql.SqlNode)

Example 4 with SqlLiteral

use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.

the class RelToSqlConverter method visit.

/**
 * @see #dispatch
 */
public Result visit(Match e) {
    final RelNode input = e.getInput();
    final Result x = visitChild(0, input);
    final Context context = matchRecognizeContext(x.qualifiedContext());
    SqlNode tableRef = x.asQueryOrValues();
    final List<SqlNode> partitionSqlList = new ArrayList<>();
    if (e.getPartitionKeys() != null) {
        for (RexNode rex : e.getPartitionKeys()) {
            SqlNode sqlNode = context.toSql(null, rex);
            partitionSqlList.add(sqlNode);
        }
    }
    final SqlNodeList partitionList = new SqlNodeList(partitionSqlList, POS);
    final List<SqlNode> orderBySqlList = new ArrayList<>();
    if (e.getOrderKeys() != null) {
        for (RelFieldCollation fc : e.getOrderKeys().getFieldCollations()) {
            if (fc.nullDirection != RelFieldCollation.NullDirection.UNSPECIFIED) {
                boolean first = fc.nullDirection == RelFieldCollation.NullDirection.FIRST;
                SqlNode nullDirectionNode = dialect.emulateNullDirection(context.field(fc.getFieldIndex()), first, fc.direction.isDescending());
                if (nullDirectionNode != null) {
                    orderBySqlList.add(nullDirectionNode);
                    fc = new RelFieldCollation(fc.getFieldIndex(), fc.getDirection(), RelFieldCollation.NullDirection.UNSPECIFIED);
                }
            }
            orderBySqlList.add(context.toSql(fc));
        }
    }
    final SqlNodeList orderByList = new SqlNodeList(orderBySqlList, SqlParserPos.ZERO);
    final SqlLiteral rowsPerMatch = e.isAllRows() ? SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS.symbol(POS) : SqlMatchRecognize.RowsPerMatchOption.ONE_ROW.symbol(POS);
    final SqlNode after;
    if (e.getAfter() instanceof RexLiteral) {
        SqlMatchRecognize.AfterOption value = (SqlMatchRecognize.AfterOption) ((RexLiteral) e.getAfter()).getValue2();
        after = SqlLiteral.createSymbol(value, POS);
    } else {
        RexCall call = (RexCall) e.getAfter();
        String operand = RexLiteral.stringValue(call.getOperands().get(0));
        after = call.getOperator().createCall(POS, new SqlIdentifier(operand, POS));
    }
    RexNode rexPattern = e.getPattern();
    final SqlNode pattern = context.toSql(null, rexPattern);
    final SqlLiteral strictStart = SqlLiteral.createBoolean(e.isStrictStart(), POS);
    final SqlLiteral strictEnd = SqlLiteral.createBoolean(e.isStrictEnd(), POS);
    RexLiteral rexInterval = (RexLiteral) e.getInterval();
    SqlIntervalLiteral interval = null;
    if (rexInterval != null) {
        interval = (SqlIntervalLiteral) context.toSql(null, rexInterval);
    }
    final SqlNodeList subsetList = new SqlNodeList(POS);
    for (Map.Entry<String, SortedSet<String>> entry : e.getSubsets().entrySet()) {
        SqlNode left = new SqlIdentifier(entry.getKey(), POS);
        List<SqlNode> rhl = Lists.newArrayList();
        for (String right : entry.getValue()) {
            rhl.add(new SqlIdentifier(right, POS));
        }
        subsetList.add(SqlStdOperatorTable.EQUALS.createCall(POS, left, new SqlNodeList(rhl, POS)));
    }
    final SqlNodeList measureList = new SqlNodeList(POS);
    for (Map.Entry<String, RexNode> entry : e.getMeasures().entrySet()) {
        final String alias = entry.getKey();
        final SqlNode sqlNode = context.toSql(null, entry.getValue());
        measureList.add(as(sqlNode, alias));
    }
    final SqlNodeList patternDefList = new SqlNodeList(POS);
    for (Map.Entry<String, RexNode> entry : e.getPatternDefinitions().entrySet()) {
        final String alias = entry.getKey();
        final SqlNode sqlNode = context.toSql(null, entry.getValue());
        patternDefList.add(as(sqlNode, alias));
    }
    final SqlNode matchRecognize = new SqlMatchRecognize(POS, tableRef, pattern, strictStart, strictEnd, patternDefList, measureList, after, subsetList, rowsPerMatch, partitionList, orderByList, interval);
    return result(matchRecognize, Expressions.list(Clause.FROM), e, null);
}
Also used : RexLiteral(org.apache.calcite.rex.RexLiteral) SqlIntervalLiteral(org.apache.calcite.sql.SqlIntervalLiteral) ArrayList(java.util.ArrayList) SqlMatchRecognize(org.apache.calcite.sql.SqlMatchRecognize) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) SortedSet(java.util.SortedSet) RexCall(org.apache.calcite.rex.RexCall) RelNode(org.apache.calcite.rel.RelNode) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlLiteral(org.apache.calcite.sql.SqlLiteral) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) SqlNode(org.apache.calcite.sql.SqlNode) RexNode(org.apache.calcite.rex.RexNode)

Example 5 with SqlLiteral

use of org.apache.calcite.sql.SqlLiteral in project calcite by apache.

the class SqlToRelConverter method convertMatchRecognize.

protected void convertMatchRecognize(Blackboard bb, SqlCall call) {
    final SqlMatchRecognize matchRecognize = (SqlMatchRecognize) call;
    final SqlValidatorNamespace ns = validator.getNamespace(matchRecognize);
    final SqlValidatorScope scope = validator.getMatchRecognizeScope(matchRecognize);
    final Blackboard matchBb = createBlackboard(scope, null, false);
    final RelDataType rowType = ns.getRowType();
    // convert inner query, could be a table name or a derived table
    SqlNode expr = matchRecognize.getTableRef();
    convertFrom(matchBb, expr);
    final RelNode input = matchBb.root;
    // PARTITION BY
    final SqlNodeList partitionList = matchRecognize.getPartitionList();
    final List<RexNode> partitionKeys = new ArrayList<>();
    for (SqlNode partition : partitionList) {
        RexNode e = matchBb.convertExpression(partition);
        partitionKeys.add(e);
    }
    // ORDER BY
    final SqlNodeList orderList = matchRecognize.getOrderList();
    final List<RelFieldCollation> orderKeys = new ArrayList<>();
    for (SqlNode order : orderList) {
        final RelFieldCollation.Direction direction;
        switch(order.getKind()) {
            case DESCENDING:
                direction = RelFieldCollation.Direction.DESCENDING;
                order = ((SqlCall) order).operand(0);
                break;
            case NULLS_FIRST:
            case NULLS_LAST:
                throw new AssertionError();
            default:
                direction = RelFieldCollation.Direction.ASCENDING;
                break;
        }
        final RelFieldCollation.NullDirection nullDirection = validator.getDefaultNullCollation().last(desc(direction)) ? RelFieldCollation.NullDirection.LAST : RelFieldCollation.NullDirection.FIRST;
        RexNode e = matchBb.convertExpression(order);
        orderKeys.add(new RelFieldCollation(((RexInputRef) e).getIndex(), direction, nullDirection));
    }
    final RelCollation orders = cluster.traitSet().canonize(RelCollations.of(orderKeys));
    // convert pattern
    final Set<String> patternVarsSet = new HashSet<>();
    SqlNode pattern = matchRecognize.getPattern();
    final SqlBasicVisitor<RexNode> patternVarVisitor = new SqlBasicVisitor<RexNode>() {

        @Override
        public RexNode visit(SqlCall call) {
            List<SqlNode> operands = call.getOperandList();
            List<RexNode> newOperands = Lists.newArrayList();
            for (SqlNode node : operands) {
                newOperands.add(node.accept(this));
            }
            return rexBuilder.makeCall(validator.getUnknownType(), call.getOperator(), newOperands);
        }

        @Override
        public RexNode visit(SqlIdentifier id) {
            assert id.isSimple();
            patternVarsSet.add(id.getSimple());
            return rexBuilder.makeLiteral(id.getSimple());
        }

        @Override
        public RexNode visit(SqlLiteral literal) {
            if (literal instanceof SqlNumericLiteral) {
                return rexBuilder.makeExactLiteral(BigDecimal.valueOf(literal.intValue(true)));
            } else {
                return rexBuilder.makeLiteral(literal.booleanValue());
            }
        }
    };
    final RexNode patternNode = pattern.accept(patternVarVisitor);
    SqlLiteral interval = matchRecognize.getInterval();
    RexNode intervalNode = null;
    if (interval != null) {
        intervalNode = matchBb.convertLiteral(interval);
    }
    // convert subset
    final SqlNodeList subsets = matchRecognize.getSubsetList();
    final Map<String, TreeSet<String>> subsetMap = Maps.newHashMap();
    for (SqlNode node : subsets) {
        List<SqlNode> operands = ((SqlCall) node).getOperandList();
        SqlIdentifier left = (SqlIdentifier) operands.get(0);
        patternVarsSet.add(left.getSimple());
        SqlNodeList rights = (SqlNodeList) operands.get(1);
        final TreeSet<String> list = new TreeSet<String>();
        for (SqlNode right : rights) {
            assert right instanceof SqlIdentifier;
            list.add(((SqlIdentifier) right).getSimple());
        }
        subsetMap.put(left.getSimple(), list);
    }
    SqlNode afterMatch = matchRecognize.getAfter();
    if (afterMatch == null) {
        afterMatch = SqlMatchRecognize.AfterOption.SKIP_TO_NEXT_ROW.symbol(SqlParserPos.ZERO);
    }
    final RexNode after;
    if (afterMatch instanceof SqlCall) {
        List<SqlNode> operands = ((SqlCall) afterMatch).getOperandList();
        SqlOperator operator = ((SqlCall) afterMatch).getOperator();
        assert operands.size() == 1;
        SqlIdentifier id = (SqlIdentifier) operands.get(0);
        assert patternVarsSet.contains(id.getSimple()) : id.getSimple() + " not defined in pattern";
        RexNode rex = rexBuilder.makeLiteral(id.getSimple());
        after = rexBuilder.makeCall(validator.getUnknownType(), operator, ImmutableList.of(rex));
    } else {
        after = matchBb.convertExpression(afterMatch);
    }
    matchBb.setPatternVarRef(true);
    // convert measures
    final ImmutableMap.Builder<String, RexNode> measureNodes = ImmutableMap.builder();
    for (SqlNode measure : matchRecognize.getMeasureList()) {
        List<SqlNode> operands = ((SqlCall) measure).getOperandList();
        String alias = ((SqlIdentifier) operands.get(1)).getSimple();
        RexNode rex = matchBb.convertExpression(operands.get(0));
        measureNodes.put(alias, rex);
    }
    // convert definitions
    final ImmutableMap.Builder<String, RexNode> definitionNodes = ImmutableMap.builder();
    for (SqlNode def : matchRecognize.getPatternDefList()) {
        List<SqlNode> operands = ((SqlCall) def).getOperandList();
        String alias = ((SqlIdentifier) operands.get(1)).getSimple();
        RexNode rex = matchBb.convertExpression(operands.get(0));
        definitionNodes.put(alias, rex);
    }
    final SqlLiteral rowsPerMatch = matchRecognize.getRowsPerMatch();
    final boolean allRows = rowsPerMatch != null && rowsPerMatch.getValue() == SqlMatchRecognize.RowsPerMatchOption.ALL_ROWS;
    matchBb.setPatternVarRef(false);
    final RelFactories.MatchFactory factory = RelFactories.DEFAULT_MATCH_FACTORY;
    final RelNode rel = factory.createMatch(input, patternNode, rowType, matchRecognize.getStrictStart().booleanValue(), matchRecognize.getStrictEnd().booleanValue(), definitionNodes.build(), measureNodes.build(), after, subsetMap, allRows, partitionKeys, orders, intervalNode);
    bb.setRoot(rel, false);
}
Also used : SqlValidatorScope(org.apache.calcite.sql.validate.SqlValidatorScope) SqlOperator(org.apache.calcite.sql.SqlOperator) ArrayList(java.util.ArrayList) RelDataType(org.apache.calcite.rel.type.RelDataType) NlsString(org.apache.calcite.util.NlsString) SqlIdentifier(org.apache.calcite.sql.SqlIdentifier) TreeSet(java.util.TreeSet) SqlBasicVisitor(org.apache.calcite.sql.util.SqlBasicVisitor) RelFactories(org.apache.calcite.rel.core.RelFactories) SqlNode(org.apache.calcite.sql.SqlNode) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) SqlCall(org.apache.calcite.sql.SqlCall) SqlMatchRecognize(org.apache.calcite.sql.SqlMatchRecognize) ImmutableMap(com.google.common.collect.ImmutableMap) RelCollation(org.apache.calcite.rel.RelCollation) RelNode(org.apache.calcite.rel.RelNode) RelFieldCollation(org.apache.calcite.rel.RelFieldCollation) SqlNodeList(org.apache.calcite.sql.SqlNodeList) RexInputRef(org.apache.calcite.rex.RexInputRef) SqlValidatorNamespace(org.apache.calcite.sql.validate.SqlValidatorNamespace) SqlLiteral(org.apache.calcite.sql.SqlLiteral) SqlNumericLiteral(org.apache.calcite.sql.SqlNumericLiteral) RexNode(org.apache.calcite.rex.RexNode)

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