gabotechs commented on code in PR #22607: URL: https://github.com/apache/datafusion/pull/22607#discussion_r3322671211
########## datafusion/sqllogictest/test_files/range_partitioning.slt: ########## @@ -0,0 +1,81 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# The sqllogictest harness registers range_partitioned(range_key, non_range_key, value) +# as an in-memory source with four physical source partitions: +# +# partition 0: range_key in [1, 10), rows (1, 1, 10), (5, 2, 50) +# partition 1: range_key in [10, 20), rows (10, 1, 100), (15, 2, 150) +# partition 2: range_key in [20, 30), rows (20, 1, 200), (25, 2, 250) +# partition 3: range_key in [30, ...), rows (30, 1, 300), (35, 2, 350) + +statement ok +set datafusion.explain.physical_plan_only = true; + +########## +# TEST 1: Aggregate on Range Partition Column +# Scanning range_key preserves source Range partitioning metadata. +# Planning still inserts Hash repartitioning today; later optimizer PRs can +# use this baseline to show when the repartition is removed. +########## + +query TT +EXPLAIN SELECT range_key, SUM(value) FROM range_partitioned GROUP BY range_key; +---- +physical_plan +01)AggregateExec: mode=FinalPartitioned, gby=[range_key@0 as range_key], aggr=[sum(range_partitioned.value)] +02)--RepartitionExec: partitioning=Hash([range_key@0], 4), input_partitions=4 +03)----AggregateExec: mode=Partial, gby=[range_key@0 as range_key], aggr=[sum(range_partitioned.value)] +04)------DataSourceExec: partitions=4, partition_sizes=[1, 1, 1, 1], output_partitioning=Range([range_key@0 ASC], [(10), (20), (30)], 4) + Review Comment: One thing that bugs me here is that the first and large partitions are infinetely large ([-inf, 10), [10, 20), [20, 30), [30, +inf]). You probably discussed this in https://github.com/apache/datafusion/pull/22590, but I'm not able to find the conversation. Do you have any thoughts about why we preferred having the first and last partitions declare an infinite size? ########## datafusion/sqllogictest/src/test_context.rs: ########## @@ -286,6 +303,212 @@ fn register_strict_schema_provider(ctx: &SessionContext) { ); } +// ============================================================================== +// Range Partitioned Table (sqllogictest-only) +// ============================================================================== + +#[derive(Debug)] +struct RangePartitionedTable { + schema: SchemaRef, + partitions: Vec<Vec<RecordBatch>>, + range_column_index: usize, + split_points: Vec<SplitPoint>, +} + +#[async_trait] +impl TableProvider for RangePartitionedTable { + fn schema(&self) -> SchemaRef { + Arc::clone(&self.schema) + } + + fn table_type(&self) -> TableType { + TableType::Base + } + + async fn scan( + &self, + state: &dyn Session, + projection: Option<&Vec<usize>>, + _filters: &[Expr], + _limit: Option<usize>, + ) -> Result<Arc<dyn ExecutionPlan>> { + let projected_schema = project_schema(&self.schema, projection)?; + let mut source = MemorySourceConfig::try_new( + &self.partitions, + Arc::clone(&self.schema), + projection.cloned(), + )?; + source = source.with_show_sizes(state.config_options().explain.show_sizes); + + let output_partitioning = + self.output_partitioning(projection, &projected_schema)?; + let source = RangePartitionedSource { + inner: source, + output_partitioning, + }; + + Ok(DataSourceExec::from_data_source(source)) + } +} + +impl RangePartitionedTable { + fn output_partitioning( + &self, + projection: Option<&Vec<usize>>, + projected_schema: &SchemaRef, + ) -> Result<Partitioning> { + let Some(projected_range_index) = + projected_index(self.range_column_index, projection) + else { + return Ok(Partitioning::UnknownPartitioning(self.partitions.len())); + }; + + let range_column = projected_schema.field(projected_range_index).name(); + let ordering = LexOrdering::new(vec![PhysicalSortExpr::new( + physical_col(range_column, projected_schema)?, + SortOptions::default(), + )]) + .expect("range ordering should not be empty"); + + Ok(Partitioning::Range(RangePartitioning::try_new( + ordering, + self.split_points.clone(), + )?)) + } +} + +fn projected_index( + column_index: usize, + projection: Option<&Vec<usize>>, +) -> Option<usize> { + projection + .map(|projection| projection.iter().position(|idx| *idx == column_index)) + .unwrap_or(Some(column_index)) +} + +#[derive(Clone, Debug)] +struct RangePartitionedSource { + inner: MemorySourceConfig, + output_partitioning: Partitioning, +} + +impl DataSource for RangePartitionedSource { + fn open( + &self, + partition: usize, + context: Arc<TaskContext>, + ) -> Result<SendableRecordBatchStream> { + self.inner.open(partition, context) + } + + fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result { + self.inner.fmt_as(t, f)?; + match t { + DisplayFormatType::Default | DisplayFormatType::Verbose => { + write!(f, ", output_partitioning={}", self.output_partitioning) + } + DisplayFormatType::TreeRender => Ok(()), + } + } + + fn output_partitioning(&self) -> Partitioning { + self.output_partitioning.clone() + } + + fn eq_properties(&self) -> EquivalenceProperties { + self.inner.eq_properties() + } + + fn scheduling_type(&self) -> SchedulingType { + self.inner.scheduling_type() + } + + fn partition_statistics(&self, partition: Option<usize>) -> Result<Arc<Statistics>> { + self.inner.partition_statistics(partition) + } + + fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn DataSource>> { + Some(Arc::new(Self { + inner: self.inner.clone().with_limit(limit), + output_partitioning: self.output_partitioning.clone(), + })) + } + + fn fetch(&self) -> Option<usize> { + self.inner.fetch() + } + + fn try_swapping_with_projection( + &self, + _projection: &ProjectionExprs, + ) -> Result<Option<Arc<dyn DataSource>>> { + // Range partitioning metadata is projection-sensitive. This fixture + // computes it in TableProvider::scan, so do not rewrite later + // ProjectionExec nodes into the source. + Ok(None) + } +} + +fn register_range_partitioned_table(ctx: &SessionContext) { Review Comment: :thinking: could it be feasable to have a table function instead? just in case this single table is not capable of satisfying all corner cases in the future. Just food for thought, if you think a hardcoded table is good then let's stick with it (it's actually simpler) ########## datafusion/sqllogictest/test_files/range_partitioning.slt: ########## @@ -0,0 +1,81 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# The sqllogictest harness registers range_partitioned(range_key, non_range_key, value) +# as an in-memory source with four physical source partitions: +# +# partition 0: range_key in [1, 10), rows (1, 1, 10), (5, 2, 50) Review Comment: As the column here is an `Int32`, I imagine the actual range getting exposed here is [i32::MIN, 10), instead of [1, 10). ########## datafusion/sqllogictest/test_files/range_partitioning.slt: ########## @@ -0,0 +1,81 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# The sqllogictest harness registers range_partitioned(range_key, non_range_key, value) +# as an in-memory source with four physical source partitions: +# +# partition 0: range_key in [1, 10), rows (1, 1, 10), (5, 2, 50) +# partition 1: range_key in [10, 20), rows (10, 1, 100), (15, 2, 150) +# partition 2: range_key in [20, 30), rows (20, 1, 200), (25, 2, 250) +# partition 3: range_key in [30, ...), rows (30, 1, 300), (35, 2, 350) + +statement ok +set datafusion.explain.physical_plan_only = true; + Review Comment: Some other tests that come to mind: - A JOIN, where both sizes are partitioned by range partitioning. It would be interesting to see in the plan how no RepartitionExec is introduced in the future (today it probably will). - A UNION. Maybe in the future is possible to maintain Range partitioning across unions. I know some people represent some kind of "range partitioning" today by UNION-ing multiple children, where each children handles a different range of data. ########## datafusion/sqllogictest/src/test_context.rs: ########## @@ -286,6 +303,212 @@ fn register_strict_schema_provider(ctx: &SessionContext) { ); } +// ============================================================================== +// Range Partitioned Table (sqllogictest-only) +// ============================================================================== + +#[derive(Debug)] +struct RangePartitionedTable { + schema: SchemaRef, + partitions: Vec<Vec<RecordBatch>>, + range_column_index: usize, Review Comment: Rather than this just being a column index, I imagine that you'll want this to be an arbitrary expression for trickier tests no? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
