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    pub(crate) fn capture(body: &str, message: &str) -> Option<Self> {
18        let mut matched = None;
19        for (character_index, (offset, delimiter)) in message.char_indices().enumerate() {
20            let literal = &message[offset + delimiter.len_utf8()..];
21            let escapes = match delimiter {
22                '$' if literal
23                    .strip_prefix(body)
24                    .is_some_and(|rest| rest.starts_with('$')) =>
25                {
26                    Vec::new()
27                }
28                '\'' => match match_literal(body, literal) {
29                    Some(escapes) => escapes,
30                    None => continue,
31                },
32                _ => continue,
33            };
34            if matched.is_some() {
35                return None;
36            }
37            matched = Some(Self {
38                prefix_characters: u32::try_from(character_index + 1).ok()?,
39                escaped_characters: escapes,
40            });
41        }
42        matched
43    }
44
45    pub(crate) fn position(&self, position: u32) -> Option<u32> {
46        let before = position.checked_sub(1)?;
47        let escapes = self
48            .escaped_characters
49            .partition_point(|index| *index < before);
50        self.prefix_characters
51            .checked_add(position)?
52            .checked_add(u32::try_from(escapes).ok()?)
53    }
54}
55
56fn match_literal(body: &str, literal: &str) -> Option<Vec<u32>> {
57    let mut literal = literal.chars().peekable();
58    let mut escaped = Vec::new();
59    for (index, character) in body.chars().enumerate() {
60        match literal.peek().copied()? {
61            '\\' => {
62                literal.next();
63                escaped.push(u32::try_from(index).ok()?);
64            }
65            '\'' => {
66                literal.next();
67                if literal.peek() != Some(&'\'') {
68                    return None;
69                }
70                escaped.push(u32::try_from(index).ok()?);
71            }
72            _ => {}
73        }
74        if literal.next() != Some(character) {
75            return None;
76        }
77    }
78    (literal.next() == Some('\'') && literal.next() != Some('\'')).then_some(escaped)
79}
80
81impl super::CreateFunction {
82    /// 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.
83    pub fn source_body_error(&self, error: crate::SQLError) -> crate::SQLError {
84        match &self.body {
85            super::FunctionBody::Source(body) if self.language == "sql" => {
86                error.in_routine_source(body, self.body_origin.as_ref())
87            }
88            _ => error,
89        }
90    }
91}