Java Code Examples for org.apache.calcite.util.Util#skip()

The following examples show how to use org.apache.calcite.util.Util#skip() . 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: Window.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Presents a view of the {@link RexWinAggCall} list as a list of
 * {@link AggregateCall}.
 */
public List<AggregateCall> getAggregateCalls(Window windowRel) {
    final List<String> fieldNames = Util.skip(windowRel.getRowType().getFieldNames(),
            windowRel.getInput().getRowType().getFieldCount());
    return new AbstractList<AggregateCall>() {
        @Override
        public int size() {
            return aggCalls.size();
        }

        @Override
        public AggregateCall get(int index) {
            final RexWinAggCall aggCall = aggCalls.get(index);
            final SqlAggFunction op = (SqlAggFunction) aggCall.getOperator();
            return AggregateCall.create(op, aggCall.isDistinct(), false,
                    getProjectOrdinals(aggCall.getOperands()), -1, RelCollations.EMPTY, aggCall.getType(),
                    fieldNames.get(aggCall.getOrdinal()));
        }
    };
}
 
Example 2
Source File: Window.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Presents a view of the {@link RexWinAggCall} list as a list of
 * {@link AggregateCall}.
 */
public List<AggregateCall> getAggregateCalls(Window windowRel) {
  final List<String> fieldNames =
      Util.skip(windowRel.getRowType().getFieldNames(),
          windowRel.getInput().getRowType().getFieldCount());
  return new AbstractList<AggregateCall>() {
    public int size() {
      return aggCalls.size();
    }

    public AggregateCall get(int index) {
      final RexWinAggCall aggCall = aggCalls.get(index);
      final SqlAggFunction op = (SqlAggFunction) aggCall.getOperator();
      return AggregateCall.create(op, aggCall.distinct, false,
          aggCall.ignoreNulls, getProjectOrdinals(aggCall.getOperands()),
          -1, RelCollations.EMPTY,
          aggCall.getType(), fieldNames.get(aggCall.ordinal));
    }
  };
}
 
Example 3
Source File: SqlParserUtil.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public PrecedenceClimbingParser parser(int start,
    Predicate<PrecedenceClimbingParser.Token> predicate) {
  final PrecedenceClimbingParser.Builder builder =
      new PrecedenceClimbingParser.Builder();
  for (Object o : Util.skip(list, start)) {
    if (o instanceof ToTreeListItem) {
      final ToTreeListItem item = (ToTreeListItem) o;
      final SqlOperator op = item.getOperator();
      if (op instanceof SqlPrefixOperator) {
        builder.prefix(item, op.getLeftPrec());
      } else if (op instanceof SqlPostfixOperator) {
        builder.postfix(item, op.getRightPrec());
      } else if (op instanceof SqlBinaryOperator) {
        builder.infix(item, op.getLeftPrec(),
            op.getLeftPrec() < op.getRightPrec());
      } else if (op instanceof SqlSpecialOperator) {
        builder.special(item, op.getLeftPrec(), op.getRightPrec(),
            (parser, op2) -> {
              final List<PrecedenceClimbingParser.Token> tokens =
                  parser.all();
              final SqlSpecialOperator op1 =
                  (SqlSpecialOperator) ((ToTreeListItem) op2.o).op;
              SqlSpecialOperator.ReduceResult r =
                  op1.reduceExpr(tokens.indexOf(op2),
                      new TokenSequenceImpl(parser));
              return new PrecedenceClimbingParser.Result(
                  tokens.get(r.startOrdinal),
                  tokens.get(r.endOrdinal - 1),
                  parser.atom(r.node));
            });
      } else {
        throw new AssertionError();
      }
    } else {
      builder.atom(o);
    }
  }
  return builder.build();
}
 
Example 4
Source File: AliasNamespace.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected RelDataType validateImpl(RelDataType targetRowType) {
  final List<String> nameList = new ArrayList<>();
  final List<SqlNode> operands = call.getOperandList();
  final SqlValidatorNamespace childNs =
      validator.getNamespace(operands.get(0));
  final RelDataType rowType = childNs.getRowTypeSansSystemColumns();
  final List<SqlNode> columnNames = Util.skip(operands, 2);
  for (final SqlNode operand : columnNames) {
    String name = ((SqlIdentifier) operand).getSimple();
    if (nameList.contains(name)) {
      throw validator.newValidationError(operand,
          RESOURCE.aliasListDuplicate(name));
    }
    nameList.add(name);
  }
  if (nameList.size() != rowType.getFieldCount()) {
    // Position error over all column names
    final SqlNode node = operands.size() == 3
        ? operands.get(2)
        : new SqlNodeList(columnNames, SqlParserPos.sum(columnNames));
    throw validator.newValidationError(node,
        RESOURCE.aliasListDegree(rowType.getFieldCount(), getString(rowType),
            nameList.size()));
  }
  final List<RelDataType> typeList = new ArrayList<>();
  for (RelDataTypeField field : rowType.getFieldList()) {
    typeList.add(field.getType());
  }
  return validator.getTypeFactory().createStructType(
      typeList,
      nameList);
}
 
Example 5
Source File: SqlParserUtil.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public PrecedenceClimbingParser parser(int start,
    Predicate<PrecedenceClimbingParser.Token> predicate) {
  final PrecedenceClimbingParser.Builder builder =
      new PrecedenceClimbingParser.Builder();
  for (Object o : Util.skip(list, start)) {
    if (o instanceof ToTreeListItem) {
      final ToTreeListItem item = (ToTreeListItem) o;
      final SqlOperator op = item.getOperator();
      if (op instanceof SqlPrefixOperator) {
        builder.prefix(item, op.getLeftPrec());
      } else if (op instanceof SqlPostfixOperator) {
        builder.postfix(item, op.getRightPrec());
      } else if (op instanceof SqlBinaryOperator) {
        builder.infix(item, op.getLeftPrec(),
            op.getLeftPrec() < op.getRightPrec());
      } else if (op instanceof SqlSpecialOperator) {
        builder.special(item, op.getLeftPrec(), op.getRightPrec(),
            (parser, op2) -> {
              final List<PrecedenceClimbingParser.Token> tokens =
                  parser.all();
              final SqlSpecialOperator op1 =
                  (SqlSpecialOperator) ((ToTreeListItem) op2.o).op;
              SqlSpecialOperator.ReduceResult r =
                  op1.reduceExpr(tokens.indexOf(op2),
                      new TokenSequenceImpl(parser));
              return new PrecedenceClimbingParser.Result(
                  tokens.get(r.startOrdinal),
                  tokens.get(r.endOrdinal - 1),
                  parser.atom(r.node));
            });
      } else {
        throw new AssertionError();
      }
    } else {
      builder.atom(o);
    }
  }
  return builder.build();
}
 
Example 6
Source File: StandardConvertletTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RexNode convertWindowFunction(
    SqlRexContext cx,
    SqlWindowTableFunction fun,
    SqlCall call) {
  // The first operand of window function is actually a query, skip that.
  final List<SqlNode> operands = Util.skip(call.getOperandList(), 1);
  final List<RexNode> exprs = convertExpressionList(cx, operands,
      SqlOperandTypeChecker.Consistency.NONE);
  RelDataType returnType =
      cx.getValidator().getValidatedNodeTypeIfKnown(call);
  if (returnType == null) {
    returnType = cx.getRexBuilder().deriveReturnType(fun, exprs);
  }
  return cx.getRexBuilder().makeCall(returnType, fun, exprs);
}
 
Example 7
Source File: DruidRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Aggregate aggregate = call.rel(0);
  final Project project = call.rel(1);
  final DruidQuery query = call.rel(2);
  if (!DruidQuery.isValidSignature(query.signature() + 'p' + 'a')) {
    return;
  }
  if (aggregate.getGroupSets().size() != 1) {
    return;
  }
  if (DruidQuery
      .computeProjectGroupSet(project, aggregate.getGroupSet(), query.table.getRowType(), query)
      == null) {
    return;
  }
  final List<String> aggNames = Util
      .skip(aggregate.getRowType().getFieldNames(), aggregate.getGroupSet().cardinality());
  if (DruidQuery.computeDruidJsonAgg(aggregate.getAggCallList(), aggNames, project, query)
      == null) {
    return;
  }
  final RelNode newProject = project.copy(project.getTraitSet(),
          ImmutableList.of(Util.last(query.rels)));
  final RelNode newAggregate = aggregate.copy(aggregate.getTraitSet(),
          ImmutableList.of(newProject));
  List<Integer> filterRefs = getFilterRefs(aggregate.getAggCallList());
  final DruidQuery query2;
  if (filterRefs.size() > 0) {
    query2 = optimizeFilteredAggregations(call, query, (Project) newProject,
        (Aggregate) newAggregate);
  } else {
    final DruidQuery query1 = DruidQuery.extendQuery(query, newProject);
    query2 = DruidQuery.extendQuery(query1, newAggregate);
  }
  call.transformTo(query2);
}
 
Example 8
Source File: DruidRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void onMatch(RelOptRuleCall call) {
  final Aggregate aggregate = call.rel(0);
  final DruidQuery query = call.rel(1);
  final RelNode topDruidNode = query.getTopNode();
  final Project project = topDruidNode instanceof Project ? (Project) topDruidNode : null;
  if (!DruidQuery.isValidSignature(query.signature() + 'a')) {
    return;
  }

  if (aggregate.getGroupSets().size() != 1) {
    return;
  }
  if (DruidQuery
      .computeProjectGroupSet(project, aggregate.getGroupSet(), query.table.getRowType(), query)
      == null) {
    return;
  }
  final List<String> aggNames = Util
      .skip(aggregate.getRowType().getFieldNames(), aggregate.getGroupSet().cardinality());
  if (DruidQuery.computeDruidJsonAgg(aggregate.getAggCallList(), aggNames, project, query)
      == null) {
    return;
  }
  final RelNode newAggregate = aggregate
      .copy(aggregate.getTraitSet(), ImmutableList.of(query.getTopNode()));
  call.transformTo(DruidQuery.extendQuery(query, newAggregate));
}
 
Example 9
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 5 votes vote down vote up
/** Moves fields according to the permutation. */
public void permute(List<SqlNode> selectItems,
	List<Map.Entry<String, RelDataType>> fields) {
	if (trivial) {
		return;
	}

	final List<SqlNode> oldSelectItems = ImmutableList.copyOf(selectItems);
	selectItems.clear();
	final List<Map.Entry<String, RelDataType>> oldFields =
		ImmutableList.copyOf(fields);
	fields.clear();
	for (ImmutableIntList source : sources) {
		final int p0 = source.get(0);
		Map.Entry<String, RelDataType> field = oldFields.get(p0);
		final String name = field.getKey();
		RelDataType type = field.getValue();
		SqlNode selectItem = oldSelectItems.get(p0);
		for (int p1 : Util.skip(source)) {
			final Map.Entry<String, RelDataType> field1 = oldFields.get(p1);
			final SqlNode selectItem1 = oldSelectItems.get(p1);
			final RelDataType type1 = field1.getValue();
			// output is nullable only if both inputs are
			final boolean nullable = type.isNullable() && type1.isNullable();
			final RelDataType type2 =
				SqlTypeUtil.leastRestrictiveForComparison(typeFactory, type,
					type1);
			selectItem =
				SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO,
					SqlStdOperatorTable.COALESCE.createCall(SqlParserPos.ZERO,
						maybeCast(selectItem, type, type2),
						maybeCast(selectItem1, type1, type2)),
					new SqlIdentifier(name, SqlParserPos.ZERO));
			type = typeFactory.createTypeWithNullability(type2, nullable);
		}
		fields.add(Pair.of(name, type));
		selectItems.add(selectItem);
	}
}
 
Example 10
Source File: SqlValidatorImpl.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/** Moves fields according to the permutation. */
public void permute(List<SqlNode> selectItems,
	List<Map.Entry<String, RelDataType>> fields) {
	if (trivial) {
		return;
	}

	final List<SqlNode> oldSelectItems = ImmutableList.copyOf(selectItems);
	selectItems.clear();
	final List<Map.Entry<String, RelDataType>> oldFields =
		ImmutableList.copyOf(fields);
	fields.clear();
	for (ImmutableIntList source : sources) {
		final int p0 = source.get(0);
		Map.Entry<String, RelDataType> field = oldFields.get(p0);
		final String name = field.getKey();
		RelDataType type = field.getValue();
		SqlNode selectItem = oldSelectItems.get(p0);
		for (int p1 : Util.skip(source)) {
			final Map.Entry<String, RelDataType> field1 = oldFields.get(p1);
			final SqlNode selectItem1 = oldSelectItems.get(p1);
			final RelDataType type1 = field1.getValue();
			// output is nullable only if both inputs are
			final boolean nullable = type.isNullable() && type1.isNullable();
			final RelDataType type2 =
				SqlTypeUtil.leastRestrictiveForComparison(typeFactory, type,
					type1);
			selectItem =
				SqlStdOperatorTable.AS.createCall(SqlParserPos.ZERO,
					SqlStdOperatorTable.COALESCE.createCall(SqlParserPos.ZERO,
						maybeCast(selectItem, type, type2),
						maybeCast(selectItem1, type1, type2)),
					new SqlIdentifier(name, SqlParserPos.ZERO));
			type = typeFactory.createTypeWithNullability(type2, nullable);
		}
		fields.add(Pair.of(name, type));
		selectItems.add(selectItem);
	}
}
 
Example 11
Source File: AliasNamespace.java    From Bats with Apache License 2.0 5 votes vote down vote up
protected RelDataType validateImpl(RelDataType targetRowType) {
  final List<String> nameList = new ArrayList<>();
  final List<SqlNode> operands = call.getOperandList();
  final SqlValidatorNamespace childNs =
      validator.getNamespace(operands.get(0));
  final RelDataType rowType = childNs.getRowTypeSansSystemColumns();
  final List<SqlNode> columnNames = Util.skip(operands, 2);
  for (final SqlNode operand : columnNames) {
    String name = ((SqlIdentifier) operand).getSimple();
    if (nameList.contains(name)) {
      throw validator.newValidationError(operand,
          RESOURCE.aliasListDuplicate(name));
    }
    nameList.add(name);
  }
  if (nameList.size() != rowType.getFieldCount()) {
    // Position error over all column names
    final SqlNode node = operands.size() == 3
        ? operands.get(2)
        : new SqlNodeList(columnNames, SqlParserPos.sum(columnNames));
    throw validator.newValidationError(node,
        RESOURCE.aliasListDegree(rowType.getFieldCount(), getString(rowType),
            nameList.size()));
  }
  final List<RelDataType> typeList = new ArrayList<>();
  for (RelDataTypeField field : rowType.getFieldList()) {
    typeList.add(field.getType());
  }
  return validator.getTypeFactory().createStructType(
      typeList,
      nameList);
}
 
Example 12
Source File: DruidDateTimeUtils.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Nullable
protected static List<Range<Long>> leafToRanges(RexCall call, boolean withNot) {
  switch (call.getKind()) {
  case EQUALS:
  case LESS_THAN:
  case LESS_THAN_OR_EQUAL:
  case GREATER_THAN:
  case GREATER_THAN_OR_EQUAL: {
    final Long value;
    SqlKind kind = call.getKind();
    if (call.getOperands().get(0) instanceof RexInputRef
        && literalValue(call.getOperands().get(1)) != null) {
      value = literalValue(call.getOperands().get(1));
    } else if (call.getOperands().get(1) instanceof RexInputRef
        && literalValue(call.getOperands().get(0)) != null) {
      value = literalValue(call.getOperands().get(0));
      kind = kind.reverse();
    } else {
      return null;
    }
    switch (kind) {
    case LESS_THAN:
      return ImmutableList.of(withNot ? Range.atLeast(value) : Range.lessThan(value));
    case LESS_THAN_OR_EQUAL:
      return ImmutableList.of(withNot ? Range.greaterThan(value) : Range.atMost(value));
    case GREATER_THAN:
      return ImmutableList.of(withNot ? Range.atMost(value) : Range.greaterThan(value));
    case GREATER_THAN_OR_EQUAL:
      return ImmutableList.of(withNot ? Range.lessThan(value) : Range.atLeast(value));
    default:
      if (!withNot) {
        return ImmutableList.of(Range.closed(value, value));
      }
      return ImmutableList.of(Range.lessThan(value), Range.greaterThan(value));
    }
  }
  case BETWEEN: {
    final Long value1;
    final Long value2;
    if (literalValue(call.getOperands().get(2)) != null
        && literalValue(call.getOperands().get(3)) != null) {
      value1 = literalValue(call.getOperands().get(2));
      value2 = literalValue(call.getOperands().get(3));
    } else {
      return null;
    }

    boolean inverted = value1.compareTo(value2) > 0;
    if (!withNot) {
      return ImmutableList.of(
          inverted ? Range.closed(value2, value1) : Range.closed(value1, value2));
    }
    return ImmutableList.of(Range.lessThan(inverted ? value2 : value1),
        Range.greaterThan(inverted ? value1 : value2));
  }
  case IN: {
    ImmutableList.Builder<Range<Long>> ranges =
        ImmutableList.builder();
    for (RexNode operand : Util.skip(call.operands)) {
      final Long element = literalValue(operand);
      if (element == null) {
        return null;
      }
      if (withNot) {
        ranges.add(Range.lessThan(element));
        ranges.add(Range.greaterThan(element));
      } else {
        ranges.add(Range.closed(element, element));
      }
    }
    return ranges.build();
  }
  default:
    return null;
  }
}
 
Example 13
Source File: RelOptUtil.java    From Bats with Apache License 2.0 4 votes vote down vote up
/**
 * Pushes down parts of a join condition.
 *
 * <p>For example, given
 * "emp JOIN dept ON emp.deptno + 1 = dept.deptno", adds a project above
 * "emp" that computes the expression
 * "emp.deptno + 1". The resulting join condition is a simple combination
 * of AND, equals, and input fields.
 */
private static RexNode pushDownEqualJoinConditions(RexNode node, int leftCount, int rightCount,
        List<RexNode> extraLeftExprs, List<RexNode> extraRightExprs) {
    switch (node.getKind()) {
    case AND:
    case EQUALS:
        final RexCall call = (RexCall) node;
        final List<RexNode> list = new ArrayList<>();
        List<RexNode> operands = Lists.newArrayList(call.getOperands());
        for (int i = 0; i < operands.size(); i++) {
            RexNode operand = operands.get(i);
            final int left2 = leftCount + extraLeftExprs.size();
            final int right2 = rightCount + extraRightExprs.size();
            final RexNode e = pushDownEqualJoinConditions(operand, leftCount, rightCount, extraLeftExprs,
                    extraRightExprs);
            final List<RexNode> remainingOperands = Util.skip(operands, i + 1);
            final int left3 = leftCount + extraLeftExprs.size();
            fix(remainingOperands, left2, left3);
            fix(list, left2, left3);
            list.add(e);
        }
        if (!list.equals(call.getOperands())) {
            return call.clone(call.getType(), list);
        }
        return call;
    case OR:
    case INPUT_REF:
    case LITERAL:
    case NOT:
        return node;
    default:
        final ImmutableBitSet bits = RelOptUtil.InputFinder.bits(node);
        final int mid = leftCount + extraLeftExprs.size();
        switch (Side.of(bits, mid)) {
        case LEFT:
            fix(extraRightExprs, mid, mid + 1);
            extraLeftExprs.add(node);
            return RexBuilder.getRexFactory().makeInputRef(mid, node.getType());
        case RIGHT:
            final int index2 = mid + rightCount + extraRightExprs.size();
            extraRightExprs.add(node);
            return RexBuilder.getRexFactory().makeInputRef(index2, node.getType());
        case BOTH:
        case EMPTY:
        default:
            return node;
        }
    }
}
 
Example 14
Source File: SqlTypeExplicitPrecedenceList.java    From Bats with Apache License 2.0 4 votes vote down vote up
private static SqlTypeExplicitPrecedenceList numeric(SqlTypeName typeName) {
  int i = getListPosition(typeName, COMPACT_NUMERIC_TYPES);
  return new SqlTypeExplicitPrecedenceList(
      Util.skip(COMPACT_NUMERIC_TYPES, i));
}
 
Example 15
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override Expression implementSafe(RexToLixTranslator translator,
    RexCall call, List<Expression> argValueList) {
  final Expression expression;
  final List<Expression> newOperands = new ArrayList<>();
  newOperands.add(argValueList.get(0));
  newOperands.add(argValueList.get(1));
  List<Expression> leftExprs = Util.skip(argValueList, 2);
  // Default value for JSON_VALUE behaviors.
  Expression emptyBehavior = Expressions.constant(SqlJsonValueEmptyOrErrorBehavior.NULL);
  Expression defaultValueOnEmpty = Expressions.constant(null);
  Expression errorBehavior = Expressions.constant(SqlJsonValueEmptyOrErrorBehavior.NULL);
  Expression defaultValueOnError = Expressions.constant(null);
  // Patched up with user defines.
  if (leftExprs.size() > 0) {
    for (int i = 0; i < leftExprs.size(); i++) {
      Expression expr = leftExprs.get(i);
      final Object exprVal = translator.getLiteralValue(expr);
      if (exprVal != null) {
        int defaultSymbolIdx = i - 2;
        if (exprVal == SqlJsonEmptyOrError.EMPTY) {
          if (defaultSymbolIdx >= 0
              && translator.getLiteralValue(leftExprs.get(defaultSymbolIdx))
                  == SqlJsonValueEmptyOrErrorBehavior.DEFAULT) {
            defaultValueOnEmpty = leftExprs.get(i - 1);
            emptyBehavior = leftExprs.get(defaultSymbolIdx);
          } else {
            emptyBehavior = leftExprs.get(i - 1);
          }
        } else if (exprVal == SqlJsonEmptyOrError.ERROR) {
          if (defaultSymbolIdx >= 0
              && translator.getLiteralValue(leftExprs.get(defaultSymbolIdx))
                  == SqlJsonValueEmptyOrErrorBehavior.DEFAULT) {
            defaultValueOnError = leftExprs.get(i - 1);
            errorBehavior = leftExprs.get(defaultSymbolIdx);
          } else {
            errorBehavior = leftExprs.get(i - 1);
          }
        }
      }
    }
  }
  newOperands.add(emptyBehavior);
  newOperands.add(defaultValueOnEmpty);
  newOperands.add(errorBehavior);
  newOperands.add(defaultValueOnError);
  Class clazz = method.getDeclaringClass();
  expression = EnumUtils.call(clazz, method.getName(), newOperands);

  final Type returnType =
      translator.typeFactory.getJavaClass(call.getType());
  return EnumUtils.convert(expression, returnType);
}
 
Example 16
Source File: EmptyScope.java    From Bats with Apache License 2.0 4 votes vote down vote up
private void resolve_(final CalciteSchema rootSchema, List<String> names,
    List<String> schemaNames, SqlNameMatcher nameMatcher, Path path,
    Resolved resolved) {
  final List<String> concat = ImmutableList.<String>builder()
      .addAll(schemaNames).addAll(names).build();
  CalciteSchema schema = rootSchema;
  SqlValidatorNamespace namespace = null;
  List<String> remainingNames = concat;
  for (String schemaName : concat) {
    if (schema == rootSchema
        && nameMatcher.matches(schemaName, schema.name)) {
      remainingNames = Util.skip(remainingNames);
      continue;
    }
    final CalciteSchema subSchema =
        schema.getSubSchema(schemaName, nameMatcher.isCaseSensitive());
    if (subSchema != null) {
      path = path.plus(null, -1, subSchema.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      schema = subSchema;
      namespace = new SchemaNamespace(validator,
          ImmutableList.copyOf(path.stepNames()));
      continue;
    }
    CalciteSchema.TableEntry entry =
        schema.getTable(schemaName, nameMatcher.isCaseSensitive());
    if (entry == null) {
      entry = schema.getTableBasedOnNullaryFunction(schemaName,
          nameMatcher.isCaseSensitive());
    }
    if (entry != null) {
      path = path.plus(null, -1, entry.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      final Table table = entry.getTable();
      SqlValidatorTable table2 = null;
      if (table instanceof Wrapper) {
        table2 = ((Wrapper) table).unwrap(PreparingTable.class);
      }
      if (table2 == null) {
        final RelOptSchema relOptSchema =
            validator.catalogReader.unwrap(RelOptSchema.class);
        final RelDataType rowType = table.getRowType(validator.typeFactory);
        table2 = RelOptTableImpl.create(relOptSchema, rowType, entry, null);
      }
      namespace = new TableNamespace(validator, table2);
      resolved.found(namespace, false, null, path, remainingNames);
      return;
    }
    // neither sub-schema nor table
    if (namespace != null
        && !remainingNames.equals(names)) {
      resolved.found(namespace, false, null, path, remainingNames);
    }
    return;
  }
}
 
Example 17
Source File: SqlQualified.java    From calcite with Apache License 2.0 4 votes vote down vote up
public final List<String> suffix() {
  return Util.skip(identifier.names, prefixLength);
}
 
Example 18
Source File: EmptyScope.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void resolve_(final CalciteSchema rootSchema, List<String> names,
    List<String> schemaNames, SqlNameMatcher nameMatcher, Path path,
    Resolved resolved) {
  final List<String> concat = ImmutableList.<String>builder()
      .addAll(schemaNames).addAll(names).build();
  CalciteSchema schema = rootSchema;
  SqlValidatorNamespace namespace = null;
  List<String> remainingNames = concat;
  for (String schemaName : concat) {
    if (schema == rootSchema
        && nameMatcher.matches(schemaName, schema.name)) {
      remainingNames = Util.skip(remainingNames);
      continue;
    }
    final CalciteSchema subSchema =
        schema.getSubSchema(schemaName, nameMatcher.isCaseSensitive());
    if (subSchema != null) {
      path = path.plus(null, -1, subSchema.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      schema = subSchema;
      namespace = new SchemaNamespace(validator,
          ImmutableList.copyOf(path.stepNames()));
      continue;
    }
    CalciteSchema.TableEntry entry =
        schema.getTable(schemaName, nameMatcher.isCaseSensitive());
    if (entry == null) {
      entry = schema.getTableBasedOnNullaryFunction(schemaName,
          nameMatcher.isCaseSensitive());
    }
    if (entry != null) {
      path = path.plus(null, -1, entry.name, StructKind.NONE);
      remainingNames = Util.skip(remainingNames);
      final Table table = entry.getTable();
      SqlValidatorTable table2 = null;
      if (table instanceof Wrapper) {
        table2 = ((Wrapper) table).unwrap(Prepare.PreparingTable.class);
      }
      if (table2 == null) {
        final RelOptSchema relOptSchema =
            validator.catalogReader.unwrap(RelOptSchema.class);
        final RelDataType rowType = table.getRowType(validator.typeFactory);
        table2 = RelOptTableImpl.create(relOptSchema, rowType, entry, null);
      }
      namespace = new TableNamespace(validator, table2);
      resolved.found(namespace, false, null, path, remainingNames);
      return;
    }
    // neither sub-schema nor table
    if (namespace != null
        && !remainingNames.equals(names)) {
      resolved.found(namespace, false, null, path, remainingNames);
    }
    return;
  }
}
 
Example 19
Source File: SqlQualified.java    From Bats with Apache License 2.0 4 votes vote down vote up
public final List<String> suffix() {
  return Util.skip(identifier.names, prefixLength);
}
 
Example 20
Source File: SqlTypeExplicitPrecedenceList.java    From calcite with Apache License 2.0 4 votes vote down vote up
private static SqlTypeExplicitPrecedenceList numeric(SqlTypeName typeName) {
  int i = getListPosition(typeName, NUMERIC_TYPES);
  return new SqlTypeExplicitPrecedenceList(
      Util.skip(NUMERIC_TYPES, i));
}