Skip to main content

uqa_core/relation_identity/
production.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Canonical names stream decoded components into their admitted destination.
8
9use super::{RelationName, RelationReference};
10use crate::{
11    memory::{Produced, ProductionControl, ProductionString},
12    ValueRetentionError,
13};
14
15impl RelationReference<'_> {
16    /// Decode borrowed components directly into their retained identity buffers.
17    pub fn identity_with_control(
18        &self,
19        default_schema: RelationName<'_>,
20        control: &ProductionControl<'_>,
21    ) -> Result<Produced<super::RelationIdentity>, ValueRetentionError> {
22        let schema = control.format(format_args!("{}", self.schema.unwrap_or(default_schema)))?;
23        let name = control.format(format_args!("{}", self.name))?;
24        let (schema, schema_memory) = schema.into_parts();
25        let (name, name_memory) = name.into_parts();
26        control.finish(
27            super::RelationIdentity { schema, name },
28            control.combine(schema_memory, name_memory),
29        )
30    }
31
32    pub fn render_with_control(
33        &self,
34        control: &ProductionControl<'_>,
35    ) -> Result<Produced<String>, ValueRetentionError> {
36        control.check()?;
37        let mut output = ProductionString::new(*control);
38        if let Some(schema) = self.schema {
39            component(schema, &mut output, control)?;
40            output.push('.')?;
41        }
42        component(self.name, &mut output, control)?;
43        output.finish()
44    }
45}
46
47fn component(
48    name: RelationName<'_>,
49    output: &mut ProductionString<'_>,
50    control: &ProductionControl<'_>,
51) -> Result<(), ValueRetentionError> {
52    let mut bare = name.chars().next().is_some();
53    for (index, character) in name.chars().enumerate() {
54        control.check()?;
55        bare &= match character {
56            'a'..='z' | '_' => true,
57            '0'..='9' | '$' => index != 0,
58            _ => false,
59        };
60    }
61    if !bare {
62        output.push('"')?;
63    }
64    for character in name.chars() {
65        control.check()?;
66        if character == '"' {
67            output.push('"')?;
68        }
69        output.push(character)?;
70    }
71    if !bare {
72        output.push('"')?;
73    }
74    Ok(())
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use crate::{memory::MemoryBudget, CancellationToken, RelationIdentity};
81
82    #[test]
83    fn reference_names_admit_exact_storage_and_preserve_escaped_components() {
84        for (source, expected) in [
85            ("public.table", "public.table"),
86            ("\"A.Schema\".\"a\"\"b\"", "\"A.Schema\".\"a\"\"b\""),
87            ("\"한국어\"", "\"한국어\""),
88            ("\"foo\".\"bar\"", "foo.bar"),
89        ] {
90            let reference = RelationIdentity::borrowed_reference(source).unwrap();
91            let budget = MemoryBudget::new(1024);
92            let cancellation = CancellationToken::new();
93            let control = ProductionControl::new(&budget, &cancellation, &cancellation);
94            let mut output = None;
95            let measured = allocation_counter::measure(|| {
96                output = Some(reference.render_with_control(&control).unwrap());
97            });
98            let output = output.unwrap();
99            assert_eq!(output.as_str(), expected);
100            assert_eq!(measured.bytes_current, budget.used() as i64);
101            assert_eq!(budget.used(), output.capacity());
102            drop(output);
103            assert_eq!(budget.used(), 0);
104            for available in 0..expected.len() {
105                let budget = MemoryBudget::new(available);
106                let control = ProductionControl::new(&budget, &cancellation, &cancellation);
107                assert!(matches!(
108                    reference.render_with_control(&control),
109                    Err(ValueRetentionError::Memory(_))
110                ));
111                assert_eq!(budget.used(), 0);
112            }
113        }
114    }
115}