org.apache.calcite.sql.SqlCall Java Examples

The following examples show how to use org.apache.calcite.sql.SqlCall. 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: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
@Nullable public SqlCall makeNullaryCall(SqlIdentifier id) {
	if (id.names.size() == 1 && !id.isComponentQuoted(0)) {
		final List<SqlOperator> list = new ArrayList<>();
		opTab.lookupOperatorOverloads(id, null, SqlSyntax.FUNCTION, list,
				catalogReader.nameMatcher());
		for (SqlOperator operator : list) {
			if (operator.getSyntax() == SqlSyntax.FUNCTION_ID) {
				// Even though this looks like an identifier, it is a
				// actually a call to a function. Construct a fake
				// call to this function, so we can use the regular
				// operator validation.
				return new SqlBasicCall(operator, SqlNode.EMPTY_ARRAY,
						id.getParserPosition(), true, null);
			}
		}
	}
	return null;
}
 
Example #2
Source File: OracleSqlDialect.java    From Bats with 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) {
    SqlUtil.unparseFunctionSyntax(OracleSqlOperatorTable.SUBSTR, writer, call);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      final SqlLiteral timeUnitNode = call.operand(1);
      final TimeUnitRange timeUnit = timeUnitNode.getValueAs(TimeUnitRange.class);

      SqlCall call2 = SqlFloorFunction.replaceTimeUnitOperand(call, timeUnit.name(),
          timeUnitNode.getParserPosition());
      SqlFloorFunction.unparseDatetimeFunction(writer, call2, "TRUNC", true);
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example #3
Source File: MssqlSqlDialect.java    From Bats with 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 #4
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private void checkRollUp(SqlNode grandParent, SqlNode parent,
	SqlNode current, SqlValidatorScope scope, String optionalClause) {
	current = stripAs(current);
	if (current instanceof SqlCall && !(current instanceof SqlSelect)) {
		// Validate OVER separately
		checkRollUpInWindow(getWindowInOver(current), scope);
		current = stripOver(current);

		List<SqlNode> children = ((SqlCall) stripDot(current)).getOperandList();
		for (SqlNode child : children) {
			checkRollUp(parent, current, child, scope, optionalClause);
		}
	} else if (current instanceof SqlIdentifier) {
		SqlIdentifier id = (SqlIdentifier) current;
		if (!id.isStar() && isRolledUpColumn(id, scope)) {
			if (!isAggregation(parent.getKind())
				|| !isRolledUpColumnAllowedInAgg(id, scope, (SqlCall) parent, grandParent)) {
				String context = optionalClause != null ? optionalClause : parent.getKind().toString();
				throw newValidationError(id,
					RESOURCE.rolledUpNotAllowed(deriveAlias(id, 0), context));
			}
		}
	}
}
 
Example #5
Source File: ServerDdlExecutor.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Wraps a query to rename its columns. Used by CREATE VIEW and CREATE
 * MATERIALIZED VIEW. */
static SqlNode renameColumns(SqlNodeList columnList, SqlNode query) {
  if (columnList == null) {
    return query;
  }
  final SqlParserPos p = query.getParserPosition();
  final SqlNodeList selectList = SqlNodeList.SINGLETON_STAR;
  final SqlCall from =
      SqlStdOperatorTable.AS.createCall(p,
          ImmutableList.<SqlNode>builder()
              .add(query)
              .add(new SqlIdentifier("_", p))
              .addAll(columnList)
              .build());
  return new SqlSelect(p, null, selectList, from, null, null, null, null,
      null, null, null, null);
}
 
Example #6
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/** Converts a {@link SqlCall} to a {@link RexCall} with a perhaps different
 * operator. */
private RexNode convertCall(
    SqlRexContext cx,
    SqlCall call,
    SqlOperator op) {
  final List<SqlNode> operands = call.getOperandList();
  final RexBuilder rexBuilder = cx.getRexBuilder();
  final SqlOperandTypeChecker.Consistency consistency =
      op.getOperandTypeChecker() == null
          ? SqlOperandTypeChecker.Consistency.NONE
          : op.getOperandTypeChecker().getConsistency();
  final List<RexNode> exprs =
      convertExpressionList(cx, operands, consistency);
  RelDataType type = rexBuilder.deriveReturnType(op, exprs);
  return rexBuilder.makeCall(type, op, RexUtil.flatten(exprs, op));
}
 
Example #7
Source File: SqlStdOperatorTable.java    From Bats with Apache License 2.0 6 votes vote down vote up
/** Converts a call to a grouped window function to a call to its auxiliary
 * window function(s). For other calls returns null.
 *
 * <p>For example, converts {@code TUMBLE_START(rowtime, INTERVAL '1' HOUR))}
 * to {@code TUMBLE(rowtime, INTERVAL '1' HOUR))}. */
public static List<Pair<SqlNode, AuxiliaryConverter>> convertGroupToAuxiliaryCalls(
    SqlCall call) {
  final SqlOperator op = call.getOperator();
  if (op instanceof SqlGroupedWindowFunction
      && op.isGroup()) {
    ImmutableList.Builder<Pair<SqlNode, AuxiliaryConverter>> builder =
        ImmutableList.builder();
    for (final SqlGroupedWindowFunction f
        : ((SqlGroupedWindowFunction) op).getAuxiliaryFunctions()) {
      builder.add(
          Pair.of(copy(call, f),
              new AuxiliaryConverter.Impl(f)));
    }
    return builder.build();
  }
  return ImmutableList.of();
}
 
Example #8
Source File: FlattenConvertlet.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  SqlFlattenOperator operator = (SqlFlattenOperator) call.getOperator();
  final List<RexNode> exprs = new LinkedList<>();

  for (SqlNode node : call.getOperandList()) {
    exprs.add(cx.convertExpression(node));
  }

  SqlFlattenOperator indexedOperator = operator.withIndex(((SqlValidatorImpl)cx.getValidator()).nextFlattenIndex());
  final RexBuilder rexBuilder = cx.getRexBuilder();
  // Since we don't have any way of knowing if the output of the flatten is nullable, we should always assume it is.
  // This is especially important when accelerating a count(column) query, because the normalizer will convert it to
  // a count(1) if it thinks this column is non-nullable, and then remove the flatten altogether. This is actually a
  // problem with the fact that flatten is not really a project operator (because it can output more than one row per input).
  RelDataType type = rexBuilder
    .getTypeFactory()
    .createTypeWithNullability(
      rexBuilder
        .getTypeFactory()
        .createSqlType(SqlTypeName.ANY),
      true
    );
  return rexBuilder.makeCall(type, indexedOperator, exprs);

}
 
Example #9
Source File: SqlImplementor.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
protected boolean hasNestedAggregations(LogicalAggregate rel) {
  List<AggregateCall> aggCallList = rel.getAggCallList();
  HashSet<Integer> aggregatesArgs = new HashSet<>();
  for (AggregateCall aggregateCall : aggCallList) {
    aggregatesArgs.addAll(aggregateCall.getArgList());
  }
  for (Integer aggregatesArg : aggregatesArgs) {
    SqlNode selectNode = ((SqlSelect) node).getSelectList().get(aggregatesArg);
    if (!(selectNode instanceof SqlBasicCall)) {
      continue;
    }
    for (SqlNode operand : ((SqlBasicCall) selectNode).getOperands()) {
      if (operand instanceof SqlCall) {
        final SqlOperator operator = ((SqlCall) operand).getOperator();
        if (operator instanceof SqlAggFunction) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example #10
Source File: DremioSqlDialect.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void unparseCall(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
  // Translate the PI function call to PI()
  if (call.getOperator() == SqlStdOperatorTable.PI) {
    super.unparseCall(
      writer,
      PI_FUNCTION.createCall(new SqlNodeList(call.getOperandList(), SqlParserPos.ZERO)),
      leftPrec, rightPrec);
  } else if (call.getOperator().equals(FunctionRegistry.E_FUNCTION)) {
    // Translate the E() function call to EXP(1)
    final SqlCall newCall = SqlStdOperatorTable.EXP.createCall(
      SqlParserPos.ZERO, SqlLiteral.createExactNumeric("1", SqlParserPos.ZERO));
    super.unparseCall(writer, newCall, leftPrec, rightPrec);
  } else if (call.getKind() == SqlKind.JOIN) {
    this.unparseJoin(writer, (SqlJoin) call, leftPrec, rightPrec);
  } else {
    super.unparseCall(writer, call, leftPrec, rightPrec);
  }
}
 
Example #11
Source File: SelectScope.java    From Bats with Apache License 2.0 6 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlNode expr) {
  SqlMonotonicity monotonicity = expr.getMonotonicity(this);
  if (monotonicity != SqlMonotonicity.NOT_MONOTONIC) {
    return monotonicity;
  }

  // TODO: compare fully qualified names
  final SqlNodeList orderList = getOrderList();
  if (orderList.size() > 0) {
    SqlNode order0 = orderList.get(0);
    monotonicity = SqlMonotonicity.INCREASING;
    if ((order0 instanceof SqlCall)
        && (((SqlCall) order0).getOperator()
        == SqlStdOperatorTable.DESC)) {
      monotonicity = monotonicity.reverse();
      order0 = ((SqlCall) order0).operand(0);
    }
    if (expr.equalsDeep(order0, Litmus.IGNORE)) {
      return monotonicity;
    }
  }

  return SqlMonotonicity.NOT_MONOTONIC;
}
 
Example #12
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Validates an expression.
 *
 * @param expr  Expression
 * @param scope Scope in which expression occurs
 */
private void validateExpr(SqlNode expr, SqlValidatorScope scope) {
	if (expr instanceof SqlCall) {
		final SqlOperator op = ((SqlCall) expr).getOperator();
		if (op.isAggregator() && op.requiresOver()) {
			throw newValidationError(expr,
				RESOURCE.absentOverClause());
		}
	}

	// Call on the expression to validate itself.
	expr.validateExpr(this, scope);

	// Perform any validation specific to the scope. For example, an
	// aggregating scope requires that expressions are valid aggregations.
	scope.validateExpr(expr);
}
 
Example #13
Source File: SqlSubstringFunction.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startFunCall(getName());
  call.operand(0).unparse(writer, leftPrec, rightPrec);
  writer.sep("FROM");
  call.operand(1).unparse(writer, leftPrec, rightPrec);

  if (3 == call.operandCount()) {
    writer.sep("FOR");
    call.operand(2).unparse(writer, leftPrec, rightPrec);
  }

  writer.endFunCall(frame);
}
 
Example #14
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
private static SqlNode stripOver(SqlNode node) {
	switch (node.getKind()) {
		case OVER:
			return ((SqlCall) node).getOperandList().get(0);
		default:
			return node;
	}
}
 
Example #15
Source File: ReflectiveConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Registers method if it: a. is public, and b. is named "convertXxx", and
 * c. has a return type of "RexNode" or a subtype d. has a 3 parameters with
 * types: ConvertletContext; SqlOperator (or a subtype), SqlCall (or a
 * subtype).
 */
private void registerOpTypeMethod(final Method method) {
  if (!Modifier.isPublic(method.getModifiers())) {
    return;
  }
  if (!method.getName().startsWith("convert")) {
    return;
  }
  if (!RexNode.class.isAssignableFrom(method.getReturnType())) {
    return;
  }
  final Class[] parameterTypes = method.getParameterTypes();
  if (parameterTypes.length != 3) {
    return;
  }
  if (parameterTypes[0] != SqlRexContext.class) {
    return;
  }
  final Class opClass = parameterTypes[1];
  if (!SqlOperator.class.isAssignableFrom(opClass)) {
    return;
  }
  final Class parameterType = parameterTypes[2];
  if (!SqlCall.class.isAssignableFrom(parameterType)) {
    return;
  }
  map.put(opClass, (SqlRexConvertlet) (cx, call) -> {
    try {
      return (RexNode) method.invoke(ReflectiveConvertletTable.this,
          cx, call.getOperator(), call);
    } catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException("while converting " + call, e);
    }
  });
}
 
Example #16
Source File: SqlJsonArrayAggAggFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType deriveType(SqlValidator validator,
    SqlValidatorScope scope, SqlCall call) {
  // To prevent operator rewriting by SqlFunction#deriveType.
  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    ((SqlValidatorImpl) validator).setValidatedNodeType(operand, nodeType);
  }
  return validateOperands(validator, scope, call);
}
 
Example #17
Source File: ClickHouseSqlDialect.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void unparseCall(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  if (call.getOperator() == SqlStdOperatorTable.SUBSTRING) {
    RelToSqlConverterUtil.specialOperatorByName("substring")
        .unparse(writer, call, 0, 0);
  } else {
    switch (call.getKind()) {
    case FLOOR:
      if (call.operandCount() != 2) {
        super.unparseCall(writer, call, leftPrec, rightPrec);
        return;
      }

      unparseFloor(writer, call);
      break;

    case COUNT:
      // CH returns NULL rather than 0 for COUNT(DISTINCT) of NULL values.
      // https://github.com/yandex/ClickHouse/issues/2494
      // Wrap the call in a CH specific coalesce (assumeNotNull).
      if (call.getFunctionQuantifier() != null
          && call.getFunctionQuantifier().toString().equals("DISTINCT")) {
        writer.print("assumeNotNull");
        SqlWriter.Frame frame = writer.startList("(", ")");
        super.unparseCall(writer, call, leftPrec, rightPrec);
        writer.endList(frame);
      } else {
        super.unparseCall(writer, call, leftPrec, rightPrec);
      }
      break;

    default:
      super.unparseCall(writer, call, leftPrec, rightPrec);
    }
  }
}
 
Example #18
Source File: SqlDatetimeSubtractionOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
public void unparse(
    SqlWriter writer,
    SqlCall call,
    int leftPrec,
    int rightPrec) {
  writer.getDialect().unparseSqlDatetimeArithmetic(
      writer, call, SqlKind.MINUS, leftPrec, rightPrec);
}
 
Example #19
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a BETWEEN expression.
 *
 * <p>Called automatically via reflection.
 */
public RexNode convertBetween(
    SqlRexContext cx,
    SqlBetweenOperator op,
    SqlCall call) {
  final List<RexNode> list =
      convertExpressionList(cx, call.getOperandList(),
          op.getOperandTypeChecker().getConsistency());
  final RexNode x = list.get(SqlBetweenOperator.VALUE_OPERAND);
  final RexNode y = list.get(SqlBetweenOperator.LOWER_OPERAND);
  final RexNode z = list.get(SqlBetweenOperator.UPPER_OPERAND);

  final RexBuilder rexBuilder = cx.getRexBuilder();
  RexNode ge1 = ge(rexBuilder, x, y);
  RexNode le1 = le(rexBuilder, x, z);
  RexNode and1 = and(rexBuilder, ge1, le1);

  RexNode res;
  final SqlBetweenOperator.Flag symmetric = op.flag;
  switch (symmetric) {
  case ASYMMETRIC:
    res = and1;
    break;
  case SYMMETRIC:
    RexNode ge2 = ge(rexBuilder, x, z);
    RexNode le2 = le(rexBuilder, x, y);
    RexNode and2 = and(rexBuilder, ge2, le2);
    res = or(rexBuilder, and1, and2);
    break;
  default:
    throw Util.unexpected(symmetric);
  }
  final SqlBetweenOperator betweenOp =
      (SqlBetweenOperator) call.getOperator();
  if (betweenOp.isNegated()) {
    res = rexBuilder.makeCall(SqlStdOperatorTable.NOT, res);
  }
  return res;
}
 
Example #20
Source File: AliasNamespace.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an AliasNamespace.
 *
 * @param validator     Validator
 * @param call          Call to AS operator
 * @param enclosingNode Enclosing node
 */
protected AliasNamespace(
    SqlValidatorImpl validator,
    SqlCall call,
    SqlNode enclosingNode) {
  super(validator, enclosingNode);
  this.call = call;
  assert call.getOperator() == SqlStdOperatorTable.AS;
}
 
Example #21
Source File: SqlRollupOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void unparseKeyword(SqlWriter writer, SqlCall call, String keyword) {
  final SqlWriter.Frame groupFrame =
      writer.startList(SqlWriter.FrameTypeEnum.GROUP_BY_LIST);
  for (SqlNode operand : call.getOperandList()) {
    writer.sep(",");
    operand.unparse(writer, 2, 3);
  }
  writer.endList(groupFrame);
  writer.keyword(keyword);
}
 
Example #22
Source File: SqlTrimFunction.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlCall createCall(
    SqlLiteral functionQualifier,
    SqlParserPos pos,
    SqlNode... operands) {
  assert functionQualifier == null;
  switch (operands.length) {
  case 1:
    // This variant occurs when someone writes TRIM(string)
    // as opposed to the sugared syntax TRIM(string FROM string).
    operands = new SqlNode[]{
      Flag.BOTH.symbol(SqlParserPos.ZERO),
      SqlLiteral.createCharString(" ", pos),
      operands[0]
    };
    break;
  case 3:
    assert operands[0] instanceof SqlLiteral
        && ((SqlLiteral) operands[0]).getValue() instanceof Flag;
    if (operands[1] == null) {
      operands[1] = SqlLiteral.createCharString(" ", pos);
    }
    break;
  default:
    throw new IllegalArgumentException(
        "invalid operand count " + Arrays.toString(operands));
  }
  return super.createCall(functionQualifier, pos, operands);
}
 
Example #23
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the FROM clause of a query, or (recursively) a child node of
 * the FROM clause: AS, OVER, JOIN, VALUES, or sub-query.
 *
 * @param node          Node in FROM clause, typically a table or derived
 *                      table
 * @param targetRowType Desired row type of this expression, or
 *                      {@link #unknownType} if not fussy. Must not be null.
 * @param scope         Scope
 */
protected void validateFrom(
	SqlNode node,
	RelDataType targetRowType,
	SqlValidatorScope scope) {
	Objects.requireNonNull(targetRowType);
	switch (node.getKind()) {
		case AS:
			validateFrom(
				((SqlCall) node).operand(0),
				targetRowType,
				scope);
			break;
		case VALUES:
			validateValues((SqlCall) node, targetRowType, scope);
			break;
		case JOIN:
			validateJoin((SqlJoin) node, scope);
			break;
		case OVER:
			validateOver((SqlCall) node, scope);
			break;
		default:
			validateQuery(node, scope, targetRowType);
			break;
	}

	// Validate the namespace representation of the node, just in case the
	// validation did not occur implicitly.
	getNamespace(node, scope).validate(targetRowType);
}
 
Example #24
Source File: SqlOverlapsOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
void arg(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec, int i) {
  if (SqlUtil.isCallTo(call.operand(i), SqlStdOperatorTable.ROW)) {
    SqlCall row = call.operand(i);
    writer.keyword("PERIOD");
    writer.sep("(", true);
    row.operand(0).unparse(writer, leftPrec, rightPrec);
    writer.sep(",", true);
    row.operand(1).unparse(writer, leftPrec, rightPrec);
    writer.sep(")", true);
  } else {
    call.operand(i).unparse(writer, leftPrec, rightPrec);
  }
}
 
Example #25
Source File: SqlCountAggFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Check for COUNT(*) function.  If it is we don't
  // want to try and derive the "*"
  if (call.isCountStar()) {
    return validator.getTypeFactory().createSqlType(
        SqlTypeName.BIGINT);
  }
  return super.deriveType(validator, scope, call);
}
 
Example #26
Source File: SqlStdOperatorTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call,
    int leftPrec, int rightPrec) {
  call.operand(0).unparse(writer, this.getLeftPrec(), this.getRightPrec());
  int startNum = ((SqlNumericLiteral) call.operand(1)).intValue(true);
  SqlNumericLiteral endRepNum = call.operand(2);
  boolean isReluctant = ((SqlLiteral) call.operand(3)).booleanValue();
  int endNum = endRepNum.intValue(true);
  if (startNum == endNum) {
    writer.keyword("{ " + startNum + " }");
  } else {
    if (endNum == -1) {
      if (startNum == 0) {
        writer.keyword("*");
      } else if (startNum == 1) {
        writer.keyword("+");
      } else {
        writer.keyword("{ " + startNum + ", }");
      }
    } else {
      if (startNum == 0 && endNum == 1) {
        writer.keyword("?");
      } else if (startNum == -1) {
        writer.keyword("{ , " + endNum + " }");
      } else {
        writer.keyword("{ " + startNum + ", " + endNum + " }");
      }
    }
    if (isReluctant) {
      writer.keyword("?");
    }
  }
}
 
Example #27
Source File: DrillCalciteSqlFunctionWrapper.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  return operator.deriveType(validator,
      scope,
      call);
}
 
Example #28
Source File: SqlValidatorImpl.java    From Flink-CEPplus with 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 #29
Source File: SqlFloorFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void unparse(SqlWriter writer, SqlCall call, int leftPrec,
    int rightPrec) {
  final SqlWriter.Frame frame = writer.startFunCall(getName());
  if (call.operandCount() == 2) {
    call.operand(0).unparse(writer, 0, 100);
    writer.sep("TO");
    call.operand(1).unparse(writer, 100, 0);
  } else {
    call.operand(0).unparse(writer, 0, 0);
  }
  writer.endFunCall(frame);
}
 
Example #30
Source File: StandardConvertletTable.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RexNode convertCall(SqlRexContext cx, SqlCall call) {
  assert call.operandCount() == 1;
  final SqlNode arg = call.operand(0);
  final SqlNode expr;
  final RelDataType type =
      cx.getValidator().getValidatedNodeType(call);
  switch (kind) {
  case AVG:
    expr = expandAvg(arg, type, cx);
    break;
  case STDDEV_POP:
    expr = expandVariance(arg, type, cx, true, true);
    break;
  case STDDEV_SAMP:
    expr = expandVariance(arg, type, cx, false, true);
    break;
  case VAR_POP:
    expr = expandVariance(arg, type, cx, true, false);
    break;
  case VAR_SAMP:
    expr = expandVariance(arg, type, cx, false, false);
    break;
  default:
    throw Util.unexpected(kind);
  }
  RexNode rex = cx.convertExpression(expr);
  return cx.getRexBuilder().ensureType(type, rex, true);
}