Skip to main content

uqa_sql/plan/scalar/owned/
literals.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Literal metadata replacement preserves original composite provenance and producer ownership.
8
9use super::{OwnedScalarExpr, Result, ScalarExpr, ScalarMemory};
10use crate::{
11    plan::scalar::{
12        resources::{Control, Lowering},
13        source::Source,
14    },
15    ColumnType,
16};
17use uqa_core::memory::{BudgetedVec, Produced, ProductionControl};
18use uqa_core::Value;
19
20impl OwnedScalarExpr {
21    /// Consume an untyped literal while keeping its exact value payload lease. No metadata or child allocation belongs to this constructor.
22    pub fn into_literal_value(self, control: &ProductionControl<'_>) -> Result<Produced<Value>> {
23        assert!(
24            matches!(&*self, ScalarExpr::Literal(_)),
25            "literal value extraction requires an untyped literal"
26        );
27        let (expression, memory) = self.finish(control)?.into_parts();
28        let ScalarExpr::Literal(value) = expression else {
29            panic!("literal value extraction requires an untyped literal");
30        };
31        Ok(control.finish(value, memory)?)
32    }
33
34    /// Replace a literal's declared type and collation while preserving its parameter and original composite source. The old leaf's allocating fields share one constructor lease, so the replacement copies surviving fields under their producers before releasing that complete old lease.
35    pub fn replace_literal_type(
36        self,
37        declaration: Produced<String>,
38        bound_type: Produced<ColumnType>,
39        collation_oid: Option<u32>,
40        control: &ProductionControl<'_>,
41    ) -> Result<Self> {
42        self.assert_owner(control);
43        control.check()?;
44        let (value, composite_source, parameter_index) = match &self.expression {
45            ScalarExpr::Literal(value) => (value, None, None),
46            ScalarExpr::TypedLiteral {
47                value,
48                composite_source,
49                parameter_index,
50                ..
51            } => (value, composite_source.as_ref(), *parameter_index),
52            _ => panic!("literal type replacement requires an inline literal"),
53        };
54        let mut lowering = Lowering {
55            control: control.budget().map(|_| Control::from_production(*control)),
56            owned_children: control.budget().map(BudgetedVec::new),
57        };
58        let composite_source = lowering.composite_source(composite_source.map(Source::Borrowed))?;
59        let value = lowering.value(Source::Borrowed(value))?;
60        let (ty, declaration_memory) = declaration.into_parts();
61        let (bound_type, type_memory) = bound_type.into_parts();
62        let metadata = control.combine(declaration_memory, type_memory);
63        if let Some(owner) = &mut lowering.control {
64            owner
65                .memory
66                .absorb(metadata.expect("admitted literal metadata"));
67        }
68        let output = Self {
69            expression: ScalarExpr::TypedLiteral {
70                value,
71                ty,
72                bound_type: Some(bound_type),
73                parameter_index,
74                composite_source,
75                collation_oid,
76            },
77            memory: lowering.control.map(|control| {
78                ScalarMemory::from_parts(
79                    control.memory,
80                    lowering
81                        .owned_children
82                        .expect("mutable literal construction"),
83                )
84            }),
85        };
86        drop(self);
87        control.check()?;
88        Ok(output)
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use super::*;
95    use uqa_core::{memory::MemoryBudget, CancellationToken};
96
97    #[test]
98    fn literal_value_transfer_preserves_payload_identity_and_complete_lease() {
99        let budget = MemoryBudget::new(1 << 20);
100        let token = CancellationToken::new();
101        let control = ProductionControl::new(&budget, &token, &token);
102        let source = Value::Str("payload".repeat(1024));
103        let value = control.copy_value(&source).unwrap();
104        let Value::Str(text) = &*value else {
105            unreachable!()
106        };
107        let pointer = text.as_ptr();
108        let before = budget.used();
109        let mut output = None;
110        let allocations = allocation_counter::measure(|| {
111            let expression = OwnedScalarExpr::literal(value, &control).unwrap();
112            output = Some(expression.into_literal_value(&control).unwrap());
113        });
114        let output = output.unwrap();
115        let Value::Str(text) = &*output else {
116            unreachable!()
117        };
118        assert_eq!(text.as_ptr(), pointer);
119        assert_eq!(allocations.count_total, 0);
120        assert_eq!(output.reserved_bytes(), before);
121        assert_eq!(budget.used(), before);
122        drop(output);
123        assert_eq!(budget.used(), 0);
124    }
125
126    #[test]
127    fn literal_type_replacement_preserves_original_tuple_and_parameter_identity() {
128        let source = ScalarExpr::TypedLiteral {
129            value: Value::Str("current".repeat(1024)),
130            ty: "text".into(),
131            bound_type: Some(ColumnType::Text),
132            parameter_index: Some(7),
133            collation_oid: Some(100),
134            composite_source: Some(Box::new(crate::expr::composites::CompositeConstantSource {
135                value: Value::Str("original".repeat(1024)),
136                descriptors: Vec::new(),
137            })),
138        };
139        let budget = MemoryBudget::new(1 << 20);
140        let token = CancellationToken::new();
141        let control = ProductionControl::new(&budget, &token, &token);
142        let mut output = None;
143        let allocations = allocation_counter::measure(|| {
144            let input = source.copy_for_rewrite(&control).unwrap();
145            output = Some(
146                input
147                    .replace_literal_type(
148                        control.copy_text("pg_catalog.varchar(10)").unwrap(),
149                        ColumnType::Varchar(Some(10))
150                            .clone_with_control(&control)
151                            .unwrap(),
152                        Some(951),
153                        &control,
154                    )
155                    .unwrap(),
156            );
157        });
158        let output = output.unwrap();
159        let ScalarExpr::TypedLiteral {
160            value,
161            ty,
162            bound_type,
163            parameter_index,
164            collation_oid,
165            composite_source,
166        } = &*output
167        else {
168            panic!("typed literal")
169        };
170        assert_eq!(value, &Value::Str("current".repeat(1024)));
171        assert_eq!(ty, "pg_catalog.varchar(10)");
172        assert_eq!(bound_type, &Some(ColumnType::Varchar(Some(10))));
173        assert_eq!(*parameter_index, Some(7));
174        assert_eq!(*collation_oid, Some(951));
175        assert_eq!(
176            composite_source.as_ref().unwrap().value,
177            Value::Str("original".repeat(1024))
178        );
179        assert_eq!(
180            allocations.bytes_current,
181            i64::try_from(budget.used()).unwrap()
182        );
183        assert_eq!(output.reserved_bytes(), budget.used());
184        drop(output);
185        assert_eq!(budget.used(), 0);
186    }
187}