vortex-scan 0.94.0

Scanning operations for Vortex
Documentation
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors

use std::fmt::Formatter;

use vortex_array::ArrayRef;
use vortex_array::dtype::DType;
use vortex_array::dtype::Nullability;
use vortex_array::dtype::PType;
use vortex_array::scalar_fn::Arity;
use vortex_array::scalar_fn::ChildName;
use vortex_array::scalar_fn::EmptyOptions;
use vortex_array::scalar_fn::ExecutionArgs;
use vortex_array::scalar_fn::ScalarFnId;
use vortex_array::scalar_fn::ScalarFnVTable;
use vortex_array::scalar_fn::display::ExprDisplay;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_expr::Expression;
use vortex_expr::ScalarFnExprExt;
use vortex_session::registry::CachedId;

#[derive(Clone)]
/// A reference to the global row index supplied by a scan.
pub struct RowIdx;

impl ScalarFnVTable for RowIdx {
    type Options = EmptyOptions;

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

    fn arity(&self, _options: &Self::Options) -> Arity {
        Arity::Exact(0)
    }

    fn child_name(&self, _instance: &Self::Options, _child_idx: usize) -> ChildName {
        unreachable!()
    }

    fn fmt_sql(
        &self,
        _options: &Self::Options,
        _expr: &dyn ExprDisplay,
        f: &mut Formatter<'_>,
    ) -> std::fmt::Result {
        write!(f, "#row_idx")
    }

    fn return_dtype(&self, _options: &Self::Options, _arg_dtypes: &[DType]) -> VortexResult<DType> {
        Ok(DType::Primitive(PType::U64, Nullability::NonNullable))
    }

    fn execute(
        &self,
        _options: &Self::Options,
        _args: &dyn ExecutionArgs,
        _ctx: &mut vortex_array::ExecutionCtx,
    ) -> VortexResult<ArrayRef> {
        vortex_bail!(
            "RowIdxExpr should not be executed directly, use it in the context of a Vortex scan and it will be substituted for a row index array"
        );
    }

    fn is_strict(&self, _options: &Self::Options) -> bool {
        true
    }
}

/// Returns an expression for the global scan row index.
pub fn row_idx() -> Expression {
    RowIdx.new_expr(EmptyOptions, [])
}

#[cfg(test)]
mod tests {
    use vortex_expr::Lambda;
    use vortex_expr::checked_add;
    use vortex_expr::var;

    use super::row_idx;

    /// The scan replaces `row_idx()` before anything runs, but never looks inside a lambda's body,
    /// so a lambda can't read it. `Lambda::new` recognizes it by its id.
    #[test]
    fn a_lambda_cannot_read_row_idx() {
        let error = Lambda::new(["x"], checked_add(var("x"), row_idx()))
            .expect_err("row_idx() is not a parameter");
        assert!(
            error
                .to_string()
                .contains("lambda (x) can only read its parameters, not #row_idx"),
            "{error}"
        );
    }
}