mae_macros 0.1.7

Procedural macros for Mae-Technologies micro-services — derive helpers, schema binding, and async test harness.
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
//! Internal helper utilities for the `MaeRepo` derive macro.
//!
//! These functions inspect a [`DeriveInput`] struct's named fields and emit
//! the `proc_macro2::TokenStream` bodies for `InsertRow`, `UpdateRow`,
//! `Field`, and `PatchField` respectively.  They are `pub(crate)` and are
//! not part of the public API.

use quote::quote;
use syn::{Data, DataStruct, DeriveInput, Field, Fields, LitStr};

type Body = proc_macro2::TokenStream;
type BodyIdent = proc_macro2::TokenStream;

/// Generates the `PatchField` typed enum and its trait implementations.
///
/// `PatchField` is an enum where each variant carries the field's value type.
/// Fields marked `#[locked]` or `#[insert_only]` are excluded (they cannot be
/// patched).
///
/// # Returns
///
/// `(body, ident_tokens)` where `body` is the full `TokenStream` defining the
/// `PatchField` enum and its `impl` blocks, and `ident_tokens` is always
/// `quote! { PatchField }`.
#[doc(hidden)]
pub fn to_patches(ast: &DeriveInput) -> (Body, BodyIdent) {
    let fields = match &ast.data {
        Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => &fields.named,
        _ => {
            return (
                syn::Error::new_spanned(&ast.ident, "expected a struct with named fields")
                    .to_compile_error(),
                quote! { PatchField }
            );
        }
    };

    let mut to_arg = vec![];
    let mut to_string = vec![];
    let mut typed_enum = vec![];
    let body_ident = quote! { PatchField };
    let mut debug_bindings = vec![];
    let mut patch_to_field_arms = vec![];
    let mut patch_to_filter_arms = vec![];

    fields.iter().for_each(|f| {
        let name_ident = f.ident.as_ref().ok_or_else(|| {
            syn::Error::new_spanned(&ast.ident, "missing a name field (missing ident.)")
                .to_compile_error()
        });

        // we need to check if either there are no attrs, or if attr != locked | != insert_only
        if let Ok(name_ident) = name_ident
            && f.attrs
                .iter()
                .all(|a| !a.path().is_ident("locked") && !a.path().is_ident("insert_only"))
        {
            let ty = &f.ty;
            let name_str = name_ident.to_string();

            to_arg.push(quote! {
                #body_ident::#name_ident(arg) => args.add(arg)
            });
            to_string.push(quote! {
                #body_ident::#name_ident(_) => #name_str.to_string()
            });

            debug_bindings.push(quote! {
                #body_ident::#name_ident(b) => write!(f, "{:?}", b)
            });

            typed_enum.push(quote! { #name_ident(#ty) });

            patch_to_field_arms.push(quote! {
                #body_ident::#name_ident(_) => Field::#name_ident
            });

            patch_to_filter_arms.push(quote! {
                #body_ident::#name_ident(v) => mae::repo::filter::FilterOp::Begin(
                    Field::#name_ident,
                    v.into_mae_filter(),
                )
            });
        }
    });

    let body = quote! {
        #[allow(non_snake_case, non_camel_case_types, nonstandard_style)]
        #[derive(Clone)]
        pub enum #body_ident {
            #(#typed_enum,)*
        }

        impl std::fmt::Display for #body_ident {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{}", match self {
                    #(#to_string,)*
                })
            }
        }

        impl mae::repo::__private__::ToSqlParts for #body_ident {
            fn to_sql_parts(&self) -> mae::repo::__private__::AsSqlParts {
                // NOTE: cannot accurately get the bind_idx. Catch it at a higher level
                (vec![self.to_string()], None)

            }
        }

        impl mae::repo::__private__::BindArgs for #body_ident {
            fn bind(&self, mut args: &mut sqlx::postgres::PgArguments) {
                use sqlx::Arguments;
                let _ = match self {
                    #(#to_arg,)*
                };
            }
            fn bind_len(&self) -> usize {
                // NOTE: There will always be one arg for a PatchField
                1
            }
        }

        impl std::fmt::Debug for #body_ident {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                match self {
                    #(#debug_bindings,)*
                }
            }
        }

        /// Convert a [`PatchField`] variant into its corresponding [`Field`],
        /// discarding the contained value.
        impl From<#body_ident> for Field {
            fn from(patch: #body_ident) -> Field {
                match patch {
                    #(#patch_to_field_arms,)*
                }
            }
        }

        /// Convert a [`PatchField`] variant into a [`FilterOp<Field>`] using an
        /// equality condition (`Begin … Equals / StringIs`).
        ///
        /// Relies on [`mae::repo::filter::IntoMaeFilter`] which is
        /// implemented for the primitive types (`i32`, `String`, and their
        /// `Option` wrappers) that appear in schema field definitions.
        impl From<#body_ident> for mae::repo::filter::FilterOp<Field> {
            fn from(patch: #body_ident) -> mae::repo::filter::FilterOp<Field> {
                use mae::repo::filter::IntoMaeFilter;
                match patch {
                    #(#patch_to_filter_arms,)*
                }
            }
        }
    };
    (body, body_ident)
}

/// Generates the `Field` column-name enum and its trait implementations.
///
/// `Field` has one variant per named field in the struct, plus an `All` variant
/// whose `Display` impl emits a comma-separated list of all column names
/// (suitable for `SELECT <Field::All> FROM …`).
///
/// Fields marked `#[locked]` or any other attribute are still included in
/// `Field` — it covers the full column surface including read-only columns.
///
/// # Returns
///
/// `(body, ident_tokens)` where `body` is the full `TokenStream` defining the
/// `Field` enum, `Field::iter()`, and its `impl` blocks, and `ident_tokens` is
/// always `quote! { Field }`.
#[doc(hidden)]
pub fn to_fields(ast: &DeriveInput) -> (Body, BodyIdent) {
    let fields = match &ast.data {
        Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => &fields.named,
        _ => {
            return (
                syn::Error::new_spanned(&ast.ident, "expected a struct with named fields")
                    .to_compile_error(),
                quote! { Field }
            );
        }
    };

    let mut all_cols: Vec<String> = Vec::new();
    let mut to_string_arms: Vec<proc_macro2::TokenStream> = Vec::new();
    let mut variants: Vec<proc_macro2::TokenStream> = Vec::new();
    let mut iter_variants: Vec<proc_macro2::TokenStream> = Vec::new();

    let body_ident = quote! { Field };

    for f in fields.iter() {
        let Some(name) = f.ident.as_ref() else {
            variants.push(
                syn::Error::new_spanned(f, "expected a named field (missing ident)")
                    .to_compile_error()
            );
            continue;
        };

        let name_str = name.to_string();

        all_cols.push(name_str.clone());

        to_string_arms.push(quote! {
            #body_ident::#name => #name_str.to_string()
        });

        variants.push(quote! { #name });
        iter_variants.push(quote! { #body_ident::#name });
    }

    let all_cols_str = all_cols.join(", ");

    let body = quote! {
        #[allow(non_snake_case, non_camel_case_types, nonstandard_style)]
        #[derive(Clone)]
        pub enum #body_ident {
            All,
            #(#variants,)*
        }

        impl #body_ident {
            /// Returns an iterator over every concrete [`Field`] variant
            /// (excludes [`Field::All`]).
            ///
            /// Useful for test-data generation and introspection of the
            /// full column set.
            pub fn iter() -> impl Iterator<Item = #body_ident> {
                [#(#iter_variants,)*].into_iter()
            }
        }

        impl mae::repo::__private__::ToSqlParts for #body_ident {
            fn to_sql_parts(&self) -> mae::repo::__private__::AsSqlParts {
                (vec![self.to_string()], None)
            }
        }

        impl std::fmt::Display for #body_ident {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{}", match self {
                    Self::All => #all_cols_str.into(),
                    #(#to_string_arms,)*
                })
            }
        }
    };

    (body, body_ident)
}

/// Generates either `InsertRow` or `UpdateRow` and their trait implementations.
///
/// Which row type is produced depends on `attr_black_list`:
///
/// - Pass `["locked", "update_only"]` to produce **`InsertRow`** — a plain
///   struct whose fields map 1-to-1 to the writable insert columns.
/// - Pass `["locked", "insert_only"]` to produce **`UpdateRow`** — a struct
///   where each field is `Option<T>`; only `Some` variants contribute SQL
///   `SET` clauses and bound arguments.
///
/// Both generated types implement `ToSqlParts`, `BindArgs`, `Debug`, and
/// `From<RowType> for Vec<FilterOp<Field>>`.
///
/// # Arguments
///
/// - `ast` — the parsed struct `DeriveInput`.
/// - `attr_black_list` — list of field-attribute names to skip (as `String`).
///
/// # Returns
///
/// `(body, ident_tokens)` where `body` is the full generated `TokenStream` and
/// `ident_tokens` is either `quote! { InsertRow }` or `quote! { UpdateRow }`.
#[doc(hidden)]
pub fn to_row(ast: &DeriveInput, attr_black_list: Vec<String>) -> (Body, BodyIdent) {
    let fields = match &ast.data {
        Data::Struct(DataStruct { fields: Fields::Named(fields), .. }) => &fields.named,
        _ => {
            return (
                syn::Error::new_spanned(&ast.ident, "expected a struct with named fields")
                    .to_compile_error(),
                quote! { Row }
            );
        }
    };

    let is_insert_row = attr_black_list.contains(&"update_only".to_string());
    let _is_update_row = !is_insert_row;

    let body_ident = if is_insert_row {
        quote! { InsertRow}
    } else {
        quote! {UpdateRow}
    };

    let mut props = vec![];
    let mut string_some = vec![];
    let mut bind_some = vec![];
    let mut bind_len = vec![];
    let mut debug_bindings = vec![];
    let mut row_to_filter_arms = vec![];

    fields.iter().for_each(|f| {
        let name_ident = f.ident.as_ref().ok_or_else(|| {
            syn::Error::new_spanned(&ast.ident, "missing a name field (missing ident.)",)
                .to_compile_error()
        },);

        // we need to check if either there are no attrs, or if attr != locked | != insert_only
        if let Ok(name_ident,) = name_ident
            && f.attrs.iter().all(|a| attr_black_list.iter().all(|abl| !a.path().is_ident(abl,),),)
        {
            let ty = &f.ty;
            if is_insert_row {
                props.push(quote! { pub #name_ident: #ty },);

                let name_str = name_ident.to_string();
                string_some.push(quote! {
                    i += 1;
                    sql.push(format!("{}", #name_str));
                    sql_i.push(format!("${}", i));
                },);

                bind_len.push(quote! {
                        count += 1;
                },);
                bind_some.push(quote! {
                    let _ = args.add(&self.#name_ident);
                },);
                debug_bindings.push(quote! {
                    sql_i += 1;
                    write!(f, "\n\t${} = {:?}", sql_i, &self.#name_ident)?;
                },);

                row_to_filter_arms.push(quote! {
                    {
                        use mae::repo::filter::IntoMaeFilter;
                        let filter = row.#name_ident.clone().into_mae_filter();
                        if out.is_empty() {
                            out.push(mae::repo::filter::FilterOp::Begin(Field::#name_ident, filter,),);
                        } else {
                            out.push(mae::repo::filter::FilterOp::And(Field::#name_ident, filter,),);
                        }
                    }
                },);
            } else {
                props.push(quote! { pub #name_ident: Option<#ty> },);

                let name_str = name_ident.to_string();
                string_some.push(quote! {
                if let Some(v) = &self.#name_ident {
                    i += 1;
                    sql.push(format!("{}", #name_str));
                    sql_i.push(format!("${}", i));
                };},);

                bind_len.push(quote! {
                    if let Some(v) = &self.#name_ident {
                        count += 1;
                    };
                },);
                bind_some.push(quote! {
                if let Some(v) = &self.#name_ident {
                    let _ = args.add(v);
                };},);
                debug_bindings.push(quote! {
                    if let Some(v) = &self.#name_ident {
                        sql_i += 1;
                        write!(f, "\n\t${} = {:?}", sql_i, v)?;
                    };
                },);

                row_to_filter_arms.push(quote! {
                    if let Some(v) = row.#name_ident.clone() {
                        use mae::repo::filter::IntoMaeFilter;
                        let filter = v.into_mae_filter();
                        if out.is_empty() {
                            out.push(mae::repo::filter::FilterOp::Begin(Field::#name_ident, filter,),);
                        } else {
                            out.push(mae::repo::filter::FilterOp::And(Field::#name_ident, filter,),);
                        }
                    }
                },);
            }
        }
    },);

    let body = quote! {
        #[allow(non_snake_case, non_camel_case_types, nonstandard_style)]
        #[derive(Clone)]
        pub struct #body_ident {
            #(#props,)*
        }

        impl mae::repo::__private__::ToSqlParts for #body_ident {
            fn to_sql_parts(&self) -> mae::repo::__private__::AsSqlParts {
                let mut i = 0;
                let mut sql = vec![];
                let mut sql_i = vec![];
                #(#string_some)*

                (sql, Some(sql_i))
            }
        }

        impl mae::repo::__private__::BindArgs for #body_ident {
            fn bind(&self, mut args: &mut sqlx::postgres::PgArguments) {
                use sqlx::Arguments;
                #(#bind_some)*
            }
            fn bind_len(&self) -> usize {
                let mut count = 0;
                #(#bind_len)*
                count
            }
        }

        impl std::fmt::Debug for #body_ident {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                let mut sql_i = 0;
                #(#debug_bindings)*
                std::fmt::Result::Ok(())
            }
        }

        /// Convert a row into a list of [`FilterOp<Field>`] conditions.
        ///
        /// For [`InsertRow`] every field becomes a filter condition.
        /// For [`UpdateRow`] only the `Some` fields are emitted; `None`
        /// fields are skipped so callers can build partial WHERE clauses.
        ///
        /// The first condition uses [`FilterOp::Begin`]; subsequent ones
        /// use [`FilterOp::And`].
        impl From<#body_ident> for Vec<mae::repo::filter::FilterOp<Field>> {
            fn from(row: #body_ident) -> Vec<mae::repo::filter::FilterOp<Field>> {
                let mut out: Vec<mae::repo::filter::FilterOp<Field>> = vec![];
                #(#row_to_filter_arms)*
                out
            }
        }
    };
    (body, body_ident)
}

// ── Attribute-search utilities ────────────────────────────────────────────────

/// Searches a field's attributes for one matching `attr_name`.
///
/// Returns the field's identifier if the attribute is present, or `None`
/// if either the field is unnamed (tuple field) or the attribute is absent.
///
/// Only the attribute path is checked; no arguments are parsed.
#[doc(hidden)]
#[allow(dead_code)]
fn find_get_attr(field: &Field, attr_name: &'static str) -> Option<syn::Ident> {
    let Some(ident) = field.ident.clone() else {
        return None; // ignore tuple fields
    };

    for attr in &field.attrs {
        if attr.path().is_ident(attr_name) {
            return Some(ident);
        }
    }

    None
}

/// Searches a field's attributes for one matching `attr_name` and parses its
/// single string-literal argument.
///
/// Returns `Ok(Some((ident, value)))` if the attribute is found and its
/// argument is a valid string literal, `Ok(None)` if the attribute is absent
/// or the field is unnamed, and `Err` if the argument fails to parse as a
/// `LitStr`.
///
/// Expected attribute form: `#[attr_name("literal value")]`.
#[doc(hidden)]
#[allow(dead_code)]
fn find_get_attr_with_args(
    field: &Field,
    attr_name: &'static str
) -> Result<Option<(syn::Ident, String)>, syn::Error> {
    let Some(ident) = field.ident.clone() else {
        return Ok(None); // ignore tuple fields
    };

    for attr in &field.attrs {
        if attr.path().is_ident(attr_name) {
            let lit: LitStr = attr.parse_args().map_err(|_| {
                syn::Error::new_spanned(attr, format!("expected #[{}(\"...\")]", attr_name))
            })?;
            return Ok(Some((ident, lit.value())));
        }
    }

    Ok(None)
}