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, Default, PartialEq, Eq)]
36pub enum CallSqlFragmentAssembly {
37    #[default]
38    Whole,
39    OpaqueConcatenation(Option<Box<CallSqlFragment>>),
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
63mod prefix_end;
64pub use prefix_end::CallSqlPrefixEnd;
65
66/// Embedded-SQL facts for one source file.
67#[derive(Clone, Default, PartialEq, Eq)]
68pub struct EmbeddedSqlFileFacts {
69    pub lock_helper_summaries: crate::fx::FxHashMap<String, super::walk::lock_helpers::Summary>,
70    pub imported_lock_helpers: Vec<super::walk::lock_helpers::Invocation>,
71    pub path: PathBuf,
72    pub executor_bindings: Vec<String>,
73    pub calls: Vec<EmbeddedSqlCall>,
74    /// Calls through imported types absent from executorTypeNames; never executed.
75    pub undeclared_executor_types: Vec<super::UndeclaredExecutorType>,
76    /// Private call identities, parallel to `calls`; public summaries stay unchanged.
77    pub call_spans: Vec<(u32, u32)>,
78    /// Summaries of this file's helpers, collected during its single AST pass.
79    pub exported_helpers: crate::fx::FxHashMap<String, super::helpers::HelperSummary>,
80    /// Lowered bodies of the same helpers, run per call site by the projection.
81    pub exported_programs:
82        crate::fx::FxHashMap<String, std::sync::Arc<super::helpers::program::Program>>,
83    pub exported_constants: crate::fx::FxHashMap<String, super::helpers::ExportedConstant>,
84    /// Executor SQL that is complete once imported helpers resolve.
85    pub pending_imported: Vec<super::helpers::PendingImportedSql>,
86    /// Caller lines of the imported-helper calls completed into a call, by span.
87    pub imported_call_lines: crate::fx::FxHashMap<(u32, u32), Vec<u32>>,
88    /// Real TypeScript comments from the same parse, excluding SQL literal text.
89    pub source_comment_spans: Vec<(u32, u32)>,
90    pub fragments: Vec<EmbeddedSqlFragment>,
91    /// Private complete alternatives, parallel to the legacy fragment records.
92    pub fragment_sites: Vec<Option<u32>>,
93    pub fragment_variants: Vec<Vec<EmbeddedSqlVariant>>,
94    /// Fragments attached to unanalyzable executor calls, keyed by call span.
95    pub call_fragments: crate::fx::FxHashMap<(u32, u32), Vec<CallSqlFragment>>,
96    /// Appended SQL fragments on builder parameters (e.g. `q: SQLStatement`).
97    /// Fragments appended to an outer SQL builder from a runtime for-of loop.
98    pub runtime_loop_appends: Vec<CallSqlFragment>,
99    pub param_append_fragments: Vec<CallSqlFragment>,
100    /// Configured `executor_factory_names` this file imports from the configured module.
101    pub matched_factory_names: Vec<String>,
102    /// Configured `executor_type_names` this file imports from the configured module.
103    pub matched_type_names: Vec<String>,
104    /// Relative imports of configured names, projected after the request resolver exists.
105    pub pending_relative: PendingRelativeScope,
106    /// SQL-looking member `.query` calls with no executor proof, by source span.
107    pub unproven_member_queries: Vec<crate::embedded::UnprovenMemberQuery>,
108    /// PostgreSQL rules that share this options profile. Empty means the
109    /// extract has no check rule, so suppression does not apply.
110    pub postgres_rule_ids: Vec<String>,
111    /// When false, a later relative projection must not add member spans.
112    /// Every configured rule for this profile excluded the file.
113    pub record_unproven_spans: bool,
114}
115
116// Fragment alternatives are internal provenance, so the legacy public debug
117// surface remains byte-identical even when precise fragment origins exist.
118impl std::fmt::Debug for EmbeddedSqlFileFacts {
119    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        formatter
121            .debug_struct("EmbeddedSqlFileFacts")
122            .field("path", &self.path)
123            .field("executor_bindings", &self.executor_bindings)
124            .field("calls", &self.calls)
125            .field("call_spans", &self.call_spans)
126            .field("fragments", &self.fragments)
127            .field("matched_factory_names", &self.matched_factory_names)
128            .field("matched_type_names", &self.matched_type_names)
129            .field("pending_relative", &self.pending_relative)
130            .finish()
131    }
132}
133
134impl EmbeddedSqlFileFacts {
135    /// Replace the unrecovered call at `span` with its completed form. Only a
136    /// call still left `Dynamic` by the walk is replaced.
137    pub fn apply_imported_sql(
138        &mut self,
139        span: (u32, u32),
140        completed: EmbeddedSqlCall,
141        lines: Vec<u32>,
142    ) {
143        let Some(index) = self
144            .call_spans
145            .iter()
146            .position(|candidate| *candidate == span)
147        else {
148            return;
149        };
150        let call = &self.calls[index];
151        if call.kind == super::EmbeddedSqlKind::Dynamic && call.variants.is_empty() {
152            let completed_unanalyzable = completed.is_unanalyzable();
153            self.calls[index] = completed;
154            self.imported_call_lines.insert(span, lines);
155            if !completed_unanalyzable {
156                self.call_fragments.remove(&span);
157            }
158        }
159    }
160}