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

The following examples show how to use org.apache.calcite.sql.validate.SqlValidator. 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: SqlPostfixOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
protected RelDataType adjustType(
    SqlValidator validator,
    SqlCall call,
    RelDataType type) {
  if (SqlTypeUtil.inCharFamily(type)) {
    // Determine coercibility and resulting collation name of
    // unary operator if needed.
    RelDataType operandType =
        validator.getValidatedNodeType(call.operand(0));
    if (null == operandType) {
      throw new AssertionError("operand's type should have been derived");
    }
    if (SqlTypeUtil.inCharFamily(operandType)) {
      SqlCollation collation = operandType.getCollation();
      assert null != collation
          : "An implicit or explicit collation should have been set";
      type =
          validator.getTypeFactory()
              .createTypeWithCharsetAndCollation(
                  type,
                  type.getCharset(),
                  collation);
    }
  }
  return type;
}
 
Example #2
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 #3
Source File: SqlOperator.java    From Bats with Apache License 2.0 6 votes vote down vote up
protected List<SqlNode> constructOperandList(
    SqlValidator validator,
    SqlCall call,
    List<String> argNames) {
  if (argNames == null) {
    return call.getOperandList();
  }
  if (argNames.size() < call.getOperandList().size()) {
    throw validator.newValidationError(call,
        RESOURCE.someButNotAllArgumentsAreNamed());
  }
  final int duplicate = Util.firstDuplicate(argNames);
  if (duplicate >= 0) {
    throw validator.newValidationError(call,
        RESOURCE.duplicateArgumentName(argNames.get(duplicate)));
  }
  final ImmutableList.Builder<SqlNode> argBuilder = ImmutableList.builder();
  for (SqlNode operand : call.getOperandList()) {
    if (operand.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) {
      final List<SqlNode> operandList = ((SqlCall) operand).getOperandList();
      argBuilder.add(operandList.get(0));
    }
  }
  return argBuilder.build();
}
 
Example #4
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 #5
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 #6
Source File: SqlCall.java    From calcite 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 #7
Source File: SqlJsonValueFunction.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  final SqlValidator validator = callBinding.getValidator();
  RelDataType defaultValueOnEmptyType =
      validator.getValidatedNodeType(callBinding.operand(2));
  RelDataType defaultValueOnErrorType =
      validator.getValidatedNodeType(callBinding.operand(4));
  RelDataType returnType =
      validator.deriveType(callBinding.getScope(), callBinding.operand(5));
  if (!canCastFrom(callBinding, throwOnFailure, defaultValueOnEmptyType,
      returnType)) {
    return false;
  }
  if (!canCastFrom(callBinding, throwOnFailure, defaultValueOnErrorType,
      returnType)) {
    return false;
  }
  return true;
}
 
Example #8
Source File: SqlProcedureCallOperator.java    From Bats with 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);
}
 
Example #9
Source File: SqlTumbleTableFunction.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public boolean checkOperandTypes(SqlCallBinding callBinding,
    boolean throwOnFailure) {
  // There should only be three operands, and number of operands are checked before
  // this call.
  final SqlNode operand0 = callBinding.operand(0);
  final SqlValidator validator = callBinding.getValidator();
  final RelDataType type = validator.getValidatedNodeType(operand0);
  if (type.getSqlTypeName() != SqlTypeName.ROW) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  final SqlNode operand1 = callBinding.operand(1);
  if (operand1.getKind() != SqlKind.DESCRIPTOR) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  validateColumnNames(validator, type.getFieldNames(), ((SqlCall) operand1).getOperandList());
  final RelDataType type2 = validator.getValidatedNodeType(callBinding.operand(2));
  if (!SqlTypeUtil.isInterval(type2)) {
    return throwValidationSignatureErrorOrReturnFalse(callBinding, throwOnFailure);
  }
  return true;
}
 
Example #10
Source File: AbstractSqlTester.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void checkIntervalConv(String sql, String expected) {
  SqlValidator validator = getValidator();
  final SqlCall n = (SqlCall) parseAndValidate(validator, sql);

  SqlNode node = null;
  for (int i = 0; i < n.operandCount(); i++) {
    node = stripAs(n.operand(i));
    if (node instanceof SqlCall) {
      node = ((SqlCall) node).operand(0);
      break;
    }
  }

  assertNotNull(node);
  SqlIntervalLiteral intervalLiteral = (SqlIntervalLiteral) node;
  SqlIntervalLiteral.IntervalValue interval =
      (SqlIntervalLiteral.IntervalValue) intervalLiteral.getValue();
  long l =
      interval.getIntervalQualifier().isYearMonth()
          ? SqlParserUtil.intervalToMonths(interval)
          : SqlParserUtil.intervalToMillis(interval);
  String actual = l + "";
  assertEquals(expected, actual);
}
 
Example #11
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public RelRoot expandView(RelDataType rowType, String queryString,
    List<String> schemaPath, List<String> viewPath) {
  expansionDepth++;

  SqlParser parser = prepare.createParser(queryString);
  SqlNode sqlNode;
  try {
    sqlNode = parser.parseQuery();
  } catch (SqlParseException e) {
    throw new RuntimeException("parse failed", e);
  }
  // View may have different schema path than current connection.
  final CatalogReader catalogReader =
      this.catalogReader.withSchemaPath(schemaPath);
  SqlValidator validator = createSqlValidator(catalogReader);
  final SqlToRelConverter.Config config = SqlToRelConverter.configBuilder()
          .withTrimUnusedFields(true).build();
  SqlToRelConverter sqlToRelConverter =
      getSqlToRelConverter(validator, catalogReader, config);
  RelRoot root =
      sqlToRelConverter.convertQuery(sqlNode, true, false);

  --expansionDepth;
  return root;
}
 
Example #12
Source File: AbstractSqlTester.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void assertExceptionIsThrown(String sql, String expectedMsgPattern) {
  final SqlValidator validator;
  final SqlNode sqlNode;
  final SqlParserUtil.StringAndPos sap = SqlParserUtil.findPos(sql);
  try {
    sqlNode = parseQuery(sap.sql);
    validator = getValidator();
  } catch (Throwable e) {
    checkParseEx(e, expectedMsgPattern, sap.sql);
    return;
  }

  Throwable thrown = null;
  try {
    validator.validate(sqlNode);
  } catch (Throwable ex) {
    thrown = ex;
  }

  SqlTests.checkEx(thrown, expectedMsgPattern, sap, SqlTests.Stage.VALIDATE);
}
 
Example #13
Source File: SqlAggFunction.java    From calcite 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 #14
Source File: PlannerImpl.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public RelRoot expandView(RelDataType rowType, String queryString,
                          List<String> schemaPath, List<String> viewPath) {
    if (planner == null) {
        ready();
    }
    SqlParser parser = SqlParser.create(queryString, parserConfig);
    SqlNode sqlNode;
    try {
        sqlNode = parser.parseQuery();
    } catch (SqlParseException e) {
        throw new RuntimeException("parse failed", e);
    }

    final CalciteCatalogReader catalogReader =
            createCatalogReader().withSchemaPath(schemaPath);
    final SqlValidator validator = createSqlValidator(catalogReader);

    final RexBuilder rexBuilder = createRexBuilder();
    final RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
    final SqlToRelConverter.Config config = SqlToRelConverter
            .configBuilder()
            .withConfig(sqlToRelConverterConfig)
            .withTrimUnusedFields(false)
            .build();
    final SqlToRelConverter sqlToRelConverter =
            new SqlToRelConverter(this, validator,
                    catalogReader, cluster, convertletTable, config);

    final RelRoot root =
            sqlToRelConverter.convertQuery(sqlNode, true, false);
    final RelRoot root2 =
            root.withRel(sqlToRelConverter.flattenTypes(root.rel, true));
    final RelBuilder relBuilder =
            config.getRelBuilderFactory().create(cluster, null);
    return root2.withRel(
            RelDecorrelator.decorrelateQuery(root.rel, relBuilder));
}
 
Example #15
Source File: SqlSetOption.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void validate(SqlValidator validator,
    SqlValidatorScope scope) {
  validator.validate(value);
}
 
Example #16
Source File: PlannerImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private SqlValidator createSqlValidator(CalciteCatalogReader catalogReader) {
  final SqlOperatorTable opTab =
      ChainedSqlOperatorTable.of(operatorTable, catalogReader);
  return new CalciteSqlValidator(opTab,
      catalogReader,
      typeFactory,
      sqlValidatorConfig
          .withDefaultNullCollation(connectionConfig.defaultNullCollation())
          .withLenientOperatorLookup(connectionConfig.lenientOperatorLookup())
          .withSqlConformance(connectionConfig.conformance())
          .withIdentifierExpansion(true));
}
 
Example #17
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 #18
Source File: SqlNullTreatmentOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void validateCall(
    SqlCall call,
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlValidatorScope operandScope) {
  assert call.getOperator() == this;
  assert call.operandCount() == 1;
  SqlCall aggCall = call.operand(0);
  if (!aggCall.getOperator().isAggregator()
      || !((SqlAggFunction) aggCall.getOperator()).allowsNullTreatment()) {
    throw validator.newValidationError(aggCall,
        RESOURCE.disallowsNullTreatment(aggCall.getOperator().getName()));
  }
}
 
Example #19
Source File: SqlWithinGroupOperator.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
  return validateOperands(validator, scope, call);
}
 
Example #20
Source File: CalcitePrepare.java    From calcite with Apache License 2.0 5 votes vote down vote up
public ParseResult(CalcitePrepareImpl prepare, SqlValidator validator,
    String sql,
    SqlNode sqlNode, RelDataType rowType) {
  super();
  this.prepare = prepare;
  this.sql = sql;
  this.sqlNode = sqlNode;
  this.rowType = rowType;
  this.typeFactory = validator.getTypeFactory();
}
 
Example #21
Source File: SqlOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Derives the type of a call to this operator.
 *
 * <p>This method is an intrinsic part of the validation process so, unlike
 * {@link #inferReturnType}, specific operators would not typically override
 * this method.
 *
 * @param validator Validator
 * @param scope     Scope of validation
 * @param call      Call to this operator
 * @return Type of call
 */
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    assert nodeType != null;
  }

  final List<SqlNode> args = constructOperandList(validator, call, null);

  final List<RelDataType> argTypes = constructArgTypeList(validator, scope,
      call, args, false);

  final SqlOperator sqlOperator =
      SqlUtil.lookupRoutine(validator.getOperatorTable(), getNameAsId(),
          argTypes, null, null, getSyntax(), getKind());

  ((SqlBasicCall) call).setOperator(sqlOperator);
  RelDataType type = call.getOperator().validateOperands(validator, scope, call);

  // Validate and determine coercibility and resulting collation
  // name of binary operator if needed.
  type = adjustType(validator, call, type);
  SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
  return type;
}
 
Example #22
Source File: SqlMapTypeNameSpec.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType deriveType(SqlValidator validator) {
	return validator.getTypeFactory()
		.createMapType(
			keyType.deriveType(validator),
			valType.deriveType(validator));
}
 
Example #23
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);
}
 
Example #24
Source File: SqlOperator.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Derives the type of a call to this operator.
 *
 * <p>This method is an intrinsic part of the validation process so, unlike
 * {@link #inferReturnType}, specific operators would not typically override
 * this method.
 *
 * @param validator Validator
 * @param scope     Scope of validation
 * @param call      Call to this operator
 * @return Type of call
 */
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    assert nodeType != null;
  }

  final List<SqlNode> args = constructOperandList(validator, call, null);

  final List<RelDataType> argTypes = constructArgTypeList(validator, scope,
      call, args, false);

  // Always disable type coercion for builtin operator operands,
  // they are handled by the TypeCoercion specifically.
  final SqlOperator sqlOperator =
      SqlUtil.lookupRoutine(validator.getOperatorTable(), getNameAsId(),
          argTypes, null, null, getSyntax(), getKind(),
          validator.getCatalogReader().nameMatcher(), false);

  ((SqlBasicCall) call).setOperator(sqlOperator);
  RelDataType type = call.getOperator().validateOperands(validator, scope, call);

  // Validate and determine coercibility and resulting collation
  // name of binary operator if needed.
  type = adjustType(validator, call, type);
  SqlValidatorUtil.checkCharsetAndCollateConsistentIfCharType(type);
  return type;
}
 
Example #25
Source File: SqlBetweenOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
private List<RelDataType> collectOperandTypes(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  List<RelDataType> argTypes =
      SqlTypeUtil.deriveAndCollectTypes(
          validator, scope, call.getOperandList());
  return ImmutableNullableList.of(
      argTypes.get(VALUE_OPERAND),
      argTypes.get(LOWER_OPERAND),
      argTypes.get(UPPER_OPERAND));
}
 
Example #26
Source File: BatsOptimizerTest.java    From Bats with Apache License 2.0 5 votes vote down vote up
static RelNode testSqlToRelConverter(RelOptPlanner planner) throws Exception {
    RexBuilder rexBuilder = createRexBuilder();
    RelOptCluster cluster = RelOptCluster.create(planner, rexBuilder);
    RelOptTable.ViewExpander viewExpander = ViewExpanders.simpleContext(cluster);

    Pair<SqlNode, SqlValidator> pair = testSqlValidator();
    SqlNode sqlNode = pair.left;
    SqlValidator validator = pair.right;
    CatalogReader catalogReader = createCalciteCatalogReader();
    SqlRexConvertletTable convertletTable = StandardConvertletTable.INSTANCE;
    SqlToRelConverter.Config config = SqlToRelConverter.Config.DEFAULT;
    // 不转换成EnumerableTableScan,而是LogicalTableScan
    config = SqlToRelConverter.configBuilder().withConvertTableAccess(false).build();

    SqlToRelConverter converter = new SqlToRelConverter(viewExpander, validator, catalogReader, cluster,
            convertletTable, config);

    boolean needsValidation = false;
    boolean top = false;
    RelRoot root = converter.convertQuery(sqlNode, needsValidation, top);
    RelNode relNode = root.rel;

    String plan = RelOptUtil.toString(relNode);
    System.out.println("Logical Plan:");
    System.out.println("------------------------------------------------------------------");
    System.out.println(plan);
    System.out.println();

    // testPrograms(root.rel);

    return relNode;
}
 
Example #27
Source File: SqlFilterOperator.java    From Bats 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 #28
Source File: SqlOperator.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected void checkOperandCount(
    SqlValidator validator,
    SqlOperandTypeChecker argType,
    SqlCall call) {
  SqlOperandCountRange od = call.getOperator().getOperandCountRange();
  if (od.isValidCount(call.operandCount())) {
    return;
  }
  if (od.getMin() == od.getMax()) {
    throw validator.newValidationError(call,
        RESOURCE.invalidArgCount(call.getOperator().getName(), od.getMin()));
  } else {
    throw validator.newValidationError(call, RESOURCE.wrongNumOfArguments());
  }
}
 
Example #29
Source File: Prepare.java    From calcite with Apache License 2.0 5 votes vote down vote up
public PreparedResult prepareSql(
    SqlNode sqlQuery,
    Class runtimeContextClass,
    SqlValidator validator,
    boolean needsValidation) {
  return prepareSql(
      sqlQuery,
      sqlQuery,
      runtimeContextClass,
      validator,
      needsValidation);
}
 
Example #30
Source File: DrillCalciteSqlAggFunctionWrapper.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);
}