vortex-array 0.94.0

Vortex in memory columnar data format
Documentation
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::fmt::Display;
use std::fmt::Formatter;
use std::hash::Hash;
use std::sync::Arc;

use itertools::Itertools as _;
use prost::Message;
use vortex_error::VortexResult;
use vortex_session::VortexSession;
use vortex_session::registry::CachedId;

use crate::ArrayRef;
use crate::ExecutionCtx;
use crate::IntoArray;
use crate::arrays::StructArray;
use crate::dtype::DType;
use crate::dtype::FieldName;
use crate::dtype::FieldNames;
use crate::dtype::Nullability;
use crate::dtype::StructFields;
use crate::proto::expr as pb;
use crate::scalar_fn::Arity;
use crate::scalar_fn::ChildName;
use crate::scalar_fn::ExecutionArgs;
use crate::scalar_fn::ReduceNode;
use crate::scalar_fn::ReduceNodeValidity;
use crate::scalar_fn::ScalarFnId;
use crate::scalar_fn::ScalarFnVTable;
use crate::scalar_fn::display::ExprDisplay;
use crate::validity::Validity;

/// Pack zero or more expressions into a structure with named fields.
#[derive(Clone)]
pub struct Pack;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PackOptions {
    pub names: FieldNames,
    pub nullability: Nullability,
}

impl Display for PackOptions {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "names: [{}], nullability: {:#}",
            self.names.iter().join(", "),
            self.nullability
        )
    }
}

impl ScalarFnVTable for Pack {
    type Options = PackOptions;

    fn id(&self) -> ScalarFnId {
        static ID: CachedId = CachedId::new("vortex.pack");
        *ID
    }

    fn serialize(&self, instance: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
        Ok(Some(
            pb::PackOpts {
                paths: instance
                    .names
                    .iter()
                    .map(|n| n.as_ref().to_owned())
                    .collect(),
                nullable: instance.nullability.into(),
            }
            .encode_to_vec(),
        ))
    }

    fn deserialize(
        &self,
        _metadata: &[u8],
        _session: &VortexSession,
    ) -> VortexResult<Self::Options> {
        let opts = pb::PackOpts::decode(_metadata)?;
        let names: FieldNames = opts
            .paths
            .iter()
            .map(|name| FieldName::from(name.as_str()))
            .collect();
        Ok(PackOptions {
            names,
            nullability: opts.nullable.into(),
        })
    }

    fn arity(&self, options: &Self::Options) -> Arity {
        Arity::Exact(options.names.len())
    }

    fn child_name(&self, instance: &Self::Options, child_idx: usize) -> ChildName {
        match instance.names.get(child_idx) {
            Some(name) => ChildName::from(Arc::clone(name.inner())),
            None => unreachable!(
                "Invalid child index {} for Pack expression with {} fields",
                child_idx,
                instance.names.len()
            ),
        }
    }

    fn fmt_sql(
        &self,
        options: &Self::Options,
        expr: &dyn ExprDisplay,
        f: &mut Formatter<'_>,
    ) -> std::fmt::Result {
        write!(f, "pack(")?;
        for (i, name) in options.names.iter().enumerate() {
            write!(f, "{}: ", name)?;
            Display::fmt(expr.display_child(i), f)?;
            if i + 1 < options.names.len() {
                write!(f, ", ")?;
            }
        }
        write!(f, "){}", options.nullability)
    }

    fn return_dtype(&self, options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
        Ok(DType::Struct(
            StructFields::new(options.names.clone(), arg_dtypes.to_vec()),
            options.nullability,
        ))
    }

    fn validity<T: ReduceNode>(
        &self,
        _options: &Self::Options,
        node: &T,
    ) -> VortexResult<ReduceNodeValidity<T>> {
        Ok(ReduceNodeValidity::Reduced(node.new_constant(true.into())))
    }

    fn execute(
        &self,
        options: &Self::Options,
        args: &dyn ExecutionArgs,
        ctx: &mut ExecutionCtx,
    ) -> VortexResult<ArrayRef> {
        let len = args.row_count();
        let value_arrays: Vec<ArrayRef> = (0..args.num_inputs())
            .map(|i| args.get(i))
            .collect::<VortexResult<_>>()?;
        let validity: Validity = options.nullability.into();
        StructArray::try_new(options.names.clone(), value_arrays, len, validity)?
            .into_array()
            .execute(ctx)
    }

    fn is_strict(&self, _instance: &Self::Options) -> bool {
        // A null field value does not force the packed struct row to be null.
        false
    }

    fn is_infallible(&self, _instance: &Self::Options) -> bool {
        true
    }
}