1use crate::url::ListingTableUrl;
9use crate::write::FileSinkConfig;
10use datafusion_common::error::Result;
11use datafusion_physical_plan::SendableRecordBatchStream;
12use std::borrow::Cow;
13use std::collections::HashMap;
14use std::sync::Arc;
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use arrow::array::{
18 ArrayAccessor, RecordBatch, StringArray, StructArray, builder::UInt64Builder,
19 cast::AsArray, downcast_dictionary_array,
20};
21use arrow::datatypes::{DataType, Schema};
22use datafusion_common::cast::{
23 as_boolean_array, as_date32_array, as_date64_array, as_float16_array,
24 as_float32_array, as_float64_array, as_int8_array, as_int16_array, as_int32_array,
25 as_int64_array, as_large_string_array, as_string_array, as_string_view_array,
26 as_uint8_array, as_uint16_array, as_uint32_array, as_uint64_array,
27};
28use datafusion_common::{
29 exec_datafusion_err, exec_err, internal_datafusion_err, not_impl_err,
30};
31use datafusion_common_runtime::SpawnedTask;
32
33use chrono::NaiveDate;
34use datafusion_execution::TaskContext;
35use futures::StreamExt;
36use object_store::path::Path;
37use rand::distr::SampleString;
38use tokio::sync::mpsc::{self, Receiver, Sender, UnboundedReceiver, UnboundedSender};
39
40pub type FileSize = Arc<AtomicU64>;
42type RecordBatchReceiver = Receiver<RecordBatch>;
43pub type DemuxedStreamReceiver = UnboundedReceiver<(FileMetadata, RecordBatchReceiver)>;
44
45pub(crate) fn start_demuxer_task(
91 config: &FileSinkConfig,
92 data: SendableRecordBatchStream,
93 context: &Arc<TaskContext>,
94) -> (SpawnedTask<Result<()>>, DemuxedStreamReceiver) {
95 let (tx, rx) = mpsc::unbounded_channel();
96 let context = Arc::clone(context);
97 let file_extension = config.file_extension.clone();
98 let base_output_path = config.table_paths[0].clone();
99 let task = if config.table_partition_cols.is_empty() {
100 let single_file_output = config
101 .file_output_mode
102 .single_file_output(&base_output_path);
103 SpawnedTask::spawn(async move {
104 row_count_demuxer(
105 tx,
106 data,
107 context,
108 base_output_path,
109 file_extension,
110 single_file_output,
111 )
112 .await
113 })
114 } else {
115 let partition_by = config.table_partition_cols.clone();
118 let keep_partition_by_columns = config.keep_partition_by_columns;
119 SpawnedTask::spawn(async move {
120 hive_style_partitions_demuxer(
121 tx,
122 data,
123 context,
124 partition_by,
125 base_output_path,
126 file_extension,
127 keep_partition_by_columns,
128 )
129 .await
130 })
131 };
132
133 (task, rx)
134}
135
136async fn row_count_demuxer(
139 mut tx: UnboundedSender<(FileMetadata, RecordBatchReceiver)>,
140 mut input: SendableRecordBatchStream,
141 context: Arc<TaskContext>,
142 base_output_path: ListingTableUrl,
143 file_extension: String,
144 single_file_output: bool,
145) -> Result<()> {
146 let exec_options = &context.session_config().options().execution;
147
148 let max_rows_per_file = exec_options.soft_max_rows_per_output_file.get();
149 let max_bytes_per_file = exec_options.soft_max_bytes_per_output_file.get();
150 let max_buffered_batches = exec_options.max_buffered_batches_per_output_file.get();
151 let minimum_parallel_files = exec_options.minimum_parallel_output_files.get();
152 let mut part_idx = 0;
153 let write_id = rand::distr::Alphanumeric.sample_string(&mut rand::rng(), 16);
154
155 let mut open_file_streams = Vec::with_capacity(minimum_parallel_files);
156 let mut file_sizes = Vec::with_capacity(minimum_parallel_files);
157
158 let mut next_send_steam = 0;
159 let mut row_counts = Vec::with_capacity(minimum_parallel_files);
160
161 let minimum_parallel_files = if single_file_output {
163 1
164 } else {
165 minimum_parallel_files
166 };
167
168 let max_rows_per_file = if single_file_output {
169 usize::MAX
170 } else {
171 max_rows_per_file
172 };
173
174 let max_bytes_per_file = if single_file_output {
175 u64::MAX
176 } else {
177 max_bytes_per_file as u64
178 };
179
180 if single_file_output {
181 let (file_stream, file_size) = create_new_file_stream(
183 &base_output_path,
184 &write_id,
185 part_idx,
186 &file_extension,
187 single_file_output,
188 max_buffered_batches,
189 &mut tx,
190 )?;
191 open_file_streams.push(file_stream);
192 file_sizes.push(file_size);
193 row_counts.push(0);
194 part_idx += 1;
195 }
196
197 let schema = input.schema();
198 let mut is_batch_received = false;
199
200 while let Some(rb) = input.next().await.transpose()? {
201 is_batch_received = true;
202 if open_file_streams.len() < minimum_parallel_files {
204 let (file_stream, file_size) = create_new_file_stream(
205 &base_output_path,
206 &write_id,
207 part_idx,
208 &file_extension,
209 single_file_output,
210 max_buffered_batches,
211 &mut tx,
212 )?;
213 open_file_streams.push(file_stream);
214 file_sizes.push(file_size);
215 row_counts.push(0);
216 part_idx += 1;
217 }
218 if row_counts[next_send_steam] >= max_rows_per_file
219 || file_sizes[next_send_steam].load(Ordering::Relaxed) >= max_bytes_per_file
220 {
221 row_counts[next_send_steam] = 0;
222 let (file_stream, file_size) = create_new_file_stream(
223 &base_output_path,
224 &write_id,
225 part_idx,
226 &file_extension,
227 single_file_output,
228 max_buffered_batches,
229 &mut tx,
230 )?;
231 open_file_streams[next_send_steam] = file_stream;
232 file_sizes[next_send_steam] = file_size;
233 part_idx += 1;
234 }
235 row_counts[next_send_steam] += rb.num_rows();
236 open_file_streams[next_send_steam]
237 .send(rb)
238 .await
239 .map_err(|_| {
240 exec_datafusion_err!("Error sending RecordBatch to file stream!")
241 })?;
242
243 next_send_steam = (next_send_steam + 1) % minimum_parallel_files;
244 }
245
246 if single_file_output && !is_batch_received {
248 open_file_streams
249 .first_mut()
250 .ok_or_else(|| internal_datafusion_err!("Expected a single output file"))?
251 .send(RecordBatch::new_empty(schema))
252 .await
253 .map_err(|_| {
254 exec_datafusion_err!("Error sending empty RecordBatch to file stream!")
255 })?;
256 }
257
258 Ok(())
259}
260
261fn generate_file_path(
263 base_output_path: &ListingTableUrl,
264 write_id: &str,
265 part_idx: usize,
266 file_extension: &str,
267 single_file_output: bool,
268) -> Path {
269 if !single_file_output {
270 base_output_path
271 .prefix()
272 .clone()
273 .join(format!("{write_id}_{part_idx}.{file_extension}"))
274 } else {
275 base_output_path.prefix().to_owned()
276 }
277}
278
279fn create_new_file_stream(
281 base_output_path: &ListingTableUrl,
282 write_id: &str,
283 part_idx: usize,
284 file_extension: &str,
285 single_file_output: bool,
286 max_buffered_batches: usize,
287 tx: &mut UnboundedSender<(FileMetadata, RecordBatchReceiver)>,
288) -> Result<(Sender<RecordBatch>, FileSize)> {
289 let file_size = Arc::new(AtomicU64::new(0));
290 let file_metadata = FileMetadata {
291 path: generate_file_path(
292 base_output_path,
293 write_id,
294 part_idx,
295 file_extension,
296 single_file_output,
297 ),
298 size: Arc::clone(&file_size),
299 };
300 let (tx_file, rx_file) = mpsc::channel(max_buffered_batches / 2);
301 tx.send((file_metadata, rx_file))
302 .map_err(|_| exec_datafusion_err!("Error sending RecordBatch to file stream!"))?;
303 Ok((tx_file, file_size))
304}
305
306async fn hive_style_partitions_demuxer(
310 tx: UnboundedSender<(FileMetadata, RecordBatchReceiver)>,
311 mut input: SendableRecordBatchStream,
312 context: Arc<TaskContext>,
313 partition_by: Vec<(String, DataType)>,
314 base_output_path: ListingTableUrl,
315 file_extension: String,
316 keep_partition_by_columns: bool,
317) -> Result<()> {
318 let write_id = rand::distr::Alphanumeric.sample_string(&mut rand::rng(), 16);
319
320 let exec_options = &context.session_config().options().execution;
321 let max_buffered_recordbatches =
322 exec_options.max_buffered_batches_per_output_file.get();
323
324 let mut value_map: HashMap<Vec<String>, Sender<RecordBatch>> = HashMap::new();
326
327 while let Some(rb) = input.next().await.transpose()? {
328 let all_partition_values = compute_partition_keys_by_row(
330 &rb,
331 &partition_by,
332 &exec_options.listing_table_hive_default_partition_name,
333 )?;
334
335 let take_map = compute_take_arrays(&rb, &all_partition_values);
337
338 let struct_array: StructArray = rb.clone().into();
339 for (part_key, mut builder) in take_map.into_iter() {
341 let take_indices = builder.finish();
344 let parted_batch = RecordBatch::from(
345 arrow::compute::take(&struct_array, &take_indices, None)?.as_struct(),
346 );
347
348 let part_tx = match value_map.get_mut(&part_key) {
350 Some(part_tx) => part_tx,
351 None => {
352 let (part_tx, part_rx) =
354 mpsc::channel::<RecordBatch>(max_buffered_recordbatches);
355 let file_metadata = FileMetadata {
356 path: compute_hive_style_file_path(
357 &part_key,
358 &partition_by,
359 &write_id,
360 &file_extension,
361 &base_output_path,
362 ),
363 size: Arc::new(AtomicU64::new(0)),
364 };
365
366 tx.send((file_metadata, part_rx)).map_err(|_| {
367 exec_datafusion_err!("Error sending new file stream!")
368 })?;
369
370 value_map.insert(part_key.clone(), part_tx);
371 value_map.get_mut(&part_key).ok_or_else(|| {
372 exec_datafusion_err!("Key must exist since it was just inserted!")
373 })?
374 }
375 };
376
377 let final_batch_to_send = if keep_partition_by_columns {
378 parted_batch
379 } else {
380 remove_partition_by_columns(&parted_batch, &partition_by)?
381 };
382
383 part_tx.send(final_batch_to_send).await.map_err(|_| {
385 internal_datafusion_err!("Unexpected error sending parted batch!")
386 })?;
387 }
388 }
389
390 Ok(())
391}
392
393pub struct FileMetadata {
394 pub path: Path,
395 pub size: FileSize,
396}
397
398fn compute_partition_keys_by_row<'a>(
399 rb: &'a RecordBatch,
400 partition_by: &'a [(String, DataType)],
401 null_partition_name: &str,
402) -> Result<Vec<Vec<Cow<'a, str>>>> {
403 let mut all_partition_values = Vec::with_capacity(partition_by.len());
404
405 const EPOCH_DAYS_FROM_CE: i32 = 719_163;
406
407 let schema = rb.schema();
413 for (col, _) in partition_by.iter() {
414 let mut partition_values = Vec::with_capacity(rb.num_rows());
415
416 let dtype = schema.field_with_name(col)?.data_type();
417 let col_array = rb.column_by_name(col).ok_or(exec_datafusion_err!(
418 "PartitionBy Column {} does not exist in source data! Got schema {schema}.",
419 col
420 ))?;
421 if col_array.logical_null_count() > 0 {
422 return exec_err!(
423 "NULL values are not supported for partition column '{col}'"
424 );
425 }
426
427 match dtype {
428 DataType::Utf8 => {
429 let array = as_string_array(col_array)?;
430 for i in 0..rb.num_rows() {
431 partition_values.push(Cow::from(array.value(i)));
432 }
433 }
434 DataType::LargeUtf8 => {
435 let array = as_large_string_array(col_array)?;
436 for i in 0..rb.num_rows() {
437 partition_values.push(Cow::from(array.value(i)));
438 }
439 }
440 DataType::Utf8View => {
441 let array = as_string_view_array(col_array)?;
442 for i in 0..rb.num_rows() {
443 partition_values.push(Cow::from(array.value(i)));
444 }
445 }
446 DataType::Boolean => {
447 let array = as_boolean_array(col_array)?;
448 for i in 0..rb.num_rows() {
449 partition_values.push(Cow::from(array.value(i).to_string()));
450 }
451 }
452 DataType::Date32 => {
453 let array = as_date32_array(col_array)?;
454 let format = "%Y-%m-%d";
456 for i in 0..rb.num_rows() {
457 let date = NaiveDate::from_num_days_from_ce_opt(
458 EPOCH_DAYS_FROM_CE + array.value(i),
459 )
460 .unwrap()
461 .format(format)
462 .to_string();
463 partition_values.push(Cow::from(date));
464 }
465 }
466 DataType::Date64 => {
467 let array = as_date64_array(col_array)?;
468 let format = "%Y-%m-%d";
470 for i in 0..rb.num_rows() {
471 let date = NaiveDate::from_num_days_from_ce_opt(
472 EPOCH_DAYS_FROM_CE + (array.value(i) / 86_400_000) as i32,
473 )
474 .unwrap()
475 .format(format)
476 .to_string();
477 partition_values.push(Cow::from(date));
478 }
479 }
480 DataType::Int8 => {
481 let array = as_int8_array(col_array)?;
482 for i in 0..rb.num_rows() {
483 partition_values.push(Cow::from(array.value(i).to_string()));
484 }
485 }
486 DataType::Int16 => {
487 let array = as_int16_array(col_array)?;
488 for i in 0..rb.num_rows() {
489 partition_values.push(Cow::from(array.value(i).to_string()));
490 }
491 }
492 DataType::Int32 => {
493 let array = as_int32_array(col_array)?;
494 for i in 0..rb.num_rows() {
495 partition_values.push(Cow::from(array.value(i).to_string()));
496 }
497 }
498 DataType::Int64 => {
499 let array = as_int64_array(col_array)?;
500 for i in 0..rb.num_rows() {
501 partition_values.push(Cow::from(array.value(i).to_string()));
502 }
503 }
504 DataType::UInt8 => {
505 let array = as_uint8_array(col_array)?;
506 for i in 0..rb.num_rows() {
507 partition_values.push(Cow::from(array.value(i).to_string()));
508 }
509 }
510 DataType::UInt16 => {
511 let array = as_uint16_array(col_array)?;
512 for i in 0..rb.num_rows() {
513 partition_values.push(Cow::from(array.value(i).to_string()));
514 }
515 }
516 DataType::UInt32 => {
517 let array = as_uint32_array(col_array)?;
518 for i in 0..rb.num_rows() {
519 partition_values.push(Cow::from(array.value(i).to_string()));
520 }
521 }
522 DataType::UInt64 => {
523 let array = as_uint64_array(col_array)?;
524 for i in 0..rb.num_rows() {
525 partition_values.push(Cow::from(array.value(i).to_string()));
526 }
527 }
528 DataType::Float16 => {
529 let array = as_float16_array(col_array)?;
530 for i in 0..rb.num_rows() {
531 partition_values.push(Cow::from(array.value(i).to_string()));
532 }
533 }
534 DataType::Float32 => {
535 let array = as_float32_array(col_array)?;
536 for i in 0..rb.num_rows() {
537 partition_values.push(Cow::from(array.value(i).to_string()));
538 }
539 }
540 DataType::Float64 => {
541 let array = as_float64_array(col_array)?;
542 for i in 0..rb.num_rows() {
543 partition_values.push(Cow::from(array.value(i).to_string()));
544 }
545 }
546 DataType::Dictionary(_, _) => {
547 downcast_dictionary_array!(
548 col_array => {
549 let array = col_array.downcast_dict::<StringArray>()
550 .ok_or(exec_datafusion_err!("it is not yet supported to write to hive partitions with datatype {}",
551 dtype))?;
552
553 for i in 0..rb.num_rows() {
554 partition_values.push(Cow::from(array.value(i)));
555 }
556 },
557 _ => unreachable!(),
558 )
559 }
560 _ => {
561 return not_impl_err!(
562 "it is not yet supported to write to hive partitions with datatype {}",
563 dtype
564 );
565 }
566 }
567
568 if !null_partition_name.is_empty()
569 && partition_values.iter().any(|v| v == null_partition_name)
570 {
571 return exec_err!(
572 "Cannot write value '{null_partition_name}' for partition column '{col}': \
573 it is the null partition name and would be read back as NULL"
574 );
575 }
576
577 all_partition_values.push(partition_values);
578 }
579
580 Ok(all_partition_values)
581}
582
583fn compute_take_arrays(
584 rb: &RecordBatch,
585 all_partition_values: &[Vec<Cow<str>>],
586) -> HashMap<Vec<String>, UInt64Builder> {
587 let mut take_map: HashMap<Vec<String>, UInt64Builder> = HashMap::new();
588 let mut part_key = vec![String::new(); all_partition_values.len()];
590 for i in 0..rb.num_rows() {
591 for (key, vals) in part_key.iter_mut().zip(all_partition_values) {
592 key.clear();
593 key.push_str(&vals[i]);
594 }
595 let builder = match take_map.get_mut(&part_key) {
596 Some(builder) => builder,
597 None => take_map.entry(part_key.clone()).or_default(),
598 };
599 builder.append_value(i as u64);
600 }
601 take_map
602}
603
604fn remove_partition_by_columns(
605 parted_batch: &RecordBatch,
606 partition_by: &[(String, DataType)],
607) -> Result<RecordBatch> {
608 let (non_part_cols, non_part_fields): (Vec<_>, Vec<_>) = parted_batch
609 .columns()
610 .iter()
611 .zip(parted_batch.schema().fields())
612 .filter_map(|(a, f)| {
613 if !partition_by.iter().any(|(s, _)| s == f.name()) {
614 Some((Arc::clone(a), (**f).clone()))
615 } else {
616 None
617 }
618 })
619 .unzip();
620
621 let non_part_schema = Schema::new(non_part_fields);
622 let final_batch_to_send =
623 RecordBatch::try_new(Arc::new(non_part_schema), non_part_cols)?;
624
625 Ok(final_batch_to_send)
626}
627
628fn compute_hive_style_file_path(
629 part_key: &[String],
630 partition_by: &[(String, DataType)],
631 write_id: &str,
632 file_extension: &str,
633 base_output_path: &ListingTableUrl,
634) -> Path {
635 let mut file_path = base_output_path.prefix().clone();
636 for j in 0..part_key.len() {
637 file_path = file_path.join(format!("{}={}", partition_by[j].0, part_key[j]));
638 }
639
640 file_path.join(format!("{write_id}.{file_extension}"))
641}
642
643#[cfg(test)]
644mod tests {
645 use super::*;
646 use arrow::array::{Array, ArrayRef, DictionaryArray, Int32Array};
647 use arrow::datatypes::Int32Type;
648 use datafusion_common::config::HIVE_DEFAULT_PARTITION_NAME;
649
650 fn partition_batch(column: ArrayRef) -> RecordBatch {
651 RecordBatch::try_from_iter_with_nullable([("p", column, true)]).unwrap()
652 }
653
654 #[test]
655 fn partition_keys_reject_null_values() {
656 let columns: Vec<ArrayRef> = vec![
657 Arc::new(Int32Array::from(vec![Some(0), None])),
658 Arc::new(StringArray::from(vec![Some(""), None])),
659 ];
660 for column in columns {
661 let partition_by = vec![("p".to_string(), column.data_type().clone())];
662 let batch = partition_batch(column);
663 let err = compute_partition_keys_by_row(
664 &batch,
665 &partition_by,
666 HIVE_DEFAULT_PARTITION_NAME,
667 )
668 .unwrap_err();
669 assert_eq!(
670 err.strip_backtrace(),
671 "Execution error: NULL values are not supported for partition column 'p'"
672 );
673 }
674 }
675
676 #[test]
677 fn partition_keys_accept_slice_without_nulls() {
678 let column = Int32Array::from(vec![None, Some(0), Some(1)]).slice(1, 2);
679 let batch = partition_batch(Arc::new(column));
680 let partition_by = vec![("p".to_string(), DataType::Int32)];
681 let keys = compute_partition_keys_by_row(
682 &batch,
683 &partition_by,
684 HIVE_DEFAULT_PARTITION_NAME,
685 )
686 .unwrap();
687 assert_eq!(keys, vec![vec![Cow::Borrowed("0"), Cow::Borrowed("1")]]);
688 }
689
690 fn dictionary_with_null_value() -> DictionaryArray<Int32Type> {
691 DictionaryArray::try_new(
692 Int32Array::from(vec![0, 1]),
693 Arc::new(StringArray::from(vec![Some("a"), None])),
694 )
695 .unwrap()
696 }
697
698 #[test]
699 fn partition_keys_reject_dictionary_null_values() {
700 let column = dictionary_with_null_value();
701 let partition_by = vec![("p".to_string(), column.data_type().clone())];
702 let batch = partition_batch(Arc::new(column));
703 let err = compute_partition_keys_by_row(
704 &batch,
705 &partition_by,
706 HIVE_DEFAULT_PARTITION_NAME,
707 )
708 .unwrap_err();
709 assert_eq!(
710 err.strip_backtrace(),
711 "Execution error: NULL values are not supported for partition column 'p'"
712 );
713 }
714
715 #[test]
716 fn partition_keys_reject_dictionary_null_keys() {
717 let column = DictionaryArray::<Int32Type>::try_new(
718 Int32Array::from(vec![Some(0), None]),
719 Arc::new(StringArray::from(vec!["a"])),
720 )
721 .unwrap();
722 let partition_by = vec![("p".to_string(), column.data_type().clone())];
723 let batch = partition_batch(Arc::new(column));
724 let err = compute_partition_keys_by_row(
725 &batch,
726 &partition_by,
727 HIVE_DEFAULT_PARTITION_NAME,
728 )
729 .unwrap_err();
730 assert_eq!(
731 err.strip_backtrace(),
732 "Execution error: NULL values are not supported for partition column 'p'"
733 );
734 }
735
736 #[test]
737 fn partition_keys_accept_unused_dictionary_null_values() {
738 let column = dictionary_with_null_value().slice(0, 1);
739 let partition_by = vec![("p".to_string(), column.data_type().clone())];
740 let batch = partition_batch(Arc::new(column));
741 let keys = compute_partition_keys_by_row(
742 &batch,
743 &partition_by,
744 HIVE_DEFAULT_PARTITION_NAME,
745 )
746 .unwrap();
747 assert_eq!(keys, vec![vec![Cow::Borrowed("a")]]);
748 }
749
750 #[test]
751 fn partition_keys_reject_null_partition_name() {
752 let columns: Vec<ArrayRef> = vec![
753 Arc::new(StringArray::from(vec!["a", HIVE_DEFAULT_PARTITION_NAME])),
754 Arc::new(DictionaryArray::<Int32Type>::new(
755 Int32Array::from(vec![0, 1]),
756 Arc::new(StringArray::from(vec!["a", HIVE_DEFAULT_PARTITION_NAME])),
757 )),
758 ];
759 for column in columns {
760 let partition_by = vec![("p".to_string(), column.data_type().clone())];
761 let batch = partition_batch(column);
762 let err = compute_partition_keys_by_row(
763 &batch,
764 &partition_by,
765 HIVE_DEFAULT_PARTITION_NAME,
766 )
767 .unwrap_err();
768 assert_eq!(
769 err.strip_backtrace(),
770 "Execution error: Cannot write value '__HIVE_DEFAULT_PARTITION__' for partition column 'p': it is the null partition name and would be read back as NULL"
771 );
772 }
773 }
774
775 #[test]
776 fn partition_keys_accept_null_partition_name_when_disabled() {
777 let column = StringArray::from(vec![HIVE_DEFAULT_PARTITION_NAME]);
778 let batch = partition_batch(Arc::new(column));
779 let partition_by = vec![("p".to_string(), DataType::Utf8)];
780 let keys = compute_partition_keys_by_row(&batch, &partition_by, "").unwrap();
781 assert_eq!(keys, vec![vec![Cow::Borrowed(HIVE_DEFAULT_PARTITION_NAME)]]);
782 }
783}