Skip to main content

no_mistakes_postgres_engine/embedded/call/
variants.rs

1use super::super::SqlByteOrigins;
2use super::{EmbeddedSqlCall, EmbeddedSqlKind, EmbeddedSqlSourcePosition};
3use std::borrow::Cow;
4
5/// Default variant budget; append exploration also retains every singleton.
6pub const MAX_EMBEDDED_SQL_VARIANTS: usize = 16;
7
8/// One alternative per entry of an imported frozen object record.
9pub const MAX_FROZEN_OBJECT_SQL_VARIANTS: usize = 64;
10
11/// One complete alternative, with its own physical origin and generated binds.
12#[derive(Debug, Clone, PartialEq, Eq)]
13pub struct EmbeddedSqlVariant {
14    pub sql_text: String,
15    /// Physical source byte origin for each byte of `sql_text`.
16    pub sql_source_offsets: SqlByteOrigins,
17    #[doc(hidden)]
18    pub invocations: super::super::site_identity::Invocations,
19    pub line: u32,
20    pub sql_source_positions: Vec<EmbeddedSqlSourcePosition>,
21    pub recovered_placeholder_positions: Vec<(u32, u32)>,
22    /// Private append occurrences that contributed SQL to this alternative.
23    #[doc(hidden)]
24    pub append_sites: Vec<u32>,
25    #[doc(hidden)]
26    pub first_append_offset: Option<usize>,
27    /// Feasible outcomes remain beyond a site cap, sampled loop, or opaque interpolation.
28    #[doc(hidden)]
29    pub variants_truncated: bool,
30    #[doc(hidden)]
31    pub closed_domain: bool,
32    /// Filled from a parameter type annotation, not a runtime value.
33    #[doc(hidden)]
34    pub type_annotation: bool,
35}
36
37impl EmbeddedSqlVariant {
38    #[doc(hidden)]
39    pub fn push_unique(values: &mut Vec<Self>, value: Self) {
40        let index = values
41            .iter()
42            .position(|other| {
43                other.sql_text == value.sql_text
44                    && other.sql_source_offsets == value.sql_source_offsets
45                    && other.line == value.line
46                    && other.sql_source_positions == value.sql_source_positions
47                    && other.recovered_placeholder_positions
48                        == value.recovered_placeholder_positions
49            })
50            .unwrap_or_else(|| {
51                values.push(value.clone());
52                values.len() - 1
53            });
54        values[index].first_append_offset = values[index]
55            .first_append_offset
56            .zip(value.first_append_offset)
57            .map(|(left, right)| left.max(right));
58        values[index].variants_truncated |= value.variants_truncated;
59        values[index].closed_domain &= value.closed_domain;
60        values[index].type_annotation |= value.type_annotation;
61        for site in value.append_sites {
62            if !values[index].append_sites.contains(&site) {
63                values[index].append_sites.push(site);
64            }
65        }
66    }
67}
68
69impl EmbeddedSqlCall {
70    /// Whether the sole complete version mirrors the legacy raw SQL fields.
71    /// Keep this source presentation for diagnostics while retaining the
72    /// variant's occurrence provenance for consumers that need it.
73    #[doc(hidden)]
74    pub fn mirrors_single_variant(&self) -> bool {
75        let [variant] = self.variants.as_slice() else {
76            return false;
77        };
78        self.kind != EmbeddedSqlKind::Dynamic
79            && !variant.variants_truncated
80            && self.sql_text.as_deref() == Some(variant.sql_text.as_str())
81            && self.recovered_placeholder_positions == variant.recovered_placeholder_positions
82    }
83
84    #[doc(hidden)]
85    pub fn source_offset_at_sql_offset(&self, offset: usize) -> Option<usize> {
86        self.variants
87            .first()
88            .map_or_else(
89                || {
90                    self.sql_source_offsets
91                        .get(offset)
92                        .filter(|offset| *offset != 0)
93                },
94                |variant| variant.sql_source_offsets.get(offset),
95            )
96            .map(|offset| offset as usize)
97    }
98    #[doc(hidden)]
99    pub fn source_offset_at_sql_position(
100        &self,
101        sql: &str,
102        line: usize,
103        column: usize,
104    ) -> Option<usize> {
105        let mut current = (1, 1);
106        for (offset, character) in sql.char_indices() {
107            if current == (line, column) {
108                return self.source_offset_at_sql_offset(offset);
109            }
110            if character == '\n' {
111                current = (current.0 + 1, 1);
112            } else {
113                current.1 += 1;
114            }
115        }
116        None
117    }
118    /// Project prepared alternatives internally without creating public call sites.
119    #[doc(hidden)]
120    pub fn statement_calls(&self) -> impl Iterator<Item = Cow<'_, Self>> + Clone {
121        let mirrored = self.mirrors_single_variant();
122        std::iter::once(Cow::Borrowed(self))
123            .take(usize::from(self.variants.is_empty() || mirrored))
124            .chain(
125                self.variants
126                    .iter()
127                    .filter(move |_| !mirrored)
128                    .map(|variant| {
129                        Cow::Owned(Self {
130                            lock_scope_analysis: self.lock_scope_analysis,
131                            track_share_lock_writes: self.track_share_lock_writes,
132                            track_redundant_prelocks: self.track_redundant_prelocks,
133                            next_discarded_query: self.next_discarded_query,
134                            stable_prelock_parameters: self.stable_prelock_parameters.clone(),
135                            helper_definition: self.helper_definition,
136                            lock_helper: self.lock_helper.clone(),
137                            transaction_id: self.transaction_id,
138                            caller_transaction_id: self.caller_transaction_id,
139                            transaction_line: self.transaction_line,
140                            executor_transaction_known: self.executor_transaction_known,
141                            execution_unconditional: self.execution_unconditional,
142                            execution_awaited: self.execution_awaited,
143                            execution_scope: self.execution_scope,
144                            execution_range: self.execution_range,
145                            bound_parameters: self.bound_parameters.clone(),
146                            bound_value_origins: self.bound_value_origins.clone(),
147                            bound_value_sql: self.bound_value_sql.clone(),
148                            line: self.line,
149                            callee: self.callee.clone(),
150                            sql_text: Some(variant.sql_text.clone()),
151                            kind: if variant.variants_truncated {
152                                EmbeddedSqlKind::Dynamic
153                            } else {
154                                EmbeddedSqlKind::Composed
155                            },
156                            declaration_line: Some(variant.line),
157                            sql_source_positions: variant.sql_source_positions.clone(),
158                            sql_source_offsets: SqlByteOrigins::default(),
159                            recovered_placeholder_positions: variant
160                                .recovered_placeholder_positions
161                                .clone(),
162                            variants: vec![variant.clone()],
163                        })
164                    }),
165            )
166    }
167    #[doc(hidden)]
168    pub fn variants_truncated(&self) -> bool {
169        self.variants
170            .iter()
171            .any(|variant| variant.variants_truncated)
172    }
173    #[doc(hidden)]
174    pub fn is_unanalyzable(&self) -> bool {
175        self.kind == EmbeddedSqlKind::Dynamic
176            && (self.variants.is_empty() || self.variants_truncated())
177    }
178}