sqlw_macro 0.1.0

Procedural macros for sqlw
Documentation
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
pub mod parser {
    use syn::Token;
    use syn::parse::{Parse, ParseStream, Result};

    pub enum SqlPart {
        Literal(LiteralToken),
        FieldRef(FieldPath),
        Variable(VariableBinding),
        Group(GroupContent),
    }

    pub struct LiteralToken {
        pub token: proc_macro2::TokenTree,
    }

    impl Parse for LiteralToken {
        fn parse(input: ParseStream) -> Result<Self> {
            Ok(LiteralToken {
                token: input.parse()?,
            })
        }
    }

    pub struct FieldPath {
        pub path: syn::Path,
    }

    impl Parse for FieldPath {
        fn parse(input: ParseStream) -> Result<Self> {
            Ok(FieldPath {
                path: input.parse()?,
            })
        }
    }

    pub struct VariableBinding {
        pub expr: syn::Expr,
    }

    impl Parse for VariableBinding {
        fn parse(input: ParseStream) -> Result<Self> {
            let content;
            syn::braced!(content in input);
            Ok(VariableBinding {
                expr: content.parse()?,
            })
        }
    }

    pub struct GroupContent {
        pub inner: Box<ParsedQuery>,
    }

    pub struct ParsedQuery {
        pub sql_parts: Vec<SqlPart>,
    }

    impl Parse for ParsedQuery {
        fn parse(input: ParseStream) -> Result<Self> {
            let mut sql_parts = Vec::new();

            while !input.is_empty() {
                // Try parsing as a path (field reference)
                if input.peek(syn::Ident) && input.peek2(Token![::]) {
                    sql_parts.push(SqlPart::FieldRef(input.parse()?));
                }
                // Try parsing as a variable binding `{expr}`
                else if input.peek(syn::token::Brace) {
                    sql_parts.push(SqlPart::Variable(input.parse()?));
                }
                // Otherwise it's a literal token
                else {
                    let token: proc_macro2::TokenTree = input.parse()?;

                    // Try parsing as a group (parentheses), parse its contents
                    if let proc_macro2::TokenTree::Group(group) = &token {
                        if group.delimiter() == proc_macro2::Delimiter::Parenthesis {
                            // Recursively parse the group's contents
                            let inner: ParsedQuery = syn::parse2(group.stream())?;
                            sql_parts.push(SqlPart::Group(GroupContent {
                                inner: Box::new(inner),
                            }));
                            continue;
                        }
                    }

                    sql_parts.push(SqlPart::Literal(LiteralToken { token }));
                }
            }

            Ok(ParsedQuery { sql_parts })
        }
    }
}

pub mod analyzer {
    use super::parser::{ParsedQuery, SqlPart};

    /// Represents the binding information for a single placeholder.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub struct PlaceholderBinding {
        /// The path to the column definition (e.g., `User::ID`)
        /// if this placeholder can be type-checked.
        pub column_path: Option<syn::Path>,
    }

    /// Analyze SQL parts to map placeholders to their column types.
    ///
    /// Uses a simple heuristic: each placeholder is associated with the
    /// most recent field reference that appeared before it in the same scope.
    ///
    /// This works well for patterns like `WHERE User::ID = {id}` where the
    /// field reference appears immediately before the placeholder.
    ///
    /// For more complex patterns, placeholders fall back to untyped binding.
    pub fn analyze_bindings(query: &ParsedQuery) -> Vec<PlaceholderBinding> {
        let mut bindings = Vec::new();
        analyze_parts(&query.sql_parts, &mut bindings, None);
        bindings
    }

    fn analyze_parts(
        parts: &[SqlPart],
        bindings: &mut Vec<PlaceholderBinding>,
        last_field_ref: Option<syn::Path>,
    ) {
        for i in 0..parts.len() {
            match &parts[i] {
                SqlPart::FieldRef(field) => {
                    // Pass the slice starting from this field reference
                    analyze_parts_with_field(&parts[i..], bindings, field.path.clone(), true);
                }
                SqlPart::Variable(_) => {
                    bindings.push(PlaceholderBinding {
                        column_path: last_field_ref.clone(),
                    });
                }
                SqlPart::Group(group) => {
                    // For groups, reset field tracking - don't inherit from outer scope
                    analyze_parts(&group.inner.sql_parts, bindings, None);
                }
                SqlPart::Literal(_) => {
                    // Literals don't affect field tracking
                }
            }
        }
    }

    fn analyze_parts_with_field(
        parts: &[SqlPart],
        bindings: &mut Vec<PlaceholderBinding>,
        field_path: syn::Path,
        skip_first: bool,
    ) {
        // After seeing a field reference, look for a placeholder following it
        let start_idx = if skip_first { 1 } else { 0 };
        for i in start_idx..parts.len() {
            match &parts[i] {
                SqlPart::Literal(lit) => {
                    // Stop if we hit certain keywords that end this pattern
                    let token_str = lit.token.to_string();
                    let upper = token_str.to_uppercase();
                    if upper == "AND"
                        || upper == "OR"
                        || upper == ","
                        || upper == "HAVING"
                        || upper == "LIMIT"
                        || upper == "OFFSET"
                        || upper == "GROUP"
                        || upper == "ORDER"
                        || upper == "BY"
                    {
                        break;
                    }
                }
                SqlPart::FieldRef(_) => {
                    // Another field reference, stop
                    break;
                }
                SqlPart::Variable(_) => {
                    // Found a placeholder after the field reference
                    bindings.push(PlaceholderBinding {
                        column_path: Some(field_path.clone()),
                    });
                    // Continue processing remaining parts with no field
                    analyze_parts(&parts[i + 1..], bindings, None);
                    return;
                }
                SqlPart::Group(group) => {
                    // Recursively process group
                    analyze_parts(&group.inner.sql_parts, bindings, None);
                }
            }
        }
    }
}

pub mod codegen {
    use super::parser::{ParsedQuery, SqlPart};
    use proc_macro2::TokenStream;
    use quote::quote;

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum TokenType {
        Word,       // Identifiers, keywords, numbers, strings, placeholders
        OpenParen,  // (
        CloseParen, // )
        Comma,      // ,
        Operator,   // =, >, <, !=, etc.
        Dot,        // .
    }

    fn classify_token(s: &str) -> TokenType {
        match s {
            "(" => TokenType::OpenParen,
            ")" => TokenType::CloseParen,
            "," => TokenType::Comma,
            "." => TokenType::Dot,
            "=" | ">" | "<" | ">=" | "<=" | "!=" | "<>" | "+" | "-" | "*" | "/" | "%" => {
                TokenType::Operator
            }
            _ => TokenType::Word,
        }
    }

    fn needs_space(prev: TokenType, next: TokenType) -> bool {
        use TokenType::*;
        match (prev, next) {
            // Never space around dots
            (Dot, _) | (_, Dot) => false,

            // No space after open paren
            (OpenParen, _) => false,

            // No space before close paren or comma
            (_, CloseParen) | (_, Comma) => false,

            // Space after comma
            (Comma, _) => true,

            // Space after close paren to words, operators, or open paren
            (CloseParen, Word) | (CloseParen, OpenParen) | (CloseParen, Operator) => true,

            // Space between words
            (Word, Word) => true,

            // Word before open paren = function call, no space
            (Word, OpenParen) => false,

            // Space around operators
            (Word, Operator) | (Operator, Word) | (Operator, OpenParen) => true,

            // Default: no space
            _ => false,
        }
    }

    pub enum PlaceholderStyle {
        Qmark,    // ?
        Numbered, // $1, $2, $3...
    }

    pub struct CodeGenerator {
        query: ParsedQuery,
        placeholder_style: PlaceholderStyle,
    }

    impl CodeGenerator {
        pub fn new(query: ParsedQuery, placeholder_style: PlaceholderStyle) -> Self {
            Self {
                query,
                placeholder_style,
            }
        }

        pub fn generate(self) -> TokenStream {
            // Analyze bindings to get type information
            let bindings = super::analyzer::analyze_bindings(&self.query);
            let (sql_building, _, _) =
                self.generate_sql_parts(&self.query.sql_parts, &bindings, None, 0, 0);

            quote! {
                {
                    let mut __sql = String::new();
                    let mut __args: Vec<sqlw::Value> = Vec::new();

                    #sql_building

                    sqlw::Query::new(__sql, __args)
                }
            }
        }

        fn generate_sql_parts(
            &self,
            parts: &[SqlPart],
            bindings: &[super::analyzer::PlaceholderBinding],
            mut last_type: Option<TokenType>,
            mut placeholder_idx: usize,
            mut binding_idx: usize,
        ) -> (TokenStream, usize, usize) {
            let mut statements = Vec::new();

            for part in parts {
                match part {
                    SqlPart::Literal(lit) => {
                        let token_str = lit.token.to_string();
                        let current_type = classify_token(&token_str);

                        if let Some(prev) = last_type {
                            if needs_space(prev, current_type) {
                                statements.push(quote! {
                                    __sql.push(' ');
                                });
                            }
                        }

                        statements.push(quote! {
                            __sql.push_str(#token_str);
                        });

                        last_type = Some(current_type);
                    }
                    SqlPart::FieldRef(field) => {
                        let path = &field.path;
                        let current_type = TokenType::Word;

                        if let Some(prev) = last_type {
                            if needs_space(prev, current_type) {
                                statements.push(quote! {
                                    __sql.push(' ');
                                });
                            }
                        }

                        statements.push(quote! {
                            __sql.push_str(&#path.desc());
                        });

                        last_type = Some(current_type);
                    }
                    SqlPart::Variable(var) => {
                        let expr = &var.expr;
                        let current_type = TokenType::Word;
                        placeholder_idx += 1;

                        if let Some(prev) = last_type {
                            if needs_space(prev, current_type) {
                                statements.push(quote! {
                                    __sql.push(' ');
                                });
                            }
                        }

                        let placeholder = match self.placeholder_style {
                            PlaceholderStyle::Qmark => "?".to_string(),
                            PlaceholderStyle::Numbered => format!("${}", placeholder_idx),
                        };

                        // Use type-checked binding if available
                        let binding = if binding_idx < bindings.len() {
                            &bindings[binding_idx]
                        } else {
                            // Fallback to untyped if index out of bounds
                            &super::analyzer::PlaceholderBinding { column_path: None }
                        };
                        binding_idx += 1;

                        let arg_push = if let Some(col_path) = &binding.column_path {
                            quote! {
                                __args.push(sqlw::bind(#col_path, #expr));
                            }
                        } else {
                            quote! {
                                __args.push((#expr).into());
                            }
                        };

                        statements.push(quote! {
                            #arg_push
                            __sql.push_str(#placeholder);
                        });

                        last_type = Some(current_type);
                    }
                    SqlPart::Group(group) => {
                        let current_type = TokenType::OpenParen;

                        if let Some(prev) = last_type {
                            if needs_space(prev, current_type) {
                                statements.push(quote! {
                                    __sql.push(' ');
                                });
                            }
                        }

                        statements.push(quote! {
                            __sql.push('(');
                        });

                        last_type = Some(current_type);

                        let (inner_code, new_idx, new_binding_idx) = self.generate_sql_parts(
                            &group.inner.sql_parts,
                            bindings,
                            last_type,
                            placeholder_idx,
                            binding_idx,
                        );
                        placeholder_idx = new_idx;
                        binding_idx = new_binding_idx;
                        statements.push(inner_code);

                        last_type = self.get_last_token_type(&group.inner.sql_parts);

                        let close_type = TokenType::CloseParen;
                        if let Some(prev) = last_type {
                            if needs_space(prev, close_type) {
                                statements.push(quote! {
                                    __sql.push(' ');
                                });
                            }
                        }

                        statements.push(quote! {
                            __sql.push(')');
                        });

                        last_type = Some(close_type);
                    }
                }
            }

            let statements_stream = quote! {
                #(#statements)*
            };

            (statements_stream, placeholder_idx, binding_idx)
        }

        fn get_last_token_type(&self, parts: &[SqlPart]) -> Option<TokenType> {
            parts.last().map(|part| match part {
                SqlPart::Literal(lit) => classify_token(&lit.token.to_string()),
                SqlPart::FieldRef(_) => TokenType::Word,
                SqlPart::Variable(_) => TokenType::Word,
                SqlPart::Group(_) => TokenType::CloseParen,
            })
        }
    }
}