evento-macro 2.0.0-alpha.17

A collection of libraries and tools that help you build DDD, CQRS, and event sourcing.
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
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use std::collections::{HashMap, HashSet};
use syn::{Data, DeriveInput, Fields, Result, Type};

/// Holds parsed cursor field information
#[derive(Clone)]
struct CursorField {
    field_name: syn::Ident,
    field_type: Type,
    column_path: syn::Path,
    order: usize,
}

/// Parse the #[cursor(...)] attribute
/// Supports two formats:
/// - Named: #[cursor(name, Column::Variant, order)]
/// - Unnamed: #[cursor(Column::Variant, order)] - uses "cursor" as default name
///   Returns (cursor_name, column_path, order)
fn parse_cursor_attr(attr: &syn::Attribute) -> Result<Option<(String, syn::Path, usize)>> {
    if !attr.path().is_ident("cursor") {
        return Ok(None);
    }

    let result = attr.parse_args_with(|input: syn::parse::ParseStream| {
        // Try to determine if this is named or unnamed format
        // by looking at the first identifier and what follows

        let first_ident: syn::Ident = input.parse()?;

        if input.peek(syn::Token![::]) {
            // It's a path like `Column::Variant` - unnamed format
            // We need to reconstruct the path starting with first_ident
            let mut segments = syn::punctuated::Punctuated::new();
            segments.push(syn::PathSegment::from(first_ident));

            while input.peek(syn::Token![::]) {
                input.parse::<syn::Token![::]>()?;
                let seg: syn::PathSegment = input.parse()?;
                segments.push(seg);
            }

            let path = syn::Path {
                leading_colon: None,
                segments,
            };

            input.parse::<syn::Token![,]>()?;
            let lit: syn::LitInt = input.parse()?;
            let order: usize = lit.base10_parse()?;

            // Use "cursor" as default name for unnamed format
            Ok(("cursor".to_string(), path, order))
        } else {
            // Named format: name, Column::Variant, order
            let name = first_ident.to_string();

            input.parse::<syn::Token![,]>()?;
            let path: syn::Path = input.parse()?;
            input.parse::<syn::Token![,]>()?;
            let lit: syn::LitInt = input.parse()?;
            let order: usize = lit.base10_parse()?;

            Ok((name, path, order))
        }
    })?;

    Ok(Some(result))
}

/// Generate a short name from a field name (e.g., "created_at" -> "c")
/// Handles duplicates by adding more characters from subsequent parts
fn generate_short_name(field_name: &str, used: &HashSet<String>) -> String {
    let parts: Vec<&str> = field_name.split('_').collect();

    // Try first letter
    let mut short = parts[0].chars().next().unwrap_or('x').to_string();
    if !used.contains(&short) {
        return short;
    }

    // Try adding first letter of subsequent parts
    for part in parts.iter().skip(1) {
        if let Some(c) = part.chars().next() {
            short.push(c);
            if !used.contains(&short) {
                return short;
            }
        }
    }

    // Fallback: add numbers
    let base = parts[0].chars().next().unwrap_or('x').to_string();
    let mut counter = 2;
    loop {
        let candidate = format!("{}{}", base, counter);
        if !used.contains(&candidate) {
            return candidate;
        }
        counter += 1;
    }
}

/// Convert snake_case to PascalCase
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(c) => c.to_uppercase().chain(chars).collect(),
                None => String::new(),
            }
        })
        .collect()
}

/// Extract the enum type from the column path (e.g., ContactAdmin::Id -> ContactAdmin)
fn extract_enum_type(path: &syn::Path) -> Result<syn::Path> {
    if path.segments.len() < 2 {
        return Err(syn::Error::new_spanned(
            path,
            "Expected path with at least two segments (e.g., Column::Variant)",
        ));
    }

    // Collect all segments except the last one (the variant)
    let segments: syn::punctuated::Punctuated<syn::PathSegment, syn::Token![::]> = path
        .segments
        .iter()
        .take(path.segments.len() - 1)
        .cloned()
        .collect();

    Ok(syn::Path {
        leading_colon: path.leading_colon,
        segments,
    })
}

/// Check if a type is likely a Copy type (primitive types)
fn is_copy_type(ty: &Type) -> bool {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            let ident = segment.ident.to_string();
            return matches!(
                ident.as_str(),
                "u8" | "u16"
                    | "u32"
                    | "u64"
                    | "u128"
                    | "usize"
                    | "i8"
                    | "i16"
                    | "i32"
                    | "i64"
                    | "i128"
                    | "isize"
                    | "f32"
                    | "f64"
                    | "bool"
                    | "char"
            );
        }
    }
    false
}

/// Generate code for a single cursor variant
fn generate_cursor_code(
    struct_name: &syn::Ident,
    cursor_name: &str,
    cursor_fields: &mut [CursorField],
) -> Result<TokenStream> {
    // Sort by order (ascending) for the cursor struct
    cursor_fields.sort_by_key(|f| f.order);

    // Generate short names for each field
    let mut used_short_names = HashSet::new();
    let short_names: Vec<syn::Ident> = cursor_fields
        .iter()
        .map(|f| {
            let short = generate_short_name(&f.field_name.to_string(), &used_short_names);
            used_short_names.insert(short.clone());
            format_ident!("{}", short)
        })
        .collect();

    // Extract the column enum type from the first field
    let column_enum_type = extract_enum_type(&cursor_fields[0].column_path)?;

    let field_count = cursor_fields.len();
    // let field_count = Literal::usize_unsuffixed(cursor_fields.len());

    // Generate cursor struct fields with doc comments
    let cursor_struct_fields = cursor_fields.iter().zip(&short_names).map(|(f, short)| {
        let field_type = &f.field_type;
        let doc = format!(" {}", f.field_name);
        quote! {
            #[doc = #doc]
            pub #short: #field_type
        }
    });

    // Sort by order descending for columns() and values() (higher order first)
    let mut sorted_indices: Vec<usize> = (0..cursor_fields.len()).collect();
    sorted_indices.sort_by(|&a, &b| cursor_fields[b].order.cmp(&cursor_fields[a].order));

    // Generate columns (descending order)
    let column_variants = sorted_indices.iter().map(|&i| {
        let variant = cursor_fields[i].column_path.segments.last().unwrap();
        let variant_ident = &variant.ident;
        quote! { #column_enum_type::#variant_ident }
    });

    // Generate values (same descending order)
    let values = sorted_indices.iter().map(|&i| {
        let short = &short_names[i];
        quote! { cursor.#short.into() }
    });

    // Check if this is the default "cursor" name (no wrapper needed)
    if cursor_name == "cursor" {
        let cursor_struct_name = format_ident!("{}Cursor", struct_name);

        // Generate serialize assignments (direct access to self)
        let serialize_assignments = cursor_fields.iter().zip(&short_names).map(|(f, short)| {
            let field_name = &f.field_name;
            if is_copy_type(&f.field_type) {
                quote! { #short: self.#field_name }
            } else {
                quote! { #short: self.#field_name.to_owned() }
            }
        });

        Ok(quote! {
            // Cursor struct
            #[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
            pub struct #cursor_struct_name {
                #(#cursor_struct_fields),*
            }

            impl evento::cursor::Cursor for #struct_name {
                type T = #cursor_struct_name;

                fn serialize(&self) -> Self::T {
                    #cursor_struct_name {
                        #(#serialize_assignments),*
                    }
                }
            }

            impl evento::sql::Bind for #struct_name {
                type T = #column_enum_type;
                type I = [Self::T; #field_count];
                type V = [sea_query::Expr; #field_count];
                type Cursor = Self;

                fn columns() -> Self::I {
                    [#(#column_variants),*]
                }

                fn values(
                    cursor: <<Self as evento::sql::Bind>::Cursor as evento::cursor::Cursor>::T,
                ) -> Self::V {
                    [#(#values),*]
                }
            }
        }
        .into())
    } else {
        // Named cursor - create newtype wrapper
        let wrapper_name = format_ident!("{}{}", struct_name, to_pascal_case(cursor_name));
        let cursor_struct_name =
            format_ident!("{}{}Cursor", struct_name, to_pascal_case(cursor_name));

        // Generate serialize assignments (access through self.0)
        let serialize_assignments: Vec<_> = cursor_fields
            .iter()
            .zip(&short_names)
            .map(|(f, short)| {
                let field_name = &f.field_name;
                if is_copy_type(&f.field_type) {
                    quote! { #short: self.0.#field_name }
                } else {
                    quote! { #short: self.0.#field_name.to_owned() }
                }
            })
            .collect();

        Ok(quote! {
            // Newtype wrapper
            #[derive(Debug, Clone)]
            pub struct #wrapper_name(pub #struct_name);

            impl ::core::ops::Deref for #wrapper_name {
                type Target = #struct_name;

                fn deref(&self) -> &Self::Target {
                    &self.0
                }
            }

            impl<'r, R: sqlx::Row> sqlx::FromRow<'r, R> for #wrapper_name
            where
                #struct_name: ::sqlx::FromRow<'r, R>,
            {
                fn from_row(row: &'r R) -> ::sqlx::Result<Self> {
                    Ok(#wrapper_name(#struct_name::from_row(row)?))
                }
            }

            // Cursor struct
            #[derive(Debug, Clone, bitcode::Encode, bitcode::Decode)]
            pub struct #cursor_struct_name {
                #(#cursor_struct_fields),*
            }

            impl evento::cursor::Cursor for #wrapper_name {
                type T = #cursor_struct_name;

                fn serialize(&self) -> Self::T {
                    #cursor_struct_name {
                        #(#serialize_assignments),*
                    }
                }
            }

            impl evento::sql::Bind for #wrapper_name {
                type T = #column_enum_type;
                type I = [Self::T; #field_count];
                type V = [sea_query::Expr; #field_count];
                type Cursor = Self;

                fn columns() -> Self::I {
                    [#(#column_variants),*]
                }

                fn values(
                    cursor: <<Self as evento::sql::Bind>::Cursor as evento::cursor::Cursor>::T,
                ) -> Self::V {
                    [#(#values),*]
                }
            }
        }
        .into())
    }
}

/// Main implementation for the Cursor derive macro
pub fn cursor_impl(input: &DeriveInput) -> Result<TokenStream> {
    let struct_name = &input.ident;

    // Extract fields with #[cursor] attribute
    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => &fields.named,
            Fields::Unnamed(_) => {
                return Err(syn::Error::new_spanned(
                    struct_name,
                    "Cursor derive only supports structs with named fields",
                ));
            }
            Fields::Unit => {
                return Err(syn::Error::new_spanned(
                    struct_name,
                    "Cursor derive does not support unit structs",
                ));
            }
        },
        Data::Enum(_) => {
            return Err(syn::Error::new_spanned(
                struct_name,
                "Cursor derive does not support enums",
            ));
        }
        Data::Union(_) => {
            return Err(syn::Error::new_spanned(
                struct_name,
                "Cursor derive does not support unions",
            ));
        }
    };

    // Group fields by cursor name
    let mut cursor_groups: HashMap<String, Vec<CursorField>> = HashMap::new();

    for field in fields {
        for attr in &field.attrs {
            if let Some((cursor_name, column_path, order)) = parse_cursor_attr(attr)? {
                cursor_groups
                    .entry(cursor_name)
                    .or_default()
                    .push(CursorField {
                        field_name: field.ident.clone().unwrap(),
                        field_type: field.ty.clone(),
                        column_path,
                        order,
                    });
            }
        }
    }

    if cursor_groups.is_empty() {
        return Err(syn::Error::new_spanned(
            struct_name,
            "No fields marked with #[cursor] attribute. Add #[cursor(name, Column::Variant, order)] to at least one field.",
        ));
    }

    // Generate code for each cursor variant
    let mut all_tokens = TokenStream::new();

    for (cursor_name, mut fields) in cursor_groups {
        let tokens = generate_cursor_code(struct_name, &cursor_name, &mut fields)?;
        all_tokens.extend(tokens);
    }

    Ok(all_tokens)
}