Skip to main content

no_mistakes_postgres_engine/embedded/
bindings.rs

1use super::scoped_bindings::ScopedExecutors;
2use super::EmbeddedSqlOptions;
3use no_mistakes_ts_facts::syntax_helpers::unwrap_ts_wrappers;
4use oxc_ast::ast::{
5    CallExpression, Expression, ImportDeclaration, ImportDeclarationSpecifier, ImportOrExportKind,
6    ModuleExportName, Program, Statement,
7};
8use std::collections::HashSet;
9
10const TRANSACTION_IMPORTS: &[&str] = &["withTransaction", "withTransactionOptions"];
11const QUERY_PROPERTY: &str = "query";
12// `executor_bindings` is a long-standing public `HashSet<String>` helper. Keep
13// member-query selection in that value without confusing it with a local JS
14// identifier (NUL cannot occur in one), and filter it from reported facts.
15pub(super) const MEMBER_QUERY_OPT_IN: &str = "\0no-mistakes:member-query";
16const SQL_TEMPLATE_STRINGS: &str = "sql-template-strings";
17const SQL_STATEMENT: &str = "SQLStatement";
18
19pub(super) fn sql_statement_type_bindings(program: &Program<'_>) -> HashSet<String> {
20    let mut bindings = HashSet::new();
21    for statement in &program.body {
22        let Statement::ImportDeclaration(import) = statement else {
23            continue;
24        };
25        if no_mistakes_ts_facts::ast::js_literal(&import.source).as_ref() != SQL_TEMPLATE_STRINGS {
26            continue;
27        }
28        let Some(specifiers) = &import.specifiers else {
29            continue;
30        };
31        for specifier in specifiers {
32            let ImportDeclarationSpecifier::ImportSpecifier(named) = specifier else {
33                continue;
34            };
35            if module_export_name(&named.imported) == SQL_STATEMENT {
36                bindings.insert(named.local.name.to_string());
37            }
38        }
39    }
40    bindings
41}
42
43/// Local identifiers bound as SQL executors by the configured specifier.
44///
45/// The set also carries a reserved non-identifier marker when `.query()`
46/// member calls are enabled by the options. Use [`is_database_call`] rather
47/// than inspecting the marker directly.
48pub fn executor_bindings(program: &Program<'_>, options: &EmbeddedSqlOptions) -> HashSet<String> {
49    let mut bindings = HashSet::new();
50    for statement in &program.body {
51        let Statement::ImportDeclaration(import) = statement else {
52            continue;
53        };
54        collect_import_bindings(import, options, &mut bindings);
55    }
56    if member_query_enabled(options) {
57        bindings.insert(MEMBER_QUERY_OPT_IN.to_string());
58    }
59    bindings
60}
61
62fn member_query_enabled(options: &EmbeddedSqlOptions) -> bool {
63    options.import_specifier.is_empty()
64        && options
65            .executor_names
66            .iter()
67            .any(|name| name == QUERY_PROPERTY)
68}
69
70fn executor_name_enabled(options: &EmbeddedSqlOptions, imported: &str) -> bool {
71    options.executor_names.iter().any(|name| name == imported)
72        || (options.uses_legacy_executor_defaults()
73            && !options.import_specifier.is_empty()
74            && ["query", "read", "write"].contains(&imported))
75}
76
77fn collect_import_bindings(
78    import: &ImportDeclaration<'_>,
79    options: &EmbeddedSqlOptions,
80    bindings: &mut HashSet<String>,
81) {
82    if import.import_kind == ImportOrExportKind::Type
83        || (!options.import_specifier.is_empty()
84            && no_mistakes_ts_facts::ast::js_literal(&import.source).as_ref()
85                != options.import_specifier)
86    {
87        return;
88    }
89    let Some(specifiers) = &import.specifiers else {
90        return;
91    };
92    for specifier in specifiers {
93        let ImportDeclarationSpecifier::ImportSpecifier(named) = specifier else {
94            continue;
95        };
96        if named.import_kind == ImportOrExportKind::Type {
97            continue;
98        }
99        let imported = module_export_name(&named.imported);
100        if !options.import_specifier.is_empty() && TRANSACTION_IMPORTS.contains(&imported.as_str())
101        {
102            bindings.insert(QUERY_PROPERTY.to_string());
103        }
104        if executor_name_enabled(options, &imported) {
105            bindings.insert(named.local.name.to_string());
106        }
107    }
108}
109
110fn module_export_name(name: &ModuleExportName<'_>) -> String {
111    no_mistakes_ts_facts::ast::module_export_name(name).into_owned()
112}
113
114/// True when `call` is a bound direct executor or an explicitly broad `.query`
115/// call. Receiver provenance needs the full extractor's lexical scopes.
116pub fn is_database_call(call: &CallExpression<'_>, bindings: &HashSet<String>) -> bool {
117    callee_name(call, bindings, &ScopedExecutors::default()).is_some()
118}
119
120pub fn member_query_receiver<'a>(call: &'a CallExpression<'a>) -> Option<&'a Expression<'a>> {
121    match unwrap_ts_wrappers(&call.callee) {
122        Expression::StaticMemberExpression(member) if member.property.name == QUERY_PROPERTY => {
123            Some(&member.object)
124        }
125        Expression::ComputedMemberExpression(member) if static_query_key(&member.expression) => {
126            Some(&member.object)
127        }
128        _ => None,
129    }
130}
131
132pub(super) fn callee_name(
133    call: &CallExpression<'_>,
134    bindings: &HashSet<String>,
135    scoped: &ScopedExecutors,
136) -> Option<String> {
137    match unwrap_ts_wrappers(&call.callee) {
138        Expression::Identifier(ident)
139            if bindings.contains(ident.name.as_str())
140                || scoped.contains(ident.name.as_str(), call.span.start) =>
141        {
142            Some(ident.name.to_string())
143        }
144        Expression::StaticMemberExpression(member)
145            if member.property.name == QUERY_PROPERTY && bindings.contains(MEMBER_QUERY_OPT_IN) =>
146        {
147            Some(QUERY_PROPERTY.to_string())
148        }
149        Expression::ComputedMemberExpression(member) => (bindings.contains(MEMBER_QUERY_OPT_IN)
150            && static_query_key(&member.expression))
151        .then(|| QUERY_PROPERTY.to_string()),
152        _ => None,
153    }
154}
155
156fn static_query_key(expr: &Expression<'_>) -> bool {
157    match unwrap_ts_wrappers(expr) {
158        Expression::StringLiteral(literal) => literal.value == QUERY_PROPERTY,
159        Expression::TemplateLiteral(template)
160            if template.expressions.is_empty() && template.quasis.len() == 1 =>
161        {
162            no_mistakes_ts_facts::ast::template_quasi_text(&template.quasis[0]) == QUERY_PROPERTY
163        }
164        _ => false,
165    }
166}