uqa_sql/ast/
routine_source.rs1#[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 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}