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

The following examples show how to use org.apache.calcite.sql.validate.SqlValidator. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   Source File: SqlOperator.java    License: 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 2
Source Project: Bats   Source File: SqlProcedureCallOperator.java    License: Apache License 2.0 6 votes vote down vote up
public SqlNode rewriteCall(SqlValidator validator, SqlCall call) {
  // for now, rewrite "CALL f(x)" to "SELECT f(x) FROM VALUES(0)"
  // TODO jvs 18-Jan-2005:  rewrite to SELECT * FROM TABLE f(x)
  // once we support function calls as tables
  return new SqlSelect(SqlParserPos.ZERO,
      null,
      new SqlNodeList(
          Collections.singletonList(call.operand(0)),
          SqlParserPos.ZERO),
      SqlStdOperatorTable.VALUES.createCall(
          SqlParserPos.ZERO,
          SqlStdOperatorTable.ROW.createCall(
              SqlParserPos.ZERO,
              SqlLiteral.createExactNumeric("0", SqlParserPos.ZERO))),
      null,
      null,
      null,
      null,
      null,
      null,
      null);
}
 
Example 3
Source Project: calcite   Source File: SqlTumbleTableFunction.java    License: 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 4
Source Project: calcite   Source File: AbstractSqlTester.java    License: 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 5
Source Project: Bats   Source File: SqlPostfixOperator.java    License: 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 6
Source Project: calcite   Source File: AbstractSqlTester.java    License: 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 7
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: 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 8
Source Project: Bats   Source File: SqlJsonValueFunction.java    License: 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 9
Source Project: calcite   Source File: SqlCall.java    License: 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 Project: calcite   Source File: SqlIdentifier.java    License: 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 11
Source Project: Bats   Source File: SqlCall.java    License: 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 12
Source Project: Bats   Source File: SqlOperator.java    License: 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 Project: Bats   Source File: BatsOptimizerTest.java    License: 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 14
Source Project: calcite   Source File: SqlJdbcFunctionCall.java    License: Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Override SqlFunction.deriveType, because function-resolution is
  // not relevant to a JDBC function call.
  // REVIEW: jhyde, 2006/4/18: Should SqlJdbcFunctionCall even be a
  // subclass of SqlFunction?

  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    ((SqlValidatorImpl) validator).setValidatedNodeType(operand, nodeType);
  }
  return validateOperands(validator, scope, call);
}
 
Example 15
Source Project: calcite   Source File: StandardConvertletTable.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Casts a RexNode value to the validated type of a SqlCall. If the value
 * was already of the validated type, then the value is returned without an
 * additional cast.
 */
public static RexNode castToValidatedType(SqlNode node, RexNode e,
    SqlValidator validator, RexBuilder rexBuilder) {
  final RelDataType type = validator.getValidatedNodeType(node);
  if (e.getType() == type) {
    return e;
  }
  return rexBuilder.makeCast(type, e);
}
 
Example 16
Source Project: flink   Source File: ExtendedSqlCollectionTypeNameSpec.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RelDataType deriveType(SqlValidator validator) {
	RelDataType elementType = getElementTypeName().deriveType(validator);
	elementType = validator.getTypeFactory()
		.createTypeWithNullability(elementType, elementNullable);
	return createCollectionType(elementType, validator.getTypeFactory());
}
 
Example 17
Source Project: calcite   Source File: Frameworks.java    License: Apache License 2.0 5 votes vote down vote up
StdFrameworkConfig(Context context,
    SqlRexConvertletTable convertletTable,
    SqlOperatorTable operatorTable,
    ImmutableList<Program> programs,
    ImmutableList<RelTraitDef> traitDefs,
    SqlParser.Config parserConfig,
    SqlValidator.Config sqlValidatorConfig,
    SqlToRelConverter.Config sqlToRelConverterConfig,
    SchemaPlus defaultSchema,
    RelOptCostFactory costFactory,
    RelDataTypeSystem typeSystem,
    RexExecutor executor,
    boolean evolveLattice,
    SqlStatisticProvider statisticProvider,
    RelOptTable.ViewExpander viewExpander) {
  this.context = context;
  this.convertletTable = convertletTable;
  this.operatorTable = operatorTable;
  this.programs = programs;
  this.traitDefs = traitDefs;
  this.parserConfig = parserConfig;
  this.sqlValidatorConfig = sqlValidatorConfig;
  this.sqlToRelConverterConfig = sqlToRelConverterConfig;
  this.defaultSchema = defaultSchema;
  this.costFactory = costFactory;
  this.typeSystem = typeSystem;
  this.executor = executor;
  this.evolveLattice = evolveLattice;
  this.statisticProvider = statisticProvider;
  this.viewExpander = viewExpander;
}
 
Example 18
Source Project: Bats   Source File: CalciteResult.java    License: Apache License 2.0 5 votes vote down vote up
public ParseResult(SqlValidator validator, String sql, SqlNode sqlNode, RelDataType rowType) {
    super();
    this.sql = sql;
    this.sqlNode = sqlNode;
    this.rowType = rowType;
    this.typeFactory = validator.getTypeFactory();
}
 
Example 19
Source Project: calcite   Source File: SqlJdbcFunctionCall.java    License: Apache License 2.0 5 votes vote down vote up
@Override public SqlNode rewriteCall(SqlValidator validator,
    SqlCall call) {
  if (null == lookupMakeCallObj) {
    throw validator.newValidationError(call,
        RESOURCE.functionUndefined(getName()));
  }
  return lookupMakeCallObj.getOperator().rewriteCall(validator, call);
}
 
Example 20
Source Project: calcite   Source File: Frameworks.java    License: Apache License 2.0 5 votes vote down vote up
/** Creates a ConfigBuilder, initializing to defaults. */
private ConfigBuilder() {
  convertletTable = StandardConvertletTable.INSTANCE;
  operatorTable = SqlStdOperatorTable.instance();
  programs = ImmutableList.of();
  context = Contexts.empty();
  parserConfig = SqlParser.Config.DEFAULT;
  sqlValidatorConfig = SqlValidator.Config.DEFAULT;
  sqlToRelConverterConfig = SqlToRelConverter.Config.DEFAULT;
  typeSystem = RelDataTypeSystem.DEFAULT;
  evolveLattice = false;
  statisticProvider = QuerySqlStatisticProvider.SILENT_CACHING_INSTANCE;
}
 
Example 21
Source Project: calcite   Source File: SqlAsOperator.java    License: Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // special case for AS:  never try to derive type for alias
  RelDataType nodeType =
      validator.deriveType(scope, call.operand(0));
  assert nodeType != null;
  return validateOperands(validator, scope, call);
}
 
Example 22
Source Project: calcite   Source File: SqlSequenceValueOperator.java    License: 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 23
Source Project: flink   Source File: FlinkDDLDataTypeTest.java    License: Apache License 2.0 5 votes vote down vote up
public SqlValidator getValidator() {
	final SqlConformance conformance =
		(SqlConformance) options.get("conformance");
	final boolean enableTypeCoercion = (boolean) options.get("enableTypeCoercion");
	return validatorFactory.create(operatorTable,
		catalogReader,
		typeFactory,
		conformance)
		.setEnableTypeCoercion(enableTypeCoercion);
}
 
Example 24
Source Project: Bats   Source File: SqlJdbcFunctionCall.java    License: Apache License 2.0 5 votes vote down vote up
public RelDataType deriveType(
    SqlValidator validator,
    SqlValidatorScope scope,
    SqlCall call) {
  // Override SqlFunction.deriveType, because function-resolution is
  // not relevant to a JDBC function call.
  // REVIEW: jhyde, 2006/4/18: Should SqlJdbcFunctionCall even be a
  // subclass of SqlFunction?

  for (SqlNode operand : call.getOperandList()) {
    RelDataType nodeType = validator.deriveType(scope, operand);
    ((SqlValidatorImpl) validator).setValidatedNodeType(operand, nodeType);
  }
  return validateOperands(validator, scope, call);
}
 
Example 25
Source Project: calcite   Source File: SqlOperator.java    License: 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 26
Source Project: calcite   Source File: SqlOperator.java    License: 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 27
Source Project: calcite   Source File: Prepare.java    License: 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 28
Source Project: Bats   Source File: SqlOperator.java    License: 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 Project: Bats   Source File: SqlFilterOperator.java    License: 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 30
Source Project: Bats   Source File: SqlBetweenOperator.java    License: 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));
}