sqlx_conditional_queries_core/
analyze.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use syn::spanned::Spanned;

use crate::parse::ParsedConditionalQueryAs;

#[derive(Debug, thiserror::Error)]
pub enum AnalyzeError {
    #[error("expected string literal")]
    ExpectedStringLiteral(proc_macro2::Span),
    #[error("mismatch between number of names ({names}) and values ({values})")]
    BindingNameValueLengthMismatch {
        names: usize,
        names_span: proc_macro2::Span,
        values: usize,
        values_span: proc_macro2::Span,
    },
}

/// This represents the finished second step in the processing pipeline.
/// The compile time bindings have been further processed to a form that allows us to easily create
/// the cartesian product and thereby all query variations in the next step.
#[derive(Debug)]
pub(crate) struct AnalyzedConditionalQueryAs {
    pub(crate) output_type: syn::Ident,
    pub(crate) query_string: syn::LitStr,
    pub(crate) compile_time_bindings: Vec<CompileTimeBinding>,
}

/// This represents a single combination of a single compiletime binding of a query.
#[derive(Debug)]
pub(crate) struct CompileTimeBinding {
    /// The actual expression used in the match statement.
    /// E.g. for `match something`, this would be `something`.
    pub(crate) expression: syn::Expr,
    /// Each entry in this Vec represents a single expanded `match` and the
    /// binding names with the binding values from that specific arm.
    /// (`match arm pattern`, Vec(binding_name, binding_value)`
    pub(crate) arms: Vec<(syn::Pat, Vec<(syn::Ident, syn::LitStr)>)>,
}

/// Further parse and analyze all compiletime binding statements.
/// Each binding is split into individual entries of this form:
/// (`match arm pattern`, Vec(binding_name, binding_value)`
pub(crate) fn analyze(
    parsed: ParsedConditionalQueryAs,
) -> Result<AnalyzedConditionalQueryAs, AnalyzeError> {
    let mut compile_time_bindings = Vec::new();

    for (names, match_expr) in parsed.compile_time_bindings {
        let binding_names_span = names.span();
        // Convert the OneOrPunctuated enum in a list of `Ident`s.
        // `One(T)` will be converted into a Vec with a single entry.
        let binding_names: Vec<_> = names.into_iter().collect();

        let mut bindings = Vec::new();
        for arm in match_expr.arms {
            let arm_span = arm.body.span();

            let binding_values = match *arm.body {
                // If the match arm expression just contains a literal, use that.
                syn::Expr::Lit(syn::ExprLit {
                    lit: syn::Lit::Str(literal),
                    ..
                }) => vec![literal],

                // If there's a tuple, treat each literal inside that tuple as a binding value.
                syn::Expr::Tuple(tuple) => {
                    let mut values = Vec::new();
                    for elem in tuple.elems {
                        match elem {
                            syn::Expr::Lit(syn::ExprLit {
                                lit: syn::Lit::Str(literal),
                                ..
                            }) => values.push(literal),

                            _ => return Err(AnalyzeError::ExpectedStringLiteral(elem.span())),
                        }
                    }
                    values
                }

                body => return Err(AnalyzeError::ExpectedStringLiteral(body.span())),
            };

            // There must always be a matching amount of binding values in each match arm.
            // Error if there are more or fewer values than binding names.
            if binding_names.len() != binding_values.len() {
                return Err(AnalyzeError::BindingNameValueLengthMismatch {
                    names: binding_names.len(),
                    names_span: binding_names_span,
                    values: binding_values.len(),
                    values_span: arm_span,
                });
            }

            bindings.push((
                arm.pat,
                binding_names
                    .iter()
                    .cloned()
                    .zip(binding_values)
                    .collect::<Vec<_>>(),
            ));
        }

        compile_time_bindings.push(CompileTimeBinding {
            expression: *match_expr.expr,
            arms: bindings,
        });
    }

    Ok(AnalyzedConditionalQueryAs {
        output_type: parsed.output_type,
        query_string: parsed.query_string,
        compile_time_bindings,
    })
}

#[cfg(test)]
mod tests {
    use quote::ToTokens;

    use super::*;

    #[test]
    fn valid_syntax() {
        let parsed = syn::parse_str::<ParsedConditionalQueryAs>(
            r#"
                SomeType,
                "some SQL query",
                #binding = match foo {
                    bar => "baz",
                },
                #(a, b) = match c {
                    d => ("e", "f"),
                },
            "#,
        )
        .unwrap();
        let mut analyzed = analyze(parsed.clone()).unwrap();

        assert_eq!(parsed.output_type, analyzed.output_type);
        assert_eq!(parsed.query_string, analyzed.query_string);

        assert_eq!(analyzed.compile_time_bindings.len(), 2);

        {
            let compile_time_binding = dbg!(analyzed.compile_time_bindings.remove(0));
            assert_eq!(
                compile_time_binding
                    .expression
                    .to_token_stream()
                    .to_string(),
                "foo",
            );

            assert_eq!(compile_time_binding.arms.len(), 1);
            {
                let arm = &compile_time_binding.arms[0];
                assert_eq!(arm.0.to_token_stream().to_string(), "bar");
                assert_eq!(
                    arm.1
                        .iter()
                        .map(|v| (
                            v.0.to_token_stream().to_string(),
                            v.1.to_token_stream().to_string(),
                        ))
                        .collect::<Vec<_>>(),
                    &[("binding".to_string(), "\"baz\"".to_string())],
                );
            }
        }

        {
            let compile_time_binding = dbg!(analyzed.compile_time_bindings.remove(0));
            assert_eq!(
                compile_time_binding
                    .expression
                    .to_token_stream()
                    .to_string(),
                "c",
            );

            assert_eq!(
                compile_time_binding
                    .arms
                    .iter()
                    .map(|v| v.0.to_token_stream().to_string())
                    .collect::<Vec<_>>(),
                &["d"],
            );

            assert_eq!(compile_time_binding.arms.len(), 1);
            {
                let arm = &compile_time_binding.arms[0];
                assert_eq!(arm.0.to_token_stream().to_string(), "d");
                assert_eq!(
                    arm.1
                        .iter()
                        .map(|v| (
                            v.0.to_token_stream().to_string(),
                            v.1.to_token_stream().to_string(),
                        ))
                        .collect::<Vec<_>>(),
                    &[
                        ("a".to_string(), "\"e\"".to_string()),
                        ("b".to_string(), "\"f\"".to_string())
                    ],
                );
            }
        }
    }
}