Skip to main content

uqa_core/relation_identity/
borrowed.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Borrow canonical relation-reference components without copying their decoded names.
8
9use std::{cmp::Ordering, fmt, str::Chars};
10
11/// One decoded SQL identifier, borrowed from a decoded name or a validated quoted reference.
12#[derive(Debug, Clone, Copy)]
13pub struct RelationName<'a> {
14    text: &'a str,
15    escaped: bool,
16}
17
18impl<'a> RelationName<'a> {
19    /// Borrow an already decoded identifier; punctuation remains part of the name.
20    pub fn decoded(text: &'a str) -> Self {
21        Self {
22            text,
23            escaped: false,
24        }
25    }
26
27    /// Iterate decoded Unicode characters without allocating a temporary string.
28    pub fn chars(self) -> impl Iterator<Item = char> + 'a {
29        DecodedChars {
30            chars: self.text.chars(),
31            escaped: self.escaped,
32        }
33    }
34}
35
36struct DecodedChars<'a> {
37    chars: Chars<'a>,
38    escaped: bool,
39}
40
41impl Iterator for DecodedChars<'_> {
42    type Item = char;
43    fn next(&mut self) -> Option<char> {
44        let character = self.chars.next()?;
45        if self.escaped && character == '"' {
46            self.chars.next();
47        }
48        Some(character)
49    }
50}
51
52impl PartialEq for RelationName<'_> {
53    fn eq(&self, other: &Self) -> bool {
54        self.chars().eq(other.chars())
55    }
56}
57impl Eq for RelationName<'_> {}
58impl PartialOrd for RelationName<'_> {
59    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
60        Some(self.cmp(other))
61    }
62}
63impl Ord for RelationName<'_> {
64    fn cmp(&self, other: &Self) -> Ordering {
65        self.chars().cmp(other.chars())
66    }
67}
68impl fmt::Display for RelationName<'_> {
69    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70        use fmt::Write as _;
71        for character in self.chars() {
72            formatter.write_char(character)?;
73        }
74        Ok(())
75    }
76}
77
78/// A borrowed local or schema-qualified SQL relation reference.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub struct RelationReference<'a> {
81    pub schema: Option<RelationName<'a>>,
82    pub name: RelationName<'a>,
83}
84
85pub(super) enum InvalidReference {
86    Empty,
87    Unterminated,
88    Invalid,
89}
90
91/// A borrowed parse diagnostic. Formatting streams the original input without constructing an intermediate error string.
92pub struct RelationReferenceError<'a> {
93    kind: InvalidReference,
94    input: &'a str,
95}
96impl fmt::Debug for RelationReferenceError<'_> {
97    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
98        fmt::Display::fmt(self, formatter)
99    }
100}
101impl fmt::Display for RelationReferenceError<'_> {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        match self.kind {
104            InvalidReference::Empty => formatter.write_str("persisted relation name is empty"),
105            InvalidReference::Unterminated => write!(
106                formatter,
107                "unterminated quoted relation name `{}`",
108                self.input
109            ),
110            InvalidReference::Invalid => write!(
111                formatter,
112                "invalid persisted relation name `{}`",
113                self.input
114            ),
115        }
116    }
117}
118
119pub(super) fn parse_result(
120    value: &str,
121) -> Result<RelationReference<'_>, RelationReferenceError<'_>> {
122    parse(value).map_err(|kind| RelationReferenceError { kind, input: value })
123}
124
125pub(super) fn parse(value: &str) -> Result<RelationReference<'_>, InvalidReference> {
126    if value.is_empty() {
127        return Err(InvalidReference::Empty);
128    }
129    let mut remaining = value;
130    let first = component(&mut remaining)?;
131    if remaining.is_empty() {
132        return Ok(RelationReference {
133            schema: None,
134            name: first,
135        });
136    }
137    let name = component(&mut remaining)?;
138    if !remaining.is_empty() {
139        return Err(InvalidReference::Invalid);
140    }
141    Ok(RelationReference {
142        schema: Some(first),
143        name,
144    })
145}
146
147fn component<'a>(remaining: &mut &'a str) -> Result<RelationName<'a>, InvalidReference> {
148    let input = *remaining;
149    let quoted = input.starts_with('"');
150    let start = usize::from(quoted);
151    let bytes = input.as_bytes();
152    let mut index = start;
153    let end;
154    if quoted {
155        loop {
156            match bytes.get(index) {
157                None => return Err(InvalidReference::Unterminated),
158                Some(b'"') if bytes.get(index + 1) == Some(&b'"') => index += 2,
159                Some(b'"') => {
160                    end = index;
161                    index += 1;
162                    break;
163                }
164                Some(_) => index += 1,
165            }
166        }
167    } else {
168        while let Some(byte) = bytes.get(index) {
169            match byte {
170                b'.' => break,
171                b'"' => return Err(InvalidReference::Invalid),
172                _ => index += 1,
173            }
174        }
175        end = index;
176    }
177    if end == start {
178        return Err(InvalidReference::Invalid);
179    }
180    *remaining = match bytes.get(index) {
181        None => "",
182        Some(b'.') if index + 1 < bytes.len() => &input[index + 1..],
183        _ => return Err(InvalidReference::Invalid),
184    };
185    Ok(RelationName {
186        text: &input[start..end],
187        escaped: quoted,
188    })
189}