Skip to main content

arrow/util/
data_gen.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Utilities to generate random arrays and batches
19
20use std::sync::Arc;
21
22use rand::{
23    Rng, RngExt,
24    distr::uniform::{SampleRange, SampleUniform},
25};
26
27use crate::array::*;
28use crate::error::{ArrowError, Result};
29use crate::{
30    buffer::{Buffer, MutableBuffer},
31    datatypes::*,
32};
33
34use super::{bench_util::*, bit_util, test_util::seedable_rng};
35
36/// Create a random [RecordBatch] from a schema
37pub fn create_random_batch(
38    schema: SchemaRef,
39    size: usize,
40    null_density: f32,
41    true_density: f32,
42) -> Result<RecordBatch> {
43    let columns = schema
44        .fields()
45        .iter()
46        .map(|field| create_random_array(field, size, null_density, true_density))
47        .collect::<Result<Vec<ArrayRef>>>()?;
48
49    RecordBatch::try_new_with_options(
50        schema,
51        columns,
52        &RecordBatchOptions::new().with_match_field_names(false),
53    )
54}
55
56/// Create a random [ArrayRef] from a [DataType] with a length,
57/// null density and true density (for [BooleanArray]).
58///
59/// # Arguments
60///
61/// * `field` - The field containing the data type for which to create a random array
62/// * `size` - The number of elements in the generated array
63/// * `null_density` - The approximate fraction of null values in the resulting array (0.0 to 1.0)
64/// * `true_density` - The approximate fraction of true values in boolean arrays (0.0 to 1.0)
65///
66pub fn create_random_array(
67    field: &Field,
68    size: usize,
69    mut null_density: f32,
70    true_density: f32,
71) -> Result<ArrayRef> {
72    // Override nullability in case of not nested and not dictionary
73    // For nested we don't want to override as we want to keep the nullability for the children
74    // For dictionary it handle the nullability internally
75    if !field.data_type().is_nested() && !matches!(field.data_type(), Dictionary(_, _)) {
76        // Override null density with 0.0 if the array is non-nullable
77        null_density = match field.is_nullable() {
78            true => null_density,
79            false => 0.0,
80        };
81    }
82
83    use DataType::*;
84    let array = match field.data_type() {
85        Null => Arc::new(NullArray::new(size)) as ArrayRef,
86        Boolean => Arc::new(create_boolean_array(size, null_density, true_density)),
87        Int8 => Arc::new(create_primitive_array::<Int8Type>(size, null_density)),
88        Int16 => Arc::new(create_primitive_array::<Int16Type>(size, null_density)),
89        Int32 => Arc::new(create_primitive_array::<Int32Type>(size, null_density)),
90        Int64 => Arc::new(create_primitive_array::<Int64Type>(size, null_density)),
91        UInt8 => Arc::new(create_primitive_array::<UInt8Type>(size, null_density)),
92        UInt16 => Arc::new(create_primitive_array::<UInt16Type>(size, null_density)),
93        UInt32 => Arc::new(create_primitive_array::<UInt32Type>(size, null_density)),
94        UInt64 => Arc::new(create_primitive_array::<UInt64Type>(size, null_density)),
95        Float16 => Arc::new(create_nullable_f16_array(size, null_density)),
96        Float32 => Arc::new(create_primitive_array::<Float32Type>(size, null_density)),
97        Float64 => Arc::new(create_primitive_array::<Float64Type>(size, null_density)),
98        Timestamp(unit, tz) => match unit {
99            TimeUnit::Second => Arc::new(
100                create_random_temporal_array::<TimestampSecondType>(size, null_density)
101                    .with_timezone_opt(tz.clone()),
102            ) as ArrayRef,
103            TimeUnit::Millisecond => Arc::new(
104                create_random_temporal_array::<TimestampMillisecondType>(size, null_density)
105                    .with_timezone_opt(tz.clone()),
106            ),
107            TimeUnit::Microsecond => Arc::new(
108                create_random_temporal_array::<TimestampMicrosecondType>(size, null_density)
109                    .with_timezone_opt(tz.clone()),
110            ),
111            TimeUnit::Nanosecond => Arc::new(
112                create_random_temporal_array::<TimestampNanosecondType>(size, null_density)
113                    .with_timezone_opt(tz.clone()),
114            ),
115        },
116        Date32 => Arc::new(create_random_temporal_array::<Date32Type>(
117            size,
118            null_density,
119        )),
120        Date64 => Arc::new(create_random_temporal_array::<Date64Type>(
121            size,
122            null_density,
123        )),
124        Time32(unit) => match unit {
125            TimeUnit::Second => Arc::new(create_random_temporal_array::<Time32SecondType>(
126                size,
127                null_density,
128            )) as ArrayRef,
129            TimeUnit::Millisecond => Arc::new(
130                create_random_temporal_array::<Time32MillisecondType>(size, null_density),
131            ),
132            _ => {
133                return Err(ArrowError::InvalidArgumentError(format!(
134                    "Unsupported unit {unit:?} for Time32"
135                )));
136            }
137        },
138        Time64(unit) => match unit {
139            TimeUnit::Microsecond => Arc::new(
140                create_random_temporal_array::<Time64MicrosecondType>(size, null_density),
141            ) as ArrayRef,
142            TimeUnit::Nanosecond => Arc::new(create_random_temporal_array::<Time64NanosecondType>(
143                size,
144                null_density,
145            )),
146            _ => {
147                return Err(ArrowError::InvalidArgumentError(format!(
148                    "Unsupported unit {unit:?} for Time64"
149                )));
150            }
151        },
152        Utf8 => Arc::new(create_string_array::<i32>(size, null_density)),
153        LargeUtf8 => Arc::new(create_string_array::<i64>(size, null_density)),
154        Utf8View => Arc::new(create_string_view_array_with_len(
155            size,
156            null_density,
157            4,
158            false,
159        )),
160        Binary => Arc::new(create_binary_array::<i32>(size, null_density)),
161        LargeBinary => Arc::new(create_binary_array::<i64>(size, null_density)),
162        FixedSizeBinary(len) => {
163            let len = TryInto::<usize>::try_into(*len).map_err(|_| {
164                ArrowError::InvalidArgumentError(format!("cannot use FixedSizeBinary({len})"))
165            })?;
166            Arc::new(create_fsb_array(size, null_density, len))
167        }
168        BinaryView => Arc::new(
169            create_string_view_array_with_len(size, null_density, 4, false).to_binary_view(),
170        ),
171        List(_) => create_random_list_array(field, size, null_density, true_density)?,
172        LargeList(_) => create_random_list_array(field, size, null_density, true_density)?,
173        Struct(_) => create_random_struct_array(field, size, null_density, true_density)?,
174        d @ Dictionary(_, value_type) if crate::compute::can_cast_types(value_type, d) => {
175            let f = Field::new(
176                field.name(),
177                value_type.as_ref().clone(),
178                field.is_nullable(),
179            );
180            let v = create_random_array(&f, size, null_density, true_density)?;
181            crate::compute::cast(&v, d)?
182        }
183        Map(_, _) => create_random_map_array(field, size, null_density, true_density)?,
184        Decimal32(_, _) => create_random_decimal_array(field, size, null_density)?,
185        Decimal64(_, _) => create_random_decimal_array(field, size, null_density)?,
186        Decimal128(_, _) => create_random_decimal_array(field, size, null_density)?,
187        Decimal256(_, _) => create_random_decimal_array(field, size, null_density)?,
188        RunEndEncoded(index, value) => {
189            create_random_run_end_encoded_array(index, value, size, null_density, true_density)?
190        }
191        other => {
192            return Err(ArrowError::NotYetImplemented(format!(
193                "Generating random arrays not yet implemented for {other:?}"
194            )));
195        }
196    };
197
198    if !field.is_nullable() {
199        assert_eq!(array.null_count(), 0);
200    }
201
202    Ok(array)
203}
204
205#[inline]
206fn create_random_decimal_array(field: &Field, size: usize, null_density: f32) -> Result<ArrayRef> {
207    let mut rng = seedable_rng();
208
209    match field.data_type() {
210        DataType::Decimal32(precision, scale) => {
211            let values = (0..size)
212                .map(|_| {
213                    if rng.random::<f32>() < null_density {
214                        None
215                    } else {
216                        Some(rng.random::<i32>())
217                    }
218                })
219                .collect::<Vec<_>>();
220            Ok(Arc::new(
221                Decimal32Array::from(values).with_precision_and_scale(*precision, *scale)?,
222            ))
223        }
224        DataType::Decimal64(precision, scale) => {
225            let values = (0..size)
226                .map(|_| {
227                    if rng.random::<f32>() < null_density {
228                        None
229                    } else {
230                        Some(rng.random::<i64>())
231                    }
232                })
233                .collect::<Vec<_>>();
234            Ok(Arc::new(
235                Decimal64Array::from(values).with_precision_and_scale(*precision, *scale)?,
236            ))
237        }
238        DataType::Decimal128(precision, scale) => {
239            let values = (0..size)
240                .map(|_| {
241                    if rng.random::<f32>() < null_density {
242                        None
243                    } else {
244                        Some(rng.random::<i128>())
245                    }
246                })
247                .collect::<Vec<_>>();
248            Ok(Arc::new(
249                Decimal128Array::from(values).with_precision_and_scale(*precision, *scale)?,
250            ))
251        }
252        DataType::Decimal256(precision, scale) => {
253            let values = (0..size)
254                .map(|_| {
255                    if rng.random::<f32>() < null_density {
256                        None
257                    } else {
258                        Some(i256::from_parts(rng.random::<u128>(), rng.random::<i128>()))
259                    }
260                })
261                .collect::<Vec<_>>();
262            Ok(Arc::new(
263                Decimal256Array::from(values).with_precision_and_scale(*precision, *scale)?,
264            ))
265        }
266        _ => Err(ArrowError::InvalidArgumentError(format!(
267            "Cannot create decimal array for field {field}"
268        ))),
269    }
270}
271#[inline]
272fn create_random_run_end_encoded_array(
273    index: &Field,
274    value: &Field,
275    size: usize,
276    null_density: f32,
277    true_density: f32,
278) -> Result<ArrayRef> {
279    const MIN_RUN: usize = 8;
280    const MAX_RUN: usize = 32;
281
282    let mut rng = seedable_rng();
283    let mut run_lengths: Vec<usize> = Vec::new();
284    let mut remaining = size;
285    while remaining > 0 {
286        let len = rng.random_range(MIN_RUN..=MAX_RUN).min(remaining);
287        run_lengths.push(len);
288        remaining -= len;
289    }
290    let num_runs = run_lengths.len();
291
292    let mut cumulative: i64 = 0;
293    let run_ends_i64: Vec<i64> = run_lengths
294        .iter()
295        .map(|&l| {
296            cumulative += l as i64;
297            cumulative
298        })
299        .collect();
300
301    let values = create_random_array(value, num_runs, null_density, true_density)?;
302
303    match index.data_type() {
304        DataType::Int16 => {
305            let run_ends: Int16Array = run_ends_i64.iter().map(|&v| v as i16).collect();
306            Ok(Arc::new(RunArray::<Int16Type>::try_new(
307                &run_ends, &values,
308            )?))
309        }
310        DataType::Int32 => {
311            let run_ends: Int32Array = run_ends_i64.iter().map(|&v| v as i32).collect();
312            Ok(Arc::new(RunArray::<Int32Type>::try_new(
313                &run_ends, &values,
314            )?))
315        }
316        DataType::Int64 => {
317            let run_ends: Int64Array = run_ends_i64.iter().copied().collect();
318            Ok(Arc::new(RunArray::<Int64Type>::try_new(
319                &run_ends, &values,
320            )?))
321        }
322        other => Err(ArrowError::InvalidArgumentError(format!(
323            "Unsupported run-ends type for REE: {other:?}"
324        ))),
325    }
326}
327
328#[inline]
329fn create_random_list_array(
330    field: &Field,
331    size: usize,
332    null_density: f32,
333    true_density: f32,
334) -> Result<ArrayRef> {
335    // Override null density with 0.0 if the array is non-nullable
336    let list_null_density = match field.is_nullable() {
337        true => null_density,
338        false => 0.0,
339    };
340    let list_field;
341    let (offsets, child_len) = match field.data_type() {
342        DataType::List(f) => {
343            let (offsets, child_len) = create_random_offsets::<i32>(size, 0, 5);
344            list_field = f;
345            (Buffer::from(offsets.to_byte_slice()), child_len as usize)
346        }
347        DataType::LargeList(f) => {
348            let (offsets, child_len) = create_random_offsets::<i64>(size, 0, 5);
349            list_field = f;
350            (Buffer::from(offsets.to_byte_slice()), child_len as usize)
351        }
352        _ => {
353            return Err(ArrowError::InvalidArgumentError(format!(
354                "Cannot create list array for field {field}"
355            )));
356        }
357    };
358
359    // Create list's child data
360    let child_array = create_random_array(list_field, child_len, null_density, true_density)?;
361    let child_data = child_array.to_data();
362    // Create list's null buffers, if it is nullable
363    let null_buffer = match field.is_nullable() {
364        true => Some(create_random_null_buffer(size, list_null_density)),
365        false => None,
366    };
367    let list_data = unsafe {
368        ArrayData::new_unchecked(
369            field.data_type().clone(),
370            size,
371            None,
372            null_buffer,
373            0,
374            vec![offsets],
375            vec![child_data],
376        )
377    };
378    Ok(make_array(list_data))
379}
380
381#[inline]
382fn create_random_struct_array(
383    field: &Field,
384    size: usize,
385    null_density: f32,
386    true_density: f32,
387) -> Result<ArrayRef> {
388    let DataType::Struct(struct_fields) = field.data_type() else {
389        return Err(ArrowError::InvalidArgumentError(format!(
390            "Cannot create struct array for field {field}"
391        )));
392    };
393
394    let child_arrays = struct_fields
395        .iter()
396        .map(|struct_field| create_random_array(struct_field, size, null_density, true_density))
397        .collect::<Result<Vec<_>>>()?;
398
399    let null_buffer = match field.is_nullable() {
400        true => {
401            let nulls = arrow_buffer::BooleanBuffer::new(
402                create_random_null_buffer(size, null_density),
403                0,
404                size,
405            );
406            Some(nulls.into())
407        }
408        false => None,
409    };
410
411    Ok(Arc::new(StructArray::try_new(
412        struct_fields.clone(),
413        child_arrays,
414        null_buffer,
415    )?))
416}
417
418#[inline]
419fn create_random_map_array(
420    field: &Field,
421    size: usize,
422    null_density: f32,
423    true_density: f32,
424) -> Result<ArrayRef> {
425    // Override null density with 0.0 if the array is non-nullable
426    let map_null_density = match field.is_nullable() {
427        true => null_density,
428        false => 0.0,
429    };
430
431    let DataType::Map(entries_field, _) = field.data_type() else {
432        return Err(ArrowError::InvalidArgumentError(format!(
433            "Cannot create map array for field {field:?}"
434        )));
435    };
436
437    let (offsets, child_len) = create_random_offsets::<i32>(size, 0, 5);
438    let offsets = Buffer::from(offsets.to_byte_slice());
439
440    let entries = create_random_array(
441        entries_field,
442        child_len as usize,
443        null_density,
444        true_density,
445    )?
446    .to_data();
447
448    let null_buffer = match field.is_nullable() {
449        true => Some(create_random_null_buffer(size, map_null_density)),
450        false => None,
451    };
452
453    let map_data = unsafe {
454        ArrayData::new_unchecked(
455            field.data_type().clone(),
456            size,
457            None,
458            null_buffer,
459            0,
460            vec![offsets],
461            vec![entries],
462        )
463    };
464    Ok(make_array(map_data))
465}
466
467/// Generate random offsets for list arrays
468fn create_random_offsets<T: OffsetSizeTrait + SampleUniform>(
469    size: usize,
470    min: T,
471    max: T,
472) -> (Vec<T>, T) {
473    let rng = &mut seedable_rng();
474
475    let mut current_offset = T::zero();
476
477    let mut offsets = Vec::with_capacity(size + 1);
478    offsets.push(current_offset);
479
480    (0..size).for_each(|_| {
481        current_offset += rng.random_range(min..max);
482        offsets.push(current_offset);
483    });
484
485    (offsets, current_offset)
486}
487
488fn create_random_null_buffer(size: usize, null_density: f32) -> Buffer {
489    let mut rng = seedable_rng();
490    let mut mut_buf = MutableBuffer::new_null(size);
491    {
492        let mut_slice = mut_buf.as_slice_mut();
493        (0..size).for_each(|i| {
494            if rng.random::<f32>() >= null_density {
495                bit_util::set_bit(mut_slice, i)
496            }
497        })
498    };
499    mut_buf.into()
500}
501
502/// Useful for testing. The range of values are not likely to be representative of the
503/// actual bounds.
504pub trait RandomTemporalValue: ArrowTemporalType {
505    /// Returns the range of values for `impl`'d type
506    fn value_range() -> impl SampleRange<Self::Native>;
507
508    /// Generate a random value within the range of the type
509    fn gen_range<R: Rng>(rng: &mut R) -> Self::Native
510    where
511        Self::Native: SampleUniform,
512    {
513        rng.random_range(Self::value_range())
514    }
515
516    /// Generate a random value of the type
517    fn random<R: Rng>(rng: &mut R) -> Self::Native
518    where
519        Self::Native: SampleUniform,
520    {
521        Self::gen_range(rng)
522    }
523}
524
525impl RandomTemporalValue for TimestampSecondType {
526    /// Range of values for a timestamp in seconds. The range begins at the start
527    /// of the unix epoch and continues for 100 years.
528    fn value_range() -> impl SampleRange<Self::Native> {
529        0..60 * 60 * 24 * 365 * 100
530    }
531}
532
533impl RandomTemporalValue for TimestampMillisecondType {
534    /// Range of values for a timestamp in milliseconds. The range begins at the start
535    /// of the unix epoch and continues for 100 years.
536    fn value_range() -> impl SampleRange<Self::Native> {
537        0..1_000 * 60 * 60 * 24 * 365 * 100
538    }
539}
540
541impl RandomTemporalValue for TimestampMicrosecondType {
542    /// Range of values for a timestamp in microseconds. The range begins at the start
543    /// of the unix epoch and continues for 100 years.
544    fn value_range() -> impl SampleRange<Self::Native> {
545        0..1_000 * 1_000 * 60 * 60 * 24 * 365 * 100
546    }
547}
548
549impl RandomTemporalValue for TimestampNanosecondType {
550    /// Range of values for a timestamp in nanoseconds. The range begins at the start
551    /// of the unix epoch and continues for 100 years.
552    fn value_range() -> impl SampleRange<Self::Native> {
553        0..1_000 * 1_000 * 1_000 * 60 * 60 * 24 * 365 * 100
554    }
555}
556
557impl RandomTemporalValue for Date32Type {
558    /// Range of values representing the elapsed time since UNIX epoch in days. The
559    /// range begins at the start of the unix epoch and continues for 100 years.
560    fn value_range() -> impl SampleRange<Self::Native> {
561        0..365 * 100
562    }
563}
564
565impl RandomTemporalValue for Date64Type {
566    /// Range of values  representing the elapsed time since UNIX epoch in milliseconds.
567    /// The range begins at the start of the unix epoch and continues for 100 years.
568    fn value_range() -> impl SampleRange<Self::Native> {
569        0..1_000 * 60 * 60 * 24 * 365 * 100
570    }
571}
572
573impl RandomTemporalValue for Time32SecondType {
574    /// Range of values representing the elapsed time since midnight in seconds. The
575    /// range is from 0 to 24 hours.
576    fn value_range() -> impl SampleRange<Self::Native> {
577        0..60 * 60 * 24
578    }
579}
580
581impl RandomTemporalValue for Time32MillisecondType {
582    /// Range of values representing the elapsed time since midnight in milliseconds. The
583    /// range is from 0 to 24 hours.
584    fn value_range() -> impl SampleRange<Self::Native> {
585        0..1_000 * 60 * 60 * 24
586    }
587}
588
589impl RandomTemporalValue for Time64MicrosecondType {
590    /// Range of values representing the elapsed time since midnight in microseconds. The
591    /// range is from 0 to 24 hours.
592    fn value_range() -> impl SampleRange<Self::Native> {
593        0..1_000 * 1_000 * 60 * 60 * 24
594    }
595}
596
597impl RandomTemporalValue for Time64NanosecondType {
598    /// Range of values representing the elapsed time since midnight in nanoseconds. The
599    /// range is from 0 to 24 hours.
600    fn value_range() -> impl SampleRange<Self::Native> {
601        0..1_000 * 1_000 * 1_000 * 60 * 60 * 24
602    }
603}
604
605fn create_random_temporal_array<T>(size: usize, null_density: f32) -> PrimitiveArray<T>
606where
607    T: RandomTemporalValue,
608    <T as ArrowPrimitiveType>::Native: SampleUniform,
609{
610    let mut rng = seedable_rng();
611
612    (0..size)
613        .map(|_| {
614            if rng.random::<f32>() < null_density {
615                None
616            } else {
617                Some(T::random(&mut rng))
618            }
619        })
620        .collect()
621}
622
623#[cfg(test)]
624mod tests {
625    use super::*;
626
627    #[test]
628    fn test_create_batch() {
629        let size = 32;
630        let fields = vec![
631            Field::new("a", DataType::Int32, true),
632            Field::new("f16", DataType::Float16, true),
633            Field::new(
634                "timestamp_without_timezone",
635                DataType::Timestamp(TimeUnit::Nanosecond, None),
636                true,
637            ),
638            Field::new(
639                "timestamp_with_timezone",
640                DataType::Timestamp(TimeUnit::Nanosecond, Some("UTC".into())),
641                true,
642            ),
643        ];
644        let schema = Schema::new(fields);
645        let schema_ref = Arc::new(schema);
646        let batch = create_random_batch(schema_ref.clone(), size, 0.35, 0.7).unwrap();
647
648        assert_eq!(batch.schema(), schema_ref);
649        assert_eq!(batch.num_columns(), schema_ref.fields().len());
650        for array in batch.columns() {
651            assert_eq!(array.len(), size);
652        }
653    }
654
655    #[test]
656    fn test_create_batch_non_null() {
657        let size = 32;
658        let fields = vec![
659            Field::new("a", DataType::Int32, false),
660            Field::new(
661                "b",
662                DataType::List(Arc::new(Field::new_list_field(DataType::LargeUtf8, false))),
663                false,
664            ),
665            Field::new("a", DataType::Int32, false),
666        ];
667        let schema = Schema::new(fields);
668        let schema_ref = Arc::new(schema);
669        let batch = create_random_batch(schema_ref.clone(), size, 0.35, 0.7).unwrap();
670
671        assert_eq!(batch.schema(), schema_ref);
672        assert_eq!(batch.num_columns(), schema_ref.fields().len());
673        for array in batch.columns() {
674            assert_eq!(array.null_count(), 0);
675            assert_eq!(array.logical_null_count(), 0);
676        }
677        // Test that the list's child values are non-null
678        let b_array = batch.column(1);
679        let list_array = b_array.as_list::<i32>();
680        let child_array = list_array.values();
681        assert_eq!(child_array.null_count(), 0);
682        // There should be more values than the list, to show that it's a list
683        assert!(child_array.len() > list_array.len());
684    }
685
686    #[test]
687    fn test_create_struct_array() {
688        let size = 32;
689        let struct_fields = Fields::from(vec![
690            Field::new("b", DataType::Boolean, true),
691            Field::new(
692                "c",
693                DataType::LargeList(Arc::new(Field::new_list_field(
694                    DataType::List(Arc::new(Field::new_list_field(
695                        DataType::FixedSizeBinary(6),
696                        true,
697                    ))),
698                    false,
699                ))),
700                true,
701            ),
702            Field::new(
703                "d",
704                DataType::Struct(Fields::from(vec![
705                    Field::new("d_x", DataType::Int32, true),
706                    Field::new("d_y", DataType::Float32, false),
707                    Field::new("d_z", DataType::Binary, true),
708                ])),
709                true,
710            ),
711        ]);
712        let field = Field::new("struct", DataType::Struct(struct_fields), true);
713        let array = create_random_array(&field, size, 0.2, 0.5).unwrap();
714
715        assert_eq!(array.len(), 32);
716        let struct_array = array.as_any().downcast_ref::<StructArray>().unwrap();
717        assert_eq!(struct_array.columns().len(), 3);
718
719        // Test that the nested list makes sense,
720        // i.e. its children's values are more than the parent, to show repetition
721        let col_c = struct_array.column_by_name("c").unwrap();
722        let col_c = col_c.as_any().downcast_ref::<LargeListArray>().unwrap();
723        assert_eq!(col_c.len(), size);
724        let col_c_list = col_c.values().as_list::<i32>();
725        assert!(col_c_list.len() > size);
726        // Its values should be FixedSizeBinary(6)
727        let fsb = col_c_list.values();
728        assert_eq!(fsb.data_type(), &DataType::FixedSizeBinary(6));
729        assert!(fsb.len() > col_c_list.len());
730
731        // Test nested struct
732        let col_d = struct_array.column_by_name("d").unwrap();
733        let col_d = col_d.as_any().downcast_ref::<StructArray>().unwrap();
734        let col_d_y = col_d.column_by_name("d_y").unwrap();
735        assert_eq!(col_d_y.data_type(), &DataType::Float32);
736        assert_eq!(col_d_y.null_count(), 0);
737    }
738
739    #[test]
740    fn test_create_run_end_encoded_array() {
741        let size = 1000;
742        let ree_field = Field::new(
743            "ree",
744            DataType::RunEndEncoded(
745                Arc::new(Field::new("run_ends", DataType::Int32, false)),
746                Arc::new(Field::new("values", DataType::Utf8, true)),
747            ),
748            false,
749        );
750
751        let array = create_random_array(&ree_field, size, 0.25, 0.0).unwrap();
752        assert_eq!(array.len(), size);
753
754        let ree = array.as_run::<Int32Type>();
755        let run_ends = ree.run_ends().values();
756        let num_runs = run_ends.len();
757
758        assert_eq!(*run_ends.last().unwrap() as usize, size);
759
760        assert_eq!(ree.values().len(), num_runs);
761    }
762
763    #[test]
764    fn test_create_list_array_nested_nullability() {
765        let list_field = Field::new_list(
766            "not_null_list",
767            Field::new_list_field(DataType::Boolean, true),
768            false,
769        );
770
771        let list_array = create_random_array(&list_field, 100, 0.95, 0.5).unwrap();
772
773        assert_eq!(list_array.null_count(), 0);
774        assert!(list_array.as_list::<i32>().values().null_count() > 0);
775    }
776
777    #[test]
778    fn test_create_struct_array_nested_nullability() {
779        let struct_child_fields = vec![
780            Field::new("null_int", DataType::Int32, true),
781            Field::new("int", DataType::Int32, false),
782        ];
783        let struct_field = Field::new_struct("not_null_struct", struct_child_fields, false);
784
785        let struct_array = create_random_array(&struct_field, 100, 0.95, 0.5).unwrap();
786
787        assert_eq!(struct_array.null_count(), 0);
788        assert!(
789            struct_array
790                .as_struct()
791                .column_by_name("null_int")
792                .unwrap()
793                .null_count()
794                > 0
795        );
796        assert_eq!(
797            struct_array
798                .as_struct()
799                .column_by_name("int")
800                .unwrap()
801                .null_count(),
802            0
803        );
804    }
805
806    #[test]
807    fn test_create_list_array_nested_struct_nullability() {
808        let struct_child_fields = vec![
809            Field::new("null_int", DataType::Int32, true),
810            Field::new("int", DataType::Int32, false),
811        ];
812        let list_item_field =
813            Field::new_list_field(DataType::Struct(struct_child_fields.into()), true);
814        let list_field = Field::new_list("not_null_list", list_item_field, false);
815
816        let list_array = create_random_array(&list_field, 100, 0.95, 0.5).unwrap();
817
818        assert_eq!(list_array.null_count(), 0);
819        assert!(list_array.as_list::<i32>().values().null_count() > 0);
820        assert!(
821            list_array
822                .as_list::<i32>()
823                .values()
824                .as_struct()
825                .column_by_name("null_int")
826                .unwrap()
827                .null_count()
828                > 0
829        );
830        assert_eq!(
831            list_array
832                .as_list::<i32>()
833                .values()
834                .as_struct()
835                .column_by_name("int")
836                .unwrap()
837                .null_count(),
838            0
839        );
840    }
841
842    #[test]
843    fn test_create_map_array() {
844        let map_field = Field::new_map(
845            "map",
846            Field::MAP_ENTRIES_FIELD_DEFAULT_NAME,
847            Field::new(Field::MAP_KEY_FIELD_DEFAULT_NAME, DataType::Utf8, false),
848            Field::new(Field::MAP_VALUE_FIELD_DEFAULT_NAME, DataType::Utf8, true),
849            false,
850            false,
851        );
852        let array = create_random_array(&map_field, 100, 0.8, 0.5).unwrap();
853
854        assert_eq!(array.len(), 100);
855        // Map field is not null
856        assert_eq!(array.null_count(), 0);
857        assert_eq!(array.logical_null_count(), 0);
858        // Maps have multiple values like a list, so internal arrays are longer
859        assert!(array.as_map().keys().len() > array.len());
860        assert!(array.as_map().values().len() > array.len());
861        // Keys are not nullable
862        assert_eq!(array.as_map().keys().null_count(), 0);
863        // Values are nullable
864        assert!(array.as_map().values().null_count() > 0);
865
866        assert_eq!(array.as_map().keys().data_type(), &DataType::Utf8);
867        assert_eq!(array.as_map().values().data_type(), &DataType::Utf8);
868    }
869
870    #[test]
871    fn test_create_decimal_array() {
872        let size = 10;
873        let fields = vec![
874            Field::new("a", DataType::Decimal128(10, -2), true),
875            Field::new("b", DataType::Decimal256(10, -2), true),
876        ];
877        let schema = Schema::new(fields);
878        let schema_ref = Arc::new(schema);
879        let batch = create_random_batch(schema_ref.clone(), size, 0.35, 0.7).unwrap();
880
881        assert_eq!(batch.schema(), schema_ref);
882        assert_eq!(batch.num_columns(), schema_ref.fields().len());
883        for array in batch.columns() {
884            assert_eq!(array.len(), size);
885        }
886    }
887
888    #[test]
889    fn create_non_nullable_decimal_array_with_null_density() {
890        let size = 10;
891        let fields = vec![
892            Field::new("a", DataType::Decimal128(10, -2), false),
893            Field::new("b", DataType::Decimal256(10, -2), false),
894        ];
895        let schema = Schema::new(fields);
896        let schema_ref = Arc::new(schema);
897        let batch = create_random_batch(schema_ref.clone(), size, 0.35, 0.7).unwrap();
898
899        assert_eq!(batch.schema(), schema_ref);
900        assert_eq!(batch.num_columns(), schema_ref.fields().len());
901        for array in batch.columns() {
902            assert_eq!(array.len(), size);
903            assert_eq!(array.null_count(), 0);
904        }
905    }
906}