no-mistakes-postgres-engine 0.109.125

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use serde::{Deserialize, Serialize};

mod executor_selection;

const DEFAULT_EXECUTOR_NAMES: &[&str] = &["query", "read", "write"];

/// A named import the user asserts is a parameterized SQL tag.
///
/// Matching is syntactic: `name` imported from `module` or a subpath of it.
/// Empty `module` or `name` matches nothing.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustedSqlTag {
    pub module: String,
    pub name: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SqlIdentifierAssertion {
    pub module: String,
    pub name: String,
    pub allowlist_argument: usize,
}

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ExecutorOption {
    pub name: String,
}

/// Configurable executor import matching. Empty defaults select no executors.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EmbeddedSqlOptions {
    pub import_specifier: String,
    pub executor_names: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub exclude_executor_names: Vec<String>,
    /// Named imports whose call result bound to a local is an executor.
    pub executor_factory_names: Vec<String>,
    /// Imported type names whose annotated parameters are executors.
    pub executor_type_names: Vec<String>,
    #[doc(hidden)]
    #[serde(skip)]
    pub transaction_executor_type_names: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub executor_option_properties: Vec<String>,
    /// Named imports trusted as parameterized SQL tags. Empty trusts none.
    pub trusted_sql_tags: Vec<TrustedSqlTag>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub raw_sql_tags: Vec<TrustedSqlTag>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sql_identifier_assertions: Vec<SqlIdentifierAssertion>,
    /// Exact module#export identities of annotation-only literal wrappers.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub sql_literal_helpers: Vec<String>,
    #[serde(skip)]
    pub track_transaction_helpers: bool,
    #[serde(skip)]
    pub track_share_lock_writes: bool,
    #[serde(skip)]
    pub track_runtime_loop_appends: bool,
    #[serde(skip)]
    pub track_lookup_key_bindings: bool,
    #[serde(skip)]
    pub track_redundant_prelocks: bool,
    #[doc(hidden)]
    #[serde(skip)]
    pub exact_constant_origins: bool,
}
impl EmbeddedSqlOptions {
    /// A configured module enables standard executor names. Without a module,
    /// names must be explicit and may match named imports from any module.
    pub fn configured(import_specifier: &str, executor_names: &[String]) -> Self {
        let mut names = if executor_names.is_empty() && !import_specifier.is_empty() {
            DEFAULT_EXECUTOR_NAMES
                .iter()
                .map(|name| (*name).to_string())
                .collect()
        } else {
            executor_names.to_vec()
        };
        names.sort();
        names.dedup();
        Self {
            import_specifier: import_specifier.to_string(),
            executor_names: names,
            exclude_executor_names: Vec::new(),
            executor_factory_names: Vec::new(),
            executor_type_names: Vec::new(),
            transaction_executor_type_names: Vec::new(),
            executor_option_properties: Vec::new(),
            trusted_sql_tags: Vec::new(),
            raw_sql_tags: Vec::new(),
            sql_identifier_assertions: Vec::new(),
            sql_literal_helpers: Vec::new(),
            track_transaction_helpers: false,
            track_share_lock_writes: false,
            track_runtime_loop_appends: false,
            track_lookup_key_bindings: false,
            track_redundant_prelocks: false,
            exact_constant_origins: false,
        }
    }

    /// Extend the standard executor imports while retaining all defaults.
    pub fn with_extra_executor_names(mut self, extras: Option<&[String]>) -> Self {
        if let Some(extras) = extras {
            self.executor_names
                .extend(DEFAULT_EXECUTOR_NAMES.iter().map(|name| (*name).into()));
            self.executor_names.extend_from_slice(extras);
            self.executor_names.sort();
            self.executor_names.dedup();
        }
        self
    }

    /// Remove intentionally excluded imports after replacement or extension.
    pub fn with_exclude_executor_names(mut self, exclusions: &[String]) -> Self {
        self.exclude_executor_names = sorted_unique(exclusions);
        self.executor_names
            .retain(|name| !exclusions.contains(name));
        self
    }

    /// Add scoped executor sources: factory imports and executor type imports.
    pub fn with_scoped_executors(mut self, factories: &[String], types: &[String]) -> Self {
        self.executor_factory_names = sorted_unique(factories);
        self.executor_type_names = sorted_unique(types);
        self
    }

    pub fn with_transaction_executor_types(mut self, types: &[String]) -> Self {
        self.transaction_executor_type_names = sorted_unique(types);
        self.executor_type_names.extend_from_slice(types);
        self.executor_type_names.sort();
        self.executor_type_names.dedup();
        self
    }

    /// Select transaction executor overrides from explicit options properties.
    pub fn with_executor_option_properties(mut self, properties: &[String]) -> Self {
        self.executor_option_properties = sorted_unique(properties);
        self
    }

    pub fn with_executor_options(mut self, options: &[ExecutorOption]) -> Self {
        self.executor_option_properties
            .extend(options.iter().map(|option| option.name.clone()));
        self.executor_option_properties.sort();
        self.executor_option_properties.dedup();
        self
    }

    /// Configure annotation-only wrappers; argument syntax is checked separately.
    pub fn with_sql_literal_helpers(mut self, helpers: &[String]) -> Self {
        self.sql_literal_helpers = sorted_unique(helpers);
        self
    }

    pub fn with_sql_identifier_assertions(mut self, assertions: &[SqlIdentifierAssertion]) -> Self {
        self.sql_identifier_assertions = assertions.to_vec();
        self.sql_identifier_assertions.sort();
        self.sql_identifier_assertions.dedup();
        self
    }

    pub fn with_raw_sql_tags(mut self, tags: &[TrustedSqlTag]) -> Self {
        self.raw_sql_tags = tags.to_vec();
        self.raw_sql_tags.sort();
        self.raw_sql_tags.dedup();
        self
    }

    pub fn with_exact_constant_origins(mut self) -> Self {
        self.exact_constant_origins = true;
        self
    }

    /// Opt in to parameterized tags. Order does not affect the profile key.
    pub fn with_trusted_sql_tags(mut self, tags: &[TrustedSqlTag]) -> Self {
        let mut tags = tags.to_vec();
        tags.sort();
        tags.dedup();
        self.trusted_sql_tags = tags;
        self
    }
}

fn sorted_unique(names: &[String]) -> Vec<String> {
    let mut names = names.to_vec();
    names.sort();
    names.dedup();
    names
}