Skip to main content

uqa_sql/plpgsql/parameters/
inputs.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Invocation parameters retain selected values, types and lazy diagnostics under their producer.
8
9use super::{PLpgSQLVariableReference, VariableResolver};
10use crate::{ast::DeferredSQLError, ColumnType, SQLError, SQLParam};
11use uqa_core::memory::{Produced, ProductionControl};
12
13impl PLpgSQLVariableReference {
14    pub fn read_with_control(
15        &self,
16        resolver: &mut dyn VariableResolver,
17        control: &ProductionControl<'_>,
18    ) -> Result<Produced<SQLParam>, SQLError> {
19        let input = resolver
20            .resolve_input_with_control(self, control)?
21            .ok_or_else(|| {
22                SQLError::Internal("prepared PL/pgSQL variable no longer resolves".into())
23            })?;
24        let (input, memory) = input.into_parts();
25        Ok(control.finish(input.parameter, memory)?)
26    }
27}
28
29pub fn parameter_type_mismatch_with_control(
30    number: usize,
31    actual: &ColumnType,
32    expected: &ColumnType,
33    control: &ProductionControl<'_>,
34) -> Result<Produced<DeferredSQLError>, SQLError> {
35    let actual = actual.display_name_with_control(control)?;
36    let expected = expected.display_name_with_control(control)?;
37    let (sqlstate, first) = control.copy_text("42804")?.into_parts();
38    let (message, second) = control
39        .format(format_args!(
40            "type of parameter {number} ({}) does not match that when preparing the plan ({})",
41            actual.as_str(),
42            expected.as_str()
43        ))?
44        .into_parts();
45    Ok(control.finish(
46        DeferredSQLError {
47            sqlstate,
48            message,
49            detail: None,
50            hint: None,
51        },
52        control.combine(first, second),
53    )?)
54}
55
56impl DeferredSQLError {
57    pub fn capture_with_control(
58        error: &SQLError,
59        control: &ProductionControl<'_>,
60    ) -> Result<Produced<Self>, SQLError> {
61        let (sqlstate, mut memory) = control
62            .copy_text(error.sqlstate().unwrap_or("XX000"))?
63            .into_parts();
64        let (message, lease) = control.format(format_args!("{error}"))?.into_parts();
65        memory = control.combine(memory, lease);
66        let mut optional = |value: Option<&str>| -> Result<Option<String>, SQLError> {
67            value
68                .map(|value| {
69                    let (value, lease) = control.copy_text(value)?.into_parts();
70                    memory = control.combine(memory.take(), lease);
71                    Ok(value)
72                })
73                .transpose()
74        };
75        let detail = optional(error.detail())?;
76        let hint = optional(error.hint())?;
77        Ok(control.finish(
78            Self {
79                sqlstate,
80                message,
81                detail,
82                hint,
83            },
84            memory,
85        )?)
86    }
87}
88
89impl SQLParam {
90    pub fn deferred_error_with_control(
91        ty: &ColumnType,
92        error: Produced<DeferredSQLError>,
93        control: &ProductionControl<'_>,
94    ) -> Result<Produced<Self>, SQLError> {
95        let (ty, memory) = ty.clone_with_control(control)?.into_parts();
96        let (error, lease) = error.into_parts();
97        let memory = control.combine(memory, lease);
98        let memory = control.combine(memory, control.reserve(size_of::<DeferredSQLError>())?);
99        Ok(control.finish(
100            Self::DeferredError {
101                ty,
102                error: Box::new(error),
103            },
104            memory,
105        )?)
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use uqa_core::{memory::MemoryBudget, CancellationToken};
113
114    #[test]
115    fn deferred_inputs_keep_diagnostics_lazy_and_release_selected_owners() {
116        let budget = MemoryBudget::new(1 << 20);
117        let token = CancellationToken::new();
118        let control = ProductionControl::new(&budget, &token, &token);
119        let error = parameter_type_mismatch_with_control(
120            3,
121            &ColumnType::Text,
122            &ColumnType::Integer,
123            &control,
124        )
125        .unwrap();
126        assert_eq!(
127            *error,
128            crate::plpgsql::parameter_type_mismatch(3, &ColumnType::Text, &ColumnType::Integer)
129        );
130        let parameter =
131            SQLParam::deferred_error_with_control(&ColumnType::Integer, error, &control).unwrap();
132        assert_eq!(parameter.declared_scalar_type(), Some(&ColumnType::Integer));
133        assert_eq!(parameter.to_value().unwrap_err().sqlstate(), Some("42804"));
134        assert_eq!(budget.used(), parameter.reserved_bytes());
135        assert!(budget.used() > 0);
136        drop(parameter);
137        assert_eq!(budget.used(), 0);
138    }
139
140    #[test]
141    fn retained_diagnostics_admit_each_destination_and_observe_both_cancellations() {
142        let error = SQLError::Diagnostic {
143            sqlstate: "42703".into(),
144            message: "x".repeat(65536),
145            detail: Some("detail".into()),
146            hint: Some("hint".into()),
147        };
148        for cancelled in 0..3 {
149            let budget = MemoryBudget::new(if cancelled == 0 { 32 } else { 1 << 20 });
150            let original = CancellationToken::new();
151            let invoking = CancellationToken::new();
152            if cancelled == 1 {
153                original.cancel();
154            }
155            if cancelled == 2 {
156                invoking.cancel();
157            }
158            let control = ProductionControl::new(&budget, &original, &invoking);
159            let observed = allocation_counter::measure(|| {
160                assert_eq!(
161                    DeferredSQLError::capture_with_control(&error, &control)
162                        .err()
163                        .unwrap()
164                        .sqlstate(),
165                    Some(if cancelled == 0 { "53200" } else { "57014" })
166                );
167            });
168            assert!(observed.bytes_total < 4096, "{observed:?}");
169            assert_eq!(budget.used(), 0);
170        }
171        let budget = MemoryBudget::new(1 << 20);
172        let token = CancellationToken::new();
173        let control = ProductionControl::new(&budget, &token, &token);
174        let diagnostic = DeferredSQLError::capture_with_control(&error, &control).unwrap();
175        assert_eq!(*diagnostic, DeferredSQLError::from(&error));
176        assert_eq!(budget.used(), diagnostic.reserved_bytes());
177        drop(diagnostic);
178        assert_eq!(budget.used(), 0);
179    }
180}