org.apache.calcite.sql.validate.SqlValidatorScope Java Examples

The following examples show how to use org.apache.calcite.sql.validate.SqlValidatorScope. 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: TypeCoercionImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Type coercion for user defined functions(UDFs).
 */
public boolean userDefinedFunctionCoercion(SqlValidatorScope scope,
    SqlCall call, SqlFunction function) {
  final List<RelDataType> paramTypes = function.getParamTypes();
  assert paramTypes != null;
  boolean coerced = false;
  for (int i = 0; i < call.operandCount(); i++) {
    SqlNode operand = call.operand(i);
    if (operand.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) {
      final List<SqlNode> operandList = ((SqlCall) operand).getOperandList();
      String name = ((SqlIdentifier) operandList.get(1)).getSimple();
      int formalIndex = function.getParamNames().indexOf(name);
      if (formalIndex < 0) {
        return false;
      }
      // Column list operand type is not supported now.
      coerced = coerceOperandType(scope, (SqlCall) operand, 0,
          paramTypes.get(formalIndex)) || coerced;
    } else {
      coerced = coerceOperandType(scope, call, i, paramTypes.get(i)) || coerced;
    }
  }
  return coerced;
}
 
Example #2
Source File: SqlAdvisorValidator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Calls the parent class method and mask Farrago exception thrown.
 */
public RelDataType deriveType(
    SqlValidatorScope scope,
    SqlNode operand) {
  // REVIEW Do not mask Error (indicates a serious system problem) or
  // UnsupportedOperationException (a bug). I have to mask
  // UnsupportedOperationException because
  // SqlValidatorImpl.getValidatedNodeType throws it for an unrecognized
  // identifier node I have to mask Error as well because
  // AbstractNamespace.getRowType  called in super.deriveType can do a
  // Util.permAssert that throws Error
  try {
    return super.deriveType(scope, operand);
  } catch (CalciteException | UnsupportedOperationException | Error e) {
    return unknownType;
  }
}
 
Example #3
Source File: SqlFilterOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  assert call.getOperator() == this;
  assert call.operandCount() == 2;
  SqlCall aggCall = getAggCall(call);
  if (!aggCall.getOperator().isAggregator()) {
    throw validator.newValidationError(aggCall,
        RESOURCE.filterNonAggregate());
  }
  final SqlNode condition = call.operand(1);
  SqlNodeList orderList = null;
  if (hasWithinGroupCall(call)) {
    SqlCall withinGroupCall = getWithinGroupCall(call);
    orderList = withinGroupCall.operand(1);
  }
  validator.validateAggregateParams(aggCall, condition, orderList, scope);

  final RelDataType type = validator.deriveType(scope, condition);
  if (!SqlTypeUtil.inBooleanFamily(type)) {
    throw validator.newValidationError(condition,
        RESOURCE.condMustBeBoolean("FILTER"));
  }
}
 
Example #4
Source File: SqlTypeUtil.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Recreates a given RelDataType with nullability iff any of the operands
 * of a call are nullable.
 */
public static RelDataType makeNullableIfOperandsAre(
    final SqlValidator validator,
    final SqlValidatorScope scope,
    final SqlCall call,
    RelDataType type) {
  for (SqlNode operand : call.getOperandList()) {
    RelDataType operandType = validator.deriveType(scope, operand);

    if (containsNullable(operandType)) {
      RelDataTypeFactory typeFactory = validator.getTypeFactory();
      type = typeFactory.createTypeWithNullability(type, true);
      break;
    }
  }
  return type;
}
 
Example #5
Source File: SqlAdvisorValidator.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Calls the parent class method and mask Farrago exception thrown.
 */
public RelDataType deriveType(
    SqlValidatorScope scope,
    SqlNode operand) {
  // REVIEW Do not mask Error (indicates a serious system problem) or
  // UnsupportedOperationException (a bug). I have to mask
  // UnsupportedOperationException because
  // SqlValidatorImpl.getValidatedNodeType throws it for an unrecognized
  // identifier node I have to mask Error as well because
  // AbstractNamespace.getRowType  called in super.deriveType can do a
  // Util.permAssert that throws Error
  try {
    return super.deriveType(scope, operand);
  } catch (CalciteException | UnsupportedOperationException | Error e) {
    return unknownType;
  }
}
 
Example #6
Source File: SqlIdentifier.java    From calcite with Apache License 2.0 6 votes vote down vote up
public SqlMonotonicity getMonotonicity(SqlValidatorScope scope) {
  // for "star" column, whether it's static or dynamic return not_monotonic directly.
  if (Util.last(names).equals("") || DynamicRecordType.isDynamicStarColName(Util.last(names))) {
    return SqlMonotonicity.NOT_MONOTONIC;
  }

  // First check for builtin functions which don't have parentheses,
  // like "LOCALTIME".
  final SqlValidator validator = scope.getValidator();
  final SqlCall call = validator.makeNullaryCall(this);
  if (call != null) {
    return call.getMonotonicity(scope);
  }
  final SqlQualified qualified = scope.fullyQualify(this);
  final SqlIdentifier fqId = qualified.identifier;
  return qualified.namespace.resolve().getMonotonicity(Util.last(fqId.names));
}
 
Example #7
Source File: FlinkCalciteSqlValidator.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void validateJoin(SqlJoin join, SqlValidatorScope scope) {
	// Due to the improper translation of lateral table left outer join in Calcite, we need to
	// temporarily forbid the common predicates until the problem is fixed (see FLINK-7865).
	if (join.getJoinType() == JoinType.LEFT &&
			SqlUtil.stripAs(join.getRight()).getKind() == SqlKind.COLLECTION_TABLE) {
		final SqlNode condition = join.getCondition();
		if (condition != null &&
				(!SqlUtil.isLiteral(condition) || ((SqlLiteral) condition).getValueAs(Boolean.class) != Boolean.TRUE)) {
			throw new ValidationException(
				String.format(
					"Left outer joins with a table function do not accept a predicate such as %s. " +
					"Only literal TRUE is accepted.",
					condition));
		}
	}
	super.validateJoin(join, scope);
}
 
Example #8
Source File: SqlOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Validates the operands of a call, inferring the return type in the
 * process.
 *
 * @param validator active validator
 * @param scope     validation scope
 * @param call      call to be validated
 * @return inferred type
 */
public final RelDataType validateOperands(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Let subclasses know what's up.
  preValidateCall(validator, scope, call);

  // Check the number of operands
  checkOperandCount(validator, operandTypeChecker, call);

  SqlCallBinding opBinding = new SqlCallBinding(validator, scope, call);

  checkOperandTypes(
      opBinding,
      true);

  // Now infer the result type.
  RelDataType ret = inferReturnType(opBinding);
  ((SqlValidatorImpl) validator).setValidatedNodeType(call, ret);
  return ret;
}
 
Example #9
Source File: SqlCall.java    From Bats with Apache License 2.0 6 votes vote down vote up
public void findValidOptions(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlParserPos pos,
    Collection<SqlMoniker> hintList) {
  for (SqlNode operand : getOperandList()) {
    if (operand instanceof SqlIdentifier) {
      SqlIdentifier id = (SqlIdentifier) operand;
      SqlParserPos idPos = id.getParserPosition();
      if (idPos.toString().equals(pos.toString())) {
        ((SqlValidatorImpl) validator).lookupNameCompletionHints(
            scope, id.names, pos, hintList);
        return;
      }
    }
  }
  // no valid options
}
 
Example #10
Source File: SqlNodeList.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void validateExpr(SqlValidator validator, SqlValidatorScope scope) {
  // While a SqlNodeList is not always a valid expression, this
  // implementation makes that assumption. It just validates the members
  // of the list.
  //
  // One example where this is valid is the IN operator. The expression
  //
  //    empno IN (10, 20)
  //
  // results in a call with operands
  //
  //    {  SqlIdentifier({"empno"}),
  //       SqlNodeList(SqlLiteral(10), SqlLiteral(20))  }

  for (SqlNode node : list) {
    node.validateExpr(validator, scope);
  }
}
 
Example #11
Source File: SqlWithinGroupOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  assert call.getOperator() == this;
  assert call.operandCount() == 2;
  SqlCall aggCall = call.operand(0);
  if (!aggCall.getOperator().isAggregator()) {
    throw validator.newValidationError(call,
        RESOURCE.withinGroupNotAllowed(aggCall.getOperator().getName()));
  }
  final SqlNodeList orderList = call.operand(1);
  for (SqlNode order : orderList) {
    RelDataType nodeType =
        validator.deriveType(scope, order);
    assert nodeType != null;
  }
  validator.validateAggregateParams(aggCall, null, orderList, scope);
}
 
Example #12
Source File: SqlOperator.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Validates the operands of a call, inferring the return type in the
 * process.
 *
 * @param validator active validator
 * @param scope     validation scope
 * @param call      call to be validated
 * @return inferred type
 */
public final RelDataType validateOperands(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Let subclasses know what's up.
  preValidateCall(validator, scope, call);

  // Check the number of operands
  checkOperandCount(validator, operandTypeChecker, call);

  SqlCallBinding opBinding = new SqlCallBinding(validator, scope, call);

  checkOperandTypes(
      opBinding,
      true);

  // Now infer the result type.
  RelDataType ret = inferReturnType(opBinding);
  ((SqlValidatorImpl) validator).setValidatedNodeType(call, ret);
  return ret;
}
 
Example #13
Source File: SqlFunction.java    From Bats with Apache License 2.0 6 votes vote down vote up
public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  // This implementation looks for the quantifier keywords DISTINCT or
  // ALL as the first operand in the list.  If found then the literal is
  // not called to validate itself.  Further the function is checked to
  // make sure that a quantifier is valid for that particular function.
  //
  // If the first operand does not appear to be a quantifier then the
  // parent ValidateCall is invoked to do normal function validation.

  super.validateCall(call, validator, scope, operandScope);
  validateQuantifier(validator, call);
}
 
Example #14
Source File: SqlOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected List<RelDataType> constructArgTypeList(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call,
    List<SqlNode> args,
    boolean convertRowArgToColumnList) {
  // Scope for operands. Usually the same as 'scope'.
  final SqlValidatorScope operandScope = scope.getOperandScope(call);

  final ImmutableList.Builder<RelDataType> argTypeBuilder =
          ImmutableList.builder();
  for (SqlNode operand : args) {
    RelDataType nodeType;
    // for row arguments that should be converted to ColumnList
    // types, set the nodeType to a ColumnList type but defer
    // validating the arguments of the row constructor until we know
    // for sure that the row argument maps to a ColumnList type
    if (operand.getKind() == SqlKind.ROW && convertRowArgToColumnList) {
      RelDataTypeFactory typeFactory = validator.getTypeFactory();
      nodeType = typeFactory.createSqlType(SqlTypeName.COLUMN_LIST);
      ((SqlValidatorImpl) validator).setValidatedNodeType(operand, nodeType);
    } else {
      nodeType = validator.deriveType(operandScope, operand);
    }
    argTypeBuilder.add(nodeType);
  }

  return argTypeBuilder.build();
}
 
Example #15
Source File: SqlJsonObjectAggAggFunction.java    From Bats 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 #16
Source File: SqlConverter.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
protected void validateFrom(
    SqlNode node,
    RelDataType targetRowType,
    SqlValidatorScope scope) {
  switch (node.getKind()) {
    case AS:
      SqlNode sqlNode = ((SqlCall) node).operand(0);
      switch (sqlNode.getKind()) {
        case IDENTIFIER:
          SqlIdentifier tempNode = (SqlIdentifier) sqlNode;
          DrillCalciteCatalogReader catalogReader = (SqlConverter.DrillCalciteCatalogReader) getCatalogReader();

          changeNamesIfTableIsTemporary(tempNode);

          // Check the schema and throw a valid SchemaNotFound exception instead of TableNotFound exception.
          if (catalogReader.getTable(tempNode.names) == null) {
            catalogReader.isValidSchema(tempNode.names);
          }
          break;
        case UNNEST:
          if (((SqlCall) node).operandCount() < 3) {
            throw RESOURCE.validationError("Alias table and column name are required for UNNEST").ex();
          }
      }
  }
  super.validateFrom(node, targetRowType, scope);
}
 
Example #17
Source File: TypeCoercionImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Coerces the field expression at index {@code columnIndex} of source
 * in an INSERT or UPDATE query to target type.
 *
 * @param sourceScope  Query source scope
 * @param query        Query
 * @param columnIndex  Source column index to coerce type
 * @param targetType   Target type
 */
private boolean coerceSourceRowType(
    SqlValidatorScope sourceScope,
    SqlNode query,
    int columnIndex,
    RelDataType targetType) {
  switch (query.getKind()) {
  case INSERT:
    SqlInsert insert = (SqlInsert) query;
    return coerceSourceRowType(sourceScope,
        insert.getSource(),
        columnIndex,
        targetType);
  case UPDATE:
    SqlUpdate update = (SqlUpdate) query;
    if (update.getSourceExpressionList() != null) {
      final SqlNodeList sourceExpressionList = update.getSourceExpressionList();
      return coerceColumnType(sourceScope, sourceExpressionList, columnIndex, targetType);
    } else {
      return coerceSourceRowType(sourceScope,
          update.getSourceSelect(),
          columnIndex,
          targetType);
    }
  default:
    return rowTypeCoercion(sourceScope, query, columnIndex, targetType);
  }
}
 
Example #18
Source File: SqlFilterOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Validate type of the inner aggregate call
  validateOperands(validator, scope, call);

  // Assume the first operand is an aggregate call and derive its type.
  final SqlCall aggCall = getAggCall(call);

  // Pretend that group-count is 0. This tells the aggregate function that it
  // might be invoked with 0 rows in a group. Most aggregate functions will
  // return NULL in this case.
  SqlCallBinding opBinding = new SqlCallBinding(validator, scope, aggCall) {
    @Override public int getGroupCount() {
      return 0;
    }
  };

  RelDataType ret = aggCall.getOperator().inferReturnType(opBinding);

  // Copied from validateOperands
  ((SqlValidatorImpl) validator).setValidatedNodeType(call, ret);
  ((SqlValidatorImpl) validator).setValidatedNodeType(aggCall, ret);
  if (hasWithinGroupCall(call)) {
    ((SqlValidatorImpl) validator).setValidatedNodeType(getWithinGroupCall(call), ret);
  }
  return ret;
}
 
Example #19
Source File: SqlMatchRecognize.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  validator.validateMatchRecognize(call);
}
 
Example #20
Source File: SqlAdvisorValidator.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void registerId(SqlIdentifier id, SqlValidatorScope scope) {
  for (int i = 0; i < id.names.size(); i++) {
    final SqlParserPos subPos = id.getComponentParserPosition(i);
    SqlIdentifier subId =
        i == id.names.size() - 1
            ? id
            : new SqlIdentifier(id.names.subList(0, i + 1), subPos);
    idPositions.put(subPos.toString(), new IdInfo(scope, subId));
  }
}
 
Example #21
Source File: SqlJsonArrayAggAggFunction.java    From Bats 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 #22
Source File: SqlCursorConstructor.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  SqlSelect subSelect = call.operand(0);
  validator.declareCursor(subSelect, scope);
  subSelect.validateExpr(validator, scope);
  return super.deriveType(validator, scope, call);
}
 
Example #23
Source File: SqlDotOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public RelDataType deriveType(SqlValidator validator,
    SqlValidatorScope scope, SqlCall call) {
  final SqlNode operand = call.getOperandList().get(0);
  final RelDataType nodeType =
      validator.deriveType(scope, operand);
  assert nodeType != null;
  if (!nodeType.isStruct()) {
    throw SqlUtil.newContextException(operand.getParserPosition(),
        Static.RESOURCE.incompatibleTypes());
  }

  final SqlNode fieldId = call.operand(1);
  final String fieldName = fieldId.toString();
  final RelDataTypeField field =
      nodeType.getField(fieldName, false, false);
  if (field == null) {
    throw SqlUtil.newContextException(fieldId.getParserPosition(),
        Static.RESOURCE.unknownField(fieldName));
  }
  RelDataType type = field.getType();

  // Validate and determine coercibility and resulting collation
  // name of binary operator if needed.
  type = adjustType(validator, call, type);
  SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
  return type;
}
 
Example #24
Source File: SqlMultisetQueryConstructor.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  SqlSelect subSelect = call.operand(0);
  subSelect.validateExpr(validator, scope);
  SqlValidatorNamespace ns = validator.getNamespace(subSelect);
  assert null != ns.getRowType();
  return SqlTypeUtil.createMultisetType(
      validator.getTypeFactory(),
      ns.getRowType(),
      false);
}
 
Example #25
Source File: SqlAggFunction.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  super.validateCall(call, validator, scope, operandScope);
  validator.validateAggregateParams(call, null, null, scope);
}
 
Example #26
Source File: AbstractSqlTester.java    From calcite with Apache License 2.0 5 votes vote down vote up
public SqlMonotonicity getMonotonicity(String sql) {
  final SqlValidator validator = getValidator();
  final SqlNode node = parseAndValidate(validator, sql);
  final SqlSelect select = (SqlSelect) node;
  final SqlNode selectItem0 = select.getSelectList().get(0);
  final SqlValidatorScope scope = validator.getSelectScope(select);
  return selectItem0.getMonotonicity(scope);
}
 
Example #27
Source File: SqlCaseOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Do not try to derive the types of the operands. We will do that
  // later, top down.
  return validateOperands(validator, scope, call);
}
 
Example #28
Source File: SqlTypeUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Iterates over all operands, derives their types, and collects them into
 * a list.
 */
public static List<RelDataType> deriveAndCollectTypes(
    SqlValidator validator,
    SqlValidatorScope scope,
    List<SqlNode> operands) {
  // NOTE: Do not use an AbstractList. Don't want to be lazy. We want
  // errors.
  List<RelDataType> types = new ArrayList<>();
  for (SqlNode operand : operands) {
    types.add(validator.deriveType(scope, operand));
  }
  return types;
}
 
Example #29
Source File: PlannerTest.java    From calcite 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 #30
Source File: SqlSequenceValueOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void validateCall(SqlCall call, SqlValidator validator,
    SqlValidatorScope scope, SqlValidatorScope operandScope) {
  List<SqlNode> operands = call.getOperandList();
  assert operands.size() == 1;
  assert operands.get(0) instanceof SqlIdentifier;
  SqlIdentifier id = (SqlIdentifier) operands.get(0);
  validator.validateSequenceValue(scope, id);
}