Skip to main content

uqa_sql/plan/scalar/owned/
constructors.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Replacement nodes keep their constructor inputs and independently movable children owned.
8
9use super::{OwnedScalarExpr, Result, ScalarExpr, ScalarMemory};
10use crate::{ir::RetainedScalarLiteral, ColumnType};
11use uqa_core::{
12    memory::{Produced, ProductionControl},
13    Value,
14};
15
16impl OwnedScalarExpr {
17    /// Construct a typed literal from independently admitted value and type metadata. This operation only transfers storage; it performs no type resolution, conversion or evaluation.
18    pub fn typed_literal(
19        value: Produced<Value>,
20        declaration: Produced<String>,
21        bound_type: Option<Produced<ColumnType>>,
22        collation_oid: Option<u32>,
23        parameter_index: Option<usize>,
24        control: &ProductionControl<'_>,
25    ) -> Result<Self> {
26        control.check()?;
27        let mut output = Self {
28            expression: ScalarExpr::Literal(Value::Null),
29            memory: control.empty_reservation().map(|direct| ScalarMemory {
30                children: Vec::new(),
31                direct,
32            }),
33        };
34        let (value, value_memory) = value.into_parts();
35        let (ty, type_memory) = declaration.into_parts();
36        let (bound_type, bound_memory) = match bound_type {
37            Some(ty) => {
38                let (ty, memory) = ty.into_parts();
39                (Some(ty), memory)
40            }
41            None => (None, control.empty_reservation()),
42        };
43        output.expression = ScalarExpr::TypedLiteral {
44            value,
45            ty,
46            bound_type,
47            collation_oid,
48            composite_source: None,
49            parameter_index,
50        };
51        let memory = control.combine(control.combine(value_memory, type_memory), bound_memory);
52        if let Some(owner) = &mut output.memory {
53            owner
54                .direct
55                .absorb(memory.expect("admitted literal fields"));
56        }
57        control.check()?;
58        Ok(output)
59    }
60
61    /// Attach an already retained constant without charging its independently shared payload a second time.
62    pub fn retained_literal(
63        literal: RetainedScalarLiteral,
64        control: &ProductionControl<'_>,
65    ) -> Result<Self> {
66        let output = Self {
67            expression: ScalarExpr::RetainedLiteral(literal),
68            memory: control.empty_reservation().map(|direct| ScalarMemory {
69                children: Vec::new(),
70                direct,
71            }),
72        };
73        control.check()?;
74        Ok(output)
75    }
76
77    /// Wrap an independently owned child in a cast. The child box and ownership slot are admitted before allocation; the destination declaration retains its original producer lease.
78    pub fn cast(
79        child: Self,
80        declaration: Produced<String>,
81        implicit: bool,
82        control: &ProductionControl<'_>,
83    ) -> Result<Self> {
84        child.assert_owner(control);
85        control.check()?;
86        let mut output = Self {
87            expression: ScalarExpr::Literal(Value::Null),
88            memory: control.empty_reservation().map(|direct| ScalarMemory {
89                children: Vec::new(),
90                direct,
91            }),
92        };
93        if let Some(owner) = &mut output.memory {
94            owner.reserve_children(1)?;
95        }
96        let boxed = control.reserve(size_of::<ScalarExpr>())?;
97        let Self { expression, memory } = child;
98        let (ty, declaration_memory) = declaration.into_parts();
99        output.expression = ScalarExpr::Cast {
100            expr: Box::new(expression),
101            ty,
102            implicit,
103        };
104        let direct = control.combine(boxed, declaration_memory);
105        if let Some(owner) = &mut output.memory {
106            owner.push_child(memory).expect("admitted cast child slot");
107            owner.direct.absorb(direct.expect("admitted cast fields"));
108        }
109        control.check()?;
110        Ok(output)
111    }
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117    use uqa_core::{memory::MemoryBudget, CancellationToken};
118
119    #[test]
120    fn typed_replacements_and_casts_preserve_exact_live_constructor_ownership() {
121        let value = Value::Str("payload".repeat(1024));
122        let ty = ColumnType::Named("catalog.type".repeat(32));
123        let budget = MemoryBudget::new(1 << 20);
124        let token = CancellationToken::new();
125        let control = ProductionControl::new(&budget, &token, &token);
126        let mut output = None;
127        let allocated = allocation_counter::measure(|| {
128            let child = OwnedScalarExpr::typed_literal(
129                control.copy_value(&value).unwrap(),
130                control.copy_text("declared_type").unwrap(),
131                Some(ty.clone_with_control(&control).unwrap()),
132                Some(101),
133                Some(3),
134                &control,
135            )
136            .unwrap();
137            output = Some(
138                OwnedScalarExpr::cast(
139                    child,
140                    control.copy_text("converted_type").unwrap(),
141                    true,
142                    &control,
143                )
144                .unwrap(),
145            );
146        });
147        let output = output.unwrap();
148        assert_eq!(
149            allocated.bytes_current,
150            i64::try_from(budget.used()).unwrap()
151        );
152        assert_eq!(output.reserved_bytes(), budget.used());
153        let ScalarExpr::Cast {
154            expr,
155            ty: name,
156            implicit,
157        } = &*output
158        else {
159            panic!("owned cast");
160        };
161        assert_eq!(name, "converted_type");
162        assert!(*implicit);
163        let ScalarExpr::TypedLiteral {
164            value: Value::Str(payload),
165            ..
166        } = expr.as_ref()
167        else {
168            panic!("owned typed child");
169        };
170        let pointer = payload.as_ptr();
171        let before = budget.used();
172        let mut selected = None;
173        let released = allocation_counter::measure(|| selected = Some(output.select_child(0)));
174        let selected = selected.unwrap();
175        assert_eq!(released.count_total, 0);
176        assert_eq!(
177            released.bytes_current,
178            -(i64::try_from(before).unwrap() - i64::try_from(budget.used()).unwrap())
179        );
180        let ScalarExpr::TypedLiteral {
181            value: Value::Str(payload),
182            bound_type,
183            collation_oid,
184            parameter_index,
185            ..
186        } = &*selected
187        else {
188            panic!("selected typed child");
189        };
190        assert_eq!(payload.as_ptr(), pointer);
191        assert_eq!(bound_type.as_ref(), Some(&ty));
192        assert_eq!(*collation_oid, Some(101));
193        assert_eq!(*parameter_index, Some(3));
194        drop(selected);
195        assert_eq!(budget.used(), 0);
196    }
197
198    #[test]
199    fn cast_parent_admission_and_cancellation_destroy_both_private_inputs() {
200        for mode in 0..4 {
201            let budget = MemoryBudget::new(1 << 20);
202            let original = CancellationToken::new();
203            let invoking = CancellationToken::new();
204            let control = ProductionControl::new(&budget, &original, &invoking);
205            let child = ScalarExpr::Literal(Value::Str("x".repeat(1024)))
206                .copy_for_rewrite(&control)
207                .unwrap();
208            let name = control.copy_text("integer").unwrap();
209            let spare = if mode == 1 {
210                size_of::<Option<ScalarMemory>>()
211            } else {
212                0
213            };
214            let sibling = budget.reserve(budget.available() - spare).unwrap();
215            if mode == 2 {
216                original.cancel();
217            }
218            if mode == 3 {
219                invoking.cancel();
220            }
221            let error: crate::SQLError = OwnedScalarExpr::cast(child, name, false, &control)
222                .unwrap_err()
223                .into();
224            assert_eq!(
225                error.sqlstate(),
226                Some(if mode < 2 { "53200" } else { "57014" })
227            );
228            assert_eq!(budget.used(), sibling.bytes());
229            drop(sibling);
230            assert_eq!(budget.used(), 0);
231        }
232    }
233
234    #[test]
235    fn retained_leaf_does_not_double_charge_its_shared_constant() {
236        let budget = MemoryBudget::new(1 << 20);
237        let token = CancellationToken::new();
238        let control = ProductionControl::new(&budget, &token, &token);
239        let value = retained_value(&control);
240        let literal =
241            RetainedScalarLiteral::with_control(value, None, None, None, &control).unwrap();
242        let last = literal.clone();
243        let before = budget.used();
244        let mut output = None;
245        let allocated = allocation_counter::measure(|| {
246            output = Some(OwnedScalarExpr::retained_literal(literal, &control).unwrap());
247        });
248        let output = output.unwrap();
249        assert_eq!(allocated.count_total, 0);
250        assert_eq!(output.reserved_bytes(), 0);
251        assert_eq!(budget.used(), before);
252        drop(output);
253        assert_eq!(budget.used(), before);
254        drop(last);
255        assert_eq!(budget.used(), 0);
256    }
257
258    fn retained_value(control: &ProductionControl<'_>) -> crate::ir::RetainedConstantValue {
259        crate::ir::RetainedConstantValue::from_produced(
260            control.copy_value(&Value::Str("x".repeat(1024))).unwrap(),
261            control,
262        )
263        .unwrap()
264    }
265}