1use std::cmp::Ordering;
6use std::collections::BinaryHeap;
7use std::fmt;
8use std::fmt::Debug;
9use std::ops::Deref;
10use std::slice::from_ref;
11use std::sync::Arc;
12
13use crate::sink::DataSink;
14use crate::source::{DataSource, DataSourceExec};
15
16use arrow::array::{RecordBatch, RecordBatchOptions};
17use arrow::datatypes::{Schema, SchemaRef};
18use datafusion_common::tree_node::TreeNodeRecursion;
19use datafusion_common::{
20 Result, ScalarValue, assert_or_internal_err, plan_err, project_schema,
21};
22use datafusion_execution::TaskContext;
23use datafusion_physical_expr::equivalence::project_orderings;
24use datafusion_physical_expr::projection::ProjectionExprs;
25use datafusion_physical_expr::utils::collect_columns;
26use datafusion_physical_expr::{EquivalenceProperties, LexOrdering};
27use datafusion_physical_plan::memory::MemoryStream;
28use datafusion_physical_plan::projection::{
29 all_alias_free_columns, new_projections_for_columns,
30};
31use datafusion_physical_plan::{
32 ColumnarValue, DisplayAs, DisplayFormatType, Partitioning, PhysicalExpr,
33 SendableRecordBatchStream, Statistics, common,
34};
35
36use async_trait::async_trait;
37use datafusion_physical_plan::coop::cooperative;
38use datafusion_physical_plan::execution_plan::SchedulingType;
39use futures::StreamExt;
40use itertools::Itertools;
41use tokio::sync::RwLock;
42
43#[derive(Clone, Debug)]
45pub struct MemorySourceConfig {
46 partitions: Vec<Vec<RecordBatch>>,
50 schema: SchemaRef,
52 projected_schema: SchemaRef,
54 projection: Option<Vec<usize>>,
56 sort_information: Vec<LexOrdering>,
58 show_sizes: bool,
60 fetch: Option<usize>,
63}
64
65impl DataSource for MemorySourceConfig {
66 fn open(
67 &self,
68 partition: usize,
69 _context: Arc<TaskContext>,
70 ) -> Result<SendableRecordBatchStream> {
71 Ok(Box::pin(cooperative(
72 MemoryStream::try_new(
73 self.partitions[partition].clone(),
74 Arc::clone(&self.projected_schema),
75 self.projection.clone(),
76 )?
77 .with_fetch(self.fetch),
78 )))
79 }
80
81 fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter) -> fmt::Result {
82 match t {
83 DisplayFormatType::Default | DisplayFormatType::Verbose => {
84 let partition_sizes: Vec<_> =
85 self.partitions.iter().map(|b| b.len()).collect();
86
87 let output_ordering = self
88 .sort_information
89 .first()
90 .map(|output_ordering| format!(", output_ordering={output_ordering}"))
91 .unwrap_or_default();
92
93 let eq_properties = self.eq_properties();
94 let constraints = eq_properties.constraints();
95 let constraints = if constraints.is_empty() {
96 String::new()
97 } else {
98 format!(", {constraints}")
99 };
100
101 let limit = self
102 .fetch
103 .map_or(String::new(), |limit| format!(", fetch={limit}"));
104 if self.show_sizes {
105 write!(
106 f,
107 "partitions={}, partition_sizes={partition_sizes:?}{limit}{output_ordering}{constraints}",
108 partition_sizes.len(),
109 )
110 } else {
111 write!(
112 f,
113 "partitions={}{limit}{output_ordering}{constraints}",
114 partition_sizes.len(),
115 )
116 }
117 }
118 DisplayFormatType::TreeRender => {
119 let total_rows = self
120 .partitions
121 .iter()
122 .flatten()
123 .map(RecordBatch::num_rows)
124 .sum::<usize>();
125 let total_bytes: usize = self
126 .partitions
127 .iter()
128 .flatten()
129 .map(|batch| batch.get_array_memory_size())
130 .sum();
131 writeln!(f, "format=memory")?;
132 writeln!(f, "rows={total_rows}")?;
133 writeln!(f, "bytes={total_bytes}")?;
134 Ok(())
135 }
136 }
137 }
138
139 fn repartitioned(
144 &self,
145 target_partitions: usize,
146 _repartition_file_min_size: usize,
147 output_ordering: Option<LexOrdering>,
148 ) -> Result<Option<Arc<dyn DataSource>>> {
149 if self.partitions.is_empty() || self.partitions.len() >= target_partitions
150 {
152 return Ok(None);
153 }
154
155 let maybe_repartitioned = if let Some(output_ordering) = output_ordering {
156 self.repartition_preserving_order(target_partitions, output_ordering)?
157 } else {
158 self.repartition_evenly_by_size(target_partitions)?
159 };
160
161 if let Some(repartitioned) = maybe_repartitioned {
162 Ok(Some(Arc::new(Self::try_new(
163 &repartitioned,
164 self.original_schema(),
165 self.projection.clone(),
166 )?)))
167 } else {
168 Ok(None)
169 }
170 }
171
172 fn output_partitioning(&self) -> Partitioning {
173 Partitioning::UnknownPartitioning(self.partitions.len())
174 }
175
176 fn eq_properties(&self) -> EquivalenceProperties {
177 EquivalenceProperties::new_with_orderings(
178 Arc::clone(&self.projected_schema),
179 self.sort_information.clone(),
180 )
181 }
182
183 fn scheduling_type(&self) -> SchedulingType {
184 SchedulingType::Cooperative
185 }
186
187 fn partition_statistics(&self, partition: Option<usize>) -> Result<Arc<Statistics>> {
188 if let Some(partition) = partition {
189 if let Some(batches) = self.partitions.get(partition) {
191 Ok(Arc::new(common::compute_record_batch_statistics(
192 from_ref(batches),
193 &self.schema,
194 self.projection.clone(),
195 )))
196 } else {
197 Ok(Arc::new(Statistics::new_unknown(&self.projected_schema)))
199 }
200 } else {
201 Ok(Arc::new(common::compute_record_batch_statistics(
203 &self.partitions,
204 &self.schema,
205 self.projection.clone(),
206 )))
207 }
208 }
209
210 fn with_fetch(&self, limit: Option<usize>) -> Option<Arc<dyn DataSource>> {
211 let source = self.clone();
212 Some(Arc::new(source.with_limit(limit)))
213 }
214
215 fn fetch(&self) -> Option<usize> {
216 self.fetch
217 }
218
219 fn try_swapping_with_projection(
220 &self,
221 projection: &ProjectionExprs,
222 ) -> Result<Option<Arc<dyn DataSource>>> {
223 let exprs = projection.iter().cloned().collect_vec();
226 all_alias_free_columns(exprs.as_slice())
227 .then(|| {
228 let all_projections = (0..self.schema.fields().len()).collect();
229 let new_projections = new_projections_for_columns(
230 &exprs,
231 self.projection().as_ref().unwrap_or(&all_projections),
232 );
233 let projected_schema =
234 project_schema(&self.schema, Some(&new_projections));
235
236 projected_schema.map(|projected_schema| {
237 let mut new_source = self.clone();
240 new_source.projection = Some(new_projections);
241 new_source.projected_schema = projected_schema;
242 new_source.sort_information = project_orderings(
244 &new_source.sort_information,
245 &new_source.projected_schema,
246 );
247 Arc::new(new_source) as Arc<dyn DataSource>
248 })
249 })
250 .transpose()
251 }
252
253 fn apply_expressions(
254 &self,
255 _f: &mut dyn FnMut(&Arc<dyn PhysicalExpr>) -> Result<TreeNodeRecursion>,
256 ) -> Result<TreeNodeRecursion> {
257 Ok(TreeNodeRecursion::Continue)
258 }
259
260 #[cfg(feature = "proto")]
266 fn try_to_proto(
267 &self,
268 ctx: &datafusion_physical_plan::proto::ExecutionPlanEncodeCtx<'_>,
269 ) -> Result<Option<datafusion_proto_models::protobuf::PhysicalPlanNode>> {
270 use datafusion_common::utils::usize_to_wire;
271 use datafusion_physical_expr_common::sort_expr::sort_exprs_try_to_proto;
272 use datafusion_proto_models::protobuf;
273
274 let Self {
278 partitions: source_partitions,
279 schema,
280 projected_schema: _,
282 projection: source_projection,
283 sort_information,
284 show_sizes,
285 fetch,
286 } = self;
287
288 let proto_partitions = source_partitions
289 .iter()
290 .map(|batches| record_batches_to_ipc_bytes(batches))
291 .collect::<Result<Vec<_>>>()?;
292
293 let proto_projection = match source_projection.as_ref() {
296 None => Vec::new(),
297 Some(v) if v.is_empty() => vec![u32::MAX],
298 Some(v) => v.iter().map(|x| *x as u32).collect(),
299 };
300
301 let mut proto_sort_information = Vec::with_capacity(sort_information.len());
302 for ordering in sort_information {
303 let physical_sort_expr_nodes =
304 sort_exprs_try_to_proto(ordering.iter(), &ctx.expr_ctx())?;
305 proto_sort_information.push(protobuf::PhysicalSortExprNodeCollection {
306 physical_sort_expr_nodes,
307 });
308 }
309
310 Ok(Some(protobuf::PhysicalPlanNode {
311 physical_plan_type: Some(
312 protobuf::physical_plan_node::PhysicalPlanType::MemoryScan(
313 protobuf::MemoryScanExecNode {
314 partitions: proto_partitions,
315 schema: Some(schema.as_ref().try_into()?),
316 projection: proto_projection,
317 sort_information: proto_sort_information,
318 show_sizes: *show_sizes,
319 fetch: fetch
320 .map(|fetch| {
321 usize_to_wire(fetch, "MemoryScanExecNode", "fetch")
322 })
323 .transpose()?,
324 },
325 ),
326 ),
327 }))
328 }
329}
330
331impl MemorySourceConfig {
332 pub fn try_new(
335 partitions: &[Vec<RecordBatch>],
336 schema: SchemaRef,
337 projection: Option<Vec<usize>>,
338 ) -> Result<Self> {
339 let projected_schema = project_schema(&schema, projection.as_ref())?;
340 Ok(Self {
341 partitions: partitions.to_vec(),
342 schema,
343 projected_schema,
344 projection,
345 sort_information: vec![],
346 show_sizes: true,
347 fetch: None,
348 })
349 }
350
351 pub fn try_new_exec(
354 partitions: &[Vec<RecordBatch>],
355 schema: SchemaRef,
356 projection: Option<Vec<usize>>,
357 ) -> Result<Arc<DataSourceExec>> {
358 let source = Self::try_new(partitions, schema, projection)?;
359 Ok(DataSourceExec::from_data_source(source))
360 }
361
362 #[expect(clippy::needless_pass_by_value)]
364 pub fn try_new_as_values(
365 schema: SchemaRef,
366 data: Vec<Vec<Arc<dyn PhysicalExpr>>>,
367 ) -> Result<Arc<DataSourceExec>> {
368 if data.is_empty() {
369 return plan_err!("Values list cannot be empty");
370 }
371
372 let n_row = data.len();
373 let n_col = schema.fields().len();
374
375 let placeholder_schema = Arc::new(Schema::empty());
378 let placeholder_batch = RecordBatch::try_new_with_options(
379 Arc::clone(&placeholder_schema),
380 vec![],
381 &RecordBatchOptions::new().with_row_count(Some(1)),
382 )?;
383
384 let arrays = (0..n_col)
386 .map(|j| {
387 (0..n_row)
388 .map(|i| {
389 let expr = &data[i][j];
390 let result = expr.evaluate(&placeholder_batch)?;
391
392 match result {
393 ColumnarValue::Scalar(scalar) => Ok(scalar),
394 ColumnarValue::Array(array) if array.len() == 1 => {
395 ScalarValue::try_from_array(&array, 0)
396 }
397 ColumnarValue::Array(_) => {
398 plan_err!("Cannot have array values in a values list")
399 }
400 }
401 })
402 .collect::<Result<Vec<_>>>()
403 .and_then(ScalarValue::iter_to_array)
404 })
405 .collect::<Result<Vec<_>>>()?;
406
407 let batch = RecordBatch::try_new_with_options(
408 Arc::clone(&schema),
409 arrays,
410 &RecordBatchOptions::new().with_row_count(Some(n_row)),
411 )?;
412
413 let partitions = vec![batch];
414 Self::try_new_from_batches(Arc::clone(&schema), partitions)
415 }
416
417 #[expect(clippy::needless_pass_by_value)]
422 pub fn try_new_from_batches(
423 schema: SchemaRef,
424 batches: Vec<RecordBatch>,
425 ) -> Result<Arc<DataSourceExec>> {
426 if batches.is_empty() {
427 return plan_err!("Values list cannot be empty");
428 }
429
430 for batch in &batches {
431 let batch_schema = batch.schema();
432 if batch_schema != schema {
433 return plan_err!(
434 "Batch has invalid schema. Expected: {}, got: {}",
435 schema,
436 batch_schema
437 );
438 }
439 }
440
441 let partitions = vec![batches];
442 let source = Self {
443 partitions,
444 schema: Arc::clone(&schema),
445 projected_schema: Arc::clone(&schema),
446 projection: None,
447 sort_information: vec![],
448 show_sizes: true,
449 fetch: None,
450 };
451 Ok(DataSourceExec::from_data_source(source))
452 }
453
454 pub fn with_limit(mut self, limit: Option<usize>) -> Self {
456 self.fetch = limit;
457 self
458 }
459
460 pub fn with_show_sizes(mut self, show_sizes: bool) -> Self {
462 self.show_sizes = show_sizes;
463 self
464 }
465
466 pub fn partitions(&self) -> &[Vec<RecordBatch>] {
468 &self.partitions
469 }
470
471 pub fn projection(&self) -> &Option<Vec<usize>> {
473 &self.projection
474 }
475
476 pub fn show_sizes(&self) -> bool {
478 self.show_sizes
479 }
480
481 pub fn sort_information(&self) -> &[LexOrdering] {
483 &self.sort_information
484 }
485
486 pub fn try_with_sort_information(
506 mut self,
507 mut sort_information: Vec<LexOrdering>,
508 ) -> Result<Self> {
509 Self::validate_sort_information(&sort_information, &self.schema, "original")?;
511
512 if self.projection.is_some() {
514 sort_information =
515 project_orderings(&sort_information, &self.projected_schema);
516 }
517
518 self.sort_information = sort_information;
519 Ok(self)
520 }
521
522 fn validate_sort_information(
523 sort_information: &[LexOrdering],
524 schema: &Schema,
525 schema_name: &str,
526 ) -> Result<()> {
527 let fields = schema.fields();
528 let ambiguous_column = sort_information
529 .iter()
530 .flat_map(|ordering| ordering.iter())
531 .flat_map(|expr| collect_columns(&expr.expr))
532 .find(|col| {
533 fields
534 .get(col.index())
535 .map(|field| field.name() != col.name())
536 .unwrap_or(true)
537 });
538 assert_or_internal_err!(
539 ambiguous_column.is_none(),
540 "Column {:?} is not found in the {schema_name} schema of the MemorySourceConfig",
541 ambiguous_column.as_ref().unwrap()
542 );
543 Ok(())
544 }
545
546 pub fn original_schema(&self) -> SchemaRef {
548 Arc::clone(&self.schema)
549 }
550
551 fn repartition_preserving_order(
557 &self,
558 target_partitions: usize,
559 output_ordering: LexOrdering,
560 ) -> Result<Option<Vec<Vec<RecordBatch>>>> {
561 if !self.eq_properties().ordering_satisfy(output_ordering)? {
562 Ok(None)
563 } else {
564 let total_num_batches =
565 self.partitions.iter().map(|b| b.len()).sum::<usize>();
566 if total_num_batches < target_partitions {
567 return Ok(None);
569 }
570
571 let cnt_to_repartition = target_partitions - self.partitions.len();
572
573 let to_repartition = self
576 .partitions
577 .iter()
578 .enumerate()
579 .map(|(idx, batches)| RePartition {
580 idx: idx + (cnt_to_repartition * idx), row_count: batches.iter().map(|batch| batch.num_rows()).sum(),
582 batches: batches.clone(),
583 })
584 .collect_vec();
585
586 let mut max_heap = BinaryHeap::with_capacity(target_partitions);
589 for rep in to_repartition {
590 max_heap.push(CompareByRowCount(rep));
591 }
592
593 let mut cannot_split_further = Vec::with_capacity(target_partitions);
596 for _ in 0..cnt_to_repartition {
597 loop {
599 let Some(to_split) = max_heap.pop() else {
601 break;
603 };
604
605 let mut new_partitions = to_split.into_inner().split();
607 if new_partitions.len() > 1 {
608 for new_partition in new_partitions {
609 max_heap.push(CompareByRowCount(new_partition));
610 }
611 break;
613 } else {
614 cannot_split_further.push(new_partitions.remove(0));
615 }
616 }
617 }
618 let mut partitions = max_heap
619 .drain()
620 .map(CompareByRowCount::into_inner)
621 .collect_vec();
622 partitions.extend(cannot_split_further);
623
624 partitions.sort_by_key(|p| p.idx);
627 let partitions = partitions.into_iter().map(|rep| rep.batches).collect_vec();
628
629 Ok(Some(partitions))
630 }
631 }
632
633 fn repartition_evenly_by_size(
642 &self,
643 target_partitions: usize,
644 ) -> Result<Option<Vec<Vec<RecordBatch>>>> {
645 let mut flatten_batches =
647 self.partitions.clone().into_iter().flatten().collect_vec();
648 if flatten_batches.len() < target_partitions {
649 return Ok(None);
650 }
651
652 let total_num_rows = flatten_batches.iter().map(|b| b.num_rows()).sum::<usize>();
654 flatten_batches.sort_by_key(|b| std::cmp::Reverse(b.num_rows()));
656
657 let mut partitions =
659 vec![Vec::with_capacity(flatten_batches.len()); target_partitions];
660 let mut target_partition_size = total_num_rows.div_ceil(target_partitions);
661 let mut total_rows_seen = 0;
662 let mut curr_bin_row_count = 0;
663 let mut idx = 0;
664 for batch in flatten_batches {
665 let row_cnt = batch.num_rows();
666 idx = std::cmp::min(idx, target_partitions - 1);
667
668 partitions[idx].push(batch);
669 curr_bin_row_count += row_cnt;
670 total_rows_seen += row_cnt;
671
672 if curr_bin_row_count >= target_partition_size {
673 idx += 1;
674 curr_bin_row_count = 0;
675
676 if total_rows_seen < total_num_rows {
679 target_partition_size = (total_num_rows - total_rows_seen)
680 .div_ceil(target_partitions - idx);
681 }
682 }
683 }
684
685 Ok(Some(partitions))
686 }
687}
688
689#[cfg(feature = "proto")]
690impl MemorySourceConfig {
691 pub fn try_from_proto(
695 node: &datafusion_proto_models::protobuf::PhysicalPlanNode,
696 ctx: &datafusion_physical_plan::proto::ExecutionPlanDecodeCtx<'_>,
697 ) -> Result<Arc<dyn datafusion_physical_plan::ExecutionPlan>> {
698 use datafusion_common::internal_datafusion_err;
699 use datafusion_common::utils::usize_from_wire;
700 use datafusion_physical_expr_common::sort_expr::optional_ordering_try_from_proto;
701 use datafusion_proto_models::protobuf;
702
703 let scan = datafusion_physical_plan::expect_plan_variant!(
704 node,
705 protobuf::physical_plan_node::PhysicalPlanType::MemoryScan,
706 "MemorySourceConfig",
707 );
708
709 let protobuf::MemoryScanExecNode {
712 partitions: proto_partitions,
713 schema: encoded_schema,
714 projection: proto_projection,
715 sort_information: proto_sort_information,
716 show_sizes,
717 fetch: proto_fetch,
718 } = scan;
719
720 let partitions = proto_partitions
721 .iter()
722 .map(|buf| record_batches_from_ipc_bytes(buf))
723 .collect::<Result<Vec<_>>>()?;
724
725 let proto_schema = encoded_schema.as_ref().ok_or_else(|| {
726 internal_datafusion_err!("schema in MemoryScanExecNode is missing.")
727 })?;
728 let source_schema: SchemaRef = SchemaRef::new(proto_schema.try_into()?);
729
730 let projection = match proto_projection.as_slice() {
732 [] => None,
733 [u32::MAX] => Some(Vec::new()),
734 indices => Some(indices.iter().map(|i| *i as usize).collect()),
735 };
736 let fetch = proto_fetch
737 .map(|fetch| usize_from_wire(fetch, "MemoryScanExecNode", "fetch"))
738 .transpose()?;
739 let mut source = Self::try_new(&partitions, source_schema, projection)?
740 .with_limit(fetch)
741 .with_show_sizes(*show_sizes);
742
743 let mut decoded_sort_information =
747 Vec::with_capacity(proto_sort_information.len());
748 for ordering in proto_sort_information {
749 let protobuf::PhysicalSortExprNodeCollection {
750 physical_sort_expr_nodes,
751 } = ordering;
752 if let Some(ordering) = optional_ordering_try_from_proto(
753 physical_sort_expr_nodes,
754 &ctx.expr_ctx(&source.projected_schema),
755 )? {
756 decoded_sort_information.push(ordering);
757 }
758 }
759 Self::validate_sort_information(
760 &decoded_sort_information,
761 &source.projected_schema,
762 "projected",
763 )?;
764 source.sort_information = decoded_sort_information;
765
766 Ok(DataSourceExec::from_data_source(source))
767 }
768}
769
770#[cfg(feature = "proto")]
773fn record_batches_to_ipc_bytes(batches: &[RecordBatch]) -> Result<Vec<u8>> {
774 use arrow::ipc::writer::StreamWriter;
775
776 if batches.is_empty() {
777 return Ok(vec![]);
778 }
779 let schema = batches[0].schema();
780 let mut buf = Vec::new();
781 let mut writer = StreamWriter::try_new(&mut buf, &schema)?;
782 for batch in batches {
783 writer.write(batch)?;
784 }
785 writer.finish()?;
786 Ok(buf)
787}
788
789#[cfg(feature = "proto")]
791fn record_batches_from_ipc_bytes(buf: &[u8]) -> Result<Vec<RecordBatch>> {
792 use arrow::ipc::reader::StreamReader;
793
794 if buf.is_empty() {
795 return Ok(vec![]);
796 }
797 let reader = StreamReader::try_new(buf, None)?;
798 let mut batches = Vec::new();
799 for batch in reader {
800 batches.push(batch?);
801 }
802 Ok(batches)
803}
804
805struct RePartition {
809 idx: usize,
811 row_count: usize,
814 batches: Vec<RecordBatch>,
816}
817
818impl RePartition {
819 fn split(self) -> Vec<Self> {
823 if self.batches.len() == 1 {
824 return vec![self];
825 }
826
827 let new_0 = RePartition {
828 idx: self.idx, row_count: 0,
830 batches: vec![],
831 };
832 let new_1 = RePartition {
833 idx: self.idx + 1, row_count: 0,
835 batches: vec![],
836 };
837 let split_pt = self.row_count / 2;
838
839 let [new_0, new_1] = self.batches.into_iter().fold(
840 [new_0, new_1],
841 |[mut new0, mut new1], batch| {
842 if new0.row_count < split_pt {
843 new0.add_batch(batch);
844 } else {
845 new1.add_batch(batch);
846 }
847 [new0, new1]
848 },
849 );
850 vec![new_0, new_1]
851 }
852
853 fn add_batch(&mut self, batch: RecordBatch) {
854 self.row_count += batch.num_rows();
855 self.batches.push(batch);
856 }
857}
858
859impl fmt::Display for RePartition {
860 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
861 write!(
862 f,
863 "{}rows-in-{}batches@{}",
864 self.row_count,
865 self.batches.len(),
866 self.idx
867 )
868 }
869}
870
871struct CompareByRowCount(RePartition);
872impl CompareByRowCount {
873 fn into_inner(self) -> RePartition {
874 self.0
875 }
876}
877impl Ord for CompareByRowCount {
878 fn cmp(&self, other: &Self) -> Ordering {
879 self.0.row_count.cmp(&other.0.row_count)
880 }
881}
882impl PartialOrd for CompareByRowCount {
883 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
884 Some(self.cmp(other))
885 }
886}
887impl PartialEq for CompareByRowCount {
888 fn eq(&self, other: &Self) -> bool {
889 self.cmp(other) == Ordering::Equal
891 }
892}
893impl Eq for CompareByRowCount {}
894impl Deref for CompareByRowCount {
895 type Target = RePartition;
896 fn deref(&self) -> &Self::Target {
897 &self.0
898 }
899}
900
901pub type PartitionData = Arc<RwLock<Vec<RecordBatch>>>;
903
904pub struct MemSink {
908 batches: Vec<PartitionData>,
910 schema: SchemaRef,
911 overwrite: bool,
912}
913
914impl Debug for MemSink {
915 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
916 f.debug_struct("MemSink")
917 .field("num_partitions", &self.batches.len())
918 .finish()
919 }
920}
921
922impl DisplayAs for MemSink {
923 fn fmt_as(&self, t: DisplayFormatType, f: &mut fmt::Formatter<'_>) -> fmt::Result {
924 match t {
925 DisplayFormatType::Default | DisplayFormatType::Verbose => {
926 let partition_count = self.batches.len();
927 write!(f, "MemoryTable (partitions={partition_count})")
928 }
929 DisplayFormatType::TreeRender => {
930 write!(f, "")
932 }
933 }
934 }
935}
936
937impl MemSink {
938 pub fn try_new(batches: Vec<PartitionData>, schema: SchemaRef) -> Result<Self> {
942 if batches.is_empty() {
943 return plan_err!("Cannot insert into MemTable with zero partitions");
944 }
945 Ok(Self {
946 batches,
947 schema,
948 overwrite: false,
949 })
950 }
951
952 pub fn with_overwrite(mut self, overwrite: bool) -> Self {
954 self.overwrite = overwrite;
955 self
956 }
957}
958
959#[async_trait]
960impl DataSink for MemSink {
961 fn schema(&self) -> &SchemaRef {
962 &self.schema
963 }
964
965 async fn write_all(
966 &self,
967 mut data: SendableRecordBatchStream,
968 _context: &Arc<TaskContext>,
969 ) -> Result<u64> {
970 let num_partitions = self.batches.len();
971
972 let mut new_batches = vec![vec![]; num_partitions];
975 let mut i = 0;
976 let mut row_count = 0;
977 while let Some(batch) = data.next().await.transpose()? {
978 row_count += batch.num_rows();
979 new_batches[i].push(batch);
980 i = (i + 1) % num_partitions;
981 }
982
983 for (target, mut batches) in self.batches.iter().zip(new_batches) {
985 let mut target = target.write().await;
986 if self.overwrite {
987 *target = batches;
988 } else {
989 target.append(&mut batches);
991 }
992 }
993
994 Ok(row_count as u64)
995 }
996}
997
998#[cfg(test)]
999mod memory_source_tests {
1000 use std::sync::Arc;
1001
1002 use crate::memory::MemorySourceConfig;
1003 use crate::source::DataSourceExec;
1004
1005 use arrow::compute::SortOptions;
1006 use arrow::datatypes::{DataType, Field, Schema};
1007 use datafusion_common::Result;
1008 use datafusion_physical_expr::expressions::col;
1009 use datafusion_physical_expr_common::sort_expr::{LexOrdering, PhysicalSortExpr};
1010 use datafusion_physical_plan::ExecutionPlan;
1011
1012 #[test]
1013 fn test_memory_order_eq() -> Result<()> {
1014 let schema = Arc::new(Schema::new(vec![
1015 Field::new("a", DataType::Int64, false),
1016 Field::new("b", DataType::Int64, false),
1017 Field::new("c", DataType::Int64, false),
1018 ]));
1019 let sort1: LexOrdering = [
1020 PhysicalSortExpr {
1021 expr: col("a", &schema)?,
1022 options: SortOptions::default(),
1023 },
1024 PhysicalSortExpr {
1025 expr: col("b", &schema)?,
1026 options: SortOptions::default(),
1027 },
1028 ]
1029 .into();
1030 let sort2: LexOrdering = [PhysicalSortExpr {
1031 expr: col("c", &schema)?,
1032 options: SortOptions::default(),
1033 }]
1034 .into();
1035 let mut expected_output_order = sort1.clone();
1036 expected_output_order.extend(sort2.clone());
1037
1038 let sort_information = vec![sort1.clone(), sort2.clone()];
1039 let mem_exec = DataSourceExec::from_data_source(
1040 MemorySourceConfig::try_new(&[vec![]], schema, None)?
1041 .try_with_sort_information(sort_information)?,
1042 );
1043
1044 assert_eq!(
1045 mem_exec.properties().output_ordering().unwrap(),
1046 &expected_output_order
1047 );
1048 let eq_properties = mem_exec.properties().equivalence_properties();
1049 assert!(eq_properties.oeq_class().contains(&sort1));
1050 assert!(eq_properties.oeq_class().contains(&sort2));
1051 Ok(())
1052 }
1053}
1054
1055#[cfg(test)]
1056mod tests {
1057 use super::*;
1058 use crate::test_util::col;
1059 use crate::tests::{aggr_test_schema, make_partition};
1060
1061 use arrow::array::{ArrayRef, Int32Array, Int64Array, StringArray};
1062 use arrow::datatypes::{DataType, Field};
1063 use datafusion_common::assert_batches_eq;
1064 use datafusion_common::stats::{ColumnStatistics, Precision};
1065 use datafusion_physical_expr::PhysicalSortExpr;
1066 use datafusion_physical_plan::expressions::lit;
1067 use datafusion_physical_plan::statistics::{StatisticsArgs, StatisticsContext};
1068
1069 use datafusion_physical_plan::ExecutionPlan;
1070
1071 #[tokio::test]
1072 async fn exec_with_limit() -> Result<()> {
1073 let task_ctx = Arc::new(TaskContext::default());
1074 let batch = make_partition(7);
1075 let schema = batch.schema();
1076 let batches = vec![batch.clone(), batch];
1077
1078 let exec = MemorySourceConfig::try_new_from_batches(schema, batches).unwrap();
1079 assert_eq!(exec.fetch(), None);
1080
1081 let exec = exec.with_fetch(Some(4)).unwrap();
1082 assert_eq!(exec.fetch(), Some(4));
1083
1084 let mut it = exec.execute(0, task_ctx)?;
1085 let mut results = vec![];
1086 while let Some(batch) = it.next().await {
1087 results.push(batch?);
1088 }
1089
1090 let expected = [
1091 "+---+", "| i |", "+---+", "| 0 |", "| 1 |", "| 2 |", "| 3 |", "+---+",
1092 ];
1093 assert_batches_eq!(expected, &results);
1094 Ok(())
1095 }
1096
1097 #[test]
1100 fn try_swapping_with_projection_preserves_fetch() {
1101 use datafusion_physical_expr::projection::ProjectionExprs;
1102
1103 let schema = Arc::new(Schema::new(vec![
1104 Field::new("a", DataType::Int32, false),
1105 Field::new("b", DataType::Utf8, false),
1106 Field::new("c", DataType::Int64, false),
1107 ]));
1108 let partitions: Vec<Vec<RecordBatch>> = vec![vec![batch(10)]];
1109 let source = MemorySourceConfig::try_new(&partitions, schema.clone(), None)
1110 .unwrap()
1111 .with_limit(Some(5));
1112
1113 assert_eq!(source.fetch, Some(5));
1114
1115 let projection = ProjectionExprs::from_indices(&[2, 0], &schema);
1117 let swapped = source
1118 .try_swapping_with_projection(&projection)
1119 .unwrap()
1120 .unwrap();
1121 let new_source = swapped.downcast_ref::<MemorySourceConfig>().unwrap();
1122
1123 assert_eq!(
1124 new_source.fetch,
1125 Some(5),
1126 "fetch limit must be preserved after projection pushdown"
1127 );
1128 }
1129
1130 #[tokio::test]
1131 async fn values_empty_case() -> Result<()> {
1132 let schema = aggr_test_schema();
1133 let empty = MemorySourceConfig::try_new_as_values(schema, vec![]);
1134 assert!(empty.is_err());
1135 Ok(())
1136 }
1137
1138 #[test]
1139 fn new_exec_with_batches() {
1140 let batch = make_partition(7);
1141 let schema = batch.schema();
1142 let batches = vec![batch.clone(), batch];
1143 let _exec = MemorySourceConfig::try_new_from_batches(schema, batches).unwrap();
1144 }
1145
1146 #[test]
1147 fn new_exec_with_batches_empty() {
1148 let batch = make_partition(7);
1149 let schema = batch.schema();
1150 let _ = MemorySourceConfig::try_new_from_batches(schema, Vec::new()).unwrap_err();
1151 }
1152
1153 #[test]
1154 fn new_exec_with_batches_invalid_schema() {
1155 let batch = make_partition(7);
1156 let batches = vec![batch.clone(), batch];
1157
1158 let invalid_schema = Arc::new(Schema::new(vec![
1159 Field::new("col0", DataType::UInt32, false),
1160 Field::new("col1", DataType::Utf8, false),
1161 ]));
1162 let _ = MemorySourceConfig::try_new_from_batches(invalid_schema, batches)
1163 .unwrap_err();
1164 }
1165
1166 #[test]
1168 fn new_exec_with_non_nullable_schema() {
1169 let schema = Arc::new(Schema::new(vec![Field::new(
1170 "col0",
1171 DataType::UInt32,
1172 false,
1173 )]));
1174 let _ = MemorySourceConfig::try_new_as_values(
1175 Arc::clone(&schema),
1176 vec![vec![lit(1u32)]],
1177 )
1178 .unwrap();
1179 let _ = MemorySourceConfig::try_new_as_values(
1181 schema,
1182 vec![vec![lit(ScalarValue::UInt32(None))]],
1183 )
1184 .unwrap_err();
1185 }
1186
1187 #[test]
1188 fn values_stats_with_nulls_only() -> Result<()> {
1189 let data = vec![
1190 vec![lit(ScalarValue::Null)],
1191 vec![lit(ScalarValue::Null)],
1192 vec![lit(ScalarValue::Null)],
1193 ];
1194 let rows = data.len();
1195 let schema =
1196 Arc::new(Schema::new(vec![Field::new("col0", DataType::Null, true)]));
1197 let values = MemorySourceConfig::try_new_as_values(schema, data)?;
1198
1199 assert_eq!(
1200 *StatisticsContext::new().compute(values.as_ref(), &StatisticsArgs::new())?,
1201 Statistics {
1202 num_rows: Precision::Exact(rows),
1203 total_byte_size: Precision::Exact(8), column_statistics: vec![ColumnStatistics {
1205 null_count: Precision::Exact(rows), distinct_count: Precision::Absent,
1207 max_value: Precision::Absent,
1208 min_value: Precision::Absent,
1209 sum_value: Precision::Absent,
1210 byte_size: Precision::Absent,
1211 },],
1212 }
1213 );
1214
1215 Ok(())
1216 }
1217
1218 fn batch(row_size: usize) -> RecordBatch {
1219 let a: ArrayRef = Arc::new(Int32Array::from(vec![1; row_size]));
1220 let b: ArrayRef = Arc::new(StringArray::from_iter(vec![Some("foo"); row_size]));
1221 let c: ArrayRef = Arc::new(Int64Array::from_iter(vec![1; row_size]));
1222 RecordBatch::try_from_iter(vec![("a", a), ("b", b), ("c", c)]).unwrap()
1223 }
1224
1225 fn schema() -> SchemaRef {
1226 batch(1).schema()
1227 }
1228
1229 fn memorysrcconfig_no_partitions(
1230 sort_information: Vec<LexOrdering>,
1231 ) -> Result<MemorySourceConfig> {
1232 let partitions = vec![];
1233 MemorySourceConfig::try_new(&partitions, schema(), None)?
1234 .try_with_sort_information(sort_information)
1235 }
1236
1237 fn memorysrcconfig_1_partition_1_batch(
1238 sort_information: Vec<LexOrdering>,
1239 ) -> Result<MemorySourceConfig> {
1240 let partitions = vec![vec![batch(100)]];
1241 MemorySourceConfig::try_new(&partitions, schema(), None)?
1242 .try_with_sort_information(sort_information)
1243 }
1244
1245 fn memorysrcconfig_3_partitions_1_batch_each(
1246 sort_information: Vec<LexOrdering>,
1247 ) -> Result<MemorySourceConfig> {
1248 let partitions = vec![vec![batch(100)], vec![batch(100)], vec![batch(100)]];
1249 MemorySourceConfig::try_new(&partitions, schema(), None)?
1250 .try_with_sort_information(sort_information)
1251 }
1252
1253 fn memorysrcconfig_3_partitions_with_2_batches_each(
1254 sort_information: Vec<LexOrdering>,
1255 ) -> Result<MemorySourceConfig> {
1256 let partitions = vec![
1257 vec![batch(100), batch(100)],
1258 vec![batch(100), batch(100)],
1259 vec![batch(100), batch(100)],
1260 ];
1261 MemorySourceConfig::try_new(&partitions, schema(), None)?
1262 .try_with_sort_information(sort_information)
1263 }
1264
1265 fn memorysrcconfig_1_partition_with_different_sized_batches(
1268 sort_information: Vec<LexOrdering>,
1269 ) -> Result<MemorySourceConfig> {
1270 let partitions = vec![vec![batch(100_000), batch(10_000), batch(100), batch(1)]];
1271 MemorySourceConfig::try_new(&partitions, schema(), None)?
1272 .try_with_sort_information(sort_information)
1273 }
1274
1275 fn memorysrcconfig_1_partition_with_ordering_not_matching_size(
1279 sort_information: Vec<LexOrdering>,
1280 ) -> Result<MemorySourceConfig> {
1281 let partitions = vec![vec![batch(100_000), batch(1), batch(100), batch(10_000)]];
1282 MemorySourceConfig::try_new(&partitions, schema(), None)?
1283 .try_with_sort_information(sort_information)
1284 }
1285
1286 fn memorysrcconfig_2_partition_with_different_sized_batches(
1287 sort_information: Vec<LexOrdering>,
1288 ) -> Result<MemorySourceConfig> {
1289 let partitions = vec![
1290 vec![batch(100_000), batch(10_000), batch(1_000)],
1291 vec![batch(2_000), batch(20)],
1292 ];
1293 MemorySourceConfig::try_new(&partitions, schema(), None)?
1294 .try_with_sort_information(sort_information)
1295 }
1296
1297 fn memorysrcconfig_2_partition_with_extreme_sized_batches(
1298 sort_information: Vec<LexOrdering>,
1299 ) -> Result<MemorySourceConfig> {
1300 let partitions = vec![
1301 vec![
1302 batch(100_000),
1303 batch(1),
1304 batch(1),
1305 batch(1),
1306 batch(1),
1307 batch(0),
1308 ],
1309 vec![batch(1), batch(1), batch(1), batch(1), batch(0), batch(100)],
1310 ];
1311 MemorySourceConfig::try_new(&partitions, schema(), None)?
1312 .try_with_sort_information(sort_information)
1313 }
1314
1315 fn assert_partitioning(
1319 partitioned_datasrc: Option<Arc<dyn DataSource>>,
1320 partition_cnt: Option<usize>,
1321 ) {
1322 let should_exist = if let Some(partition_cnt) = partition_cnt {
1323 format!("new datasource should exist and have {partition_cnt:?} partitions")
1324 } else {
1325 "new datasource should not exist".into()
1326 };
1327
1328 let actual = partitioned_datasrc
1329 .map(|datasrc| datasrc.output_partitioning().partition_count());
1330 assert_eq!(
1331 actual, partition_cnt,
1332 "partitioned datasrc does not match expected, we expected {should_exist}, instead found {actual:?}"
1333 );
1334 }
1335
1336 fn run_all_test_scenarios(
1337 output_ordering: Option<LexOrdering>,
1338 sort_information_on_config: Vec<LexOrdering>,
1339 ) -> Result<()> {
1340 let not_used = usize::MAX;
1341
1342 let mem_src_config =
1344 memorysrcconfig_no_partitions(sort_information_on_config.clone())?;
1345 let partitioned_datasrc =
1346 mem_src_config.repartitioned(1, not_used, output_ordering.clone())?;
1347 assert_partitioning(partitioned_datasrc, None);
1348
1349 let target_partitions = 1;
1351 let mem_src_config =
1352 memorysrcconfig_1_partition_1_batch(sort_information_on_config.clone())?;
1353 let partitioned_datasrc = mem_src_config.repartitioned(
1354 target_partitions,
1355 not_used,
1356 output_ordering.clone(),
1357 )?;
1358 assert_partitioning(partitioned_datasrc, None);
1359
1360 let target_partitions = 3;
1362 let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
1363 sort_information_on_config.clone(),
1364 )?;
1365 let partitioned_datasrc = mem_src_config.repartitioned(
1366 target_partitions,
1367 not_used,
1368 output_ordering.clone(),
1369 )?;
1370 assert_partitioning(partitioned_datasrc, None);
1371
1372 let target_partitions = 2;
1374 let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
1375 sort_information_on_config.clone(),
1376 )?;
1377 let partitioned_datasrc = mem_src_config.repartitioned(
1378 target_partitions,
1379 not_used,
1380 output_ordering.clone(),
1381 )?;
1382 assert_partitioning(partitioned_datasrc, None);
1383
1384 let target_partitions = 4;
1386 let mem_src_config = memorysrcconfig_3_partitions_1_batch_each(
1387 sort_information_on_config.clone(),
1388 )?;
1389 let partitioned_datasrc = mem_src_config.repartitioned(
1390 target_partitions,
1391 not_used,
1392 output_ordering.clone(),
1393 )?;
1394 assert_partitioning(partitioned_datasrc, None);
1395
1396 let target_partitions = 5;
1399 let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
1400 sort_information_on_config.clone(),
1401 )?;
1402 let partitioned_datasrc = mem_src_config.repartitioned(
1403 target_partitions,
1404 not_used,
1405 output_ordering.clone(),
1406 )?;
1407 assert_partitioning(partitioned_datasrc, Some(5));
1408
1409 let target_partitions = 6;
1412 let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
1413 sort_information_on_config.clone(),
1414 )?;
1415 let partitioned_datasrc = mem_src_config.repartitioned(
1416 target_partitions,
1417 not_used,
1418 output_ordering.clone(),
1419 )?;
1420 assert_partitioning(partitioned_datasrc, Some(6));
1421
1422 let target_partitions = 3 * 2 + 1;
1424 let mem_src_config = memorysrcconfig_3_partitions_with_2_batches_each(
1425 sort_information_on_config.clone(),
1426 )?;
1427 let partitioned_datasrc = mem_src_config.repartitioned(
1428 target_partitions,
1429 not_used,
1430 output_ordering.clone(),
1431 )?;
1432 assert_partitioning(partitioned_datasrc, None);
1433
1434 let target_partitions = 2;
1437 let mem_src_config = memorysrcconfig_1_partition_with_different_sized_batches(
1438 sort_information_on_config,
1439 )?;
1440 let partitioned_datasrc = mem_src_config.clone().repartitioned(
1441 target_partitions,
1442 not_used,
1443 output_ordering,
1444 )?;
1445 assert_partitioning(partitioned_datasrc.clone(), Some(2));
1446 let partitioned_datasrc = partitioned_datasrc.unwrap();
1449 let Some(mem_src_config) =
1450 partitioned_datasrc.downcast_ref::<MemorySourceConfig>()
1451 else {
1452 unreachable!()
1453 };
1454 let repartitioned_raw_batches = mem_src_config.partitions.clone();
1455 assert_eq!(repartitioned_raw_batches.len(), 2);
1456 let [ref p1, ref p2] = repartitioned_raw_batches[..] else {
1457 unreachable!()
1458 };
1459 assert_eq!(p1.len(), 1);
1461 assert_eq!(p1[0].num_rows(), 100_000);
1462 assert_eq!(p2.len(), 3);
1464 assert_eq!(p2[0].num_rows(), 10_000);
1465 assert_eq!(p2[1].num_rows(), 100);
1466 assert_eq!(p2[2].num_rows(), 1);
1467
1468 Ok(())
1469 }
1470
1471 #[test]
1472 fn test_repartition_no_sort_information_no_output_ordering() -> Result<()> {
1473 let no_sort = vec![];
1474 let no_output_ordering = None;
1475
1476 run_all_test_scenarios(no_output_ordering.clone(), no_sort.clone())?;
1478
1479 let target_partitions = 3;
1483 let mem_src_config =
1484 memorysrcconfig_2_partition_with_different_sized_batches(no_sort)?;
1485 let partitioned_datasrc = mem_src_config.clone().repartitioned(
1486 target_partitions,
1487 usize::MAX,
1488 no_output_ordering,
1489 )?;
1490 assert_partitioning(partitioned_datasrc.clone(), Some(3));
1491 let repartitioned_raw_batches = mem_src_config
1494 .repartition_evenly_by_size(target_partitions)?
1495 .unwrap();
1496 assert_eq!(repartitioned_raw_batches.len(), 3);
1497 let [ref p1, ref p2, ref p3] = repartitioned_raw_batches[..] else {
1498 unreachable!()
1499 };
1500 assert_eq!(p1.len(), 1);
1502 assert_eq!(p1[0].num_rows(), 100_000);
1503 assert_eq!(p2.len(), 1);
1505 assert_eq!(p2[0].num_rows(), 10_000);
1506 assert_eq!(p3.len(), 3);
1508 assert_eq!(p3[0].num_rows(), 2_000);
1509 assert_eq!(p3[1].num_rows(), 1_000);
1510 assert_eq!(p3[2].num_rows(), 20);
1511
1512 Ok(())
1513 }
1514
1515 #[test]
1516 fn test_repartition_no_sort_information_no_output_ordering_lopsized_batches()
1517 -> Result<()> {
1518 let no_sort = vec![];
1519 let no_output_ordering = None;
1520
1521 let target_partitions = 5;
1532 let mem_src_config =
1533 memorysrcconfig_2_partition_with_extreme_sized_batches(no_sort)?;
1534 let partitioned_datasrc = mem_src_config.clone().repartitioned(
1535 target_partitions,
1536 usize::MAX,
1537 no_output_ordering,
1538 )?;
1539 assert_partitioning(partitioned_datasrc.clone(), Some(5));
1540 let repartitioned_raw_batches = mem_src_config
1544 .repartition_evenly_by_size(target_partitions)?
1545 .unwrap();
1546 assert_eq!(repartitioned_raw_batches.len(), 5);
1547 let [ref p1, ref p2, ref p3, ref p4, ref p5] = repartitioned_raw_batches[..]
1548 else {
1549 unreachable!()
1550 };
1551 assert_eq!(p1.len(), 1);
1553 assert_eq!(p1[0].num_rows(), 100_000);
1554 assert_eq!(p2.len(), 1);
1556 assert_eq!(p2[0].num_rows(), 100);
1557 assert_eq!(p3.len(), 3);
1559 assert_eq!(p3[0].num_rows(), 1);
1560 assert_eq!(p3[1].num_rows(), 1);
1561 assert_eq!(p3[2].num_rows(), 1);
1562 assert_eq!(p4.len(), 3);
1564 assert_eq!(p4[0].num_rows(), 1);
1565 assert_eq!(p4[1].num_rows(), 1);
1566 assert_eq!(p4[2].num_rows(), 1);
1567 assert_eq!(p5.len(), 4);
1569 assert_eq!(p5[0].num_rows(), 1);
1570 assert_eq!(p5[1].num_rows(), 1);
1571 assert_eq!(p5[2].num_rows(), 0);
1572 assert_eq!(p5[3].num_rows(), 0);
1573
1574 Ok(())
1575 }
1576
1577 #[test]
1578 fn test_repartition_with_sort_information() -> Result<()> {
1579 let schema = schema();
1580 let sort_key: LexOrdering =
1581 [PhysicalSortExpr::new_default(col("c", &schema)?)].into();
1582 let has_sort = vec![sort_key.clone()];
1583 let output_ordering = Some(sort_key);
1584
1585 run_all_test_scenarios(output_ordering.clone(), has_sort.clone())?;
1587
1588 let target_partitions = 3;
1590 let mem_src_config =
1591 memorysrcconfig_2_partition_with_different_sized_batches(has_sort)?;
1592 let partitioned_datasrc = mem_src_config.clone().repartitioned(
1593 target_partitions,
1594 usize::MAX,
1595 output_ordering.clone(),
1596 )?;
1597 assert_partitioning(partitioned_datasrc.clone(), Some(3));
1598 let Some(output_ord) = output_ordering else {
1601 unreachable!()
1602 };
1603 let repartitioned_raw_batches = mem_src_config
1604 .repartition_preserving_order(target_partitions, output_ord)?
1605 .unwrap();
1606 assert_eq!(repartitioned_raw_batches.len(), 3);
1607 let [ref p1, ref p2, ref p3] = repartitioned_raw_batches[..] else {
1608 unreachable!()
1609 };
1610 assert_eq!(p1.len(), 1);
1612 assert_eq!(p1[0].num_rows(), 100_000);
1613 assert_eq!(p2.len(), 2);
1615 assert_eq!(p2[0].num_rows(), 10_000);
1616 assert_eq!(p2[1].num_rows(), 1_000);
1617 assert_eq!(p3.len(), 2);
1619 assert_eq!(p3[0].num_rows(), 2_000);
1620 assert_eq!(p3[1].num_rows(), 20);
1621
1622 Ok(())
1623 }
1624
1625 #[test]
1626 fn test_repartition_with_batch_ordering_not_matching_sizing() -> Result<()> {
1627 let schema = schema();
1628 let sort_key: LexOrdering =
1629 [PhysicalSortExpr::new_default(col("c", &schema)?)].into();
1630 let has_sort = vec![sort_key.clone()];
1631 let output_ordering = Some(sort_key);
1632
1633 let target_partitions = 2;
1636 let mem_src_config =
1637 memorysrcconfig_1_partition_with_ordering_not_matching_size(has_sort)?;
1638 let partitioned_datasrc = mem_src_config.clone().repartitioned(
1639 target_partitions,
1640 usize::MAX,
1641 output_ordering,
1642 )?;
1643 assert_partitioning(partitioned_datasrc.clone(), Some(2));
1644 let partitioned_datasrc = partitioned_datasrc.unwrap();
1647 let Some(mem_src_config) =
1648 partitioned_datasrc.downcast_ref::<MemorySourceConfig>()
1649 else {
1650 unreachable!()
1651 };
1652 let repartitioned_raw_batches = mem_src_config.partitions.clone();
1653 assert_eq!(repartitioned_raw_batches.len(), 2);
1654 let [ref p1, ref p2] = repartitioned_raw_batches[..] else {
1655 unreachable!()
1656 };
1657 assert_eq!(p1.len(), 1);
1659 assert_eq!(p1[0].num_rows(), 100_000);
1660 assert_eq!(p2.len(), 3);
1662 assert_eq!(p2[0].num_rows(), 1);
1663 assert_eq!(p2[1].num_rows(), 100);
1664 assert_eq!(p2[2].num_rows(), 10_000);
1665
1666 Ok(())
1667 }
1668}