uqa-sql 0.6.3

PostgreSQL-compatible SQL compiler built on libpg_query
Documentation
//
// Unified Query Algebra
//
// Copyright (c) 2023-2026 Cognica, Inc.
//

//! Bind parameters for `Engine::sql(query, params)`.

use crate::SQLError;
use uqa_core::{
    memory::{Produced, ProductionControl, ProductionVec},
    Value,
};

use crate::ast::ColumnType;

mod record;
pub use record::create_record_parameter_with_control;
mod range;
pub use range::{
    create_multirange_parameter_with_control, create_range_parameter_with_control,
    RangeParameterBounds,
};
mod array;
mod input;
pub use array::create_array_parameter_with_control;
pub use input::create_typed_parameter_with_control;
mod binding;
mod packed;
mod tensor;
pub use binding::{
    bind_declared_parameter_types, bind_parameter_type_with_control, bind_parameter_types,
};
pub use tensor::SQLTensor;

/// Value bound to a `$N` placeholder.
#[derive(Debug, Clone)]
pub enum SQLParam {
    Scalar(Value),
    /// A scalar value whose declared SQL type must survive runtime [`Value`] carrier normalization.
    TypedScalar {
        value: Value,
        ty: ColumnType,
    },
    /// A procedural parameter whose retained type is known but whose current
    /// value is invalid. Raise only if execution evaluates this parameter.
    #[doc(hidden)]
    DeferredError {
        ty: ColumnType,
        error: Box<crate::ast::DeferredSQLError>,
    },
    Vector(Vec<f32>),
    Tensor(Vec<Vec<f32>>),
    /// A validated packed tensor whose declared dimension survives an empty row set.
    TypedTensor(SQLTensor),
}

impl SQLParam {
    /// Copy a parameter without evaluating its carrier or a deferred diagnostic, retaining its declared type and every private payload under the original allowance.
    pub fn clone_with_control(
        &self,
        control: &ProductionControl<'_>,
    ) -> Result<Produced<Self>, SQLError> {
        crate::plan::copy::copy_syntax_with_control(self, control)
    }

    pub fn scalar(value: Value) -> Self {
        Self::Scalar(value)
    }

    #[must_use]
    pub fn typed_scalar(value: Value, ty: ColumnType) -> Self {
        Self::TypedScalar { value, ty }
    }

    /// Return the scalar carrier without changing the semantics of untyped [`SQLParam::Scalar`] values.
    #[must_use]
    pub fn scalar_value(&self) -> Option<&Value> {
        match self {
            Self::Scalar(value) | Self::TypedScalar { value, .. } => Some(value),
            Self::Vector(_)
            | Self::Tensor(_)
            | Self::TypedTensor(_)
            | Self::DeferredError { .. } => None,
        }
    }

    /// Return an explicit scalar type, including a deferred procedural error's retained type.
    #[must_use]
    pub fn declared_scalar_type(&self) -> Option<&ColumnType> {
        match self {
            Self::TypedScalar { ty, .. } | Self::DeferredError { ty, .. } => Some(ty),
            Self::Scalar(_) | Self::Vector(_) | Self::Tensor(_) | Self::TypedTensor(_) => None,
        }
    }

    /// Materialize the parameter carrier with ordinary SQL value semantics.
    pub fn to_value(&self) -> Result<Value, SQLError> {
        self.to_value_with_control(&ProductionControl::uncontrolled())
            .map(|value| value.into_uncontrolled().expect("ordinary parameter value"))
    }

    /// Copy a borrowed parameter while retaining every container and child payload under its producer's allowance.
    pub fn to_value_with_control(
        &self,
        control: &ProductionControl<'_>,
    ) -> Result<Produced<Value>, SQLError> {
        control.check()?;
        match self {
            Self::DeferredError { error, .. } => Err((**error).clone().into()),
            Self::Scalar(value) | Self::TypedScalar { value, .. } => Ok(control.copy_value(value)?),
            Self::Vector(values) => vector_value(values, control),
            Self::Tensor(vectors) => {
                let mut output = ProductionVec::new(*control);
                output.reserve(vectors.len())?;
                for values in vectors {
                    output.push_produced(vector_value(values, control)?)?;
                }
                let (values, memory) = output.finish()?.into_parts();
                Ok(control.finish(Value::List(values), memory)?)
            }
            Self::TypedTensor(tensor) => tensor.to_value_with_control(control),
        }
    }

    pub fn vector(v: Vec<f32>) -> Self {
        Self::Vector(v)
    }

    /// Copy a host vector after validating its SQL dimension and finite float32 elements. The completed parameter retains the caller's original allowance.
    pub fn vector_with_control(
        values: &[f32],
        control: &ProductionControl<'_>,
    ) -> Result<Produced<Self>, SQLError> {
        control.check()?;
        if values.is_empty() || u32::try_from(values.len()).is_err() {
            return Err(SQLError::TypeMismatch(
                "vector dimension must be a positive 32-bit integer".into(),
            ));
        }
        for value in values {
            crate::expr::vector_element_with_control(&Value::Float(f64::from(*value)), control)?;
        }
        let mut output = ProductionVec::new(*control);
        output.extend_from_slice(values)?;
        let (values, memory) = output.finish()?.into_parts();
        Ok(control.finish(Self::Vector(values), memory)?)
    }

    pub fn tensor(v: Vec<Vec<f32>>) -> Self {
        Self::Tensor(v)
    }
}

fn vector_value(
    values: &[f32],
    control: &ProductionControl<'_>,
) -> Result<Produced<Value>, SQLError> {
    let mut output = ProductionVec::new(*control);
    output.reserve(values.len())?;
    for value in values {
        output.push_produced(
            control.finish(Value::Float(f64::from(*value)), control.empty_reservation())?,
        )?;
    }
    let (values, memory) = output.finish()?.into_parts();
    Ok(control.finish(Value::List(values), memory)?)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deferred_parameter_keeps_scalar_carriers_compact_and_errors_lazy() {
        assert!(size_of::<SQLParam>() <= size_of::<(Value, ColumnType, usize)>());
        let error = crate::plpgsql::runtime_diagnostics::unassigned_record("r");
        let parameter = SQLParam::DeferredError {
            ty: ColumnType::SmallInteger,
            error: Box::new((&error).into()),
        };
        assert_eq!(parameter.scalar_value(), None);
        assert_eq!(
            parameter.declared_scalar_type(),
            Some(&ColumnType::SmallInteger)
        );
        let observed = parameter.to_value().unwrap_err();
        assert_eq!(observed.sqlstate(), error.sqlstate());
        assert_eq!(observed.to_string(), error.to_string());
        assert_eq!(observed.detail(), error.detail());
        assert_eq!(observed.hint(), error.hint());
    }

    #[test]
    fn typed_scalar_preserves_declared_type_without_changing_scalar_access() {
        let value = Value::Int(7);
        let typed = SQLParam::typed_scalar(value.clone(), ColumnType::SmallInteger);
        assert_eq!(typed.scalar_value(), Some(&value));
        assert_eq!(
            typed.declared_scalar_type(),
            Some(&ColumnType::SmallInteger)
        );

        let scalar = SQLParam::scalar(value.clone());
        assert_eq!(scalar.scalar_value(), Some(&value));
        assert_eq!(scalar.declared_scalar_type(), None);
    }

    #[test]
    fn host_vector_input_checks_shape_and_finiteness_before_retaining_bytes() {
        use uqa_core::{memory::MemoryBudget, CancellationToken};
        let budget = MemoryBudget::new(64);
        let original = CancellationToken::new();
        let invoking = CancellationToken::new();
        let control = ProductionControl::new(&budget, &original, &invoking);
        let held = control.copy_text("held").unwrap();
        for values in [
            vec![],
            vec![f32::NAN],
            vec![f32::INFINITY],
            vec![f32::NEG_INFINITY],
        ] {
            assert!(SQLParam::vector_with_control(&values, &control).is_err());
            assert_eq!(budget.used(), held.reserved_bytes());
        }
        assert_eq!(
            SQLParam::vector_with_control(&[1.0; 64], &control)
                .unwrap_err()
                .sqlstate(),
            Some("53200")
        );
        assert_eq!(budget.used(), held.reserved_bytes());
        for token in [&original, &invoking] {
            token.cancel();
            assert_eq!(
                SQLParam::vector_with_control(&[1.0], &control)
                    .unwrap_err()
                    .sqlstate(),
                Some("57014")
            );
            assert_eq!(budget.used(), held.reserved_bytes());
            token.reset();
        }
        let mut input = [-0.0, f32::MIN_POSITIVE, f32::MAX];
        let vector = SQLParam::vector_with_control(&input, &control).unwrap();
        input[1] = 1.0;
        assert_eq!(input[1], 1.0);
        let SQLParam::Vector(values) = &*vector else {
            panic!("expected dedicated vector");
        };
        assert_eq!(values[0].to_bits(), (-0.0_f32).to_bits());
        assert_eq!(values[1], f32::MIN_POSITIVE);
        assert_eq!(values[2], f32::MAX);
        assert_eq!(
            budget.used(),
            held.reserved_bytes() + vector.reserved_bytes()
        );
        drop(vector);
        assert_eq!(budget.used(), held.reserved_bytes());
    }

    #[test]
    fn parameter_value_owners_keep_tensor_and_scalar_payloads_until_drop() {
        use uqa_core::{memory::MemoryBudget, CancellationToken};
        let budget = MemoryBudget::new(1 << 16);
        let token = CancellationToken::new();
        let control = ProductionControl::new(&budget, &token, &token);
        for (parameter, expected) in [
            (
                SQLParam::typed_scalar(Value::Str("payload".repeat(32)), ColumnType::Text),
                Value::Str("payload".repeat(32)),
            ),
            (
                SQLParam::Vector(vec![1.0, 2.5]),
                Value::List(vec![Value::Float(1.0), Value::Float(2.5)]),
            ),
            (
                SQLParam::Tensor(vec![vec![1.0, 2.5], vec![]]),
                Value::List(vec![
                    Value::List(vec![Value::Float(1.0), Value::Float(2.5)]),
                    Value::List(vec![]),
                ]),
            ),
        ] {
            let value = parameter.to_value_with_control(&control).unwrap();
            assert_eq!(*value, expected);
            assert!(value.reserved_bytes() > 0);
            assert_eq!(budget.used(), value.reserved_bytes());
            drop(value);
            assert_eq!(budget.used(), 0);
            assert_eq!(parameter.to_value().unwrap(), expected);
        }
    }

    #[test]
    fn parameter_production_releases_partial_output_on_quota_and_both_tokens() {
        use uqa_core::{memory::MemoryBudget, CancellationToken};
        let budget = MemoryBudget::new(256);
        let original = CancellationToken::new();
        let invoking = CancellationToken::new();
        let control = ProductionControl::new(&budget, &original, &invoking);
        let held = control.copy_text("held").unwrap();
        let parameter = SQLParam::Tensor(vec![vec![1.0; 64], vec![2.0; 64]]);
        assert_eq!(
            parameter
                .to_value_with_control(&control)
                .unwrap_err()
                .sqlstate(),
            Some("53200")
        );
        assert_eq!(budget.used(), held.reserved_bytes());
        for token in [&original, &invoking] {
            token.cancel();
            assert_eq!(
                parameter
                    .to_value_with_control(&control)
                    .unwrap_err()
                    .sqlstate(),
                Some("57014")
            );
            assert_eq!(budget.used(), held.reserved_bytes());
            token.reset();
        }
        assert_eq!(
            parameter.to_value().unwrap(),
            Value::List(vec![
                Value::List(vec![Value::Float(1.0); 64]),
                Value::List(vec![Value::Float(2.0); 64])
            ])
        );
    }
}