no-mistakes-postgres-engine 0.109.131

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
#[path = "bind_values.rs"]
mod bind_values;
use super::rebase::rebase_embedded_lines;
use crate::embedded::{EmbeddedSqlFileFacts, EmbeddedSqlKind};
use crate::statements::{
    extract_sql_conflict_policy_facts, extract_sql_statement_facts_with_location_demand,
    extract_sql_statement_facts_with_policy,
};
use no_mistakes_postgres_sql::statement_facts::{SqlLocationDemand, SqlStatementFileFacts};

pub(super) fn embedded_call_facts_with_policy(
    file: &EmbeddedSqlFileFacts,
    collect_bounds: bool,
    variants_only: bool,
    demand: SqlLocationDemand,
    mut policy: crate::statements::StatementPolicySources<'_>,
) -> Vec<SqlStatementFileFacts> {
    policy.sql_batch = true;
    let exact_locations = demand != SqlLocationDemand::None;
    file.calls
        .iter()
        .enumerate()
        .filter(|(_, call)| !variants_only || !call.variants.is_empty())
        .flat_map(|(call_index, call)| {
            let mirrored = call.mirrors_single_variant();
            call.statement_calls()
                .enumerate()
                .map(move |(variant_index, version)| {
                    (
                        version,
                        !call.variants.is_empty(),
                        mirrored,
                        call_index,
                        variant_index,
                    )
                })
        })
        .filter_map(|(call, variant, mirrored, call_index, variant_index)| {
            let sql = call.sql_text.as_deref()?;
            // Ordering rejects opaque tails before consulting prepared statements.
            // Keep all facts for variants and general/bounds consumers.
            let conflict_only =
                demand == SqlLocationDemand::Conflicts && !collect_bounds && !variant;
            if conflict_only
                && (call.kind == EmbeddedSqlKind::Dynamic
                    || !no_mistakes_postgres_sql::conflict::may_have_insert_conflict(sql))
            {
                return None;
            }
            // General consumers and variants retain the complete projection.
            let projection = if variant || !call.sql_source_positions.is_empty() {
                SqlLocationDemand::Full
            } else {
                demand
            };
            let opaque_prefix = call.kind == EmbeddedSqlKind::Dynamic && !variant;
            let opaque_sql_prefix = opaque_prefix && exact_locations;
            let binds = collect_bounds.then(|| bind_values::collect(&call, &file.path));
            let mut facts = if let Some(binds) = binds.filter(|binds| !binds.is_empty()) {
                crate::statements::extract_with_bound_values(
                    sql,
                    &call.recovered_placeholder_positions,
                    projection,
                    call.lock_scope_analysis,
                    crate::statements::StatementPolicySources {
                        bind_values: binds,
                        opaque_sql_prefix,
                        share_lock_writes: call.track_share_lock_writes,
                        redundant_prelocks: call.track_redundant_prelocks,
                        ..policy.clone()
                    },
                )
            } else if conflict_only {
                extract_sql_conflict_policy_facts(sql, &call.recovered_placeholder_positions)
            } else if call.lock_scope_analysis
                && !policy.collect_grouping
                && !policy.collect_duplicate_keyed_lookups
                && !call.track_share_lock_writes
                && !call.track_redundant_prelocks
            {
                crate::statements::extract_sql_lock_scope_facts(
                    sql,
                    collect_bounds,
                    &call.recovered_placeholder_positions,
                    projection,
                    crate::statements::StatementPolicySources {
                        opaque_sql_prefix,
                        ..policy.clone()
                    },
                )
            } else if opaque_sql_prefix
                || call.lock_scope_analysis
                || policy.collect_json_writes
                || policy.collect_duplicate_keyed_lookups
                || policy.collect_index_probes
                || policy.collect_body_bounds
                || policy.collect_grouping
                || policy.collect_lookup_steps
                || policy.collect_lock_inventory
            {
                extract_sql_statement_facts_with_policy(
                    sql,
                    collect_bounds,
                    Some(&call.recovered_placeholder_positions),
                    projection,
                    crate::statements::StatementPolicySources {
                        opaque_sql_prefix,
                        share_lock_writes: call.track_share_lock_writes,
                        redundant_prelocks: call.track_redundant_prelocks,
                        ..policy.clone()
                    },
                    call.lock_scope_analysis,
                )
            } else {
                extract_sql_statement_facts_with_location_demand(
                    sql,
                    collect_bounds,
                    &call.recovered_placeholder_positions,
                    projection,
                )
            };
            if opaque_prefix {
                // Retain upstream policy operations, OFFSET syntax, and write targets
                // from opaque prefixes; literal JSON values still require complete SQL.
                let locations = exact_locations
                    .then(|| facts.variant_locations.take())
                    .flatten();
                let parse_failed = exact_locations && facts.parse_failed;
                facts = SqlStatementFileFacts {
                    statement_kinds: facts.statement_kinds,
                    setting_uses: facts.setting_uses,
                    clause_uses: facts.clause_uses,
                    function_calls: facts.function_calls,
                    offset_uses: facts.offset_uses,
                    writes: facts.writes,
                    variant_locations: locations,
                    parse_failed,
                    parse_failures: if parse_failed {
                        facts.parse_failures
                    } else {
                        Vec::new()
                    },
                    ..Default::default()
                };
            }
            facts.path = file.path.clone();
            if let Some(locations) = &mut facts.variant_locations {
                locations.original_call_line = call.line;
                locations.call_index = call_index;
                locations.variant_index = variant_index;
                locations.caller_lines = file
                    .call_spans
                    .get(call_index)
                    .and_then(|span| file.imported_call_lines.get(span))
                    .cloned()
                    .unwrap_or_default();
                locations.first_append_position = call
                    .variants
                    .first()
                    .and_then(|variant| variant.first_append_offset)
                    .and_then(|at| sql.get(..at))
                    .map(|prefix| {
                        prefix.chars().fold((1, 1), |(line, column), character| {
                            if character == '\n' {
                                (line + 1, 1)
                            } else {
                                (line, column + 1)
                            }
                        })
                    });
                locations.append_sites = call
                    .variants
                    .first()
                    .map_or_else(Vec::new, |variant| variant.append_sites.clone());
            }
            rebase_embedded_lines(&mut facts, &call, variant && !mirrored);
            Some(facts)
        })
        .collect()
}