quick-oxibooks-sql-macro 0.2.0

A procedural macro to construct type-checked and safe SQL queries for Oxibooks.
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    Ident, LitInt, Token, Type,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
};

/// Builds a type-safe QuickBooks Online query at compile time.
///
/// This macro parses SQL-like syntax and generates a `Query<T>` struct that can be used to query
/// the QuickBooks Online API. Field names are automatically validated at compile time and converted
/// from snake_case to CamelCase to match QuickBooks naming conventions.
///
/// # Syntax
///
/// ```text
/// qb_sql!(
///     select [* | field1, field2, ...]
///     from EntityType
///     [where condition [and condition ...]]
///     [order by field [asc|desc] [, field [asc|desc] ...]]
///     [limit number [offset number]]
/// )
/// ```
///
/// # Supported Operators
///
/// - `=` - Equality comparison
/// - `>`, `<`, `>=`, `<=` - Numeric comparisons
/// - `like` - Pattern matching (use `%` as wildcard)
/// - `in` - Match against multiple values: `field in (val1, val2, ...)` or `field in (iterator)`
///
/// # Examples
///
/// Basic query with field selection:
/// ```ignore
/// use quick_oxibooks_sql::qb_sql;
/// use quickbooks_types::Customer;
///
/// let query = qb_sql!(
///     select display_name, balance from Customer
///     where balance >= 1000.0
///     order by display_name asc
///     limit 10
/// );
/// ```
///
/// Using Rust variables in conditions:
/// ```ignore
/// let min_balance = 500.0;
/// let name_pattern = "Acme%";
///
/// let query = qb_sql!(
///     select * from Customer
///     where balance >= min_balance
///     and display_name like name_pattern
/// );
/// ```
///
/// Using the `in` operator with a tuple or iterator:
/// ```ignore
/// // With literal values
/// let query = qb_sql!(
///     select * from Customer
///     where id in (1, 2, 3)
/// );
///
/// // With an iterator (single expression)
/// let ids = vec!["1", "2", "3"];
/// let query = qb_sql!(
///     select * from Customer
///     where id in (ids)
/// );
/// ```
///
/// Executing a query (requires the `api` feature):
/// ```ignore
/// use quick_oxibooks::{Environment, QBContext};
/// use ureq::Agent;
///
/// let client = Agent::new();
/// let qb = QBContext::new(Environment::SANDBOX, "company_id".into(), "token".into(), &client)?;
///
/// let results = query.execute(&qb, &client)?;
/// ```
///
/// # Notes
///
/// - Field names are automatically converted from snake_case to CamelCase (e.g., `display_name` → `DisplayName`)
/// - All field names are validated at compile time against the entity type
/// - The generated query can be converted to a string with `.query_string()` or by displaying it
/// - For the `in` operator, use a tuple for literals or a single iterator expression
#[proc_macro]
pub fn qb_sql(input: TokenStream) -> TokenStream {
    let query = syn::parse_macro_input!(input as SqlQuery);
    let expanded = query.expand();
    TokenStream::from(expanded)
}

/// Represents the entire SQL query
struct SqlQuery {
    item_type: Type,
    conditions: Vec<Condition>,
    order_by: Option<OrderBy>,
    limit: Option<LimitClause>,
}

/// Represents a field, possibly nested (e.g., address.city)
enum Field {
    Root(Ident),
    Nested(Ident, Box<Field>),
}

impl Parse for Field {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let root: Ident = input.parse()?;
        if !input.peek(Token![.]) {
            return Ok(Field::Root(root));
        }
        input.parse::<Token![.]>()?;
        let nested = Field::parse(input)?;
        Ok(Field::Nested(root, Box::new(nested)))
    }
}

impl ToString for Field {
    fn to_string(&self) -> String {
        match self {
            Field::Root(ident) => ident.to_string(),
            Field::Nested(ident, nested) => format!("{}.{}", ident, nested.to_string()),
        }
    }
}

impl quote::ToTokens for Field {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            Field::Root(ident) => {
                ident.to_tokens(tokens);
            }
            Field::Nested(ident, nested) => {
                ident.to_tokens(tokens);
                tokens.extend(quote! { . });
                nested.to_tokens(tokens);
            }
        }
    }
}

/// A single WHERE condition
struct Condition {
    field: Field,
    operator: Operator,
    values: Vec<syn::Expr>,
}

/// Operator types
enum Operator {
    Equal,
    Less,
    Greater,
    LessEqual,
    GreaterEqual,
    In,
    Like,
}

/// ORDER BY clause
struct OrderBy {
    orders: Vec<OrderField>,
}

struct OrderField {
    field: Field,
    direction: Option<OrderDirection>,
}

enum OrderDirection {
    Asc,
    Desc,
}

/// LIMIT clause with optional OFFSET
struct LimitClause {
    number: LitInt,
    offset: Option<syn::Expr>,
}

impl Parse for SqlQuery {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        // Parse select * from
        input.parse::<kw::select>()?;
        input.parse::<Token![*]>()?;
        input.parse::<kw::from>()?;

        let item_type: Type = input.parse()?;

        let mut conditions = vec![];
        if input.peek(Token![where]) {
            // Parse WHERE
            input.parse::<Token![where]>()?;
            // Parse first condition
            conditions.push(Condition::parse(input)?);
            // Parse additional AND conditions
            while input.peek(kw::and) {
                input.parse::<kw::and>()?;
                conditions.push(Condition::parse(input)?);
            }
        }

        // Parse optional ORDER BY
        let order_by = if input.peek(kw::order) {
            Some(OrderBy::parse(input)?)
        } else {
            None
        };

        // Parse optional LIMIT
        let limit = if input.peek(kw::limit) {
            Some(LimitClause::parse(input)?)
        } else {
            None
        };

        Ok(SqlQuery {
            item_type,
            conditions,
            order_by,
            limit,
        })
    }
}

impl Parse for Condition {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let field: Field = input.parse()?;
        let operator = Operator::parse(input)?;

        let values = if matches!(operator, Operator::In) {
            // Parse parenthesized list for IN operator
            let content;
            syn::parenthesized!(content in input);
            let exprs = Punctuated::<syn::Expr, Token![,]>::parse_separated_nonempty(&content)?;
            exprs.into_iter().collect()
        } else {
            // Parse single value for other operators
            vec![input.parse()?]
        };

        Ok(Condition {
            field,
            operator,
            values,
        })
    }
}

impl Parse for Operator {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();

        if lookahead.peek(Token![=]) {
            input.parse::<Token![=]>()?;
            Ok(Operator::Equal)
        } else if lookahead.peek(Token![<]) {
            input.parse::<Token![<]>()?;
            if input.peek(Token![=]) {
                input.parse::<Token![=]>()?;
                Ok(Operator::LessEqual)
            } else {
                Ok(Operator::Less)
            }
        } else if lookahead.peek(Token![>]) {
            input.parse::<Token![>]>()?;
            if input.peek(Token![=]) {
                input.parse::<Token![=]>()?;
                Ok(Operator::GreaterEqual)
            } else {
                Ok(Operator::Greater)
            }
        } else if lookahead.peek(Token![in]) {
            input.parse::<Token![in]>()?;
            Ok(Operator::In)
        } else if lookahead.peek(kw::like) {
            input.parse::<kw::like>()?;
            Ok(Operator::Like)
        } else {
            Err(lookahead.error())
        }
    }
}

impl Parse for OrderBy {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::order>()?;
        input.parse::<kw::by>()?;

        let orders = Punctuated::<OrderField, Token![,]>::parse_separated_nonempty(input)?;

        Ok(OrderBy {
            orders: orders.into_iter().collect(),
        })
    }
}

impl Parse for OrderField {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let field: Field = input.parse()?;

        let direction = if input.peek(kw::asc) {
            input.parse::<kw::asc>()?;
            Some(OrderDirection::Asc)
        } else if input.peek(kw::desc) {
            input.parse::<kw::desc>()?;
            Some(OrderDirection::Desc)
        } else {
            None
        };

        Ok(OrderField { field, direction })
    }
}

impl Parse for LimitClause {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::limit>()?;
        let number: LitInt = input.parse()?;

        let offset = if input.peek(kw::offset) {
            input.parse::<kw::offset>()?;
            Some(input.parse()?)
        } else {
            None
        };

        Ok(LimitClause { number, offset })
    }
}

impl SqlQuery {
    fn expand(&self) -> proc_macro2::TokenStream {
        let item_type = &self.item_type;

        // Collect all fields for type checking
        let all_fields: Vec<&Field> = {
            let mut fields = Vec::new();

            fields.extend(self.conditions.iter().map(|c| &c.field));

            if let Some(ref order_by) = self.order_by {
                fields.extend(order_by.orders.iter().map(|o| &o.field));
            }

            fields
        };

        // Generate type checking code
        let type_check = if !all_fields.is_empty() {
            quote! {
                const _: () = {
                    fn _check_fields(v: #item_type) {
                        #(let _ = v.#all_fields;)*
                    }
                };
            }
        } else {
            quote! {}
        };

        // Generate condition code
        let condition_code: Vec<_> = self
            .conditions
            .iter()
            .map(|c| {
                let field = &c.field;
                let field_name = to_camel_case(&field.to_string());
                let operator = c.operator.to_tokens();
                let values = &c.values;

                // For IN operator with a single expression, treat it as an iterator
                let values_code = if matches!(c.operator, Operator::In) && values.len() == 1 {
                    let expr = &values[0];
                    quote! {
                      #expr.into_iter().map(|v| v.to_string()).collect::<Vec<String>>()
                    }
                } else {
                    // Multiple values or non-IN operators: call to_string on each
                    quote! { vec![#(#values.to_string()),*] }
                };

                quote! {
                    let clause = WhereClause {
                        field: stringify!(#field_name),
                        operator: #operator,
                        values: #values_code,
                    };
                    unsafe {
                        query = query.condition(clause);
                    }
                }
            })
            .collect();

        // Generate order by code
        let order_code = if let Some(ref order_by) = self.order_by {
            let orders: Vec<_> = order_by
                .orders
                .iter()
                .map(|o| {
                    let field = &o.field;
                    let field_name = to_camel_case(&field.to_string());
                    let direction = match &o.direction {
                        Some(OrderDirection::Asc) => quote! { Order::Asc },
                        Some(OrderDirection::Desc) => quote! { Order::Desc },
                        None => quote! { Order::Asc },
                    };

                    quote! {
                        unsafe {
                            query = query.order(stringify!(#field_name), #direction);
                        }
                    }
                })
                .collect();

            quote! { #(#orders)* }
        } else {
            quote! {}
        };

        // Generate limit code
        let limit_code = if let Some(ref limit) = self.limit {
            let number = &limit.number;
            let offset_code = if let Some(ref offset) = limit.offset {
                quote! { Some(#offset) }
            } else {
                quote! { None }
            };

            quote! {
                query = query.limit(#number, #offset_code);
            }
        } else {
            quote! {}
        };

        quote! {
            {
                #type_check

                let mut query = Query::<#item_type>::new();

                #(#condition_code)*
                #order_code
                #limit_code

                query
            }
        }
    }
}

impl Operator {
    fn to_tokens(&self) -> proc_macro2::TokenStream {
        match self {
            Operator::Equal => quote! { Operator::Equal },
            Operator::Less => quote! { Operator::Less },
            Operator::Greater => quote! { Operator::Greater },
            Operator::LessEqual => quote! { Operator::LessEqual },
            Operator::GreaterEqual => quote! { Operator::GreaterEqual },
            Operator::In => quote! { Operator::In },
            Operator::Like => quote! { Operator::Like },
        }
    }
}

/// Convert snake_case to CamelCase
fn to_camel_case(s: &str) -> syn::Ident {
    let camel = s
        .split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
            }
        })
        .collect::<String>();

    syn::Ident::new(&camel, proc_macro2::Span::call_site())
}

// Custom keywords
mod kw {
    syn::custom_keyword!(select);
    syn::custom_keyword!(from);
    syn::custom_keyword!(and);
    syn::custom_keyword!(order);
    syn::custom_keyword!(by);
    syn::custom_keyword!(limit);
    syn::custom_keyword!(offset);
    syn::custom_keyword!(asc);
    syn::custom_keyword!(desc);
    syn::custom_keyword!(like);
}