Search in sources :

Example 1 with FlinkContext

use of org.apache.flink.table.planner.calcite.FlinkContext in project flink by apache.

the class PushPartitionIntoTableSourceScanRule method onMatch.

@Override
public void onMatch(RelOptRuleCall call) {
    Filter filter = call.rel(0);
    LogicalTableScan scan = call.rel(1);
    TableSourceTable tableSourceTable = scan.getTable().unwrap(TableSourceTable.class);
    RelDataType inputFieldTypes = filter.getInput().getRowType();
    List<String> inputFieldNames = inputFieldTypes.getFieldNames();
    List<String> partitionFieldNames = tableSourceTable.contextResolvedTable().<ResolvedCatalogTable>getResolvedTable().getPartitionKeys();
    // extract partition predicates
    RelBuilder relBuilder = call.builder();
    RexBuilder rexBuilder = relBuilder.getRexBuilder();
    Tuple2<Seq<RexNode>, Seq<RexNode>> allPredicates = RexNodeExtractor.extractPartitionPredicateList(filter.getCondition(), FlinkRelOptUtil.getMaxCnfNodeCount(scan), inputFieldNames.toArray(new String[0]), rexBuilder, partitionFieldNames.toArray(new String[0]));
    RexNode partitionPredicate = RexUtil.composeConjunction(rexBuilder, JavaConversions.seqAsJavaList(allPredicates._1));
    if (partitionPredicate.isAlwaysTrue()) {
        return;
    }
    // build pruner
    LogicalType[] partitionFieldTypes = partitionFieldNames.stream().map(name -> {
        int index = inputFieldNames.indexOf(name);
        if (index < 0) {
            throw new TableException(String.format("Partitioned key '%s' isn't found in input columns. " + "Validator should have checked that.", name));
        }
        return inputFieldTypes.getFieldList().get(index).getType();
    }).map(FlinkTypeFactory::toLogicalType).toArray(LogicalType[]::new);
    RexNode finalPartitionPredicate = adjustPartitionPredicate(inputFieldNames, partitionFieldNames, partitionPredicate);
    FlinkContext context = ShortcutUtils.unwrapContext(scan);
    Function<List<Map<String, String>>, List<Map<String, String>>> defaultPruner = partitions -> PartitionPruner.prunePartitions(context.getTableConfig(), partitionFieldNames.toArray(new String[0]), partitionFieldTypes, partitions, finalPartitionPredicate);
    // prune partitions
    List<Map<String, String>> remainingPartitions = readPartitionsAndPrune(rexBuilder, context, tableSourceTable, defaultPruner, allPredicates._1(), inputFieldNames);
    // apply push down
    DynamicTableSource dynamicTableSource = tableSourceTable.tableSource().copy();
    PartitionPushDownSpec partitionPushDownSpec = new PartitionPushDownSpec(remainingPartitions);
    partitionPushDownSpec.apply(dynamicTableSource, SourceAbilityContext.from(scan));
    // build new statistic
    TableStats newTableStat = null;
    if (tableSourceTable.contextResolvedTable().isPermanent()) {
        ObjectIdentifier identifier = tableSourceTable.contextResolvedTable().getIdentifier();
        ObjectPath tablePath = identifier.toObjectPath();
        Catalog catalog = tableSourceTable.contextResolvedTable().getCatalog().get();
        for (Map<String, String> partition : remainingPartitions) {
            Optional<TableStats> partitionStats = getPartitionStats(catalog, tablePath, partition);
            if (!partitionStats.isPresent()) {
                // clear all information before
                newTableStat = null;
                break;
            } else {
                newTableStat = newTableStat == null ? partitionStats.get() : newTableStat.merge(partitionStats.get());
            }
        }
    }
    FlinkStatistic newStatistic = FlinkStatistic.builder().statistic(tableSourceTable.getStatistic()).tableStats(newTableStat).build();
    TableSourceTable newTableSourceTable = tableSourceTable.copy(dynamicTableSource, newStatistic, new SourceAbilitySpec[] { partitionPushDownSpec });
    LogicalTableScan newScan = LogicalTableScan.create(scan.getCluster(), newTableSourceTable, scan.getHints());
    // transform to new node
    RexNode nonPartitionPredicate = RexUtil.composeConjunction(rexBuilder, JavaConversions.seqAsJavaList(allPredicates._2()));
    if (nonPartitionPredicate.isAlwaysTrue()) {
        call.transformTo(newScan);
    } else {
        Filter newFilter = filter.copy(filter.getTraitSet(), newScan, nonPartitionPredicate);
        call.transformTo(newFilter);
    }
}
Also used : CatalogColumnStatistics(org.apache.flink.table.catalog.stats.CatalogColumnStatistics) Arrays(java.util.Arrays) SourceAbilityContext(org.apache.flink.table.planner.plan.abilities.source.SourceAbilityContext) PartitionNotExistException(org.apache.flink.table.catalog.exceptions.PartitionNotExistException) CatalogTable(org.apache.flink.table.catalog.CatalogTable) ShortcutUtils(org.apache.flink.table.planner.utils.ShortcutUtils) SupportsPartitionPushDown(org.apache.flink.table.connector.source.abilities.SupportsPartitionPushDown) FlinkTypeFactory(org.apache.flink.table.planner.calcite.FlinkTypeFactory) RexUtil(org.apache.calcite.rex.RexUtil) RexNode(org.apache.calcite.rex.RexNode) RelBuilder(org.apache.calcite.tools.RelBuilder) ResolvedExpression(org.apache.flink.table.expressions.ResolvedExpression) Map(java.util.Map) TableStats(org.apache.flink.table.plan.stats.TableStats) DynamicTableSource(org.apache.flink.table.connector.source.DynamicTableSource) PartitionPushDownSpec(org.apache.flink.table.planner.plan.abilities.source.PartitionPushDownSpec) TimeZone(java.util.TimeZone) Seq(scala.collection.Seq) FlinkContext(org.apache.flink.table.planner.calcite.FlinkContext) Tuple2(scala.Tuple2) Collectors(java.util.stream.Collectors) SourceAbilitySpec(org.apache.flink.table.planner.plan.abilities.source.SourceAbilitySpec) RexInputRef(org.apache.calcite.rex.RexInputRef) List(java.util.List) TableNotPartitionedException(org.apache.flink.table.catalog.exceptions.TableNotPartitionedException) LogicalType(org.apache.flink.table.types.logical.LogicalType) Optional(java.util.Optional) RexNodeToExpressionConverter(org.apache.flink.table.planner.plan.utils.RexNodeToExpressionConverter) LogicalTableScan(org.apache.calcite.rel.logical.LogicalTableScan) ObjectIdentifier(org.apache.flink.table.catalog.ObjectIdentifier) CatalogTableStatisticsConverter(org.apache.flink.table.planner.utils.CatalogTableStatisticsConverter) RexNodeExtractor(org.apache.flink.table.planner.plan.utils.RexNodeExtractor) Expression(org.apache.flink.table.expressions.Expression) Filter(org.apache.calcite.rel.core.Filter) ObjectPath(org.apache.flink.table.catalog.ObjectPath) Function(java.util.function.Function) ArrayList(java.util.ArrayList) CatalogTableStatistics(org.apache.flink.table.catalog.stats.CatalogTableStatistics) Catalog(org.apache.flink.table.catalog.Catalog) PartitionPruner(org.apache.flink.table.planner.plan.utils.PartitionPruner) ResolvedCatalogTable(org.apache.flink.table.catalog.ResolvedCatalogTable) RelDataType(org.apache.calcite.rel.type.RelDataType) JavaConversions(scala.collection.JavaConversions) TableNotExistException(org.apache.flink.table.catalog.exceptions.TableNotExistException) RexBuilder(org.apache.calcite.rex.RexBuilder) TableException(org.apache.flink.table.api.TableException) Option(scala.Option) FlinkRelOptUtil(org.apache.flink.table.planner.plan.utils.FlinkRelOptUtil) TableSourceTable(org.apache.flink.table.planner.plan.schema.TableSourceTable) RelOptRuleCall(org.apache.calcite.plan.RelOptRuleCall) CatalogPartitionSpec(org.apache.flink.table.catalog.CatalogPartitionSpec) RelOptRule(org.apache.calcite.plan.RelOptRule) FlinkStatistic(org.apache.flink.table.planner.plan.stats.FlinkStatistic) RexShuttle(org.apache.calcite.rex.RexShuttle) CatalogException(org.apache.flink.table.catalog.exceptions.CatalogException) ObjectPath(org.apache.flink.table.catalog.ObjectPath) LogicalType(org.apache.flink.table.types.logical.LogicalType) RelDataType(org.apache.calcite.rel.type.RelDataType) FlinkStatistic(org.apache.flink.table.planner.plan.stats.FlinkStatistic) RexBuilder(org.apache.calcite.rex.RexBuilder) List(java.util.List) ArrayList(java.util.ArrayList) TableSourceTable(org.apache.flink.table.planner.plan.schema.TableSourceTable) ObjectIdentifier(org.apache.flink.table.catalog.ObjectIdentifier) TableException(org.apache.flink.table.api.TableException) RelBuilder(org.apache.calcite.tools.RelBuilder) FlinkContext(org.apache.flink.table.planner.calcite.FlinkContext) TableStats(org.apache.flink.table.plan.stats.TableStats) LogicalTableScan(org.apache.calcite.rel.logical.LogicalTableScan) Catalog(org.apache.flink.table.catalog.Catalog) PartitionPushDownSpec(org.apache.flink.table.planner.plan.abilities.source.PartitionPushDownSpec) Filter(org.apache.calcite.rel.core.Filter) Map(java.util.Map) Seq(scala.collection.Seq) DynamicTableSource(org.apache.flink.table.connector.source.DynamicTableSource) RexNode(org.apache.calcite.rex.RexNode)

Example 2 with FlinkContext

use of org.apache.flink.table.planner.calcite.FlinkContext in project flink by apache.

the class BridgingSqlFunction method of.

/**
 * Creates an instance of a scalar or table function during translation.
 */
public static BridgingSqlFunction of(RelOptCluster cluster, ContextResolvedFunction resolvedFunction) {
    final FlinkContext context = ShortcutUtils.unwrapContext(cluster);
    final FlinkTypeFactory typeFactory = ShortcutUtils.unwrapTypeFactory(cluster);
    return of(context, typeFactory, resolvedFunction);
}
Also used : FlinkTypeFactory(org.apache.flink.table.planner.calcite.FlinkTypeFactory) FlinkContext(org.apache.flink.table.planner.calcite.FlinkContext)

Example 3 with FlinkContext

use of org.apache.flink.table.planner.calcite.FlinkContext in project flink by apache.

the class LookupKeySerdeTest method testLookupKey.

@Test
public void testLookupKey() throws IOException {
    TableConfig tableConfig = TableConfig.getDefault();
    ModuleManager moduleManager = new ModuleManager();
    CatalogManager catalogManager = CatalogManager.newBuilder().classLoader(Thread.currentThread().getContextClassLoader()).config(tableConfig.getConfiguration()).defaultCatalog("default_catalog", new GenericInMemoryCatalog("default_db")).build();
    FlinkContext flinkContext = new FlinkContextImpl(false, tableConfig, moduleManager, new FunctionCatalog(tableConfig, catalogManager, moduleManager), catalogManager, null);
    SerdeContext serdeCtx = new SerdeContext(null, flinkContext, Thread.currentThread().getContextClassLoader(), FlinkTypeFactory.INSTANCE(), FlinkSqlOperatorTable.instance());
    ObjectReader objectReader = JsonSerdeUtil.createObjectReader(serdeCtx);
    ObjectWriter objectWriter = JsonSerdeUtil.createObjectWriter(serdeCtx);
    LookupJoinUtil.LookupKey[] lookupKeys = new LookupJoinUtil.LookupKey[] { new LookupJoinUtil.ConstantLookupKey(new BigIntType(), new RexBuilder(FlinkTypeFactory.INSTANCE()).makeLiteral("a")), new LookupJoinUtil.FieldRefLookupKey(3) };
    for (LookupJoinUtil.LookupKey lookupKey : lookupKeys) {
        LookupJoinUtil.LookupKey result = objectReader.readValue(objectWriter.writeValueAsString(lookupKey), LookupJoinUtil.LookupKey.class);
        assertEquals(lookupKey, result);
    }
}
Also used : FunctionCatalog(org.apache.flink.table.catalog.FunctionCatalog) ObjectWriter(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectWriter) BigIntType(org.apache.flink.table.types.logical.BigIntType) ModuleManager(org.apache.flink.table.module.ModuleManager) FlinkContext(org.apache.flink.table.planner.calcite.FlinkContext) CatalogManager(org.apache.flink.table.catalog.CatalogManager) GenericInMemoryCatalog(org.apache.flink.table.catalog.GenericInMemoryCatalog) LookupJoinUtil(org.apache.flink.table.planner.plan.utils.LookupJoinUtil) FlinkContextImpl(org.apache.flink.table.planner.calcite.FlinkContextImpl) TableConfig(org.apache.flink.table.api.TableConfig) RexBuilder(org.apache.calcite.rex.RexBuilder) ObjectReader(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectReader) Test(org.junit.Test)

Example 4 with FlinkContext

use of org.apache.flink.table.planner.calcite.FlinkContext in project flink by apache.

the class CatalogSourceTable method toRel.

@Override
public RelNode toRel(ToRelContext toRelContext) {
    final RelOptCluster cluster = toRelContext.getCluster();
    final List<RelHint> hints = toRelContext.getTableHints();
    final FlinkContext context = ShortcutUtils.unwrapContext(cluster);
    final FlinkRelBuilder relBuilder = FlinkRelBuilder.of(cluster, relOptSchema);
    // finalize catalog table with option hints
    final Map<String, String> hintedOptions = FlinkHints.getHintedOptions(hints);
    final ContextResolvedTable catalogTable = computeContextResolvedTable(context, hintedOptions);
    // create table source
    final DynamicTableSource tableSource = createDynamicTableSource(context, catalogTable.getResolvedTable());
    // prepare table source and convert to RelNode
    return DynamicSourceUtils.convertSourceToRel(!schemaTable.isStreamingMode(), context.getTableConfig().getConfiguration(), relBuilder, schemaTable.getContextResolvedTable(), schemaTable.getStatistic(), hints, tableSource);
}
Also used : RelOptCluster(org.apache.calcite.plan.RelOptCluster) FlinkRelBuilder(org.apache.flink.table.planner.calcite.FlinkRelBuilder) ContextResolvedTable(org.apache.flink.table.catalog.ContextResolvedTable) RelHint(org.apache.calcite.rel.hint.RelHint) FlinkContext(org.apache.flink.table.planner.calcite.FlinkContext) DynamicTableSource(org.apache.flink.table.connector.source.DynamicTableSource)

Example 5 with FlinkContext

use of org.apache.flink.table.planner.calcite.FlinkContext in project flink by apache.

the class PushFilterIntoSourceScanRuleBase method extractPredicates.

protected Tuple2<RexNode[], RexNode[]> extractPredicates(String[] inputNames, RexNode filterExpression, TableScan scan, RexBuilder rexBuilder) {
    FlinkContext context = ShortcutUtils.unwrapContext(scan);
    int maxCnfNodeCount = FlinkRelOptUtil.getMaxCnfNodeCount(scan);
    RexNodeToExpressionConverter converter = new RexNodeToExpressionConverter(rexBuilder, inputNames, context.getFunctionCatalog(), context.getCatalogManager(), TimeZone.getTimeZone(context.getTableConfig().getLocalTimeZone()));
    return RexNodeExtractor.extractConjunctiveConditions(filterExpression, maxCnfNodeCount, rexBuilder, converter);
}
Also used : RexNodeToExpressionConverter(org.apache.flink.table.planner.plan.utils.RexNodeToExpressionConverter) FlinkContext(org.apache.flink.table.planner.calcite.FlinkContext)

Aggregations

FlinkContext (org.apache.flink.table.planner.calcite.FlinkContext)5 RexBuilder (org.apache.calcite.rex.RexBuilder)2 DynamicTableSource (org.apache.flink.table.connector.source.DynamicTableSource)2 FlinkTypeFactory (org.apache.flink.table.planner.calcite.FlinkTypeFactory)2 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 List (java.util.List)1 Map (java.util.Map)1 Optional (java.util.Optional)1 TimeZone (java.util.TimeZone)1 Function (java.util.function.Function)1 Collectors (java.util.stream.Collectors)1 RelOptCluster (org.apache.calcite.plan.RelOptCluster)1 RelOptRule (org.apache.calcite.plan.RelOptRule)1 RelOptRuleCall (org.apache.calcite.plan.RelOptRuleCall)1 Filter (org.apache.calcite.rel.core.Filter)1 RelHint (org.apache.calcite.rel.hint.RelHint)1 LogicalTableScan (org.apache.calcite.rel.logical.LogicalTableScan)1 RelDataType (org.apache.calcite.rel.type.RelDataType)1 RexInputRef (org.apache.calcite.rex.RexInputRef)1