Skip to main content

no_mistakes_postgres_engine/embedded/
placeholders.rs

1/// Generated interpolation markers must be distinguishable from user-authored
2/// SQL that happens to contain the public `sql_placeholder_` substring.
3pub(super) const PLACEHOLDER_MARKER: &str = "sql_placeholder_";
4pub const INTERNAL_PLACEHOLDER: &str = "\u{10FFFF}sqlph_";
5
6pub const INTERNAL_BIND: &str = "\u{10FFFF}sqlbv_";
7
8pub fn internal_bind(index: usize) -> String {
9    format!("{INTERNAL_BIND}{index}")
10}
11
12pub fn markers(text: &str) -> impl Iterator<Item = (usize, &'static str, &'static str)> + '_ {
13    text.match_indices('\u{10FFFF}').filter_map(|(at, _)| {
14        if text[at..].starts_with(INTERNAL_PLACEHOLDER) {
15            Some((at, INTERNAL_PLACEHOLDER, PLACEHOLDER_MARKER))
16        } else if text[at..].starts_with(INTERNAL_BIND) {
17            Some((at, INTERNAL_BIND, "$"))
18        } else {
19            None
20        }
21    })
22}
23
24pub(super) fn internal_placeholder(index: usize) -> String {
25    format!("{INTERNAL_PLACEHOLDER}{index}")
26}
27
28pub(super) fn publish_placeholders(text: String) -> String {
29    text.replace(INTERNAL_PLACEHOLDER, PLACEHOLDER_MARKER)
30        .replace(INTERNAL_BIND, "$")
31}
32
33/// Replace internal markers while retaining the exact SQL positions of generated values.
34pub fn publish_placeholders_with_positions(text: String) -> (String, Vec<(u32, u32)>) {
35    let mut output = String::with_capacity(text.len());
36    let mut positions = Vec::new();
37    let mut line = 1;
38    let mut column = 1;
39    let mut rest = text.as_str();
40    while let Some((at, internal, public)) = markers(rest).next() {
41        let prefix = &rest[..at];
42        output.push_str(prefix);
43        advance_position(prefix, &mut line, &mut column);
44        let after = &rest[at + internal.len()..];
45        let digits = after.bytes().take_while(u8::is_ascii_digit).count();
46        let marker = format!("{public}{}", &after[..digits]);
47        positions.push((line, column));
48        output.push_str(&marker);
49        advance_position(&marker, &mut line, &mut column);
50        rest = &after[digits..];
51    }
52    output.push_str(rest);
53    (output, positions)
54}
55
56fn advance_position(text: &str, line: &mut u32, column: &mut u32) {
57    for character in text.chars() {
58        if character == '\n' {
59            *line += 1;
60            *column = 1;
61        } else {
62            *column += 1;
63        }
64    }
65}
66
67#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
68pub struct Counts {
69    pub all: u32,
70    pub binds: u32,
71}
72impl Counts {
73    pub fn next(&mut self, marker: &str) -> u32 {
74        self.all += 1;
75        if marker == INTERNAL_BIND {
76            self.binds += 1;
77            self.binds
78        } else {
79            self.all
80        }
81    }
82    pub fn shift(self, marker: &str) -> u32 {
83        if marker == INTERNAL_BIND {
84            self.binds
85        } else {
86            self.all
87        }
88    }
89}
90impl From<u32> for Counts {
91    fn from(value: u32) -> Self {
92        Self {
93            all: value,
94            binds: value,
95        }
96    }
97}
98impl std::ops::AddAssign for Counts {
99    fn add_assign(&mut self, other: Self) {
100        self.all += other.all;
101        self.binds += other.binds;
102    }
103}
104
105pub fn count_placeholders(text: &str) -> Counts {
106    let mut counts = Counts::default();
107    for (_, internal, _) in markers(text) {
108        counts.next(internal);
109    }
110    counts
111}
112
113/// Shift generated markers, counting bound values independently of identifier holes.
114pub fn renumber_placeholders(text: &str, offset: impl Into<Counts>) -> String {
115    let offset = offset.into();
116    if offset == Counts::default() {
117        return text.to_string();
118    }
119    let mut out = String::with_capacity(text.len());
120    let mut rest = text;
121    let mut seen = Counts::default();
122    while let Some((position, internal, _)) = markers(rest).next() {
123        out.push_str(&rest[..position]);
124        let after_marker = &rest[position + internal.len()..];
125        let digits = after_marker.bytes().take_while(u8::is_ascii_digit).count();
126        let ordinal = seen.next(internal);
127        out.push_str(internal);
128        out.push_str(&(offset.shift(internal) + ordinal).to_string());
129        rest = &after_marker[digits..];
130    }
131    out.push_str(rest);
132    out
133}
134
135pub fn parameterize_values(text: &str) -> String {
136    let mut out = String::with_capacity(text.len());
137    let (mut cursor, mut binds) = (0, 0);
138    for (at, internal, _) in markers(text) {
139        let end = at
140            + internal.len()
141            + text[at + internal.len()..]
142                .bytes()
143                .take_while(u8::is_ascii_digit)
144                .count();
145        out.push_str(&text[cursor..at]);
146        if super::helpers::sentinel::in_relation_slot(text, at) {
147            out.push_str(&text[at..end]);
148        } else {
149            binds += 1;
150            out.push_str(&internal_bind(binds));
151        }
152        cursor = end;
153    }
154    out.push_str(&text[cursor..]);
155    out
156}