Java Code Examples for org.apache.calcite.sql.fun.SqlStdOperatorTable

The following examples show how to use org.apache.calcite.sql.fun.SqlStdOperatorTable. These examples are extracted from open source projects. 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 Project: Bats   Source File: DrillProjectRelBase.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Boolean visitCall(RexCall call) {
  if (call.getOperator() == SqlStdOperatorTable.ITEM) {
    final RexNode op0 = call.getOperands().get(0);
    final RexNode op1 = call.getOperands().get(1);

    if (op0 instanceof RexInputRef &&
        op1 instanceof RexLiteral && ((RexLiteral) op1).getTypeName() == SqlTypeName.CHAR) {
      return true;
    } else if (op0 instanceof RexCall &&
        op1 instanceof RexLiteral && ((RexLiteral) op1).getTypeName() == SqlTypeName.CHAR) {
      return op0.accept(this);
    }
  }

  return false;
}
 
Example 2
Source Project: flink   Source File: SqlValidatorImpl.java    License: Apache License 2.0 6 votes vote down vote up
protected SqlNode expandDynamicStar(SqlIdentifier id, SqlIdentifier fqId) {
	if (DynamicRecordType.isDynamicStarColName(Util.last(fqId.names))
		&& !DynamicRecordType.isDynamicStarColName(Util.last(id.names))) {
		// Convert a column ref into ITEM(*, 'col_name')
		// for a dynamic star field in dynTable's rowType.
		SqlNode[] inputs = new SqlNode[2];
		inputs[0] = fqId;
		inputs[1] = SqlLiteral.createCharString(
			Util.last(id.names),
			id.getParserPosition());
		return new SqlBasicCall(
			SqlStdOperatorTable.ITEM,
			inputs,
			id.getParserPosition());
	}
	return fqId;
}
 
Example 3
Source Project: calcite   Source File: RelMdUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Computes the number of distinct rows for a set of keys returned from a
 * semi-join
 *
 * @param semiJoinRel RelNode representing the semi-join
 * @param mq          metadata query
 * @param groupKey    keys that the distinct row count will be computed for
 * @param predicate   join predicate
 * @return number of distinct rows
 */
public static Double getSemiJoinDistinctRowCount(Join semiJoinRel, RelMetadataQuery mq,
    ImmutableBitSet groupKey, RexNode predicate) {
  if (predicate == null || predicate.isAlwaysTrue()) {
    if (groupKey.isEmpty()) {
      return 1D;
    }
  }
  // create a RexNode representing the selectivity of the
  // semijoin filter and pass it to getDistinctRowCount
  RexNode newPred = RelMdUtil.makeSemiJoinSelectivityRexNode(mq, semiJoinRel);
  if (predicate != null) {
    RexBuilder rexBuilder = semiJoinRel.getCluster().getRexBuilder();
    newPred =
        rexBuilder.makeCall(
            SqlStdOperatorTable.AND,
            newPred,
            predicate);
  }

  return mq.getDistinctRowCount(semiJoinRel.getLeft(), groupKey, newPred);
}
 
Example 4
Source Project: calcite   Source File: SqlProcedureCallOperator.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  // for now, rewrite "CALL f(x)" to "SELECT f(x) FROM VALUES(0)"
  // TODO jvs 18-Jan-2005:  rewrite to SELECT * FROM TABLE f(x)
  // once we support function calls as tables
  return new SqlSelect(SqlParserPos.ZERO,
      null,
      new SqlNodeList(
          Collections.singletonList(call.operand(0)),
          SqlParserPos.ZERO),
      SqlStdOperatorTable.VALUES.createCall(
          SqlParserPos.ZERO,
          SqlStdOperatorTable.ROW.createCall(
              SqlParserPos.ZERO,
              SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO))),
      null,
      null,
      null,
      null,
      null,
      null,
      null,
      null);
}
 
Example 5
Source Project: Bats   Source File: SqlNodeList.java    License: Apache License 2.0 6 votes vote down vote up
void andOrList(SqlWriter writer, SqlKind sepKind) {
  SqlBinaryOperator sepOp =
      sepKind == SqlKind.AND
          ? SqlStdOperatorTable.AND
          : SqlStdOperatorTable.OR;
  for (int i = 0; i < list.size(); i++) {
    SqlNode node = list.get(i);
    writer.sep(sepKind.name(), false);

    // The precedence pulling on the LHS of a node is the
    // right-precedence of the separator operator, except at the start
    // of the list; similarly for the RHS of a node. If the operator
    // has left precedence 4 and right precedence 5, the precedences
    // in a 3-node list will look as follows:
    //   0 <- node1 -> 4  5 <- node2 -> 4  5 <- node3 -> 0
    int lprec = (i == 0) ? 0 : sepOp.getRightPrec();
    int rprec = (i == (list.size() - 1)) ? 0 : sepOp.getLeftPrec();
    node.unparse(writer, lprec, rprec);
  }
}
 
Example 6
Source Project: Bats   Source File: AggregateReduceFunctionsRule.java    License: Apache License 2.0 6 votes vote down vote up
private RexNode getSumAggregatedRexNodeWithBinding(Aggregate oldAggRel,
    AggregateCall oldCall,
    List<AggregateCall> newCalls,
    Map<AggregateCall, RexNode> aggCallMapping,
    RelDataType operandType,
    int argOrdinal,
    int filter) {
  RelOptCluster cluster = oldAggRel.getCluster();
  final AggregateCall sumArgSquaredAggCall =
      createAggregateCallWithBinding(cluster.getTypeFactory(),
          SqlStdOperatorTable.SUM, operandType, oldAggRel, oldCall, argOrdinal, filter);

  return cluster.getRexBuilder().addAggCall(sumArgSquaredAggCall,
      oldAggRel.getGroupCount(),
      oldAggRel.indicator,
      newCalls,
      aggCallMapping,
      ImmutableList.of(sumArgSquaredAggCall.getType()));
}
 
Example 7
Source Project: calcite   Source File: RelBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Same as {@link #testJoin} using USING. */
@Test void testJoinUsing() {
  final RelBuilder builder = RelBuilder.create(config().build());
  final RelNode root2 =
      builder.scan("EMP")
          .filter(
              builder.call(SqlStdOperatorTable.IS_NULL,
                  builder.field("COMM")))
          .scan("DEPT")
          .join(JoinRelType.INNER, "DEPTNO")
          .build();
  final String expected = ""
      + "LogicalJoin(condition=[=($7, $8)], joinType=[inner])\n"
      + "  LogicalFilter(condition=[IS NULL($6)])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n"
      + "  LogicalTableScan(table=[[scott, DEPT]])\n";
  assertThat(root2, hasTree(expected));
}
 
Example 8
Source Project: calcite   Source File: MssqlSqlDialect.java    License: Apache License 2.0 6 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    if (call.operandCount() != 3) {
      throw new IllegalArgumentException("MSSQL SUBSTRING requires FROM and FOR arguments");
    }
    SqlUtil.unparseFunctionSyntax(MSSQL_SUBSTRING, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }
      unparseFloor(writer, call);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example 9
Source Project: calcite   Source File: AggregateReduceFunctionsRule.java    License: Apache License 2.0 6 votes vote down vote up
private RexNode getSumAggregatedRexNodeWithBinding(Aggregate oldAggRel,
    AggregateCall oldCall,
    List<AggregateCall> newCalls,
    Map<AggregateCall, RexNode> aggCallMapping,
    RelDataType operandType,
    int argOrdinal,
    int filter) {
  RelOptCluster cluster = oldAggRel.getCluster();
  final AggregateCall sumArgSquaredAggCall =
      createAggregateCallWithBinding(cluster.getTypeFactory(),
          SqlStdOperatorTable.SUM, operandType, oldAggRel, oldCall, argOrdinal, filter);

  return cluster.getRexBuilder().addAggCall(sumArgSquaredAggCall,
      oldAggRel.getGroupCount(),
      newCalls,
      aggCallMapping,
      ImmutableList.of(sumArgSquaredAggCall.getType()));
}
 
Example 10
Source Project: calcite   Source File: RelBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testJoinTemporalTable() {
  // Equivalent SQL:
  //   SELECT *
  //   FROM orders
  //   JOIN products_temporal FOR SYSTEM_TIME AS OF TIMESTAMP '2011-07-20 12:34:56'
  //   ON orders.product = products_temporal.id
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.scan("orders")
          .scan("products_temporal")
          .snapshot(
              builder.getRexBuilder().makeTimestampLiteral(
                  new TimestampString("2011-07-20 12:34:56"), 0))
          .join(JoinRelType.INNER,
              builder.call(SqlStdOperatorTable.EQUALS,
                  builder.field(2, 0, "PRODUCT"),
                  builder.field(2, 1, "ID")))
          .build();
  final String expected = "LogicalJoin(condition=[=($2, $4)], joinType=[inner])\n"
      + "  LogicalTableScan(table=[[scott, orders]])\n"
      + "  LogicalSnapshot(period=[2011-07-20 12:34:56])\n"
      + "    LogicalTableScan(table=[[scott, products_temporal]])\n";
  assertThat(root, hasTree(expected));
}
 
Example 11
Source Project: Bats   Source File: RelOptUtil.java    License: Apache License 2.0 6 votes vote down vote up
private static RexNode isDistinctFromInternal(RexBuilder rexBuilder, RexNode x, RexNode y, boolean neg) {

        if (neg) {
            // x is not distinct from y
            // x=y IS TRUE or ((x is null) and (y is null)),
            return rexBuilder.makeCall(SqlStdOperatorTable.OR,
                    rexBuilder.makeCall(SqlStdOperatorTable.AND, rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, x),
                            rexBuilder.makeCall(SqlStdOperatorTable.IS_NULL, y)),
                    rexBuilder.makeCall(SqlStdOperatorTable.IS_TRUE,
                            rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, x, y)));
        } else {
            // x is distinct from y
            // x=y IS NOT TRUE and ((x is not null) or (y is not null)),
            return rexBuilder.makeCall(SqlStdOperatorTable.AND,
                    rexBuilder.makeCall(SqlStdOperatorTable.OR, rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, x),
                            rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, y)),
                    rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_TRUE,
                            rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, x, y)));
        }
    }
 
Example 12
Source Project: calcite   Source File: DruidAdapter2IT.java    License: Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-1769">[CALCITE-1769]
 * Druid adapter: Push down filters involving numeric cast of literals</a>. */
@Test void testPushCastNumeric() {
  String druidQuery = "'filter':{'type':'bound','dimension':'product_id',"
      + "'upper':'10','upperStrict':true,'ordering':'numeric'}";
  sql("?")
      .withRel(b -> {
        // select product_id
        // from foodmart.foodmart
        // where product_id < cast(10 as varchar)
        final RelDataType intType =
            b.getTypeFactory().createSqlType(SqlTypeName.INTEGER);
        return b.scan("foodmart", "foodmart")
            .filter(
                b.call(SqlStdOperatorTable.LESS_THAN,
                    b.getRexBuilder().makeCall(intType,
                        SqlStdOperatorTable.CAST,
                        ImmutableList.of(b.field("product_id"))),
                    b.getRexBuilder().makeCall(intType,
                        SqlStdOperatorTable.CAST,
                        ImmutableList.of(b.literal("10")))))
            .project(b.field("product_id"))
            .build();
      })
      .queryContains(new DruidChecker(druidQuery));
}
 
Example 13
Source Project: calcite   Source File: RelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
AggCallImpl(SqlAggFunction aggFunction, boolean distinct,
    boolean approximate, boolean ignoreNulls, RexNode filter,
    String alias, ImmutableList<RexNode> operands,
    ImmutableList<RexNode> orderKeys) {
  this.aggFunction = Objects.requireNonNull(aggFunction);
  // If the aggregate function ignores DISTINCT,
  // make the DISTINCT flag FALSE.
  this.distinct = distinct
      && aggFunction.getDistinctOptionality() != Optionality.IGNORED;
  this.approximate = approximate;
  this.ignoreNulls = ignoreNulls;
  this.alias = alias;
  this.operands = Objects.requireNonNull(operands);
  this.orderKeys = Objects.requireNonNull(orderKeys);
  if (filter != null) {
    if (filter.getType().getSqlTypeName() != SqlTypeName.BOOLEAN) {
      throw RESOURCE.filterMustBeBoolean().ex();
    }
    if (filter.getType().isNullable()) {
      filter = call(SqlStdOperatorTable.IS_TRUE, filter);
    }
  }
  this.filter = filter;
}
 
Example 14
Source Project: Bats   Source File: Lattice.java    License: Apache License 2.0 5 votes vote down vote up
private SqlAggFunction resolveAgg(String aggName) {
  if (aggName.equalsIgnoreCase("count")) {
    return SqlStdOperatorTable.COUNT;
  } else if (aggName.equalsIgnoreCase("sum")) {
    return SqlStdOperatorTable.SUM;
  } else {
    throw new RuntimeException("Unknown lattice aggregate function "
        + aggName);
  }
}
 
Example 15
Source Project: flink   Source File: SqlValidatorImpl.java    License: 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 16
Source Project: Bats   Source File: RelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Determines whether any of the fields in a given relational expression may
 * contain null values, taking into account constraints on the field types and
 * also deduced predicates.
 *
 * <p>The method is cautious: It may sometimes return {@code true} when the
 * actual answer is {@code false}. In particular, it does this when there
 * is no executor, or the executor is not a sub-class of
 * {@link RexExecutorImpl}.
 */
private static boolean containsNullableFields(RelNode r) {
    final RexBuilder rexBuilder = r.getCluster().getRexBuilder();
    final RelDataType rowType = r.getRowType();
    final List<RexNode> list = new ArrayList<>();
    final RelMetadataQuery mq = r.getCluster().getMetadataQuery();
    for (RelDataTypeField field : rowType.getFieldList()) {
        if (field.getType().isNullable()) {
            list.add(rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL,
                    rexBuilder.makeInputRef(field.getType(), field.getIndex())));
        }
    }
    if (list.isEmpty()) {
        // All columns are declared NOT NULL.
        return false;
    }
    final RelOptPredicateList predicates = mq.getPulledUpPredicates(r);
    if (predicates.pulledUpPredicates.isEmpty()) {
        // We have no predicates, so cannot deduce that any of the fields
        // declared NULL are really NOT NULL.
        return true;
    }
    final RexExecutor executor = r.getCluster().getPlanner().getExecutor();
    if (!(executor instanceof RexExecutorImpl)) {
        // Cannot proceed without an executor.
        return true;
    }
    final RexImplicationChecker checker = new RexImplicationChecker(rexBuilder, (RexExecutorImpl) executor,
            rowType);
    final RexNode first = RexUtil.composeConjunction(rexBuilder, predicates.pulledUpPredicates);
    final RexNode second = RexUtil.composeConjunction(rexBuilder, list);
    // Suppose we have EMP(empno INT NOT NULL, mgr INT),
    // and predicates [empno > 0, mgr > 0].
    // We make first: "empno > 0 AND mgr > 0"
    // and second: "mgr IS NOT NULL"
    // and ask whether first implies second.
    // It does, so we have no nullable columns.
    return !checker.implies(first, second);
}
 
Example 17
Source Project: Bats   Source File: RexSimplify.java    License: Apache License 2.0 5 votes vote down vote up
private <C extends Comparable<C>> RexNode simplifyUsingPredicates(RexNode e, Class<C> clazz) {
    final Comparison comparison = Comparison.of(e);
    // Check for comparison with null values
    if (comparison == null || comparison.kind == SqlKind.NOT_EQUALS || comparison.literal.getValue() == null) {
        return e;
    }
    final C v0 = comparison.literal.getValueAs(clazz);
    final Range<C> range = range(comparison.kind, v0);
    final Range<C> range2 = residue(comparison.ref, range, predicates.pulledUpPredicates, clazz);
    if (range2 == null) {
        // Term is impossible to satisfy given these predicates
        return rexBuilder.makeLiteral(false);
    } else if (range2.equals(range)) {
        // no change
        return e;
    } else if (range2.equals(Range.all())) {
        // Range is always satisfied given these predicates; but nullability might
        // be problematic
        return simplify(rexBuilder.makeCall(SqlStdOperatorTable.IS_NOT_NULL, comparison.ref), RexUnknownAs.UNKNOWN);
    } else if (range2.lowerEndpoint().equals(range2.upperEndpoint())) {
        if (range2.lowerBoundType() == BoundType.OPEN || range2.upperBoundType() == BoundType.OPEN) {
            // range is a point, but does not include its endpoint, therefore is
            // effectively empty
            return rexBuilder.makeLiteral(false);
        }
        // range is now a point; it's worth simplifying
        return rexBuilder.makeCall(SqlStdOperatorTable.EQUALS, comparison.ref, rexBuilder.makeLiteral(
                range2.lowerEndpoint(), comparison.literal.getType(), comparison.literal.getTypeName()));
    } else {
        // range has been reduced but it's not worth simplifying
        return e;
    }
}
 
Example 18
Source Project: Bats   Source File: RexBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an invocation of the NEW operator.
 *
 * @param type  Type to be instantiated
 * @param exprs Arguments to NEW operator
 * @return Expression invoking NEW operator
 */
public RexNode makeNewInvocation(
    RelDataType type,
    List<RexNode> exprs) {
  return rexFactory.makeCall(
      type,
      SqlStdOperatorTable.NEW,
      exprs);
}
 
Example 19
Source Project: Bats   Source File: AggregateUnionTransposeRule.java    License: Apache License 2.0 5 votes vote down vote up
private List<AggregateCall> transformAggCalls(RelNode input, int groupCount,
    List<AggregateCall> origCalls) {
  final List<AggregateCall> newCalls = new ArrayList<>();
  for (Ord<AggregateCall> ord : Ord.zip(origCalls)) {
    final AggregateCall origCall = ord.e;
    if (origCall.isDistinct()
        || !SUPPORTED_AGGREGATES.containsKey(origCall.getAggregation()
            .getClass())) {
      return null;
    }
    final SqlAggFunction aggFun;
    final RelDataType aggType;
    if (origCall.getAggregation() == SqlStdOperatorTable.COUNT) {
      aggFun = SqlStdOperatorTable.SUM0;
      // count(any) is always not null, however nullability of sum might
      // depend on the number of columns in GROUP BY.
      // Here we use SUM0 since we are sure we will not face nullable
      // inputs nor we'll face empty set.
      aggType = null;
    } else {
      aggFun = origCall.getAggregation();
      aggType = origCall.getType();
    }
    AggregateCall newCall =
        AggregateCall.create(aggFun, origCall.isDistinct(),
            origCall.isApproximate(),
            ImmutableList.of(groupCount + ord.i), -1,
            origCall.collation,
            groupCount,
            input,
            aggType,
            origCall.getName());
    newCalls.add(newCall);
  }
  return newCalls;
}
 
Example 20
Source Project: calcite   Source File: RelBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testRepeatUnion2() {
  // Generates the factorial function from 0 to 7. Equivalent SQL:
  //   WITH RECURSIVE delta (n, fact) AS (
  //     VALUES (0, 1)
  //     UNION ALL
  //     SELECT n+1, (n+1)*fact FROM delta WHERE n < 7
  //   )
  //   SELECT * FROM delta
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.values(new String[] { "n", "fact" }, 0, 1)
          .transientScan("AUX")
          .filter(
              builder.call(
                  SqlStdOperatorTable.LESS_THAN,
                  builder.field("n"),
                  builder.literal(7)))
          .project(
              Arrays.asList(
                  builder.call(SqlStdOperatorTable.PLUS,
                      builder.field("n"),
                      builder.literal(1)),
                  builder.call(SqlStdOperatorTable.MULTIPLY,
                      builder.call(SqlStdOperatorTable.PLUS,
                          builder.field("n"),
                          builder.literal(1)),
                      builder.field("fact"))),
              Arrays.asList("n", "fact"))
          .repeatUnion("AUX", true)
          .build();
  final String expected = "LogicalRepeatUnion(all=[true])\n"
      + "  LogicalTableSpool(readType=[LAZY], writeType=[LAZY], table=[[AUX]])\n"
      + "    LogicalValues(tuples=[[{ 0, 1 }]])\n"
      + "  LogicalTableSpool(readType=[LAZY], writeType=[LAZY], table=[[AUX]])\n"
      + "    LogicalProject(n=[+($0, 1)], fact=[*(+($0, 1), $1)])\n"
      + "      LogicalFilter(condition=[<($0, 7)])\n"
      + "        LogicalTableScan(table=[[AUX]])\n";
  assertThat(root, hasTree(expected));
}
 
Example 21
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: 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 22
Source Project: Bats   Source File: FilterRemoveIsNotDistinctFromRule.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RexNode visitCall(RexCall call) {
    RexNode newCall = super.visitCall(call);

    if (call.getOperator() == SqlStdOperatorTable.IS_NOT_DISTINCT_FROM) {
        RexCall tmpCall = (RexCall) newCall;
        newCall = RelOptUtil.isDistinctFrom(rexBuilder, tmpCall.getOperands().get(0),
                tmpCall.getOperands().get(1), true);
    }
    return newCall;
}
 
Example 23
Source Project: calcite   Source File: RelBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a {@link Join} using USING syntax.
 *
 * <p>For each of the field names, both left and right inputs must have a
 * field of that name. Constructs a join condition that the left and right
 * fields are equal.
 *
 * @param joinType Join type
 * @param fieldNames Field names
 */
public RelBuilder join(JoinRelType joinType, String... fieldNames) {
  final List<RexNode> conditions = new ArrayList<>();
  for (String fieldName : fieldNames) {
    conditions.add(
        call(SqlStdOperatorTable.EQUALS,
            field(2, 0, fieldName),
            field(2, 1, fieldName)));
  }
  return join(joinType, conditions);
}
 
Example 24
Source Project: calcite   Source File: RelDataTypeSystemTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testDecimalAdditionReturnTypeInference() {
  RelDataType operand1 = TYPE_FACTORY.createSqlType(SqlTypeName.DECIMAL, 10, 1);
  RelDataType operand2 = TYPE_FACTORY.createSqlType(SqlTypeName.DECIMAL, 10, 2);

  RelDataType dataType = SqlStdOperatorTable.MINUS.inferReturnType(TYPE_FACTORY,
          Lists.newArrayList(operand1, operand2));
  assertEquals(12, dataType.getPrecision());
  assertEquals(2, dataType.getScale());
}
 
Example 25
Source Project: calcite   Source File: RexSimplify.java    License: Apache License 2.0 5 votes vote down vote up
private RexNode simplifyIs(RexCall call, RexUnknownAs unknownAs) {
  final SqlKind kind = call.getKind();
  final RexNode a = call.getOperands().get(0);

  // UnknownAs.FALSE corresponds to x IS TRUE evaluation
  // UnknownAs.TRUE to x IS NOT FALSE
  // Note that both UnknownAs.TRUE and UnknownAs.FALSE only changes the meaning of Unknown
  // (1) if we are already in UnknownAs.FALSE mode; x IS TRUE can be simplified to x
  // (2) similarily in UnknownAs.TRUE mode; x IS NOT FALSE can be simplified to x
  // (3) x IS FALSE could be rewritten to (NOT x) IS TRUE and from there the 1. rule applies
  // (4) x IS NOT TRUE can be rewritten to (NOT x) IS NOT FALSE and from there the 2. rule applies
  if (kind == SqlKind.IS_TRUE && unknownAs == RexUnknownAs.FALSE) {
    return simplify(a, unknownAs);
  }
  if (kind == SqlKind.IS_FALSE && unknownAs == RexUnknownAs.FALSE) {
    return simplify(rexBuilder.makeCall(SqlStdOperatorTable.NOT, a), unknownAs);
  }
  if (kind == SqlKind.IS_NOT_FALSE && unknownAs == RexUnknownAs.TRUE) {
    return simplify(a, unknownAs);
  }
  if (kind == SqlKind.IS_NOT_TRUE && unknownAs == RexUnknownAs.TRUE) {
    return simplify(rexBuilder.makeCall(SqlStdOperatorTable.NOT, a), unknownAs);
  }
  final RexNode pred = simplifyIsPredicate(kind, a);
  if (pred != null) {
    return pred;
  }

  final RexNode simplified = simplifyIs2(kind, a, unknownAs);
  if (simplified != null) {
    return simplified;
  }
  return call;
}
 
Example 26
Source Project: Flink-CEPplus   Source File: SqlValidatorImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void registerSubQueries(
	SqlValidatorScope parentScope,
	SqlNode node) {
	if (node == null) {
		return;
	}
	if (node.getKind().belongsTo(SqlKind.QUERY)
		|| node.getKind() == SqlKind.MULTISET_QUERY_CONSTRUCTOR
		|| node.getKind() == SqlKind.MULTISET_VALUE_CONSTRUCTOR) {
		registerQuery(parentScope, null, node, node, null, false);
	} else if (node instanceof SqlCall) {
		validateNodeFeature(node);
		SqlCall call = (SqlCall) node;
		for (int i = 0; i < call.operandCount(); i++) {
			registerOperandSubQueries(parentScope, call, i);
		}
	} else if (node instanceof SqlNodeList) {
		SqlNodeList list = (SqlNodeList) node;
		for (int i = 0, count = list.size(); i < count; i++) {
			SqlNode listNode = list.get(i);
			if (listNode.getKind().belongsTo(SqlKind.QUERY)) {
				listNode =
					SqlStdOperatorTable.SCALAR_QUERY.createCall(
						listNode.getParserPosition(),
						listNode);
				list.set(i, listNode);
			}
			registerSubQueries(parentScope, listNode);
		}
	} else {
		// atomic node -- can be ignored
	}
}
 
Example 27
Source Project: calcite   Source File: ReduceDecimalsRule.java    License: Apache License 2.0 5 votes vote down vote up
protected RexNode makeCase(
    RexNode whenA,
    RexNode thenA,
    RexNode whenB,
    RexNode thenB,
    RexNode elseClause) {
  return builder.makeCall(
      SqlStdOperatorTable.CASE,
      whenA,
      thenA,
      whenB,
      thenB,
      elseClause);
}
 
Example 28
Source Project: calcite   Source File: ReduceDecimalsRule.java    License: Apache License 2.0 5 votes vote down vote up
protected RexNode makePlus(
    RexNode a,
    RexNode b) {
  return builder.makeCall(
      SqlStdOperatorTable.PLUS,
      a,
      b);
}
 
Example 29
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 5 votes vote down vote up
/** Wraps a call in a {@link SqlKind#WITHIN_GROUP} call, if
 * {@code orderList} is non-empty. */
private SqlNode withOrder(SqlCall call, SqlNodeList orderList) {
    if (orderList == null || orderList.size() == 0) {
        return call;
    }
    return SqlStdOperatorTable.WITHIN_GROUP.createCall(POS, call, orderList);
}
 
Example 30
Source Project: calcite   Source File: SqlBinaryOperator.java    License: Apache License 2.0 5 votes vote down vote up
@Override public boolean validRexOperands(int count, Litmus litmus) {
  if (count != 2) {
    // Special exception for AND and OR.
    if ((this == SqlStdOperatorTable.AND
        || this == SqlStdOperatorTable.OR)
        && count > 2) {
      return true;
    }
    return litmus.fail("wrong operand count {} for {}", count, this);
  }
  return litmus.succeed();
}