Skip to main content

no_mistakes_postgres_engine/embedded/
text.rs

1use super::{placeholders, tags};
2use no_mistakes_ts_facts::syntax_helpers::unwrap_ts_wrappers;
3use oxc_ast::ast::{Expression, TemplateLiteral, UnaryOperator};
4use oxc_syntax::number::ToJsString;
5use std::collections::HashMap;
6
7/// SQL text of a literal, tagged template, or template expression.
8pub fn sql_text(expr: &Expression<'_>) -> Option<String> {
9    unpublished_sql_text(expr).map(placeholders::publish_placeholders)
10}
11
12pub fn unpublished_sql_text(expr: &Expression<'_>) -> Option<String> {
13    match unwrap_ts_wrappers(expr) {
14        Expression::StringLiteral(literal) => {
15            Some(no_mistakes_ts_facts::ast::js_literal(literal).into_owned())
16        }
17        Expression::TemplateLiteral(template) => Some(template_sql_text(template, false, false)),
18        Expression::TaggedTemplateExpression(tagged) => {
19            let use_raw = tags::is_string_raw_tag_spelling(&tagged.tag);
20            Some(template_sql_text(&tagged.quasi, use_raw, true))
21        }
22        _ => None,
23    }
24}
25
26/// `sql_text` plus identifier lookup of in-scope SQL bindings.
27pub fn executed_query_text(
28    expr: &Expression<'_>,
29    bindings: &HashMap<String, String>,
30) -> Option<String> {
31    if let Some(text) = sql_text(expr) {
32        return Some(text);
33    }
34    match unwrap_ts_wrappers(expr) {
35        Expression::Identifier(ident) => bindings.get(ident.name.as_str()).cloned(),
36        _ => None,
37    }
38}
39
40/// One hole in a template. `space` is inserted only between adjacent value
41/// holes of a tagged template.
42pub struct RenderedHole {
43    pub space: bool,
44    pub text: String,
45}
46
47pub fn render_hole(
48    previous: &str,
49    hole: &Expression<'_>,
50    index: usize,
51    already: &str,
52    separate_adjacent: bool,
53) -> RenderedHole {
54    if previous.ends_with('$') {
55        if let Some(digits) = positional_digits(hole, index) {
56            return RenderedHole {
57                space: false,
58                text: digits,
59            };
60        }
61    }
62    RenderedHole {
63        space: separate_adjacent && !already.is_empty() && previous.is_empty(),
64        text: placeholders::internal_placeholder(index),
65    }
66}
67
68fn positional_digits(hole: &Expression<'_>, index: usize) -> Option<String> {
69    let number = match unwrap_ts_wrappers(hole) {
70        Expression::NumericLiteral(literal) => literal.value,
71        Expression::UnaryExpression(unary)
72            if matches!(
73                unary.operator,
74                UnaryOperator::UnaryPlus | UnaryOperator::UnaryNegation
75            ) =>
76        {
77            let Expression::NumericLiteral(literal) = unwrap_ts_wrappers(&unary.argument) else {
78                return Some(index.to_string());
79            };
80            match unary.operator {
81                UnaryOperator::UnaryNegation => -literal.value,
82                _ => literal.value,
83            }
84        }
85        Expression::TemplateLiteral(_) | Expression::TaggedTemplateExpression(_) => return None,
86        expr if expr.is_literal() => return None,
87        _ => return Some(index.to_string()),
88    };
89    let digits = number.to_js_string();
90    digits
91        .bytes()
92        .all(|byte| byte.is_ascii_digit())
93        .then_some(digits)
94}
95
96/// `use_raw` selects `String.raw`'s own runtime semantics (the literal
97/// source characters, escape sequences un-processed) over the cooked form
98/// every other tag — the trusted `sql` tag included — returns; see
99/// [`tags::is_string_raw_tag_spelling`]. `separate_adjacent` is set only for
100/// a tagged template, so a plain string builder does not split `$${n}`.
101fn template_sql_text(
102    template: &TemplateLiteral<'_>,
103    use_raw: bool,
104    separate_adjacent: bool,
105) -> String {
106    let mut out = String::new();
107    for (index, quasi) in template.quasis.iter().enumerate() {
108        if index > 0 {
109            let previous = tags::quasi_text(&template.quasis[index - 1], use_raw);
110            let rendered = render_hole(
111                &previous,
112                &template.expressions[index - 1],
113                index,
114                &out,
115                separate_adjacent,
116            );
117            if rendered.space {
118                out.push(' ');
119            }
120            out.push_str(&rendered.text);
121        }
122        out.push_str(&tags::quasi_text(quasi, use_raw));
123    }
124    out
125}