org.apache.calcite.sql.SqlWindow Java Examples

The following examples show how to use org.apache.calcite.sql.SqlWindow. 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: SelectScope.java    From Bats with Apache License 2.0 6 votes vote down vote up
public SqlWindow lookupWindow(String name) {
  final SqlNodeList windowList = select.getWindowList();
  for (int i = 0; i < windowList.size(); i++) {
    SqlWindow window = (SqlWindow) windowList.get(i);
    final SqlIdentifier declId = window.getDeclName();
    assert declId.isSimple();
    if (declId.names.get(0).equals(name)) {
      return window;
    }
  }

  // if not in the select scope, then check window scope
  if (windowParent != null) {
    return windowParent.lookupWindow(name);
  } else {
    return null;
  }
}
 
Example #2
Source File: DremioRelToSqlConverter.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a SqlWindow that adds ORDER BY if op is one of the given functions.
 */
protected static SqlWindow addDummyOrderBy(SqlWindow window, DremioContext
  context, SqlAggFunction op, List<SqlAggFunction> opsToAddClauseFor) {
  if (!SqlNodeList.isEmptyList(window.getOrderList())) {
    return window;
  }

  // Add the ORDER BY if op is one of the given functions.
  for (SqlAggFunction function : opsToAddClauseFor) {
    if (function == op) {
      SqlNodeList dummyOrderByList = new SqlNodeList(POS);
      dummyOrderByList.add(context.field(0));

      return SqlWindow.create(window.getDeclName(), window.getRefName(), window.getPartitionList(),
        dummyOrderByList, SqlLiteral.createBoolean(window.isRows(), POS), window.getLowerBound(),
        window.getUpperBound(), SqlLiteral.createBoolean(window.isAllowPartial(), POS), POS);
    }
  }

  return window;
}
 
Example #3
Source File: SelectScope.java    From calcite with Apache License 2.0 6 votes vote down vote up
public SqlWindow lookupWindow(String name) {
  final SqlNodeList windowList = select.getWindowList();
  for (int i = 0; i < windowList.size(); i++) {
    SqlWindow window = (SqlWindow) windowList.get(i);
    final SqlIdentifier declId = window.getDeclName();
    assert declId.isSimple();
    if (declId.names.get(0).equals(name)) {
      return window;
    }
  }

  // if not in the select scope, then check window scope
  if (windowParent != null) {
    return windowParent.lookupWindow(name);
  } else {
    return null;
  }
}
 
Example #4
Source File: SqlImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlCall createOverCall(SqlAggFunction op, List<SqlNode> operands,
    SqlWindow window) {
  if (op instanceof SqlSumEmptyIsZeroAggFunction) {
    // Rewrite "SUM0(x) OVER w" to "COALESCE(SUM(x) OVER w, 0)"
    final SqlCall node =
        createOverCall(SqlStdOperatorTable.SUM, operands, window);
    return SqlStdOperatorTable.COALESCE.createCall(POS, node,
        SqlLiteral.createExactNumeric("0", POS));
  }
  final SqlCall aggFunctionCall = op.createCall(POS, operands);
  return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall,
      window);
}
 
Example #5
Source File: ConvMaster.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSqlNodeEqual(SqlNode queryNode, SqlNode exprNode) {
    if (queryNode != null && exprNode != null) {
        if (exprNode instanceof SqlIdentifier) {
            int parsedIdx = ParamNodeParser.parseParamIdx(exprNode.toString());
            if (parsedIdx >= 0) {
                SqlNode matchedBefore = matchedNodesMap.get(parsedIdx);
                if (matchedBefore != null) {
                    return ExpressionComparator.isNodeEqual(queryNode, matchedBefore, this);
                } else {
                    matchedNodesMap.put(parsedIdx, queryNode);
                    return true;
                }
            }
        } else if (exprNode instanceof SqlIntervalQualifier) {
            if (!(queryNode instanceof SqlIntervalQualifier)) {
                return false;
            }
            SqlIntervalQualifier thisNode = (SqlIntervalQualifier) queryNode;
            SqlIntervalQualifier thatNode = (SqlIntervalQualifier) exprNode;
            return thisNode.toString().equals(thatNode.toString());
        } else if (exprNode instanceof SqlWindow) {
            if (!(queryNode instanceof SqlWindow)) {
                return false;
            }
            if (((SqlWindow) exprNode).getRefName() instanceof SqlIdentifier) {
                return true;
            }
        }

    }

    return super.isSqlNodeEqual(queryNode, exprNode);
}
 
Example #6
Source File: SqlParamsFinderTest.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Test
public void testWindowCallParams() throws SqlParseException {
    SqlParser sqlParser1 = SqlParser.create("STDDEV_POP($0) OVER($1)");
    SqlNode sqlPattern = sqlParser1.parseExpression();
    SqlParser sqlParser2 = SqlParser.create("STDDEV_POP(C1) OVER (ORDER BY C1)");
    SqlNode sqlCall = sqlParser2.parseExpression();
    SqlParamsFinder sqlParamsFinder = SqlParamsFinder.newInstance((SqlCall)sqlPattern, (SqlCall)sqlCall, true);
    Map<Integer, SqlNode> paramNodes =  sqlParamsFinder.getParamNodes();

    Assert.assertEquals("C1", paramNodes.get(0).toString());
    Assert.assertEquals("(ORDER BY `C1`)", paramNodes.get(1).toString());
    Assert.assertTrue(paramNodes.get(1) instanceof SqlWindow);
}
 
Example #7
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
protected SqlCall toSql(RexProgram program, RexOver rexOver) {
  final RexWindow rexWindow = rexOver.getWindow();
  final SqlNodeList partitionList = new SqlNodeList(
    toSql(program, rexWindow.partitionKeys), POS);

  ImmutableList.Builder<SqlNode> orderNodes = ImmutableList.builder();
  if (rexWindow.orderKeys != null) {
    for (RexFieldCollation rfc : rexWindow.orderKeys) {
      orderNodes.add(toSql(program, rfc));
    }
  }
  final SqlNodeList orderList =
    new SqlNodeList(orderNodes.build(), POS);

  final SqlLiteral isRows =
    SqlLiteral.createBoolean(rexWindow.isRows(), POS);

  final SqlNode lowerBound =
    createSqlWindowBound(rexWindow.getLowerBound());
  final SqlNode upperBound =
    createSqlWindowBound(rexWindow.getUpperBound());

  // null defaults to true.
  // During parsing the allowPartial == false (e.g. disallow partial)
  // is expand into CASE expression and is handled as a such.
  // Not sure if we can collapse this CASE expression back into
  // "disallow partial" and set the allowPartial = false.
  final SqlLiteral allowPartial = null;

  final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList,
    orderList, isRows, lowerBound, upperBound, allowPartial, POS);

  final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
  final SqlCall aggFunctionCall =
    rexOver.getAggOperator().createCall(POS, nodeList);

  return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall,
    sqlWindow);
}
 
Example #8
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private SqlCall createOverCall(SqlAggFunction op, List<SqlNode> operands,
                               SqlWindow window) {
  if (op instanceof SqlSumEmptyIsZeroAggFunction) {
    // Rewrite "SUM0(x) OVER w" to "COALESCE(SUM(x) OVER w, 0)"
    final SqlCall node =
      createOverCall(SqlStdOperatorTable.SUM, operands, window);
    return SqlStdOperatorTable.COALESCE.createCall(POS, node,
      SqlLiteral.createExactNumeric("0", POS));
  }
  final SqlCall aggFunctionCall = op.createCall(POS, operands);
  return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall,
    window);
}
 
Example #9
Source File: JdbcRelBuilder.java    From calcite-sql-rewriter with Apache License 2.0 5 votes vote down vote up
public RexNode makeOver(
		SqlAggFunction operator,
		List<RexNode> expressions,
		List<RexNode> partitionKeys
) {
	final Set<SqlKind> flags = EnumSet.noneOf(SqlKind.class);

	// TODO
	// This is a temporal fix to make HAWQ work with OVER + UNLIMITED BOUNDS
	// HAWQ requires ORDER BY if andy BOUNDS are set even unlimited upper and lower BOUNDS (which is equal to
	// the entire partition - e.g. not setting BOUNDs at all --
	// Note that the unnecessary ORDER BY have negative performance impact and has to be remove once either HAWQ
	// start supporting unbounded bounds without order by or Calcite can generate shorthand OVER PARTITION BY
	// syntax.
	List<RexFieldCollation> orderKeys = expressions.stream().map(
			rexNode -> new RexFieldCollation(rexNode, flags)).collect(Collectors.toList());

	return makeOver(
			operator,
			expressions,
			partitionKeys,
			ImmutableList.copyOf(orderKeys),
			RexWindowBound.create(SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null),
			RexWindowBound.create(SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null),
			true,
			true,
			false
	);
}
 
Example #10
Source File: SqlParamsFinderTest.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWindowCallParams() throws SqlParseException {
    SqlParser sqlParser1 = SqlParser.create("STDDEV_POP($0) OVER($1)");
    SqlNode sqlPattern = sqlParser1.parseExpression();
    SqlParser sqlParser2 = SqlParser.create("STDDEV_POP(C1) OVER (ORDER BY C1)");
    SqlNode sqlCall = sqlParser2.parseExpression();
    SqlParamsFinder sqlParamsFinder = SqlParamsFinder.newInstance((SqlCall)sqlPattern, (SqlCall)sqlCall, true);
    Map<Integer, SqlNode> paramNodes =  sqlParamsFinder.getParamNodes();

    Assert.assertEquals("C1", paramNodes.get(0).toString());
    Assert.assertEquals("(ORDER BY `C1`)", paramNodes.get(1).toString());
    Assert.assertTrue(paramNodes.get(1) instanceof SqlWindow);
}
 
Example #11
Source File: ConvMaster.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSqlNodeEqual(SqlNode queryNode, SqlNode exprNode) {
    if (queryNode != null && exprNode != null) {
        if (exprNode instanceof SqlIdentifier) {
            int parsedIdx = ParamNodeParser.parseParamIdx(exprNode.toString());
            if (parsedIdx >= 0) {
                SqlNode matchedBefore = matchedNodesMap.get(parsedIdx);
                if (matchedBefore != null) {
                    return ExpressionComparator.isNodeEqual(queryNode, matchedBefore, this);
                } else {
                    matchedNodesMap.put(parsedIdx, queryNode);
                    return true;
                }
            }
        } else if (exprNode instanceof SqlIntervalQualifier) {
            if (!(queryNode instanceof SqlIntervalQualifier)) {
                return false;
            }
            SqlIntervalQualifier thisNode = (SqlIntervalQualifier) queryNode;
            SqlIntervalQualifier thatNode = (SqlIntervalQualifier) exprNode;
            return thisNode.toString().equals(thatNode.toString());
        } else if (exprNode instanceof SqlWindow) {
            if (!(queryNode instanceof SqlWindow)) {
                return false;
            }
            if (((SqlWindow) exprNode).getRefName() instanceof SqlIdentifier) {
                return true;
            }
        }

    }

    return super.isSqlNodeEqual(queryNode, exprNode);
}
 
Example #12
Source File: SqlImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlCall toSql(RexProgram program, RexOver rexOver) {
  final RexWindow rexWindow = rexOver.getWindow();
  final SqlNodeList partitionList = new SqlNodeList(
      toSql(program, rexWindow.partitionKeys), POS);

  List<SqlNode> orderNodes = Expressions.list();
  if (rexWindow.orderKeys != null) {
    for (RexFieldCollation rfc : rexWindow.orderKeys) {
      addOrderItem(orderNodes, program, rfc);
    }
  }
  final SqlNodeList orderList =
      new SqlNodeList(orderNodes, POS);

  final SqlLiteral isRows =
      SqlLiteral.createBoolean(rexWindow.isRows(), POS);

  // null defaults to true.
  // During parsing the allowPartial == false (e.g. disallow partial)
  // is expand into CASE expression and is handled as a such.
  // Not sure if we can collapse this CASE expression back into
  // "disallow partial" and set the allowPartial = false.
  final SqlLiteral allowPartial = null;

  SqlAggFunction sqlAggregateFunction = rexOver.getAggOperator();

  SqlNode lowerBound = null;
  SqlNode upperBound = null;

  if (sqlAggregateFunction.allowsFraming()) {
    lowerBound = createSqlWindowBound(rexWindow.getLowerBound());
    upperBound = createSqlWindowBound(rexWindow.getUpperBound());
  }

  final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList,
      orderList, isRows, lowerBound, upperBound, allowPartial, POS);

  final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
  return createOverCall(sqlAggregateFunction, nodeList, sqlWindow);
}
 
Example #13
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
protected SqlWindow getWindowByName(
	SqlIdentifier id,
	SqlValidatorScope scope) {
	SqlWindow window = null;
	if (id.isSimple()) {
		final String name = id.getSimple();
		window = scope.lookupWindow(name);
	}
	if (window == null) {
		throw newValidationError(id, RESOURCE.windowNotFound(id.toString()));
	}
	return window;
}
 
Example #14
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private SqlWindow getWindowInOver(SqlNode over) {
	if (over.getKind() == SqlKind.OVER) {
		SqlNode window = ((SqlCall) over).getOperandList().get(1);
		if (window instanceof SqlWindow) {
			return (SqlWindow) window;
		}
		// SqlIdentifier, gets validated elsewhere
		return null;
	}
	return null;
}
 
Example #15
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
protected SqlWindow getWindowByName(
	SqlIdentifier id,
	SqlValidatorScope scope) {
	SqlWindow window = null;
	if (id.isSimple()) {
		final String name = id.getSimple();
		window = scope.lookupWindow(name);
	}
	if (window == null) {
		throw newValidationError(id, RESOURCE.windowNotFound(id.toString()));
	}
	return window;
}
 
Example #16
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private SqlWindow getWindowInOver(SqlNode over) {
	if (over.getKind() == SqlKind.OVER) {
		SqlNode window = ((SqlCall) over).getOperandList().get(1);
		if (window instanceof SqlWindow) {
			return (SqlWindow) window;
		}
		// SqlIdentifier, gets validated elsewhere
		return null;
	}
	return null;
}
 
Example #17
Source File: JoinScope.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlWindow lookupWindow(String name) {
  // Lookup window in enclosing select.
  if (usingScope != null) {
    return usingScope.lookupWindow(name);
  } else {
    return null;
  }
}
 
Example #18
Source File: RexWindowBound.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates window bound.
 * @param node SqlNode of the bound
 * @param rexNode offset value when bound is not UNBOUNDED/CURRENT ROW
 * @return window bound
 */
public static RexWindowBound create(SqlNode node, RexNode rexNode) {
  if (SqlWindow.isUnboundedPreceding(node)
      || SqlWindow.isUnboundedFollowing(node)) {
    return new RexWindowBoundUnbounded(node);
  }
  if (SqlWindow.isCurrentRow(node)) {
    return new RexWindowBoundCurrentRow();
  }
  return new RexWindowBoundBounded(rexNode);
}
 
Example #19
Source File: RexWindowBounds.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a window bound from a {@link SqlNode}.
 *
 * @param node SqlNode of the bound
 * @param rexNode offset value when bound is not UNBOUNDED/CURRENT ROW
 * @return window bound
 */
public static RexWindowBound create(SqlNode node, RexNode rexNode) {
  if (SqlWindow.isUnboundedPreceding(node)) {
    return UNBOUNDED_PRECEDING;
  }
  if (SqlWindow.isUnboundedFollowing(node)) {
    return UNBOUNDED_FOLLOWING;
  }
  if (SqlWindow.isCurrentRow(node)) {
    return CURRENT_ROW;
  }
  return new RexBoundedWindowBound((RexCall) rexNode);
}
 
Example #20
Source File: JoinScope.java    From Bats with Apache License 2.0 5 votes vote down vote up
public SqlWindow lookupWindow(String name) {
  // Lookup window in enclosing select.
  if (usingScope != null) {
    return usingScope.lookupWindow(name);
  } else {
    return null;
  }
}
 
Example #21
Source File: RelJson.java    From Bats with Apache License 2.0 5 votes vote down vote up
private RexWindowBound toRexWindowBound(RelInput input, Map<String, Object> map) {
  if (map == null) {
    return null;
  }

  final String type = (String) map.get("type");
  switch (type) {
  case "CURRENT_ROW":
    return RexWindowBound.create(
        SqlWindow.createCurrentRow(SqlParserPos.ZERO), null);
  case "UNBOUNDED_PRECEDING":
    return RexWindowBound.create(
        SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null);
  case "UNBOUNDED_FOLLOWING":
    return RexWindowBound.create(
        SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO), null);
  case "PRECEDING":
    RexNode precedingOffset = toRex(input, map.get("offset"));
    return RexWindowBound.create(null,
        input.getCluster().getRexBuilder().makeCall(
            SqlWindow.PRECEDING_OPERATOR, precedingOffset));
  case "FOLLOWING":
    RexNode followingOffset = toRex(input, map.get("offset"));
    return RexWindowBound.create(null,
        input.getCluster().getRexBuilder().makeCall(
            SqlWindow.FOLLOWING_OPERATOR, followingOffset));
  default:
    throw new UnsupportedOperationException("cannot convert type to rex window bound " + type);
  }
}
 
Example #22
Source File: SqlImplementor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private SqlCall createOverCall(SqlAggFunction op, List<SqlNode> operands, SqlWindow window) {
    if (op instanceof SqlSumEmptyIsZeroAggFunction) {
        // Rewrite "SUM0(x) OVER w" to "COALESCE(SUM(x) OVER w, 0)"
        final SqlCall node = createOverCall(SqlStdOperatorTable.SUM, operands, window);
        return SqlStdOperatorTable.COALESCE.createCall(POS, node, SqlLiteral.createExactNumeric("0", POS));
    }
    final SqlCall aggFunctionCall = op.createCall(POS, operands);
    return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall, window);
}
 
Example #23
Source File: SqlImplementor.java    From Bats with Apache License 2.0 5 votes vote down vote up
private SqlCall toSql(RexProgram program, RexOver rexOver) {
    final RexWindow rexWindow = rexOver.getWindow();
    final SqlNodeList partitionList = new SqlNodeList(toSql(program, rexWindow.partitionKeys), POS);

    ImmutableList.Builder<SqlNode> orderNodes = ImmutableList.builder();
    if (rexWindow.orderKeys != null) {
        for (RexFieldCollation rfc : rexWindow.orderKeys) {
            orderNodes.add(toSql(program, rfc));
        }
    }
    final SqlNodeList orderList = new SqlNodeList(orderNodes.build(), POS);

    final SqlLiteral isRows = SqlLiteral.createBoolean(rexWindow.isRows(), POS);

    // null defaults to true.
    // During parsing the allowPartial == false (e.g. disallow partial)
    // is expand into CASE expression and is handled as a such.
    // Not sure if we can collapse this CASE expression back into
    // "disallow partial" and set the allowPartial = false.
    final SqlLiteral allowPartial = null;

    SqlAggFunction sqlAggregateFunction = rexOver.getAggOperator();

    SqlNode lowerBound = null;
    SqlNode upperBound = null;

    if (sqlAggregateFunction.allowsFraming()) {
        lowerBound = createSqlWindowBound(rexWindow.getLowerBound());
        upperBound = createSqlWindowBound(rexWindow.getUpperBound());
    }

    final SqlWindow sqlWindow = SqlWindow.create(null, null, partitionList, orderList, isRows, lowerBound,
            upperBound, allowPartial, POS);

    final List<SqlNode> nodeList = toSql(program, rexOver.getOperands());
    return createOverCall(sqlAggregateFunction, nodeList, sqlWindow);
}
 
Example #24
Source File: RexWindowBounds.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static RexWindowBound preceding(RexNode offset) {
  return new RexBoundedWindowBound(
      new RexCall(offset.getType(),
          SqlWindow.PRECEDING_OPERATOR, ImmutableList.of(offset)));
}
 
Example #25
Source File: DelegatingScope.java    From calcite with Apache License 2.0 4 votes vote down vote up
public SqlWindow lookupWindow(String name) {
  return parent.lookupWindow(name);
}
 
Example #26
Source File: SqlImplementor.java    From calcite with Apache License 2.0 4 votes vote down vote up
public List<SqlNode> toSql(Window.Group group, ImmutableList<RexLiteral> constants,
    int inputFieldCount) {
  final List<SqlNode> rexOvers = new ArrayList<>();
  final List<SqlNode> partitionKeys = new ArrayList<>();
  final List<SqlNode> orderByKeys = new ArrayList<>();
  for (int partition: group.keys) {
    partitionKeys.add(this.field(partition));
  }
  for (RelFieldCollation collation: group.orderKeys.getFieldCollations()) {
    this.addOrderItem(orderByKeys, collation);
  }
  SqlLiteral isRows = SqlLiteral.createBoolean(group.isRows, POS);
  SqlNode lowerBound = null;
  SqlNode upperBound = null;

  final SqlLiteral allowPartial = null;

  for (Window.RexWinAggCall winAggCall: group.aggCalls) {
    SqlAggFunction aggFunction = (SqlAggFunction) winAggCall.getOperator();
    final SqlWindow sqlWindow = SqlWindow.create(null, null,
            new SqlNodeList(partitionKeys, POS), new SqlNodeList(orderByKeys, POS),
            isRows, lowerBound, upperBound, allowPartial, POS);
    if (aggFunction.allowsFraming()) {
      lowerBound = createSqlWindowBound(group.lowerBound);
      upperBound = createSqlWindowBound(group.upperBound);
      sqlWindow.setLowerBound(lowerBound);
      sqlWindow.setUpperBound(upperBound);
    }

    RexShuttle replaceConstants = new RexShuttle() {
      @Override public RexNode visitInputRef(RexInputRef inputRef) {
        int index = inputRef.getIndex();
        RexNode ref;
        if (index > inputFieldCount - 1) {
          ref = constants.get(index - inputFieldCount);
        } else {
          ref = inputRef;
        }
        return ref;
      }
    };
    RexCall aggCall = (RexCall) winAggCall.accept(replaceConstants);
    List<SqlNode> operands = toSql(null, aggCall.operands);
    rexOvers.add(createOverCall(aggFunction, operands, sqlWindow));
  }
  return rexOvers;
}
 
Example #27
Source File: EmptyScope.java    From calcite with Apache License 2.0 4 votes vote down vote up
public SqlWindow lookupWindow(String name) {
  // No windows defined in this scope.
  return null;
}
 
Example #28
Source File: PigRelToSqlConverter.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** @see #dispatch */
public Result visit(Window e) {
  final Result x = visitChild(0, e.getInput());
  final Builder builder = x.builder(e, Clause.SELECT);
  final List<SqlNode> selectList =
      new ArrayList<>(builder.context.fieldList());

  for (Window.Group winGroup : e.groups) {
    final List<SqlNode> partitionList = Expressions.list();
    for (int i : winGroup.keys) {
      partitionList.add(builder.context.field(i));
    }

    final List<SqlNode> orderList = Expressions.list();
    for (RelFieldCollation orderKey : winGroup.collation().getFieldCollations()) {
      orderList.add(builder.context.toSql(orderKey));
    }

    final SqlNode sqlWindow =  SqlWindow.create(
        null, // Window declaration name
        null, // Window reference name
        new SqlNodeList(partitionList, POS),
        new SqlNodeList(orderList, POS),
        SqlLiteral.createBoolean(winGroup.isRows, POS),
        builder.context.toSql(winGroup.lowerBound),
        builder.context.toSql(winGroup.upperBound),
        null, // allowPartial
        POS);

    for (Window.RexWinAggCall winFunc : winGroup.aggCalls) {
      final List<SqlNode> winFuncOperands = Expressions.list();
      for (RexNode operand : winFunc.getOperands()) {
        winFuncOperands.add(builder.context.toSql(null, operand));
      }
      SqlNode aggFunc = winFunc.getOperator().createCall(new SqlNodeList(winFuncOperands, POS));
      selectList.add(SqlStdOperatorTable.OVER.createCall(POS, aggFunc, sqlWindow));
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
  }
  return builder.result();
}
 
Example #29
Source File: RexWindowBounds.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static RexWindowBound following(RexNode offset) {
  return new RexBoundedWindowBound(
      new RexCall(offset.getType(),
          SqlWindow.FOLLOWING_OPERATOR, ImmutableList.of(offset)));
}
 
Example #30
Source File: OverConvertRule.java    From flink with Apache License 2.0 4 votes vote down vote up
private RexWindowBound createBound(ConvertContext context, Expression bound, SqlKind sqlKind) {
	if (bound instanceof CallExpression) {
		CallExpression callExpr = (CallExpression) bound;
		FunctionDefinition func = callExpr.getFunctionDefinition();
		if (BuiltInFunctionDefinitions.UNBOUNDED_ROW.equals(func) || BuiltInFunctionDefinitions.UNBOUNDED_RANGE
			.equals(func)) {
			SqlNode unbounded = sqlKind.equals(SqlKind.PRECEDING) ? SqlWindow
				.createUnboundedPreceding(SqlParserPos.ZERO) :
				SqlWindow.createUnboundedFollowing(SqlParserPos.ZERO);
			return RexWindowBound.create(unbounded, null);
		} else if (BuiltInFunctionDefinitions.CURRENT_ROW.equals(func) || BuiltInFunctionDefinitions.CURRENT_RANGE
			.equals(func)) {
			SqlNode currentRow = SqlWindow.createCurrentRow(SqlParserPos.ZERO);
			return RexWindowBound.create(currentRow, null);
		} else {
			throw new IllegalArgumentException("Unexpected expression: " + bound);
		}
	} else if (bound instanceof ValueLiteralExpression) {
		RelDataType returnType = context.getTypeFactory()
			.createFieldTypeFromLogicalType(new DecimalType(true, 19, 0));
		SqlOperator sqlOperator = new SqlPostfixOperator(
			sqlKind.name(),
			sqlKind,
			2,
			new OrdinalReturnTypeInference(0),
			null,
			null);
		SqlNode[] operands = new SqlNode[] { SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO) };
		SqlNode node = new SqlBasicCall(sqlOperator, operands, SqlParserPos.ZERO);

		ValueLiteralExpression literalExpr = (ValueLiteralExpression) bound;
		RexNode literalRexNode = literalExpr.getValueAs(BigDecimal.class)
			.map(v -> context.getRelBuilder().literal(v))
			.orElse(context.getRelBuilder().literal(extractValue(literalExpr, Object.class)));

		List<RexNode> expressions = new ArrayList<>();
		expressions.add(literalRexNode);
		RexNode rexNode = context.getRelBuilder().getRexBuilder().makeCall(
			returnType, sqlOperator, expressions);
		return RexWindowBound.create(node, rexNode);
	} else {
		throw new TableException("Unexpected expression: " + bound);
	}
}