1use crate::arrow::util::pretty::pretty_format_batches_with_options;
8use arrow::array::{ArrayRef, RecordBatch};
9use arrow::error::ArrowError;
10use std::fmt::Display;
11use std::{error::Error, path::PathBuf};
12
13pub trait IntoArrayRef {
15 fn into_array_ref(self) -> ArrayRef;
16}
17
18pub fn format_batches(results: &[RecordBatch]) -> Result<impl Display, ArrowError> {
19 let datafusion_format_options = crate::config::FormatOptions::default();
20
21 let arrow_format_options: arrow::util::display::FormatOptions =
22 (&datafusion_format_options).try_into().unwrap();
23
24 pretty_format_batches_with_options(results, &arrow_format_options)
25}
26
27#[macro_export]
59macro_rules! assert_batches_eq {
60 ($EXPECTED_LINES: expr, $CHUNKS: expr) => {
61 let expected_lines: Vec<String> =
62 $EXPECTED_LINES.iter().map(|&s| s.into()).collect();
63
64 let formatted = $crate::test_util::format_batches($CHUNKS)
65 .unwrap()
66 .to_string();
67
68 let actual_lines: Vec<&str> = formatted.trim().lines().collect();
69
70 assert_eq!(
71 expected_lines, actual_lines,
72 "\n\nexpected:\n\n{:#?}\nactual:\n\n{:#?}\n\n",
73 expected_lines, actual_lines
74 );
75 };
76}
77
78pub fn batches_to_string(batches: &[RecordBatch]) -> String {
79 let actual = format_batches(batches).unwrap().to_string();
80
81 actual.trim().to_string()
82}
83
84pub fn batches_to_sort_string(batches: &[RecordBatch]) -> String {
85 let actual_lines = format_batches(batches).unwrap().to_string();
86
87 let mut actual_lines: Vec<&str> = actual_lines.trim().lines().collect();
88
89 let num_lines = actual_lines.len();
91 if num_lines > 3 {
92 actual_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()
93 }
94
95 actual_lines.join("\n")
96}
97
98#[macro_export]
108macro_rules! assert_batches_sorted_eq {
109 ($EXPECTED_LINES: expr, $CHUNKS: expr) => {
110 let mut expected_lines: Vec<String> =
111 $EXPECTED_LINES.iter().map(|&s| s.into()).collect();
112
113 let num_lines = expected_lines.len();
115 if num_lines > 3 {
116 expected_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()
117 }
118
119 let formatted = $crate::test_util::format_batches($CHUNKS)
120 .unwrap()
121 .to_string();
122 let mut actual_lines: Vec<&str> = formatted.trim().lines().collect();
125
126 let num_lines = actual_lines.len();
128 if num_lines > 3 {
129 actual_lines.as_mut_slice()[2..num_lines - 1].sort_unstable()
130 }
131
132 assert_eq!(
133 expected_lines, actual_lines,
134 "\n\nexpected:\n\n{:#?}\nactual:\n\n{:#?}\n\n",
135 expected_lines, actual_lines
136 );
137 };
138}
139
140#[macro_export]
150macro_rules! assert_contains {
151 ($ACTUAL: expr, $EXPECTED: expr) => {
152 let actual_value: String = $ACTUAL.into();
153 let expected_value: String = $EXPECTED.into();
154 assert!(
155 actual_value.contains(&expected_value),
156 "Can not find expected in actual.\n\nExpected:\n{}\n\nActual:\n{}",
157 expected_value,
158 actual_value
159 );
160 };
161}
162
163#[macro_export]
173macro_rules! assert_not_contains {
174 ($ACTUAL: expr, $UNEXPECTED: expr) => {
175 let actual_value: String = $ACTUAL.into();
176 let unexpected_value: String = $UNEXPECTED.into();
177 assert!(
178 !actual_value.contains(&unexpected_value),
179 "Found unexpected in actual.\n\nUnexpected:\n{}\n\nActual:\n{}",
180 unexpected_value,
181 actual_value
182 );
183 };
184}
185
186pub fn datafusion_test_data() -> String {
200 match get_data_dir("DATAFUSION_TEST_DATA", "../../datafusion/core/tests/data") {
201 Ok(pb) => pb.display().to_string(),
202 Err(err) => panic!("failed to get arrow data dir: {err}"),
203 }
204}
205
206pub fn arrow_test_data() -> String {
221 match get_data_dir("ARROW_TEST_DATA", "../../testing/data") {
222 Ok(pb) => pb.display().to_string(),
223 Err(err) => panic!("failed to get arrow data dir: {err}"),
224 }
225}
226
227#[cfg(feature = "parquet")]
243pub fn parquet_test_data() -> String {
244 match get_data_dir("PARQUET_TEST_DATA", "../../parquet-testing/data") {
245 Ok(pb) => {
246 let mut path = pb.display().to_string();
247 if cfg!(target_os = "windows") {
248 path = path.replace('\\', "/");
250 }
251 path
252 }
253 Err(err) => panic!("failed to get parquet data dir: {err}"),
254 }
255}
256
257pub fn get_data_dir(
267 udf_env: &str,
268 submodule_data: &str,
269) -> Result<PathBuf, Box<dyn Error>> {
270 if let Ok(dir) = std::env::var(udf_env) {
272 let trimmed = dir.trim().to_string();
273 if !trimmed.is_empty() {
274 let pb = PathBuf::from(trimmed);
275 if pb.is_dir() {
276 return Ok(pb);
277 } else {
278 return Err(format!(
279 "the data dir `{}` defined by env {} not found",
280 pb.display(),
281 udf_env
282 )
283 .into());
284 }
285 }
286 }
287
288 let dir = env!("CARGO_MANIFEST_DIR");
294
295 let pb = PathBuf::from(dir).join(submodule_data);
296 if pb.is_dir() {
297 Ok(pb)
298 } else {
299 Err(format!(
300 "env `{}` is undefined or has empty value, and the pre-defined data dir `{}` not found\n\
301 HINT: try running `git submodule update --init`",
302 udf_env,
303 pb.display(),
304 ).into())
305 }
306}
307
308#[macro_export]
309macro_rules! create_array {
310 (Boolean, $values: expr) => {
311 std::sync::Arc::new($crate::arrow::array::BooleanArray::from($values))
312 };
313 (Int8, $values: expr) => {
314 std::sync::Arc::new($crate::arrow::array::Int8Array::from($values))
315 };
316 (Int16, $values: expr) => {
317 std::sync::Arc::new($crate::arrow::array::Int16Array::from($values))
318 };
319 (Int32, $values: expr) => {
320 std::sync::Arc::new($crate::arrow::array::Int32Array::from($values))
321 };
322 (Int64, $values: expr) => {
323 std::sync::Arc::new($crate::arrow::array::Int64Array::from($values))
324 };
325 (UInt8, $values: expr) => {
326 std::sync::Arc::new($crate::arrow::array::UInt8Array::from($values))
327 };
328 (UInt16, $values: expr) => {
329 std::sync::Arc::new($crate::arrow::array::UInt16Array::from($values))
330 };
331 (UInt32, $values: expr) => {
332 std::sync::Arc::new($crate::arrow::array::UInt32Array::from($values))
333 };
334 (UInt64, $values: expr) => {
335 std::sync::Arc::new($crate::arrow::array::UInt64Array::from($values))
336 };
337 (Float16, $values: expr) => {
338 std::sync::Arc::new($crate::arrow::array::Float16Array::from($values))
339 };
340 (Float32, $values: expr) => {
341 std::sync::Arc::new($crate::arrow::array::Float32Array::from($values))
342 };
343 (Float64, $values: expr) => {
344 std::sync::Arc::new($crate::arrow::array::Float64Array::from($values))
345 };
346 (Utf8, $values: expr) => {
347 std::sync::Arc::new($crate::arrow::array::StringArray::from($values))
348 };
349}
350
351#[deprecated(since = "55.0.0", note = "Use `arrow::array::record_batch` instead")]
368#[macro_export]
369macro_rules! record_batch {
370 ($(($name: expr, $type: ident, $values: expr)),*) => {
371 {
372 let schema = std::sync::Arc::new($crate::arrow::datatypes::Schema::new(vec![
373 $(
374 $crate::arrow::datatypes::Field::new($name, $crate::arrow::datatypes::DataType::$type, true),
375 )*
376 ]));
377
378 let batch = $crate::arrow::array::RecordBatch::try_new(
379 schema,
380 vec![$(
381 $crate::create_array!($type, $values),
382 )*]
383 );
384
385 batch
386 }
387 }
388}
389
390pub mod array_conversion {
391 use arrow::array::ArrayRef;
392
393 use super::IntoArrayRef;
394
395 impl IntoArrayRef for Vec<bool> {
396 fn into_array_ref(self) -> ArrayRef {
397 create_array!(Boolean, self)
398 }
399 }
400
401 impl IntoArrayRef for Vec<Option<bool>> {
402 fn into_array_ref(self) -> ArrayRef {
403 create_array!(Boolean, self)
404 }
405 }
406
407 impl IntoArrayRef for &[bool] {
408 fn into_array_ref(self) -> ArrayRef {
409 create_array!(Boolean, self.to_vec())
410 }
411 }
412
413 impl IntoArrayRef for &[Option<bool>] {
414 fn into_array_ref(self) -> ArrayRef {
415 create_array!(Boolean, self.to_vec())
416 }
417 }
418
419 impl IntoArrayRef for Vec<i8> {
420 fn into_array_ref(self) -> ArrayRef {
421 create_array!(Int8, self)
422 }
423 }
424
425 impl IntoArrayRef for Vec<Option<i8>> {
426 fn into_array_ref(self) -> ArrayRef {
427 create_array!(Int8, self)
428 }
429 }
430
431 impl IntoArrayRef for &[i8] {
432 fn into_array_ref(self) -> ArrayRef {
433 create_array!(Int8, self.to_vec())
434 }
435 }
436
437 impl IntoArrayRef for &[Option<i8>] {
438 fn into_array_ref(self) -> ArrayRef {
439 create_array!(Int8, self.to_vec())
440 }
441 }
442
443 impl IntoArrayRef for Vec<i16> {
444 fn into_array_ref(self) -> ArrayRef {
445 create_array!(Int16, self)
446 }
447 }
448
449 impl IntoArrayRef for Vec<Option<i16>> {
450 fn into_array_ref(self) -> ArrayRef {
451 create_array!(Int16, self)
452 }
453 }
454
455 impl IntoArrayRef for &[i16] {
456 fn into_array_ref(self) -> ArrayRef {
457 create_array!(Int16, self.to_vec())
458 }
459 }
460
461 impl IntoArrayRef for &[Option<i16>] {
462 fn into_array_ref(self) -> ArrayRef {
463 create_array!(Int16, self.to_vec())
464 }
465 }
466
467 impl IntoArrayRef for Vec<i32> {
468 fn into_array_ref(self) -> ArrayRef {
469 create_array!(Int32, self)
470 }
471 }
472
473 impl IntoArrayRef for Vec<Option<i32>> {
474 fn into_array_ref(self) -> ArrayRef {
475 create_array!(Int32, self)
476 }
477 }
478
479 impl IntoArrayRef for &[i32] {
480 fn into_array_ref(self) -> ArrayRef {
481 create_array!(Int32, self.to_vec())
482 }
483 }
484
485 impl IntoArrayRef for &[Option<i32>] {
486 fn into_array_ref(self) -> ArrayRef {
487 create_array!(Int32, self.to_vec())
488 }
489 }
490
491 impl IntoArrayRef for Vec<i64> {
492 fn into_array_ref(self) -> ArrayRef {
493 create_array!(Int64, self)
494 }
495 }
496
497 impl IntoArrayRef for Vec<Option<i64>> {
498 fn into_array_ref(self) -> ArrayRef {
499 create_array!(Int64, self)
500 }
501 }
502
503 impl IntoArrayRef for &[i64] {
504 fn into_array_ref(self) -> ArrayRef {
505 create_array!(Int64, self.to_vec())
506 }
507 }
508
509 impl IntoArrayRef for &[Option<i64>] {
510 fn into_array_ref(self) -> ArrayRef {
511 create_array!(Int64, self.to_vec())
512 }
513 }
514
515 impl IntoArrayRef for Vec<u8> {
516 fn into_array_ref(self) -> ArrayRef {
517 create_array!(UInt8, self)
518 }
519 }
520
521 impl IntoArrayRef for Vec<Option<u8>> {
522 fn into_array_ref(self) -> ArrayRef {
523 create_array!(UInt8, self)
524 }
525 }
526
527 impl IntoArrayRef for &[u8] {
528 fn into_array_ref(self) -> ArrayRef {
529 create_array!(UInt8, self.to_vec())
530 }
531 }
532
533 impl IntoArrayRef for &[Option<u8>] {
534 fn into_array_ref(self) -> ArrayRef {
535 create_array!(UInt8, self.to_vec())
536 }
537 }
538
539 impl IntoArrayRef for Vec<u16> {
540 fn into_array_ref(self) -> ArrayRef {
541 create_array!(UInt16, self)
542 }
543 }
544
545 impl IntoArrayRef for Vec<Option<u16>> {
546 fn into_array_ref(self) -> ArrayRef {
547 create_array!(UInt16, self)
548 }
549 }
550
551 impl IntoArrayRef for &[u16] {
552 fn into_array_ref(self) -> ArrayRef {
553 create_array!(UInt16, self.to_vec())
554 }
555 }
556
557 impl IntoArrayRef for &[Option<u16>] {
558 fn into_array_ref(self) -> ArrayRef {
559 create_array!(UInt16, self.to_vec())
560 }
561 }
562
563 impl IntoArrayRef for Vec<u32> {
564 fn into_array_ref(self) -> ArrayRef {
565 create_array!(UInt32, self)
566 }
567 }
568
569 impl IntoArrayRef for Vec<Option<u32>> {
570 fn into_array_ref(self) -> ArrayRef {
571 create_array!(UInt32, self)
572 }
573 }
574
575 impl IntoArrayRef for &[u32] {
576 fn into_array_ref(self) -> ArrayRef {
577 create_array!(UInt32, self.to_vec())
578 }
579 }
580
581 impl IntoArrayRef for &[Option<u32>] {
582 fn into_array_ref(self) -> ArrayRef {
583 create_array!(UInt32, self.to_vec())
584 }
585 }
586
587 impl IntoArrayRef for Vec<u64> {
588 fn into_array_ref(self) -> ArrayRef {
589 create_array!(UInt64, self)
590 }
591 }
592
593 impl IntoArrayRef for Vec<Option<u64>> {
594 fn into_array_ref(self) -> ArrayRef {
595 create_array!(UInt64, self)
596 }
597 }
598
599 impl IntoArrayRef for &[u64] {
600 fn into_array_ref(self) -> ArrayRef {
601 create_array!(UInt64, self.to_vec())
602 }
603 }
604
605 impl IntoArrayRef for &[Option<u64>] {
606 fn into_array_ref(self) -> ArrayRef {
607 create_array!(UInt64, self.to_vec())
608 }
609 }
610
611 impl IntoArrayRef for Vec<half::f16> {
612 fn into_array_ref(self) -> ArrayRef {
613 create_array!(Float16, self)
614 }
615 }
616
617 impl IntoArrayRef for Vec<Option<half::f16>> {
618 fn into_array_ref(self) -> ArrayRef {
619 create_array!(Float16, self)
620 }
621 }
622
623 impl IntoArrayRef for &[half::f16] {
624 fn into_array_ref(self) -> ArrayRef {
625 create_array!(Float16, self.to_vec())
626 }
627 }
628
629 impl IntoArrayRef for &[Option<half::f16>] {
630 fn into_array_ref(self) -> ArrayRef {
631 create_array!(Float16, self.to_vec())
632 }
633 }
634
635 impl IntoArrayRef for Vec<f32> {
636 fn into_array_ref(self) -> ArrayRef {
637 create_array!(Float32, self)
638 }
639 }
640
641 impl IntoArrayRef for Vec<Option<f32>> {
642 fn into_array_ref(self) -> ArrayRef {
643 create_array!(Float32, self)
644 }
645 }
646
647 impl IntoArrayRef for &[f32] {
648 fn into_array_ref(self) -> ArrayRef {
649 create_array!(Float32, self.to_vec())
650 }
651 }
652
653 impl IntoArrayRef for &[Option<f32>] {
654 fn into_array_ref(self) -> ArrayRef {
655 create_array!(Float32, self.to_vec())
656 }
657 }
658
659 impl IntoArrayRef for Vec<f64> {
660 fn into_array_ref(self) -> ArrayRef {
661 create_array!(Float64, self)
662 }
663 }
664
665 impl IntoArrayRef for Vec<Option<f64>> {
666 fn into_array_ref(self) -> ArrayRef {
667 create_array!(Float64, self)
668 }
669 }
670
671 impl IntoArrayRef for &[f64] {
672 fn into_array_ref(self) -> ArrayRef {
673 create_array!(Float64, self.to_vec())
674 }
675 }
676
677 impl IntoArrayRef for &[Option<f64>] {
678 fn into_array_ref(self) -> ArrayRef {
679 create_array!(Float64, self.to_vec())
680 }
681 }
682
683 impl IntoArrayRef for Vec<&str> {
684 fn into_array_ref(self) -> ArrayRef {
685 create_array!(Utf8, self)
686 }
687 }
688
689 impl IntoArrayRef for Vec<Option<&str>> {
690 fn into_array_ref(self) -> ArrayRef {
691 create_array!(Utf8, self)
692 }
693 }
694
695 impl IntoArrayRef for &[&str] {
696 fn into_array_ref(self) -> ArrayRef {
697 create_array!(Utf8, self.to_vec())
698 }
699 }
700
701 impl IntoArrayRef for &[Option<&str>] {
702 fn into_array_ref(self) -> ArrayRef {
703 create_array!(Utf8, self.to_vec())
704 }
705 }
706
707 impl IntoArrayRef for Vec<String> {
708 fn into_array_ref(self) -> ArrayRef {
709 create_array!(Utf8, self)
710 }
711 }
712
713 impl IntoArrayRef for Vec<Option<String>> {
714 fn into_array_ref(self) -> ArrayRef {
715 create_array!(Utf8, self)
716 }
717 }
718
719 impl IntoArrayRef for &[String] {
720 fn into_array_ref(self) -> ArrayRef {
721 create_array!(Utf8, self.to_vec())
722 }
723 }
724
725 impl IntoArrayRef for &[Option<String>] {
726 fn into_array_ref(self) -> ArrayRef {
727 create_array!(Utf8, self.to_vec())
728 }
729 }
730}
731
732#[cfg(test)]
733mod tests {
734 use crate::cast::{as_float64_array, as_int32_array, as_string_array};
735 use crate::error::Result;
736
737 use super::*;
738 use std::env;
739
740 #[test]
741 fn test_data_dir() {
742 let udf_env = "get_data_dir";
743 let cwd = env::current_dir().unwrap();
744
745 let existing_pb = cwd.join("..");
746 let existing = existing_pb.display().to_string();
747 let existing_str = existing.as_str();
748
749 let non_existing = cwd.join("non-existing-dir").display().to_string();
750 let non_existing_str = non_existing.as_str();
751
752 unsafe {
753 env::set_var(udf_env, non_existing_str);
754 let res = get_data_dir(udf_env, existing_str);
755 assert!(res.is_err());
756
757 env::set_var(udf_env, "");
758 let res = get_data_dir(udf_env, existing_str);
759 assert!(res.is_ok());
760 assert_eq!(res.unwrap(), existing_pb);
761
762 env::set_var(udf_env, " ");
763 let res = get_data_dir(udf_env, existing_str);
764 assert!(res.is_ok());
765 assert_eq!(res.unwrap(), existing_pb);
766
767 env::set_var(udf_env, existing_str);
768 let res = get_data_dir(udf_env, existing_str);
769 assert!(res.is_ok());
770 assert_eq!(res.unwrap(), existing_pb);
771
772 env::remove_var(udf_env);
773 let res = get_data_dir(udf_env, non_existing_str);
774 assert!(res.is_err());
775
776 let res = get_data_dir(udf_env, existing_str);
777 assert!(res.is_ok());
778 assert_eq!(res.unwrap(), existing_pb);
779 }
780 }
781
782 #[test]
783 #[cfg(feature = "parquet")]
784 fn test_happy() {
785 let res = arrow_test_data();
786 assert!(PathBuf::from(res).is_dir());
787
788 let res = parquet_test_data();
789 assert!(PathBuf::from(res).is_dir());
790 }
791
792 #[test]
793 #[expect(
794 deprecated,
795 reason = "testing the deprecated record_batch! macro itself"
796 )]
797 fn test_create_record_batch() -> Result<()> {
798 use arrow::array::Array;
799
800 let batch = record_batch!(
801 ("a", Int32, vec![1, 2, 3, 4]),
802 ("b", Float64, vec![Some(4.0), None, Some(5.0), None]),
803 ("c", Utf8, vec!["alpha", "beta", "gamma", "delta"])
804 )?;
805
806 assert_eq!(3, batch.num_columns());
807 assert_eq!(4, batch.num_rows());
808
809 let values: Vec<_> = as_int32_array(batch.column(0))?
810 .values()
811 .iter()
812 .map(|v| v.to_owned())
813 .collect();
814 assert_eq!(values, vec![1, 2, 3, 4]);
815
816 let values: Vec<_> = as_float64_array(batch.column(1))?
817 .values()
818 .iter()
819 .map(|v| v.to_owned())
820 .collect();
821 assert_eq!(values, vec![4.0, 0.0, 5.0, 0.0]);
822
823 let nulls: Vec<_> = as_float64_array(batch.column(1))?
824 .nulls()
825 .unwrap()
826 .iter()
827 .collect();
828 assert_eq!(nulls, vec![true, false, true, false]);
829
830 let values: Vec<_> = as_string_array(batch.column(2))?.iter().flatten().collect();
831 assert_eq!(values, vec!["alpha", "beta", "gamma", "delta"]);
832
833 Ok(())
834 }
835}