Skip to main content

uqa_sql/ast/
routine_source.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Definition-time source mapping, following `PostgreSQL`'s `pg_proc.c` literal matching.
8
9/// Transient mapping from a routine's decoded source to its original SQL message. Ambiguous matches deliberately have no mapping, as in `PostgreSQL`'s `match_prosrc_to_query`.
10#[derive(Debug, Clone)]
11pub struct RoutineBodyOrigin {
12    prefix_characters: u32,
13    escaped_characters: Vec<u32>,
14}
15
16impl RoutineBodyOrigin {
17    /// Copy diagnostic source positions without reinterpreting the original SQL message.
18    pub(crate) fn clone_with_control(
19        &self,
20        control: &uqa_core::memory::ProductionControl<'_>,
21    ) -> Result<uqa_core::memory::Produced<Self>, crate::SQLError> {
22        let mut escaped = uqa_core::memory::ProductionVec::new(*control);
23        escaped.extend_from_slice(&self.escaped_characters)?;
24        let (escaped_characters, memory) = escaped.finish()?.into_parts();
25        Ok(control.finish(
26            Self {
27                prefix_characters: self.prefix_characters,
28                escaped_characters,
29            },
30            memory,
31        )?)
32    }
33
34    pub(crate) fn capture(body: &str, message: &str) -> Option<Self> {
35        let mut matched = None;
36        for (character_index, (offset, delimiter)) in message.char_indices().enumerate() {
37            let literal = &message[offset + delimiter.len_utf8()..];
38            let escapes = match delimiter {
39                '$' if literal
40                    .strip_prefix(body)
41                    .is_some_and(|rest| rest.starts_with('$')) =>
42                {
43                    Vec::new()
44                }
45                '\'' => match match_literal(body, literal) {
46                    Some(escapes) => escapes,
47                    None => continue,
48                },
49                _ => continue,
50            };
51            if matched.is_some() {
52                return None;
53            }
54            matched = Some(Self {
55                prefix_characters: u32::try_from(character_index + 1).ok()?,
56                escaped_characters: escapes,
57            });
58        }
59        matched
60    }
61
62    pub(crate) fn position(&self, position: u32) -> Option<u32> {
63        let before = position.checked_sub(1)?;
64        let escapes = self
65            .escaped_characters
66            .partition_point(|index| *index < before);
67        self.prefix_characters
68            .checked_add(position)?
69            .checked_add(u32::try_from(escapes).ok()?)
70    }
71}
72
73fn match_literal(body: &str, literal: &str) -> Option<Vec<u32>> {
74    let mut literal = literal.chars().peekable();
75    let mut escaped = Vec::new();
76    for (index, character) in body.chars().enumerate() {
77        match literal.peek().copied()? {
78            '\\' => {
79                literal.next();
80                escaped.push(u32::try_from(index).ok()?);
81            }
82            '\'' => {
83                literal.next();
84                if literal.peek() != Some(&'\'') {
85                    return None;
86                }
87                escaped.push(u32::try_from(index).ok()?);
88            }
89            _ => {}
90        }
91        if literal.next() != Some(character) {
92            return None;
93        }
94    }
95    (literal.next() == Some('\'') && literal.next() != Some('\'')).then_some(escaped)
96}
97
98impl super::CreateFunction {
99    /// Transpose a SQL string body's cursor into its defining request, or retain its internal source when no defining request is available. Other body forms retain their existing diagnostic.
100    pub fn source_body_error(&self, error: crate::SQLError) -> crate::SQLError {
101        match &self.body {
102            super::FunctionBody::Source(body) if self.language == "sql" => {
103                error.in_routine_source(body, self.body_origin.as_ref())
104            }
105            _ => error,
106        }
107    }
108}