no-mistakes-postgres-engine 0.109.130

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use super::ScopeVisitor;
use crate::fx::{FxHashMap, FxHashSet};
use no_mistakes_ts_facts::syntax_helpers::unwrap_ts_wrappers;
use oxc_ast::ast::*;
use oxc_span::Span;

mod parameter_effects;
pub(super) use parameter_effects::parameter_effects;
mod writes;
pub(super) use writes::Writes;

pub(super) struct ParameterFields {
    pub fields: std::collections::HashMap<String, u32>,
    pub calls: Vec<oxc_span::Span>,
    pub suspensions: Vec<oxc_span::Span>,
}

fn origins(
    visitor: &ScopeVisitor<'_>,
    tag: &TaggedTemplateExpression<'_>,
    use_span: Option<Span>,
    stable: bool,
) -> Vec<(u32, u32)> {
    let mut origins = Vec::new();
    for (index, expr) in tag.quasi.expressions.iter().enumerate() {
        if stable
            && super::super::tags::quasi_text(&tag.quasi.quasis[index + 1], false)
                .starts_with(|ch: char| ch.is_ascii_digit())
        {
            continue;
        }
        match expr {
            Expression::Identifier(id) => {
                let Some(binding) = visitor.binding(id.name.as_str()) else {
                    return Vec::new();
                };
                if let Some(identity) = binding.value_identity {
                    let declaration = identity.get() - 1;
                    if visitor.stable_primitives.contains(&declaration)
                        || (stable && visitor.scalar_literals.contains_key(&identity))
                    {
                        origins.push((id.span.start, declaration));
                    }
                }
            }
            Expression::StaticMemberExpression(member) => {
                let Some(identity) = visitor.stable_member_identity(member, use_span, tag.span)
                else {
                    return Vec::new();
                };
                origins.push((member.span.start, identity));
            }
            Expression::StringLiteral(_)
            | Expression::NumericLiteral(_)
            | Expression::BigIntLiteral(_)
            | Expression::BooleanLiteral(_)
            | Expression::NullLiteral(_) => {}
            _ => return Vec::new(),
        }
    }
    if stable || visitor.executor_options.track_lookup_key_bindings {
        return origins;
    }
    let counts = origins
        .iter()
        .fold(FxHashMap::<u32, usize>::default(), |mut counts, (_, id)| {
            *counts.entry(*id).or_default() += 1;
            counts
        });
    origins.retain(|(_, id)| counts[id] > 1);
    origins
}

pub(super) fn annotate(
    visitor: &ScopeVisitor<'_>,
    call: &CallExpression<'_>,
    fact: &mut super::super::EmbeddedSqlCall,
) {
    let Some(argument) = call.arguments.first().and_then(Argument::as_expression) else {
        return;
    };
    let transaction = fact.caller_transaction_id.is_some()
        || (fact.lock_scope_analysis && fact.transaction_id.is_some());
    let proof = match unwrap_ts_wrappers(argument) {
        Expression::Identifier(id)
            if transaction && fact.kind == super::super::EmbeddedSqlKind::ImmutableLocal =>
        {
            visitor
                .binding(id.name.as_str())
                .and_then(|binding| binding.value_identity)
                .and_then(|id| visitor.const_bind_origins.get(&id))
                .filter(|proof| {
                    proof
                        .origins
                        .iter()
                        .all(|&(_, _, id)| visitor.stable_bind_origin_is_live(id))
                })
                .cloned()
        }
        Expression::TaggedTemplateExpression(tag) => {
            project(visitor, argument, tag, Some(call.span), transaction)
        }
        _ => None,
    };
    let Some(proof) = proof else {
        return;
    };
    if fact.sql_text.as_deref() == Some(proof.sql.as_str()) {
        fact.bound_value_origins = proof.origins;
        fact.bound_value_sql = Some(proof.sql);
    }
}

#[derive(Clone)]
pub(super) struct BindOrigins {
    sql: String,
    origins: Vec<(u32, u32, u32)>,
}

pub(super) fn remember_const(visitor: &mut ScopeVisitor<'_>, declaration: &VariableDeclarator<'_>) {
    if !visitor.executor_options.track_transaction_helpers || !visitor.declaring_plain_const {
        return;
    }
    if let (BindingPattern::BindingIdentifier(name), Some(init)) =
        (&declaration.id, &declaration.init)
    {
        if let Expression::TaggedTemplateExpression(tag) = unwrap_ts_wrappers(init) {
            if let Some(id) = super::transaction::source_identity(name.span.start) {
                if let Some(proof) = project(visitor, init, tag, None, true) {
                    visitor.const_bind_origins.insert(id, proof);
                }
            }
        }
    }
}

fn project(
    visitor: &ScopeVisitor<'_>,
    argument: &Expression<'_>,
    tag: &TaggedTemplateExpression<'_>,
    use_span: Option<Span>,
    stable: bool,
) -> Option<BindOrigins> {
    let ids: FxHashMap<_, _> = origins(visitor, tag, use_span, stable)
        .into_iter()
        .collect();
    if ids.is_empty() {
        return None;
    }
    let raw = super::resolve::compose::static_fragment(argument, visitor)?;
    let source =
        super::super::source_positions::origins::expression(argument, visitor.source, &raw);
    let offsets = super::resolve::rewrite_origins(&raw, &source, 0, true);
    let (published, positions) = super::super::publish_placeholders_with_positions(raw);
    let positions: FxHashSet<_> = positions.into_iter().collect();
    let mut origins = Vec::new();
    let (mut line, mut column) = (1, 1);
    for (offset, character) in published.char_indices() {
        if positions.contains(&(line, column)) {
            if let Some(id) = offsets.get(offset).and_then(|origin| ids.get(origin)) {
                origins.push((line, column, *id));
            }
        }
        if character == '\n' {
            line += 1;
            column = 1;
        } else {
            column += 1;
        }
    }
    Some(BindOrigins {
        sql: published,
        origins,
    })
}

fn receiver_name(expression: &Expression<'_>) -> Option<String> {
    let mut expression = unwrap_ts_wrappers(expression);
    while let Some(member) = expression.as_member_expression() {
        expression = unwrap_ts_wrappers(member.object());
    }
    match expression {
        Expression::Identifier(root) => Some(root.name.to_string()),
        _ => None,
    }
}