Skip to main content

no_mistakes_postgres_engine/embedded/
fragment_debug.rs

1use super::{EmbeddedSqlCall, EmbeddedSqlVariant, PendingRelativeScope};
2use std::path::PathBuf;
3
4/// A SQL fragment returned from a builder or appended to a
5/// statement builder. These are deliberately separate from executed calls:
6/// structural policies can inspect them without treating builder code as an
7/// executed DML statement.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct EmbeddedSqlFragment {
10    pub line: u32,
11    /// `None` records a proven SQL-builder append whose argument cannot be
12    /// recovered. Structural policies can then honor their fail-closed mode.
13    pub sql_text: Option<String>,
14    /// SQL-local positions of generated interpolation markers in `sql_text`.
15    pub recovered_placeholder_positions: Vec<(u32, u32)>,
16}
17
18/// Fragment contributing to an unanalyzable executor call or builder parameter.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CallSqlFragment {
21    pub sql: String,
22    pub line: u32,
23    pub span: (u32, u32),
24    pub context_sql: Option<String>,
25    pub append_site: Option<u32>,
26    /// A nested function appends to a builder owned by an outer scope.
27    pub deferred_append: bool,
28    pub assembly: CallSqlFragmentAssembly,
29    pub source_origins: super::SqlByteOrigins,
30    pub preceding_tokens: Option<CallSqlPrefixEnd>,
31    /// The helper and builder parameter this `append` extends. Appends that share it are one builder's pieces.
32    pub append_owner: Option<u32>,
33}
34
35#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
36pub enum CallSqlFragmentAssembly {
37    #[default]
38    Whole,
39    OpaqueConcatenation,
40    TrailingPiece,
41    /// Marks an `append` whose argument cannot be recovered. It carries no
42    /// SQL (`sql` is empty) and sits at the append's position in the list.
43    Opaque,
44}
45
46impl CallSqlFragment {
47    pub fn opaque_marker(line: u32, site: u32) -> Self {
48        Self {
49            sql: String::new(),
50            line,
51            span: (site, site),
52            context_sql: None,
53            append_site: Some(site),
54            deferred_append: false,
55            assembly: CallSqlFragmentAssembly::Opaque,
56            source_origins: Default::default(),
57            preceding_tokens: None,
58            append_owner: None,
59        }
60    }
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub enum CallSqlPrefixEnd {
65    TokenBoundary,
66    WhitespaceBoundary,
67    LineComment,
68    Unclosed,
69}
70
71impl CallSqlPrefixEnd {
72    pub fn from_sql(sql: &str) -> Self {
73        use sqlparser::dialect::PostgreSqlDialect;
74        use sqlparser::tokenizer::{Token, Whitespace};
75        match no_mistakes_postgres_sql::parse::operator_boundary::tokenize(
76            &PostgreSqlDialect {},
77            sql,
78        ) {
79            Ok(tokens)
80                if matches!(
81                    tokens.last(),
82                    Some(Token::Whitespace(Whitespace::SingleLineComment { .. }))
83                ) =>
84            {
85                Self::LineComment
86            }
87            Ok(_) => Self::TokenBoundary,
88            Err(_) => Self::Unclosed,
89        }
90    }
91
92    pub fn active_sql_start(self, sql: &str) -> Option<usize> {
93        match self {
94            Self::TokenBoundary | Self::WhitespaceBoundary => Some(0),
95            Self::LineComment => sql.find(['\r', '\n']),
96            Self::Unclosed => None,
97        }
98    }
99}
100
101/// Embedded-SQL facts for one source file.
102#[derive(Clone, Default, PartialEq, Eq)]
103pub struct EmbeddedSqlFileFacts {
104    pub lock_helper_summaries: crate::fx::FxHashMap<String, super::walk::lock_helpers::Summary>,
105    pub imported_lock_helpers: Vec<super::walk::lock_helpers::Invocation>,
106    pub path: PathBuf,
107    pub executor_bindings: Vec<String>,
108    pub calls: Vec<EmbeddedSqlCall>,
109    /// Calls through imported types absent from executorTypeNames; never executed.
110    pub undeclared_executor_types: Vec<super::UndeclaredExecutorType>,
111    /// Private call identities, parallel to `calls`; public summaries stay unchanged.
112    pub call_spans: Vec<(u32, u32)>,
113    /// Summaries of this file's helpers, collected during its single AST pass.
114    pub exported_helpers: crate::fx::FxHashMap<String, super::helpers::HelperSummary>,
115    /// Lowered bodies of the same helpers, run per call site by the projection.
116    pub exported_programs:
117        crate::fx::FxHashMap<String, std::sync::Arc<super::helpers::program::Program>>,
118    pub exported_constants: crate::fx::FxHashMap<String, super::helpers::ExportedConstant>,
119    /// Executor SQL that is complete once imported helpers resolve.
120    pub pending_imported: Vec<super::helpers::PendingImportedSql>,
121    /// Caller lines of the imported-helper calls completed into a call, by span.
122    pub imported_call_lines: crate::fx::FxHashMap<(u32, u32), Vec<u32>>,
123    /// Real TypeScript comments from the same parse, excluding SQL literal text.
124    pub source_comment_spans: Vec<(u32, u32)>,
125    pub fragments: Vec<EmbeddedSqlFragment>,
126    /// Private complete alternatives, parallel to the legacy fragment records.
127    pub fragment_sites: Vec<Option<u32>>,
128    pub fragment_variants: Vec<Vec<EmbeddedSqlVariant>>,
129    /// Fragments attached to unanalyzable executor calls, keyed by call span.
130    pub call_fragments: crate::fx::FxHashMap<(u32, u32), Vec<CallSqlFragment>>,
131    /// Appended SQL fragments on builder parameters (e.g. `q: SQLStatement`).
132    /// Fragments appended to an outer SQL builder from a runtime for-of loop.
133    pub runtime_loop_appends: Vec<CallSqlFragment>,
134    pub param_append_fragments: Vec<CallSqlFragment>,
135    /// Configured `executor_factory_names` this file imports from the configured module.
136    pub matched_factory_names: Vec<String>,
137    /// Configured `executor_type_names` this file imports from the configured module.
138    pub matched_type_names: Vec<String>,
139    /// Relative imports of configured names, projected after the request resolver exists.
140    pub pending_relative: PendingRelativeScope,
141    /// SQL-looking member `.query` calls with no executor proof, by source span.
142    pub unproven_member_queries: Vec<crate::embedded::UnprovenMemberQuery>,
143    /// PostgreSQL rules that share this options profile. Empty means the
144    /// extract has no check rule, so suppression does not apply.
145    pub postgres_rule_ids: Vec<String>,
146    /// When false, a later relative projection must not add member spans.
147    /// Every configured rule for this profile excluded the file.
148    pub record_unproven_spans: bool,
149}
150
151// Fragment alternatives are internal provenance, so the legacy public debug
152// surface remains byte-identical even when precise fragment origins exist.
153impl std::fmt::Debug for EmbeddedSqlFileFacts {
154    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        formatter
156            .debug_struct("EmbeddedSqlFileFacts")
157            .field("path", &self.path)
158            .field("executor_bindings", &self.executor_bindings)
159            .field("calls", &self.calls)
160            .field("call_spans", &self.call_spans)
161            .field("fragments", &self.fragments)
162            .field("matched_factory_names", &self.matched_factory_names)
163            .field("matched_type_names", &self.matched_type_names)
164            .field("pending_relative", &self.pending_relative)
165            .finish()
166    }
167}
168
169impl EmbeddedSqlFileFacts {
170    /// Replace the unrecovered call at `span` with its completed form. Only a
171    /// call still left `Dynamic` by the walk is replaced.
172    pub fn apply_imported_sql(
173        &mut self,
174        span: (u32, u32),
175        completed: EmbeddedSqlCall,
176        lines: Vec<u32>,
177    ) {
178        let Some(index) = self
179            .call_spans
180            .iter()
181            .position(|candidate| *candidate == span)
182        else {
183            return;
184        };
185        let call = &self.calls[index];
186        if call.kind == super::EmbeddedSqlKind::Dynamic && call.variants.is_empty() {
187            let completed_unanalyzable = completed.is_unanalyzable();
188            self.calls[index] = completed;
189            self.imported_call_lines.insert(span, lines);
190            if !completed_unanalyzable {
191                self.call_fragments.remove(&span);
192            }
193        }
194    }
195}