ormada-derive 0.1.0

Proc macros for Ormada ORM - Django-like ergonomic ORM for Rust
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Proc macro for #[derive(OrmadaModel)]
//!
//! This crate provides a derive macro that automatically generates
//! Model-based create/update operations with auto field handling.

// Proc macros are allowed to use patterns that would be problematic in regular code
// This is standard practice for code generation
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]
#![allow(clippy::panic)]
#![allow(clippy::too_many_lines)]
#![allow(clippy::uninlined_format_args)]
#![allow(clippy::doc_markdown)]
#![allow(clippy::disallowed_methods)]
#![allow(clippy::option_if_let_else)]
#![allow(clippy::use_self)]
#![allow(clippy::ref_option)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::missing_panics_doc)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::module_name_repetitions)]
#![allow(clippy::redundant_clone)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unnecessary_wraps)]
#![allow(clippy::struct_excessive_bools)]
#![allow(clippy::explicit_iter_loop)]
#![allow(clippy::collection_is_never_read)]
#![allow(clippy::suspicious_doc_comments)]
#![allow(clippy::while_let_on_iterator)]
#![allow(clippy::manual_while_let_some)]
#![allow(clippy::unused_peekable)]
#![allow(dead_code)]
#![allow(unused_variables)]
#![allow(unused_must_use)]

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields};

mod atomic;
mod model;
mod projection;
mod relations;
mod schema;

/// Check if a field has a specific `sea_orm` attribute
fn has_sea_orm_attribute(field: &syn::Field, attr_name: &str) -> bool {
    for attr in &field.attrs {
        if attr.path().is_ident("sea_orm") {
            // Simple string-based check for attribute presence
            let meta_str = quote::quote!(#attr).to_string();
            if meta_str.contains(attr_name) {
                return true;
            }
        }
    }
    false
}

/// Check if a field has a specific ormada attribute
fn has_ergorm_attribute(field: &syn::Field, attr_name: &str) -> bool {
    for attr in &field.attrs {
        if attr.path().is_ident("ormada") {
            // Simple string-based check for attribute presence
            let meta_str = quote::quote!(#attr).to_string();
            if meta_str.contains(attr_name) {
                return true;
            }
        }
    }
    false
}

/// Derive macro for Ormada Model-based operations
#[proc_macro_derive(OrmadaModel, attributes(ormada))]
pub fn derive_ormada_model(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let struct_name = &input.ident;

    // Extract fields from the struct
    let fields = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Named(fields) => &fields.named,
            _ => {
                return syn::Error::new_spanned(
                    struct_name,
                    "OrmadaModel can only be derived for structs with named fields",
                )
                .to_compile_error()
                .into();
            }
        },
        _ => {
            return syn::Error::new_spanned(
                struct_name,
                "OrmadaModel can only be derived for structs",
            )
            .to_compile_error()
            .into();
        }
    };

    // Categorize fields
    let mut primary_key = None;
    let mut auto_now_add_fields = Vec::new(); // Set on create only
    let mut auto_now_fields = Vec::new(); // Set on create AND update
    let mut all_fields = Vec::new();

    for field in fields {
        let field_name = field.ident.as_ref().unwrap();
        let field_ty = &field.ty;

        all_fields.push((field_name, field_ty));

        // Detect primary key from #[sea_orm(primary_key)]
        if has_sea_orm_attribute(field, "primary_key") {
            primary_key = Some(field_name);
            continue;
        }

        // Detect auto fields from #[ormada(...)] attributes
        if has_ergorm_attribute(field, "auto_now_add") {
            auto_now_add_fields.push(field_name);
            continue;
        }

        if has_ergorm_attribute(field, "auto_now") {
            auto_now_fields.push(field_name);
        }
    }

    // Primary key is required
    if primary_key.is_none() {
        return syn::Error::new_spanned(
            struct_name,
            "Model must have a field marked with #[sea_orm(primary_key)]",
        )
        .to_compile_error()
        .into();
    }
    let primary_key = primary_key.unwrap();

    // Note: Type-specific column traits can't be implemented on enum variants
    // For now, we'll keep the generic ColumnExt trait approach
    // This is still type-safe at compile time, just not at the method level

    // Generate ActiveModel field assignments for create
    let create_field_assignments: Vec<_> = all_fields
        .iter()
        .map(|(field_name, _)| {
            if Some(*field_name) == Some(primary_key) {
                // If ID is default/zero, let DB handle it (NotSet)
                // Otherwise use the provided ID
                // We need fully qualified Default call to avoid ambiguity with PartialEq
                let field_ty = all_fields.iter().find(|(n, _)| n == field_name).unwrap().1;
                quote! {
                    #field_name: if model.#field_name == <#field_ty as Default>::default() {
                        sea_orm::ActiveValue::NotSet
                    } else {
                        sea_orm::ActiveValue::Set(model.#field_name)
                    }
                }
            } else if auto_now_add_fields.contains(field_name)
                || auto_now_fields.contains(field_name)
            {
                quote! { #field_name: sea_orm::ActiveValue::Set(now) }
            } else {
                quote! { #field_name: sea_orm::ActiveValue::Set(model.#field_name) }
            }
        })
        .collect();

    // Generate ActiveModel field assignments for save (update all fields)
    let save_field_assignments: Vec<_> = all_fields
        .iter()
        .map(|(field_name, _)| {
            if Some(*field_name) == Some(primary_key) {
                // Primary key must be Set for update to work
                quote! { #field_name: sea_orm::ActiveValue::Set(self.#field_name) }
            } else if auto_now_fields.contains(field_name) {
                // auto_now fields will be set below with current timestamp
                quote! { #field_name: sea_orm::ActiveValue::Set(now) }
            } else {
                // All other fields: update with current value
                quote! { #field_name: sea_orm::ActiveValue::Set(self.#field_name) }
            }
        })
        .collect();

    // Generate ActiveModel field assignments for update (only auto_now fields)
    let update_auto_fields = auto_now_fields.iter().map(|field_name| {
        quote! {
            active_model.#field_name = sea_orm::ActiveValue::Set({
                let now: sea_orm::prelude::DateTimeWithTimeZone = chrono::Utc::now().into();
                now
            });
        }
    });

    // Parse relations
    let relation_infos = relations::parse_relations(&input);

    // ALWAYS generate ModelWithRelations (needed even for entities without relations)
    let model_with_relations = relations::generate_model_with_relations(fields, &relation_infos);
    let from_impl = relations::generate_from_impl(fields, &relation_infos);

    // ALWAYS generate WithRelationsTrait (needed for accessor methods to work)
    let field_refs: Vec<&syn::Field> = fields.iter().collect();
    let trait_impl = relations::generate_trait_impl(&relation_infos, &field_refs);

    // Generate HasRelation implementations (compile-time typed relations)
    let has_relation_impls = relations::generate_has_relation_impls(&relation_infos);

    let expanded = quote! {
        // ===== RELATION MODELS =====
        #model_with_relations
        #from_impl
        #trait_impl

        // ===== DJANGO ENTITY TRAIT =====
        impl ::ormada::traits::OrmadaEntity for Entity {
            fn to_active_model_for_create(model: Model) -> ::core::result::Result<ActiveModel, ::ormada::error::OrmadaError> {
                let now = ::chrono::Utc::now().fixed_offset();
                ::core::result::Result::Ok(ActiveModel {
                    #(#create_field_assignments,)*
                })
            }

            async fn save_model<'a, C: ::sea_orm::ConnectionTrait>(
                db: &'a C,
                model: Model,
            ) -> Result<Model, ormada::error::OrmadaError> {
                model.save(db).await
            }
        }

        // ===== UPDATE OPERATION =====
        impl Model {
            /// Save (update) this model (Ormada-style: updates ALL fields)
            ///
            /// All model fields are updated in the database.
            /// Fields marked with #[ormada(auto_now)] are automatically set to the current timestamp.
            ///
            /// This follows Ormada's behavior where .save() updates all fields,
            /// not just modified ones.
            pub async fn save<'a, C: ::sea_orm::ConnectionTrait>(
                self,
                db: &'a C,
            ) -> Result<Self, ormada::error::OrmadaOrmError> {
                use sea_orm::Set;
                let now = ::chrono::Utc::now().fixed_offset();

                // Create ActiveModel with ALL fields marked as Set (to be updated)
                let mut active_model = ActiveModel {
                    #(#save_field_assignments,)*
                };

                // Override auto_now fields with current timestamp
                #(#update_auto_fields)*

                use sea_orm::ActiveModelTrait;
                Ok(active_model.update(db).await?)
            }
        }

        // ===== RELATION LOADING =====
        #has_relation_impls
    };

    TokenStream::from(expanded)
}

/// Attribute macro for atomic transactions
///
/// Wraps the function body in a transaction.
///
/// # Usage
///
/// ```rust,ignore
/// #[atomic(db)]
/// async fn create_user(db: &DatabaseConnection, name: String) -> Result<(), OrmadaError> {
///     // This code runs inside a transaction!
///     // 'db' is shadowed by the transaction handle
///     let user = User::objects(db).create(name).await?;
///     Ok(())
/// }
/// ```
#[proc_macro_attribute]
pub fn atomic(args: TokenStream, input: TokenStream) -> TokenStream {
    atomic::impl_atomic(args, input)
}

/// Attribute macro for defining Ormada models with clean syntax
///
/// This macro transforms a simple struct definition into a full `SeaORM` entity
/// with all the necessary derives and boilerplate.
///
/// # Model Attributes
///
/// - `table = "table_name"` - **(required)** Database table name
/// - `ordering = "field"` - Default ordering for queries
/// - `hooks = true` - Enable custom lifecycle hooks (see below)
///
/// # Usage
///
/// ```rust,ignore
/// use ormada::prelude::*;
///
/// #[ormada_model(table = "books")]
/// struct Book {
///     #[primary_key]
///     id: i32,
///
///     #[max_length(200)]
///     #[index]
///     title: String,
///
///     #[foreign_key(Author, on_delete = Cascade)]
///     author_id: i32,
///
///     #[auto_now_add]
///     created_at: DateTimeWithTimeZone,
///
///     #[auto_now]
///     updated_at: DateTimeWithTimeZone,
/// }
/// ```
///
/// # Lifecycle Hooks
///
/// By default, an empty `LifecycleHooks` implementation is auto-generated.
/// To provide custom hooks, use `hooks = true`:
///
/// ```rust,ignore
/// #[ormada_model(table = "books", hooks = true)]
/// struct Book { /* fields */ }
///
/// #[async_trait]
/// impl LifecycleHooks for book::Model {
///     async fn before_save(&mut self) -> Result<(), OrmadaError> {
///         // Custom logic before save
///         Ok(())
///     }
/// }
/// ```
///
/// # Field Attributes
///
/// ## Primary Key
/// - `#[primary_key]` - Mark field as primary key
/// - `#[primary_key(auto_increment = false)]` - Control auto-increment
///
/// ## Relationships
/// - `#[foreign_key(Model)]` - Many-to-One relationship (use Model type, not Entity)
/// - `#[foreign_key(Model, on_delete = Cascade)]` - FK with ON DELETE behavior
/// - `#[one_to_one(Model)]` - One-to-One relationship
/// - `#[one_to_one(Model, on_delete = Cascade)]` - 1:1 with ON DELETE behavior
/// - `#[many_to_many(Model, through = JoinModel)]` - Many-to-Many with intermediate table
///
/// ## Indexing
/// - `#[index]` / `#[index(name = "idx_name")]` - Create index
/// - `#[unique]` / `#[unique(name = "uniq_name")]` - Unique constraint
///
/// ## Validation
/// - `#[max_length(n)]` - String max length validation
/// - `#[min_length(n)]` - String min length validation
/// - `#[range(min = n, max = m)]` - Numeric range validation
///
/// ## Timestamps
/// - `#[auto_now]` - Auto-update timestamp on save
/// - `#[auto_now_add]` - Auto-set timestamp on creation
///
/// ## Other
/// - `#[soft_delete]` - Mark field for soft delete (must be `Option<DateTimeWithTimeZone>`)
/// - `#[skip_serializing]` - Skip field when serializing
/// - `#[skip_deserializing]` - Skip field when deserializing
#[proc_macro_attribute]
pub fn ormada_model(attr: TokenStream, item: TokenStream) -> TokenStream {
    match model::impl_ormada_model(attr.into(), item.into()) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Attribute macro for defining type-safe projections with compile-time validation
///
/// Provides a type-safe alternative to JSON-based `values()` queries.
/// Validates that all non-computed fields exist on the model at compile time.
///
/// # Usage
///
/// ```rust,ignore
/// use ormada::prelude::*;
///
/// // Simple projection (all fields must exist on Book)
/// #[ergorm_projection(model = Book)]
/// struct BookSummary {
///     title: String,
///     price: f64,
/// }
///
/// // With computed fields (for aggregations)
/// #[ergorm_projection(model = Book)]
/// struct AuthorBookStats {
///     author_id: i32,           // Validated
///     #[computed]
///     book_count: i64,          // Not validated (computed by DB)
///     #[computed]
///     avg_price: Option<f64>,   // Not validated (computed by DB)
/// }
///
/// // Query usage
/// let summaries: Vec<BookSummary> = Book::objects(db)
///     .filter(Book::Published.eq(true))
///     .project::<BookSummary>()
///     .await?;
/// ```
///
/// # Field Attributes
///
/// - `#[computed]` - Mark field as computed (e.g., aggregations). These fields
///   are not validated against the model and must be provided by the query
///   (e.g., via `.annotate()` for aggregations).
#[proc_macro_attribute]
pub fn ergorm_projection(attr: TokenStream, item: TokenStream) -> TokenStream {
    match projection::generate_projection(attr.into(), item.into()) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Attribute macro for defining schema in migration files
///
/// This macro is used in migration files to define schema snapshots.
/// It uses the same syntax as `#[ormada_model]` but is purely declarative -
/// no runtime code is generated. The CLI parses these definitions to
/// generate SQL migrations.
///
/// # Usage
///
/// ```rust,ignore
/// use ormada::migration::prelude::*;
///
/// // Initial migration - full schema definition
/// pub mod m001_initial {
///     use super::*;
///
///     #[ormada_schema(table = "books", migration = "001_initial")]
///     pub struct Book {
///         #[primary_key]
///         pub id: i32,
///
///         #[max_length(200)]
///         pub title: String,
///
///         #[foreign_key(Author)]
///         pub author_id: i32,
///     }
/// }
///
/// // Delta migration - extends previous schema
/// pub mod m002_add_isbn {
///     use super::*;
///
///     #[ormada_schema(table = "books", migration = "002", after = "001", extends = Book)]
///     pub struct Book {
///         // Only new fields - inherited fields are implicit
///         #[index]
///         pub isbn: String,
///     }
/// }
/// ```
///
/// # Attributes
///
/// - `table = "name"` - **(required)** Database table name
/// - `migration = "id"` - Migration identifier (usually matches filename)
/// - `after = "id"` - Migration this depends on (for ordering)
/// - `extends = Entity` - Extend schema from previous migration (for deltas)
/// - `migrate = false` - Exclude from migration generation
///
/// # Field Attributes
///
/// Same as `#[ormada_model]`:
/// - `#[primary_key]` - Mark as primary key
/// - `#[foreign_key(Entity)]` - Foreign key relationship
/// - `#[index]` - Create index on column
/// - `#[unique]` - Unique constraint
/// - `#[max_length(n)]` - String max length
/// - `#[default(value)]` - Default value
/// - `#[nullable]` - Allow NULL values
///
/// Additional for migrations:
/// - `#[rename(from = "old", to = "new")]` - Rename column
/// - `#[drop]` - Drop column (use `()` type)
#[proc_macro_attribute]
pub fn ormada_schema(attr: TokenStream, item: TokenStream) -> TokenStream {
    match schema::impl_ormada_schema(attr.into(), item.into()) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// Attribute macro for data migrations
///
/// Marks an async function as a data migration that runs after schema changes.
/// The function receives a database connection and uses the standard Ormada ORM API.
///
/// # Usage
///
/// ```rust,ignore
/// use ormada::migration::prelude::*;
/// use crate::models::Author;
///
/// #[ormada_data_migration(migration = "003", after = "002")]
/// async fn populate_emails(db: &DatabaseConnection) -> Result<(), OrmadaError> {
///     // Use the same Ormada ORM API as your application code!
///     Author::objects(db)
///         .filter(Author::Email.is_null())
///         .update_all(|author| {
///             author.email = format!("{}@example.com", author.name.to_lowercase());
///         })
///         .await?;
///
///     Ok(())
/// }
/// ```
///
/// # Attributes
///
/// - `migration = "id"` - **(required)** Migration identifier
/// - `after = "id"` - Migration this depends on
#[proc_macro_attribute]
pub fn ormada_data_migration(attr: TokenStream, item: TokenStream) -> TokenStream {
    match schema::impl_ormada_data_migration(attr.into(), item.into()) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}