Skip to main content

no_mistakes_postgres_engine/embedded/
fragment_debug.rs

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