no-mistakes-postgres-engine 0.109.128

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::{EmbeddedSqlCall, EmbeddedSqlVariant, PendingRelativeScope};
use std::path::PathBuf;

/// A SQL fragment returned from a builder or appended to a
/// statement builder. These are deliberately separate from executed calls:
/// structural policies can inspect them without treating builder code as an
/// executed DML statement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmbeddedSqlFragment {
    pub line: u32,
    /// `None` records a proven SQL-builder append whose argument cannot be
    /// recovered. Structural policies can then honor their fail-closed mode.
    pub sql_text: Option<String>,
    /// SQL-local positions of generated interpolation markers in `sql_text`.
    pub recovered_placeholder_positions: Vec<(u32, u32)>,
}

/// Fragment contributing to an unanalyzable executor call or builder parameter.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CallSqlFragment {
    pub sql: String,
    pub line: u32,
    pub span: (u32, u32),
    pub context_sql: Option<String>,
    pub append_site: Option<u32>,
    /// A nested function appends to a builder owned by an outer scope.
    pub deferred_append: bool,
    pub assembly: CallSqlFragmentAssembly,
    pub source_origins: super::SqlByteOrigins,
    pub preceding_tokens: Option<CallSqlPrefixEnd>,
    /// The helper and builder parameter this `append` extends. Appends that share it are one builder's pieces.
    pub append_owner: Option<u32>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum CallSqlFragmentAssembly {
    #[default]
    Whole,
    OpaqueConcatenation(Option<Box<CallSqlFragment>>),
    TrailingPiece,
    /// Marks an `append` whose argument cannot be recovered. It carries no
    /// SQL (`sql` is empty) and sits at the append's position in the list.
    Opaque,
}

impl CallSqlFragment {
    pub fn opaque_marker(line: u32, site: u32) -> Self {
        Self {
            sql: String::new(),
            line,
            span: (site, site),
            context_sql: None,
            append_site: Some(site),
            deferred_append: false,
            assembly: CallSqlFragmentAssembly::Opaque,
            source_origins: Default::default(),
            preceding_tokens: None,
            append_owner: None,
        }
    }
}

mod prefix_end;
pub use prefix_end::CallSqlPrefixEnd;

/// Embedded-SQL facts for one source file.
#[derive(Clone, Default, PartialEq, Eq)]
pub struct EmbeddedSqlFileFacts {
    pub lock_helper_summaries: crate::fx::FxHashMap<String, super::walk::lock_helpers::Summary>,
    pub imported_lock_helpers: Vec<super::walk::lock_helpers::Invocation>,
    pub path: PathBuf,
    pub executor_bindings: Vec<String>,
    pub calls: Vec<EmbeddedSqlCall>,
    /// Calls through imported types absent from executorTypeNames; never executed.
    pub undeclared_executor_types: Vec<super::UndeclaredExecutorType>,
    /// Private call identities, parallel to `calls`; public summaries stay unchanged.
    pub call_spans: Vec<(u32, u32)>,
    /// Summaries of this file's helpers, collected during its single AST pass.
    pub exported_helpers: crate::fx::FxHashMap<String, super::helpers::HelperSummary>,
    /// Lowered bodies of the same helpers, run per call site by the projection.
    pub exported_programs:
        crate::fx::FxHashMap<String, std::sync::Arc<super::helpers::program::Program>>,
    pub exported_constants: crate::fx::FxHashMap<String, super::helpers::ExportedConstant>,
    /// Executor SQL that is complete once imported helpers resolve.
    pub pending_imported: Vec<super::helpers::PendingImportedSql>,
    /// Caller lines of the imported-helper calls completed into a call, by span.
    pub imported_call_lines: crate::fx::FxHashMap<(u32, u32), Vec<u32>>,
    /// Real TypeScript comments from the same parse, excluding SQL literal text.
    pub source_comment_spans: Vec<(u32, u32)>,
    pub fragments: Vec<EmbeddedSqlFragment>,
    /// Private complete alternatives, parallel to the legacy fragment records.
    pub fragment_sites: Vec<Option<u32>>,
    pub fragment_variants: Vec<Vec<EmbeddedSqlVariant>>,
    /// Fragments attached to unanalyzable executor calls, keyed by call span.
    pub call_fragments: crate::fx::FxHashMap<(u32, u32), Vec<CallSqlFragment>>,
    /// Appended SQL fragments on builder parameters (e.g. `q: SQLStatement`).
    /// Fragments appended to an outer SQL builder from a runtime for-of loop.
    pub runtime_loop_appends: Vec<CallSqlFragment>,
    pub param_append_fragments: Vec<CallSqlFragment>,
    /// Configured `executor_factory_names` this file imports from the configured module.
    pub matched_factory_names: Vec<String>,
    /// Configured `executor_type_names` this file imports from the configured module.
    pub matched_type_names: Vec<String>,
    /// Relative imports of configured names, projected after the request resolver exists.
    pub pending_relative: PendingRelativeScope,
    /// SQL-looking member `.query` calls with no executor proof, by source span.
    pub unproven_member_queries: Vec<crate::embedded::UnprovenMemberQuery>,
    /// PostgreSQL rules that share this options profile. Empty means the
    /// extract has no check rule, so suppression does not apply.
    pub postgres_rule_ids: Vec<String>,
    /// When false, a later relative projection must not add member spans.
    /// Every configured rule for this profile excluded the file.
    pub record_unproven_spans: bool,
}

// Fragment alternatives are internal provenance, so the legacy public debug
// surface remains byte-identical even when precise fragment origins exist.
impl std::fmt::Debug for EmbeddedSqlFileFacts {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("EmbeddedSqlFileFacts")
            .field("path", &self.path)
            .field("executor_bindings", &self.executor_bindings)
            .field("calls", &self.calls)
            .field("call_spans", &self.call_spans)
            .field("fragments", &self.fragments)
            .field("matched_factory_names", &self.matched_factory_names)
            .field("matched_type_names", &self.matched_type_names)
            .field("pending_relative", &self.pending_relative)
            .finish()
    }
}

impl EmbeddedSqlFileFacts {
    /// Replace the unrecovered call at `span` with its completed form. Only a
    /// call still left `Dynamic` by the walk is replaced.
    pub fn apply_imported_sql(
        &mut self,
        span: (u32, u32),
        completed: EmbeddedSqlCall,
        lines: Vec<u32>,
    ) {
        let Some(index) = self
            .call_spans
            .iter()
            .position(|candidate| *candidate == span)
        else {
            return;
        };
        let call = &self.calls[index];
        if call.kind == super::EmbeddedSqlKind::Dynamic && call.variants.is_empty() {
            let completed_unanalyzable = completed.is_unanalyzable();
            self.calls[index] = completed;
            self.imported_call_lines.insert(span, lines);
            if !completed_unanalyzable {
                self.call_fragments.remove(&span);
            }
        }
    }
}