Java Code Examples for org.apache.calcite.plan.RelOptTable#unwrap()

The following examples show how to use org.apache.calcite.plan.RelOptTable#unwrap() . 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: StreamRules.java    From Bats with Apache License 2.0 6 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Delta delta = call.rel(0);
  final TableScan scan = call.rel(1);
  final RelOptCluster cluster = delta.getCluster();
  final RelOptTable relOptTable = scan.getTable();
  final StreamableTable streamableTable =
      relOptTable.unwrap(StreamableTable.class);
  if (streamableTable != null) {
    final Table table1 = streamableTable.stream();
    final RelOptTable relOptTable2 =
        RelOptTableImpl.create(relOptTable.getRelOptSchema(),
            relOptTable.getRowType(), table1,
            ImmutableList.<String>builder()
                .addAll(relOptTable.getQualifiedName())
                .add("(STREAM)").build());
    final LogicalTableScan newScan =
        LogicalTableScan.create(cluster, relOptTable2);
    call.transformTo(newScan);
  }
}
 
Example 2
Source File: StreamRules.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Delta delta = call.rel(0);
  final TableScan scan = call.rel(1);
  final RelOptCluster cluster = delta.getCluster();
  final RelOptTable relOptTable = scan.getTable();
  final StreamableTable streamableTable =
      relOptTable.unwrap(StreamableTable.class);
  if (streamableTable != null) {
    final Table table1 = streamableTable.stream();
    final RelOptTable relOptTable2 =
        RelOptTableImpl.create(relOptTable.getRelOptSchema(),
            relOptTable.getRowType(), table1,
            ImmutableList.<String>builder()
                .addAll(relOptTable.getQualifiedName())
                .add("(STREAM)").build());
    final LogicalTableScan newScan =
        LogicalTableScan.create(cluster, relOptTable2, scan.getHints());
    call.transformTo(newScan);
  }
}
 
Example 3
Source File: SqlValidatorUtil.java    From Bats with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve a target column name in the target table.
 *
 * @return the target field or null if the name cannot be resolved
 * @param rowType the target row type
 * @param id      the target column identifier
 * @param table   the target table or null if it is not a RelOptTable instance
 */
public static RelDataTypeField getTargetField(
    RelDataType rowType, RelDataTypeFactory typeFactory,
    SqlIdentifier id, SqlValidatorCatalogReader catalogReader,
    RelOptTable table) {
  final Table t = table == null ? null : table.unwrap(Table.class);
  if (!(t instanceof CustomColumnResolvingTable)) {
    final SqlNameMatcher nameMatcher = catalogReader.nameMatcher();
    return nameMatcher.field(rowType, id.getSimple());
  }

  final List<Pair<RelDataTypeField, List<String>>> entries =
      ((CustomColumnResolvingTable) t).resolveColumn(
          rowType, typeFactory, id.names);
  switch (entries.size()) {
  case 1:
    if (!entries.get(0).getValue().isEmpty()) {
      return null;
    }
    return entries.get(0).getKey();
  default:
    return null;
  }
}
 
Example 4
Source File: DirPrunedEnumerableTableScan.java    From Bats with Apache License 2.0 6 votes vote down vote up
/** Creates an DirPrunedEnumerableTableScan. */
public static EnumerableTableScan create(RelOptCluster cluster,
    RelOptTable relOptTable, String digestFromSelection) {
  final Table table = relOptTable.unwrap(Table.class);
  Class elementType = EnumerableTableScan.deduceElementType(table);
  final RelTraitSet traitSet =
      cluster.traitSetOf(EnumerableConvention.INSTANCE)
          .replaceIfs(RelCollationTraitDef.INSTANCE,
              () -> {
                if (table != null) {
                  return table.getStatistic().getCollations();
                }
                return ImmutableList.of();
              });
  return new DirPrunedEnumerableTableScan(cluster, traitSet, relOptTable, elementType, digestFromSelection);
}
 
Example 5
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 6 votes vote down vote up
public void validateUpdate(SqlUpdate call) {
	final SqlValidatorNamespace targetNamespace = getNamespace(call);
	validateNamespace(targetNamespace, unknownType);
	final RelOptTable relOptTable = SqlValidatorUtil.getRelOptTable(
		targetNamespace, catalogReader.unwrap(Prepare.CatalogReader.class), null, null);
	final SqlValidatorTable table = relOptTable == null
		? targetNamespace.getTable()
		: relOptTable.unwrap(SqlValidatorTable.class);

	final RelDataType targetRowType =
		createTargetRowType(
			table,
			call.getTargetColumnList(),
			true);

	final SqlSelect select = call.getSourceSelect();
	validateSelect(select, targetRowType);

	final RelDataType sourceRowType = getNamespace(call).getRowType();
	checkTypeAssignment(sourceRowType, targetRowType, call);

	checkConstraint(table, call, targetRowType);

	validateAccess(call.getTargetTable(), table, SqlAccessEnum.UPDATE);
}
 
Example 6
Source File: QuerySqlStatisticProvider.java    From calcite with Apache License 2.0 5 votes vote down vote up
public boolean isKey(RelOptTable table, List<Integer> columns) {
  final SqlDialect dialect = table.unwrap(SqlDialect.class);
  final DataSource dataSource = table.unwrap(DataSource.class);
  return withBuilder(
      (cluster, relOptSchema, relBuilder) -> {
        // The collection of columns ['DEPTNO'] is a key for 'EMP' if the
        // following query returns no rows:
        //
        //   SELECT 1
        //   FROM `EMP`
        //   GROUP BY `DEPTNO`
        //   HAVING COUNT(*) > 1
        //
        final RelOptTable.ToRelContext toRelContext =
            ViewExpanders.simpleContext(cluster);
        relBuilder.push(table.toRel(toRelContext))
            .aggregate(relBuilder.groupKey(relBuilder.fields(columns)),
                relBuilder.count())
            .filter(
                relBuilder.call(SqlStdOperatorTable.GREATER_THAN,
                    Util.last(relBuilder.fields()), relBuilder.literal(1)));
        final String sql = toSql(relBuilder.build(), dialect);

        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
          return !resultSet.next();
        } catch (SQLException e) {
          throw handle(e, sql);
        }
      });
}
 
Example 7
Source File: LogicalTableScan.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a LogicalTableScan.
 *
 * @param cluster     Cluster
 * @param relOptTable Table
 * @param hints       The hints
 */
public static LogicalTableScan create(RelOptCluster cluster,
    final RelOptTable relOptTable, List<RelHint> hints) {
  final Table table = relOptTable.unwrap(Table.class);
  final RelTraitSet traitSet =
      cluster.traitSetOf(Convention.NONE)
          .replaceIfs(RelCollationTraitDef.INSTANCE, () -> {
            if (table != null) {
              return table.getStatistic().getCollations();
            }
            return ImmutableList.of();
          });
  return new LogicalTableScan(cluster, traitSet, hints, relOptTable);
}
 
Example 8
Source File: StreamRules.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Delta delta = call.rel(0);
  final TableScan scan = call.rel(1);
  final RelOptTable relOptTable = scan.getTable();
  final StreamableTable streamableTable =
      relOptTable.unwrap(StreamableTable.class);
  final RelBuilder builder = call.builder();
  if (streamableTable == null) {
    call.transformTo(builder.values(delta.getRowType()).build());
  }
}
 
Example 9
Source File: EnumerableTableScanRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public RelNode convert(RelNode rel) {
  LogicalTableScan scan = (LogicalTableScan) rel;
  final RelOptTable relOptTable = scan.getTable();
  final Table table = relOptTable.unwrap(Table.class);
  // The QueryableTable can only be implemented as ENUMERABLE convention,
  // but some test QueryableTables do not really implement the expressions,
  // just skips the QueryableTable#getExpression invocation and returns early.
  if (table instanceof QueryableTable || relOptTable.getExpression(Object.class) != null) {
    return EnumerableTableScan.create(scan.getCluster(), relOptTable);
  }

  return null;
}
 
Example 10
Source File: FilterTableScanRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static boolean test(TableScan scan) {
  // We can only push filters into a FilterableTable or
  // ProjectableFilterableTable.
  final RelOptTable table = scan.getTable();
  return table.unwrap(FilterableTable.class) != null
      || table.unwrap(ProjectableFilterableTable.class) != null;
}
 
Example 11
Source File: QuerySqlStatisticProvider.java    From calcite with Apache License 2.0 5 votes vote down vote up
public double tableCardinality(RelOptTable table) {
  final SqlDialect dialect = table.unwrap(SqlDialect.class);
  final DataSource dataSource = table.unwrap(DataSource.class);
  return withBuilder(
      (cluster, relOptSchema, relBuilder) -> {
        // Generate:
        //   SELECT COUNT(*) FROM `EMP`
        relBuilder.push(table.toRel(ViewExpanders.simpleContext(cluster)))
            .aggregate(relBuilder.groupKey(), relBuilder.count());

        final String sql = toSql(relBuilder.build(), dialect);
        try (Connection connection = dataSource.getConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {
          if (!resultSet.next()) {
            throw new AssertionError("expected exactly 1 row: " + sql);
          }
          final double cardinality = resultSet.getDouble(1);
          if (resultSet.next()) {
            throw new AssertionError("expected exactly 1 row: " + sql);
          }
          return cardinality;
        } catch (SQLException e) {
          throw handle(e, sql);
        }
      });
}
 
Example 12
Source File: Utilities.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Gets {@link DrillTable}, either wrapped in RelOptTable, or DrillTranslatableTable.
 *
 * @param table table instance
 * @return Drill table
 */
public static DrillTable getDrillTable(RelOptTable table) {
  DrillTable drillTable = table.unwrap(DrillTable.class);
  if (drillTable == null) {
    drillTable = table.unwrap(DrillTranslatableTable.class).getDrillTable();
  }
  return drillTable;
}
 
Example 13
Source File: TableScanNode.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a TableScanNode.
 *
 * <p>Tries various table SPIs, and negotiates with the table which filters
 * and projects it can implement. Adds to the Enumerable implementations of
 * any filters and projects that cannot be implemented by the table. */
static TableScanNode create(Compiler compiler, TableScan rel,
    ImmutableList<RexNode> filters, ImmutableIntList projects) {
  final RelOptTable relOptTable = rel.getTable();
  final ProjectableFilterableTable pfTable =
      relOptTable.unwrap(ProjectableFilterableTable.class);
  if (pfTable != null) {
    return createProjectableFilterable(compiler, rel, filters, projects,
        pfTable);
  }
  final FilterableTable filterableTable =
      relOptTable.unwrap(FilterableTable.class);
  if (filterableTable != null) {
    return createFilterable(compiler, rel, filters, projects,
        filterableTable);
  }
  final ScannableTable scannableTable =
      relOptTable.unwrap(ScannableTable.class);
  if (scannableTable != null) {
    return createScannable(compiler, rel, filters, projects,
        scannableTable);
  }
  //noinspection unchecked
  final Enumerable<Row> enumerable = relOptTable.unwrap(Enumerable.class);
  if (enumerable != null) {
    return createEnumerable(compiler, rel, enumerable, null, filters,
        projects);
  }
  final QueryableTable queryableTable =
      relOptTable.unwrap(QueryableTable.class);
  if (queryableTable != null) {
    return createQueryable(compiler, rel, filters, projects,
        queryableTable);
  }
  throw new AssertionError("cannot convert table " + relOptTable
      + " to enumerable");
}
 
Example 14
Source File: LogicalTableScan.java    From Bats with Apache License 2.0 5 votes vote down vote up
/** Creates a LogicalTableScan.
 *
 * @param cluster Cluster
 * @param relOptTable Table
 */
public static LogicalTableScan create(RelOptCluster cluster,
    final RelOptTable relOptTable) {
  final Table table = relOptTable.unwrap(Table.class);
  final RelTraitSet traitSet =
      cluster.traitSetOf(Convention.NONE)
          .replaceIfs(RelCollationTraitDef.INSTANCE, () -> {
            if (table != null) {
              return table.getStatistic().getCollations();
            }
            return ImmutableList.of();
          });
  return new LogicalTableScan(cluster, traitSet, relOptTable);
}
 
Example 15
Source File: StreamRules.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override public void onMatch(RelOptRuleCall call) {
  final Delta delta = call.rel(0);
  final TableScan scan = call.rel(1);
  final RelOptTable relOptTable = scan.getTable();
  final StreamableTable streamableTable =
      relOptTable.unwrap(StreamableTable.class);
  final RelBuilder builder = call.builder();
  if (streamableTable == null) {
    call.transformTo(builder.values(delta.getRowType()).build());
  }
}
 
Example 16
Source File: Bindables.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static boolean canHandle(RelOptTable table) {
  return table.unwrap(ScannableTable.class) != null
      || table.unwrap(FilterableTable.class) != null
      || table.unwrap(ProjectableFilterableTable.class) != null;
}
 
Example 17
Source File: ProjectTableScanRule.java    From calcite with Apache License 2.0 4 votes vote down vote up
protected static boolean test(TableScan scan) {
  // We can only push projects into a ProjectableFilterableTable.
  final RelOptTable table = scan.getTable();
  return table.unwrap(ProjectableFilterableTable.class) != null;
}
 
Example 18
Source File: ConvertCountDistinctToHll.java    From dremio-oss with Apache License 2.0 4 votes vote down vote up
@Override
public void onMatch(RelOptRuleCall call) {
  final LogicalAggregate agg = call.rel(0);
  final RelNode input = agg.getInput();

  boolean distinctReplaced = false;
  List<AggregateCall> calls = new ArrayList<>();

  RelMetadataQuery query = null;

  final Boolean[] memo = new Boolean[agg.getInput().getRowType().getFieldCount()];
  for (AggregateCall c : agg.getAggCallList()) {
    final boolean candidate = c.isDistinct() && c.getArgList().size() == 1 && "COUNT".equals(c.getAggregation().getName());

    if(!candidate) {
      calls.add(c);
      continue;
    }

    final int inputOrdinal = c.getArgList().get(0);
    boolean allowed = false;
    if(memo[inputOrdinal] != null) {
      allowed = memo[inputOrdinal];
    } else {
      if(query == null) {
        query = agg.getCluster().getMetadataQuery();
      }

      Set<RelColumnOrigin> origins = query.getColumnOrigins(input, inputOrdinal);

      // see if any column origin allowed a transformation.
      for(RelColumnOrigin o : origins) {
        RelOptTable table = o.getOriginTable();
        NamespaceTable namespaceTable = table.unwrap(NamespaceTable.class);
        if(namespaceTable == null) {
          // unable to decide, no way to transform.
          return;
        }

        if(namespaceTable.isApproximateStatsAllowed()) {
          allowed = true;
        }
      }

      memo[inputOrdinal] = allowed;

    }


    if(allowed) {
      calls.add(AggregateCall.create(HyperLogLog.NDV, false, c.getArgList(), -1, c.getType(), c.getName()));
      distinctReplaced = true;
    } else {
      calls.add(c);
    }

  }

  if(!distinctReplaced) {
    return;
  }

  final RelBuilder builder = relBuilderFactory.create(agg.getCluster(), null);
  builder.push(agg.getInput());
  builder.aggregate(builder.groupKey(agg.getGroupSet().toArray()), calls);
  call.transformTo(builder.build());
}
 
Example 19
Source File: SqlValidatorImpl.java    From flink with Apache License 2.0 4 votes vote down vote up
public void validateInsert(SqlInsert insert) {
	final SqlValidatorNamespace targetNamespace = getNamespace(insert);
	validateNamespace(targetNamespace, unknownType);
	final RelOptTable relOptTable = SqlValidatorUtil.getRelOptTable(
		targetNamespace, catalogReader.unwrap(Prepare.CatalogReader.class), null, null);
	final SqlValidatorTable table = relOptTable == null
		? targetNamespace.getTable()
		: relOptTable.unwrap(SqlValidatorTable.class);

	// INSERT has an optional column name list.  If present then
	// reduce the rowtype to the columns specified.  If not present
	// then the entire target rowtype is used.
	final RelDataType targetRowType =
		createTargetRowType(
			table,
			insert.getTargetColumnList(),
			false);

	final SqlNode source = insert.getSource();
	if (source instanceof SqlSelect) {
		final SqlSelect sqlSelect = (SqlSelect) source;
		validateSelect(sqlSelect, targetRowType);
	} else {
		final SqlValidatorScope scope = scopes.get(source);
		validateQuery(source, scope, targetRowType);
	}

	// REVIEW jvs 4-Dec-2008: In FRG-365, this namespace row type is
	// discarding the type inferred by inferUnknownTypes (which was invoked
	// from validateSelect above).  It would be better if that information
	// were used here so that we never saw any untyped nulls during
	// checkTypeAssignment.
	final RelDataType sourceRowType = getNamespace(source).getRowType();
	final RelDataType logicalTargetRowType =
		getLogicalTargetRowType(targetRowType, insert);
	setValidatedNodeType(insert, logicalTargetRowType);
	final RelDataType logicalSourceRowType =
		getLogicalSourceRowType(sourceRowType, insert);

	checkFieldCount(insert.getTargetTable(), table, source,
		logicalSourceRowType, logicalTargetRowType);

	checkTypeAssignment(logicalSourceRowType, logicalTargetRowType, insert);

	checkConstraint(table, source, logicalTargetRowType);

	validateAccess(insert.getTargetTable(), table, SqlAccessEnum.INSERT);
}
 
Example 20
Source File: FilterTableScanRule.java    From Bats with Apache License 2.0 4 votes vote down vote up
public static boolean test(TableScan scan) {
  // We can only push filters into a FilterableTable or
  // ProjectableFilterableTable.
  final RelOptTable table = scan.getTable();
  return table.unwrap(FilterableTable.class) != null;
}