Skip to main content

uqa_sql/ir/
retained.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Immutable evaluated constants share storage without retaining every decoded payload.
8
9use std::{fmt, sync::Arc};
10
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12use uqa_core::Value;
13
14use crate::{ast::ColumnType, SQLError};
15
16/// Storage for an already evaluated value. Reading must reproduce the original value without invoking SQL or changing it; implementations own their resource until the final shared handle is dropped.
17pub trait ConstantValueSource: fmt::Debug + Send + Sync {
18    fn read(&self, index: u64) -> Result<Value, SQLError>;
19}
20
21/// An immutable positional value in a shared owner. Copying this handle never reads or copies the payload.
22#[derive(Clone)]
23pub struct RetainedConstantValue {
24    source: Arc<dyn ConstantValueSource>,
25    index: u64,
26}
27
28impl RetainedConstantValue {
29    pub fn new(source: Arc<dyn ConstantValueSource>, index: u64) -> Self {
30        Self { source, index }
31    }
32
33    pub fn read(&self) -> Result<Value, SQLError> {
34        crate::expr::check_statement_cancellation()?;
35        let value = self.source.read(self.index)?;
36        crate::expr::check_statement_cancellation()?;
37        Ok(value)
38    }
39}
40
41impl fmt::Debug for RetainedConstantValue {
42    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43        f.debug_struct("RetainedConstantValue")
44            .field("index", &self.index)
45            .finish_non_exhaustive()
46    }
47}
48
49impl PartialEq for RetainedConstantValue {
50    fn eq(&self, other: &Self) -> bool {
51        if Arc::ptr_eq(&self.source, &other.source) && self.index == other.index {
52            return true;
53        }
54        // IR representation comparison may conservatively decline a rewrite when a resource cannot be read. SQL evaluation retains the original fallible read and reports its error.
55        match (self.read(), other.read()) {
56            (Ok(left), Ok(right)) => left.has_same_representation(&right),
57            _ => false,
58        }
59    }
60}
61
62impl Serialize for RetainedConstantValue {
63    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
64        self.read()
65            .map_err(serde::ser::Error::custom)?
66            .serialize(serializer)
67    }
68}
69
70impl<'de> Deserialize<'de> for RetainedConstantValue {
71    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
72        let value = Value::deserialize(deserializer)?;
73        Ok(Self::new(Arc::new(OwnedConstant(value)), 0))
74    }
75}
76
77#[derive(Debug)]
78struct OwnedConstant(Value);
79
80impl ConstantValueSource for OwnedConstant {
81    fn read(&self, index: u64) -> Result<Value, SQLError> {
82        if index != 0 {
83            return Err(SQLError::Internal(
84                "retained constant index is outside its owner".into(),
85            ));
86        }
87        Ok(self.0.clone())
88    }
89}
90
91/// Selected result metadata of a constant whose bytes are owned by execution storage. This carries an evaluated datum, never an expression to evaluate again.
92#[derive(Debug, Clone, PartialEq)]
93pub struct RetainedScalarLiteral {
94    pub value: RetainedConstantValue,
95    pub ty: ColumnType,
96    pub declaration: Option<String>,
97    pub collation_oid: Option<u32>,
98}
99
100impl Serialize for RetainedScalarLiteral {
101    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
102        self.materialize()
103            .map_err(serde::ser::Error::custom)?
104            .serialize(serializer)
105    }
106}
107
108impl RetainedScalarLiteral {
109    /// Materialize one value only at an interface that requires an owned literal. Cloning plans retains the shared owner instead.
110    pub fn materialize(&self) -> Result<crate::ScalarExpr, SQLError> {
111        let value = self.value.read()?;
112        let Some(declaration) = &self.declaration else {
113            return Ok(crate::ScalarExpr::Literal(value));
114        };
115        Ok(crate::ScalarExpr::TypedLiteral {
116            value,
117            ty: declaration.clone(),
118            bound_type: Some(self.ty.clone()),
119            parameter_index: None,
120            composite_source: None,
121            collation_oid: self.collation_oid,
122        })
123    }
124}
125
126/// Planner supplies a successfully evaluated constant; execution supplies its bounded storage implementation.
127pub trait ConstantValueStorage: fmt::Debug + Send + Sync {
128    fn retain(&self, value: Value) -> Result<RetainedConstantValue, SQLError>;
129}
130
131#[cfg(test)]
132mod tests;