crudcrate 0.9.2

Derive complete REST APIs from Sea-ORM entities — endpoints, filtering, pagination, batch ops, and OpenAPI on Axum
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
#[macro_export]
macro_rules! crud_handlers {
    // Version with scoped models for auth-aware field visibility
    ($resource:ty, $update_model:ty, $create_model:ty, $list_model:ty, $response_model:ty, $scoped_list:ty, $scoped_response:ty) => {
        crudcrate::crud_handlers_impl!(
            $resource,
            $update_model,
            $create_model,
            $list_model,
            $response_model,
            $scoped_list,
            $scoped_response
        );
    };

    // Standard version with ListModel and ResponseModel (scoped = same as regular)
    ($resource:ty, $update_model:ty, $create_model:ty, $list_model:ty, $response_model:ty) => {
        crudcrate::crud_handlers_impl!(
            $resource,
            $update_model,
            $create_model,
            $list_model,
            $response_model,
            $list_model,
            $response_model
        );
    };

    // Backward compatibility - use Self as ResponseModel
    ($resource:ty, $update_model:ty, $create_model:ty, $list_model:ty) => {
        crudcrate::crud_handlers_impl!(
            $resource,
            $update_model,
            $create_model,
            $list_model,
            $resource,
            $list_model,
            $resource
        );
    };

    // Backward compatibility - use Self as ListModel and ResponseModel
    ($resource:ty, $update_model:ty, $create_model:ty) => {
        crudcrate::crud_handlers_impl!(
            $resource,
            $update_model,
            $create_model,
            $resource,
            $resource,
            $resource,
            $resource
        );
    };
}

#[macro_export]
macro_rules! crud_handlers_impl {
    ($resource:ty, $update_model:ty, $create_model:ty, $list_model:ty, $response_model:ty, $scoped_list:ty, $scoped_response:ty) => {
        use crudcrate::filter::{apply_filters, parse_pagination};
        use crudcrate::models::FilterOptions;
        use crudcrate::pagination::calculate_content_range;
        use crudcrate::sort::parse_sorting;

        use axum::{
            extract::{Path, Query, State},
            http::StatusCode,
            Json,
        };

        use axum::http::HeaderMap;
        use sea_orm::{DbErr, SqlErr};

        // utoipa's `axum_extras` feature parses handler parameter types to infer
        // OpenAPI params/bodies. A `:ty` macro fragment nested inside a path's
        // generic arguments (`crudcrate::PrimaryKeyType<$resource>`) reaches the
        // utoipa proc-macro as an opaque nonterminal it cannot descend into,
        // surfacing as a spurious "expected expression, found `let`" parse error
        // in any downstream consumer that enables `axum_extras`. Aliasing the
        // primary-key type to a plain path name lets the generated handler
        // signatures reference it without exposing the fragment to utoipa.
        #[allow(dead_code)]
        type CrudPrimaryKey = crudcrate::PrimaryKeyType<$resource>;


        #[utoipa::path(
            get,
            path = "/{id}",
            // Declared explicitly (String) so utoipa's `axum_extras` does not infer the
            // param schema from `Path<CrudPrimaryKey>` — which would require the primary-key
            // type to implement `ToSchema`/`PartialSchema`. Mirrors `BatchUpdateRequest`'s
            // `#[schema(value_type = String)]`. The path value is always a stringified id.
            params(("id" = String, Path, description = "Resource identifier")),
            responses(
                (status = axum::http::StatusCode::OK, description = "The requested resource", body = $response_model),
                (status = axum::http::StatusCode::NOT_FOUND, description = "Resource not found"),
                (status = axum::http::StatusCode::BAD_REQUEST, description = "Bad request"),
                (status = axum::http::StatusCode::INTERNAL_SERVER_ERROR, description = "Internal Server Error")
            ),
            operation_id = format!("get_one_{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            summary = format!("Get one {}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            description = format!("Retrieves one {} by its ID.\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR, <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn get_one_handler(
            axum::extract::State(db): axum::extract::State<sea_orm::DatabaseConnection>,
            axum::extract::Path(id): axum::extract::Path<CrudPrimaryKey>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
        ) -> Result<axum::response::Response, crudcrate::ApiError> {
            use axum::response::IntoResponse;

            // require_scope: if scope middleware is required but not present, return 500
            if <$resource as crudcrate::traits::CRUDResource>::REQUIRE_SCOPE && scope.is_none() {
                return Err(crudcrate::ApiError::internal(
                    "Scope middleware required for this resource but not configured",
                    Some("require_scope check failed: ScopeCondition extension not found in request".into()),
                ));
            }

            if let Some(axum::Extension(crudcrate::ScopeCondition { condition: extra })) = scope {
                // Atomic scoped fetch: ID + scope condition in a single query.
                // Prevents TOCTOU race where scope-relevant columns could change
                // between a fetch and a separate verification query.
                // get_one_scoped already returns NotFound (404) when the scope condition
                // excludes the row, so existence stays masked. Propagate the real error
                // instead of rewriting everything to 404 — genuine DB/internal faults
                // must surface as 500 (and be logged), not masquerade as a missing row.
                let result = <$resource as crudcrate::traits::CRUDResource>::get_one_scoped(&db, id, &extra)
                    .await?;

                let response: $response_model = result.into();
                let scoped: $scoped_response = response.into();
                Ok(axum::Json(scoped).into_response())
            } else {
                let result = <$resource as crudcrate::traits::CRUDResource>::get_one(&db, id)
                    .await
                    .map_err(crudcrate::ApiError::from)?;
                let response: $response_model = result.into();
                Ok(axum::Json(response).into_response())
            }
        }

        #[utoipa::path(
            get,
            path = "/",
            responses(
                (status = axum::http::StatusCode::OK, description = "List of resources", body = [$list_model]),
                (status = axum::http::StatusCode::INTERNAL_SERVER_ERROR, description = "Internal Server Error")
            ),
            params(crudcrate::models::FilterOptions),
            operation_id = format!("get_all_{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            summary = format!("Get all {}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            description = format!(
                "Retrieves all {}.\n\n{}\n\nAdditional sortable columns: {}.\n\nAdditional filterable columns: {}.",
                <$resource as CRUDResource>::RESOURCE_NAME_PLURAL,
                <$resource as CRUDResource>::RESOURCE_DESCRIPTION,
                <$resource as CRUDResource>::sortable_columns()
                    .iter()
                    .map(|(name, _)| format!("\n- {}", name))
                    .collect::<Vec<String>>()
                    .join(""),
                <$resource as CRUDResource>::filterable_columns()
                    .iter()
                    .map(|(name, _)| format!("\n- {}", name))
                    .collect::<Vec<String>>()
                    .join("")
            )
        )]
        pub async fn get_all_handler(
            axum::extract::Query(params): axum::extract::Query<crudcrate::models::FilterOptions>,
            axum::extract::State(db): axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            profile_ext: Option<axum::Extension<crudcrate::SecurityProfile>>,
        ) -> Result<axum::response::Response, crudcrate::ApiError> {
            use axum::response::IntoResponse;

            // require_scope: if scope middleware is required but not present, return 500
            if <$resource as crudcrate::traits::CRUDResource>::REQUIRE_SCOPE && scope.is_none() {
                return Err(crudcrate::ApiError::internal(
                    "Scope middleware required for this resource but not configured",
                    Some("require_scope check failed: ScopeCondition extension not found in request".into()),
                ));
            }

            let profile = crudcrate::profile::resolve(
                profile_ext,
                <$resource as crudcrate::traits::CRUDResource>::security_profile,
            );

            // Strict filter parsing: reject malformed filter JSON before falling through
            // to the lenient parser (which would silently return an unfiltered result).
            if profile.strict_filter_parsing
                && let Some(filter_str) = &params.filter
                && serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(filter_str).is_err()
            {
                return Err(crudcrate::ApiError::bad_request(
                    "Invalid JSON in filter parameter",
                ));
            }

            let (offset, limit) = crudcrate::filter::parse_pagination(&params);
            let limit = limit.min(<$resource as crudcrate::traits::CRUDResource>::max_page_size());

            let is_scoped = scope.is_some();

            // When scoped, drop excluded columns from the filterable/sortable lists
            // (and from joined sorts, below) so unauthenticated callers can't probe
            // them. Unscoped requests get the full lists.
            let scoped_excluded: &[&str] = if is_scoped {
                <$resource as crudcrate::traits::CRUDResource>::scoped_excluded_columns()
            } else {
                &[]
            };
            let filterable_columns: Vec<_> = <$resource as CRUDResource>::filterable_columns()
                .into_iter()
                .filter(|(name, _)| !scoped_excluded.contains(name))
                .collect();
            let sortable_columns: Vec<_> = <$resource as crudcrate::traits::CRUDResource>::sortable_columns()
                .into_iter()
                .filter(|(name, _)| !scoped_excluded.contains(name))
                .collect();

            let parsed_filters = crudcrate::apply_filters_with_joins::<$resource>(
                params.filter.clone(),
                &filterable_columns,
                db.get_database_backend()
            )?;

            let sort_config = crudcrate::parse_sorting_with_joins::<$resource, _>(
                &params,
                &sortable_columns,
                <$resource as crudcrate::traits::CRUDResource>::default_index_column(),
                scoped_excluded,
            );

            let mut condition = parsed_filters.main_condition;

            let scope_was_present = scope.is_some();
            if let Some(axum::Extension(crudcrate::ScopeCondition { condition: extra })) = scope {
                condition = condition.add(extra);
            };

            // Strict scope propagation: reject joined filters targeting child entities
            // that don't carry their own scope_condition. Without scope on the child,
            // the sub-query runs unrestricted and parent existence leaks via the
            // result's cardinality even when the parent scope filters the final rows.
            if profile.scope_propagation_strict
                && scope_was_present
                && !parsed_filters.joined_filters.is_empty()
            {
                for jf in &parsed_filters.joined_filters {
                    if !<$resource as crudcrate::traits::CRUDResource>::joined_field_has_scope(&jf.join_field) {
                        return Err(crudcrate::ApiError::bad_request(format!(
                            "Joined filter on '{}' not allowed under strict scope: child entity has no scope_condition",
                            jf.join_field,
                        )));
                    }
                }
            }

            // Same guard for joined sorts: ordering parent rows by a column on an
            // unscoped child leaks child existence through the row order, so reject it
            // under strict scope just as the joined-filter path above does.
            if let crudcrate::SortConfig::Joined { join_field, .. } = &sort_config {
                if profile.scope_propagation_strict
                    && scope_was_present
                    && !<$resource as crudcrate::traits::CRUDResource>::joined_field_has_scope(join_field)
                {
                    return Err(crudcrate::ApiError::bad_request(format!(
                        "Joined sort on '{join_field}' not allowed under strict scope: child entity has no scope_condition",
                    )));
                }
            }

            // Resolve dot-notation joined filters (e.g. {"vehicles.make":"BMW"})
            // into additional `Self::ID_COLUMN.is_in(...)` clauses on the main
            // condition. The derive macro's override runs a sub-query per
            // filter with the child's scope_condition applied. Default impl
            // (no derive override) returns the condition unchanged.
            let condition = <$resource as crudcrate::traits::CRUDResource>::resolve_joined_filters(
                &db,
                condition,
                &parsed_filters.joined_filters,
            ).await?;

            let items = match &sort_config {
                crudcrate::SortConfig::Column { column, direction } => {
                    let order_column = *column;
                    let order_direction = direction.clone();
                    if is_scoped {
                        <$resource as crudcrate::traits::CRUDResource>::get_all_scoped(&db, &condition, order_column, order_direction, offset, limit)
                            .await
                            .map_err(crudcrate::ApiError::from)?
                    } else {
                        <$resource as crudcrate::traits::CRUDResource>::get_all(&db, &condition, order_column, order_direction, offset, limit)
                            .await
                            .map_err(crudcrate::ApiError::from)?
                    }
                }
                crudcrate::SortConfig::Joined { join_field, column, direction } => {
                    // Joined sort orders the parent query by a correlated sub-query
                    // over the child column (see `get_all_joined_sorted`). The scoped
                    // branch does not yet propagate child scope into the ordering
                    // sub-query, so it falls back to the same parent-level ordering
                    // without the scoped child batch loading; the parent rows
                    // themselves remain scope-filtered via `condition`.
                    <$resource as crudcrate::traits::CRUDResource>::get_all_joined_sorted(
                        &db, &condition, join_field, column, direction.clone(), offset, limit,
                    )
                    .await
                    .map_err(crudcrate::ApiError::from)?
                }
            };
            let total_count = <$resource as crudcrate::traits::CRUDResource>::total_count(&db, &condition).await;
            let headers = crudcrate::pagination::calculate_content_range(offset, limit, total_count, <$resource as crudcrate::traits::CRUDResource>::RESOURCE_NAME_PLURAL);

            if is_scoped {
                let scoped: Vec<$scoped_list> = items.into_iter().map(|item| { let converted: $scoped_list = item.into(); converted }).collect();
                Ok((headers, axum::Json(scoped)).into_response())
            } else {
                Ok((headers, axum::Json(items)).into_response())
            }
        }


        #[utoipa::path(
            delete,
            path = "/{id}",
            // Declared explicitly (String) so utoipa's `axum_extras` does not infer the
            // param schema from `Path<CrudPrimaryKey>` — which would require the primary-key
            // type to implement `ToSchema`/`PartialSchema`. Mirrors `BatchUpdateRequest`'s
            // `#[schema(value_type = String)]`. The path value is always a stringified id.
            params(("id" = String, Path, description = "Resource identifier")),
            responses(
                (status = axum::http::StatusCode::NO_CONTENT, description = "Resource deleted successfully"),
                (status = axum::http::StatusCode::NOT_FOUND, description = "Resource not found"),
                (status = axum::http::StatusCode::INTERNAL_SERVER_ERROR, description = "Internal Server Error")
            ),
            operation_id = format!("delete_one_{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            summary = format!("Delete one {}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            description = format!("Deletes one {} by its ID.\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR, <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn delete_one_handler(
            state: axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            path: axum::extract::Path<CrudPrimaryKey>,
        ) -> Result<axum::http::StatusCode, crudcrate::ApiError> {
            if scope.is_some() {
                return Err(crudcrate::ApiError::forbidden("Write access denied in scoped context"));
            }
            <$resource as crudcrate::traits::CRUDResource>::delete(&state.0, path.0)
                .await
                .map(|_| axum::http::StatusCode::NO_CONTENT)
                .map_err(crudcrate::ApiError::from)
        }

        #[utoipa::path(
            post,
            path = "/",
            request_body = $create_model,
            responses(
                (
                    status =  axum::http::StatusCode::CREATED,
                    description = "Resource created successfully",
                    body = $response_model
                ),
                (
                    status = axum::http::StatusCode::CONFLICT,
                    description = "Duplicate record",
                    body = String
                )
            ),
            operation_id = format!("create_one_{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            summary = format!("Create one {}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            description = format!("Creates a new {}.\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR, <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn create_one_handler(
            state: axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            json: axum::Json<$create_model>,
        ) -> Result<(axum::http::StatusCode, axum::Json<$response_model>), crudcrate::ApiError> {
            if scope.is_some() {
                return Err(crudcrate::ApiError::forbidden("Write access denied in scoped context"));
            }
            <$resource as crudcrate::traits::CRUDResource>::create(&state.0, json.0)
                .await
                .map(|res| (axum::http::StatusCode::CREATED, axum::Json(res.into())))
                .map_err(crudcrate::ApiError::from)
        }

        #[utoipa::path(
            delete,
            path = "/batch",
            params(crudcrate::BatchOptions),
            // Explicit so utoipa does not infer the body from `Json<Vec<CrudPrimaryKey>>`,
            // which would require the primary-key type to implement `ToSchema`. Ids are
            // accepted as their string form.
            request_body = Vec<String>,
            responses(
                (status = axum::http::StatusCode::OK, description = "Resources deleted successfully", body = [String]),
                (status = 207, description = "Partial success - some items deleted, some failed"),
                (status = axum::http::StatusCode::BAD_REQUEST, description = "Bad request - batch size exceeded", body = String),
                (status = axum::http::StatusCode::INTERNAL_SERVER_ERROR, description = "Internal Server Error", body = String)
            ),
            operation_id = format!("delete_many_{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            summary = format!("Delete many {}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            description = format!("Deletes many {} by their IDs and returns array of deleted UUIDs.\n\nUse `?partial=true` for partial success mode (deletes valid items even if some fail).\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL, <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn delete_many_handler(
            state: axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            profile_ext: Option<axum::Extension<crudcrate::SecurityProfile>>,
            axum::extract::Query(options): axum::extract::Query<crudcrate::BatchOptions>,
            json: axum::Json<Vec<CrudPrimaryKey>>,
        ) -> axum::response::Response {
            use axum::response::IntoResponse;

            if scope.is_some() {
                return crudcrate::ApiError::forbidden("Write access denied in scoped context").into_response();
            }

            let profile = crudcrate::profile::resolve(
                profile_ext,
                <$resource as crudcrate::traits::CRUDResource>::security_profile,
            );

            let ids = json.0;

            // Check batch size limit
            if ids.len() > <$resource as crudcrate::traits::CRUDResource>::batch_limit() {
                return crudcrate::ApiError::bad_request(
                    format!("Batch delete limited to {} items. Received {} items.",
                        <$resource as crudcrate::traits::CRUDResource>::batch_limit(), ids.len())
                ).into_response();
            }

            if options.partial {
                // Partial success mode: process each item individually
                let mut result: crudcrate::BatchResult<crudcrate::PrimaryKeyType<$resource>> = crudcrate::BatchResult::new();

                for (index, id) in ids.into_iter().enumerate() {
                    match <$resource as crudcrate::traits::CRUDResource>::delete(&state.0, id).await {
                        // Use the deleted id returned by `delete` rather than the moved
                        // `id` — the PK value type may be non-`Copy` (e.g. a `String` PK).
                        Ok(deleted) => result.add_success(deleted),
                        Err(e) => result.add_failure(index, e.to_string()),
                    }
                }

                let status = if result.all_failed() {
                    axum::http::StatusCode::BAD_REQUEST
                } else if result.is_partial() {
                    axum::http::StatusCode::MULTI_STATUS
                } else {
                    axum::http::StatusCode::OK
                };

                if profile.expose_deleted_ids {
                    (status, axum::Json(result)).into_response()
                } else {
                    // expose_deleted_ids=false must also hide WHICH ids failed: each
                    // per-item not-found error embeds the (missing) UUID, so serializing
                    // `failed` verbatim would be an existence-enumeration oracle — the very
                    // side-channel the non-partial path collapses to `{deleted: count}`.
                    let secure = serde_json::json!({
                        "succeeded_count": result.succeeded.len(),
                        "failed_count": result.failed.len(),
                    });
                    (status, axum::Json(secure)).into_response()
                }
            } else {
                // All-or-nothing mode (default)
                match <$resource as crudcrate::traits::CRUDResource>::delete_many(&state.0, ids).await {
                    Ok(deleted_ids) => {
                        if profile.expose_deleted_ids {
                            (axum::http::StatusCode::OK, axum::Json(deleted_ids)).into_response()
                        } else {
                            let secure = serde_json::json!({"deleted": deleted_ids.len()});
                            (axum::http::StatusCode::OK, axum::Json(secure)).into_response()
                        }
                    }
                    Err(e) => crudcrate::ApiError::from(e).into_response()
                }
            }
        }

        #[utoipa::path(
            put,
            path = "/{id}",
            // Declared explicitly (String) so utoipa's `axum_extras` does not infer the
            // param schema from `Path<CrudPrimaryKey>` — which would require the primary-key
            // type to implement `ToSchema`/`PartialSchema`. Mirrors `BatchUpdateRequest`'s
            // `#[schema(value_type = String)]`. The path value is always a stringified id.
            params(("id" = String, Path, description = "Resource identifier")),
            request_body = $update_model,
            responses(
            (status =  axum::http::StatusCode::OK, description = "Resource updated successfully", body = $response_model),
            (status = axum::http::StatusCode::NOT_FOUND, description = "Resource not found"),
            (status =  axum::http::StatusCode::CONFLICT, description = "Duplicate record", body = String)
            ),
            operation_id = format!("update_one_{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            summary = format!("Update one {}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR),
            description = format!("Updates one {} by its ID.\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_SINGULAR, <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn update_one_handler(
            state: axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            path: axum::extract::Path<CrudPrimaryKey>,
            json: axum::Json<$update_model>,
        ) -> Result<axum::Json<$response_model>, crudcrate::ApiError> {
            if scope.is_some() {
                return Err(crudcrate::ApiError::forbidden("Write access denied in scoped context"));
            }
            <$resource as crudcrate::traits::CRUDResource>::update(&state.0, path.0, json.0)
                .await
                .map(|res| axum::Json(res.into()))
                .map_err(crudcrate::ApiError::from)
        }

        #[utoipa::path(
            post,
            path = "/batch",
            request_body = Vec<$create_model>,
            params(crudcrate::BatchOptions),
            responses(
                (status = axum::http::StatusCode::CREATED, description = "Resources created successfully", body = [$response_model]),
                (status = 207, description = "Partial success - some items created, some failed"),
                (status = axum::http::StatusCode::BAD_REQUEST, description = "Bad request - batch size exceeded or validation failed", body = String),
                (status = axum::http::StatusCode::CONFLICT, description = "Duplicate record", body = String),
                (status = axum::http::StatusCode::INTERNAL_SERVER_ERROR, description = "Internal Server Error", body = String)
            ),
            operation_id = format!("create_many_{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            summary = format!("Create many {}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            description = format!("Creates multiple {} in a batch. Limited to {} items per request.\n\nUse `?partial=true` for partial success mode (commits successful items even if some fail).\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL, <$resource as CRUDResource>::batch_limit(), <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn create_many_handler(
            state: axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            axum::extract::Query(options): axum::extract::Query<crudcrate::BatchOptions>,
            json: axum::Json<Vec<$create_model>>,
        ) -> axum::response::Response {
            use axum::response::IntoResponse;

            if scope.is_some() {
                return crudcrate::ApiError::forbidden("Write access denied in scoped context").into_response();
            }

            let data = json.0;

            // Check batch size limit
            if data.len() > <$resource as crudcrate::traits::CRUDResource>::batch_limit() {
                return crudcrate::ApiError::bad_request(
                    format!("Batch create limited to {} items. Received {} items.",
                        <$resource as crudcrate::traits::CRUDResource>::batch_limit(), data.len())
                ).into_response();
            }

            if options.partial {
                // Partial success mode: process each item individually.
                // Use create_many with a single-item batch (not the single `create`,
                // which on the derive path re-fetches via get_one and applies join
                // loading + read::one::transform). This keeps the partial response the
                // same flat shape as the all-or-nothing path below (which calls
                // create_many) and runs the same create::many hooks for both modes.
                let mut result: crudcrate::BatchResult<$response_model> = crudcrate::BatchResult::new();

                for (index, create_model) in data.into_iter().enumerate() {
                    match <$resource as crudcrate::traits::CRUDResource>::create_many(&state.0, vec![create_model]).await {
                        Ok(mut created) => match created.pop() {
                            Some(item) => result.add_success(item.into()),
                            None => result.add_failure(index, "create produced no row".to_string()),
                        },
                        Err(e) => result.add_failure(index, e.to_string()),
                    }
                }

                // Determine response status
                if result.all_failed() {
                    // All failed - return 400
                    (axum::http::StatusCode::BAD_REQUEST, axum::Json(result)).into_response()
                } else if result.is_partial() {
                    // Some succeeded, some failed - return 207
                    (axum::http::StatusCode::MULTI_STATUS, axum::Json(result)).into_response()
                } else {
                    // All succeeded - return 201
                    (axum::http::StatusCode::CREATED, axum::Json(result)).into_response()
                }
            } else {
                // All-or-nothing mode (default)
                match <$resource as crudcrate::traits::CRUDResource>::create_many(&state.0, data).await {
                    Ok(results) => {
                        let response: Vec<$response_model> = results.into_iter().map(|r| r.into()).collect();
                        (axum::http::StatusCode::CREATED, axum::Json(response)).into_response()
                    }
                    Err(e) => crudcrate::ApiError::from(e).into_response()
                }
            }
        }

        /// Wrapper type for batch update request items.
        /// Each item contains an `id` field and the update fields flattened into the same object.
        #[derive(Debug, Clone, serde::Deserialize, utoipa::ToSchema)]
        #[allow(dead_code)]
        pub struct BatchUpdateRequest {
            /// The ID of the resource to update
            #[schema(value_type = String)]
            pub id: crudcrate::PrimaryKeyType<$resource>,
            /// Additional update fields (flattened)
            #[serde(flatten)]
            pub data: $update_model,
        }

        #[utoipa::path(
            patch,
            path = "/batch",
            request_body = Vec<BatchUpdateRequest>,
            params(crudcrate::BatchOptions),
            responses(
                (status = axum::http::StatusCode::OK, description = "Resources updated successfully", body = [$response_model]),
                (status = 207, description = "Partial success - some items updated, some failed"),
                (status = axum::http::StatusCode::BAD_REQUEST, description = "Bad request - batch size exceeded or validation failed", body = String),
                (status = axum::http::StatusCode::NOT_FOUND, description = "One or more resources not found"),
                (status = axum::http::StatusCode::CONFLICT, description = "Duplicate record", body = String),
                (status = axum::http::StatusCode::INTERNAL_SERVER_ERROR, description = "Internal Server Error", body = String)
            ),
            operation_id = format!("update_many_{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            summary = format!("Update many {}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL),
            description = format!("Updates multiple {} in a batch. Limited to {} items per request.\n\nUse `?partial=true` for partial success mode (commits successful items even if some fail).\n\n{}", <$resource as CRUDResource>::RESOURCE_NAME_PLURAL, <$resource as CRUDResource>::batch_limit(), <$resource as CRUDResource>::RESOURCE_DESCRIPTION)
        )]
        pub async fn update_many_handler(
            state: axum::extract::State<sea_orm::DatabaseConnection>,
            scope: Option<axum::Extension<crudcrate::ScopeCondition>>,
            axum::extract::Query(options): axum::extract::Query<crudcrate::BatchOptions>,
            json: axum::Json<Vec<BatchUpdateRequest>>,
        ) -> axum::response::Response {
            use axum::response::IntoResponse;

            if scope.is_some() {
                return crudcrate::ApiError::forbidden("Write access denied in scoped context").into_response();
            }

            let updates: Vec<(crudcrate::PrimaryKeyType<$resource>, $update_model)> = json.0
                .into_iter()
                .map(|item| (item.id, item.data))
                .collect();

            // Check batch size limit
            if updates.len() > <$resource as crudcrate::traits::CRUDResource>::batch_limit() {
                return crudcrate::ApiError::bad_request(
                    format!("Batch update limited to {} items. Received {} items.",
                        <$resource as crudcrate::traits::CRUDResource>::batch_limit(), updates.len())
                ).into_response();
            }

            if options.partial {
                // Partial success mode: process each item individually
                let mut result: crudcrate::BatchResult<$response_model> = crudcrate::BatchResult::new();

                for (index, (id, update_model)) in updates.into_iter().enumerate() {
                    match <$resource as crudcrate::traits::CRUDResource>::update(&state.0, id, update_model).await {
                        Ok(updated) => result.add_success(updated.into()),
                        Err(e) => result.add_failure(index, e.to_string()),
                    }
                }

                // Determine response status
                if result.all_failed() {
                    // All failed - return 400
                    (axum::http::StatusCode::BAD_REQUEST, axum::Json(result)).into_response()
                } else if result.is_partial() {
                    // Some succeeded, some failed - return 207
                    (axum::http::StatusCode::MULTI_STATUS, axum::Json(result)).into_response()
                } else {
                    // All succeeded - return 200
                    (axum::http::StatusCode::OK, axum::Json(result)).into_response()
                }
            } else {
                // All-or-nothing mode (default)
                match <$resource as crudcrate::traits::CRUDResource>::update_many(&state.0, updates).await {
                    Ok(results) => {
                        let response: Vec<$response_model> = results.into_iter().map(|r| r.into()).collect();
                        (axum::http::StatusCode::OK, axum::Json(response)).into_response()
                    }
                    Err(e) => crudcrate::ApiError::from(e).into_response()
                }
            }
        }
    };
}

#[macro_export]
macro_rules! generate_crud_router {
    ($model:ty, $api_struct:ty, $create_model:ty, $update_model:ty) => {
        crudcrate::crud_handlers!($api_struct, $update_model, $create_model);

        pub fn router(db: &sea_orm::DatabaseConnection) -> utoipa_axum::router::OpenApiRouter
        where
            $api_struct: crudcrate::traits::CRUDResource,
        {
            use utoipa_axum::{router::OpenApiRouter, routes};

            tracing::info!(
                resource = <$api_struct as crudcrate::traits::CRUDResource>::RESOURCE_NAME_PLURAL,
                table = <$api_struct as crudcrate::traits::CRUDResource>::TABLE_NAME,
                batch_limit = <$api_struct as crudcrate::traits::CRUDResource>::batch_limit(),
                max_page_size = <$api_struct as crudcrate::traits::CRUDResource>::max_page_size(),
                "Mounting CRUD routes with security defaults: input_sanitization=enabled, sql_parameterization=enabled. See https://crudcrate.evanjt.com/latest/advanced/security.html"
            );

            OpenApiRouter::new()
                .routes(routes!(get_one_handler))
                .routes(routes!(get_all_handler))
                .routes(routes!(create_one_handler))
                .routes(routes!(create_many_handler))
                .routes(routes!(update_one_handler))
                .routes(routes!(update_many_handler))
                .routes(routes!(delete_one_handler))
                .routes(routes!(delete_many_handler))
                .layer(axum::extract::DefaultBodyLimit::max(
                    <$api_struct as crudcrate::traits::CRUDResource>::security_profile()
                        .max_request_body_bytes,
                ))
                .with_state(db.clone())
        }
    };
    ($model:ty, $api_struct:ty, $create_model:ty, $update_model:ty, $($extra_routes:expr),* $(,)?) => {
        crudcrate::crud_handlers!($api_struct, $update_model, $create_model);

        pub fn router(db: &sea_orm::DatabaseConnection) -> utoipa_axum::router::OpenApiRouter
        where
            $api_struct: crudcrate::traits::CRUDResource,
        {
            use utoipa_axum::{router::OpenApiRouter, routes};

            tracing::info!(
                resource = <$api_struct as crudcrate::traits::CRUDResource>::RESOURCE_NAME_PLURAL,
                table = <$api_struct as crudcrate::traits::CRUDResource>::TABLE_NAME,
                batch_limit = <$api_struct as crudcrate::traits::CRUDResource>::batch_limit(),
                max_page_size = <$api_struct as crudcrate::traits::CRUDResource>::max_page_size(),
                "Mounting CRUD routes with security defaults: input_sanitization=enabled, sql_parameterization=enabled. See https://crudcrate.evanjt.com/latest/advanced/security.html"
            );

            OpenApiRouter::new()
                .routes(routes!(get_one_handler))
                .routes(routes!(get_all_handler))
                .routes(routes!(create_one_handler))
                .routes(routes!(create_many_handler))
                .routes(routes!(update_one_handler))
                .routes(routes!(update_many_handler))
                .routes(routes!(delete_one_handler))
                .routes(routes!(delete_many_handler))
                $(
                    .routes($extra_routes)
                )*
                .layer(axum::extract::DefaultBodyLimit::max(
                    <$api_struct as crudcrate::traits::CRUDResource>::security_profile()
                        .max_request_body_bytes,
                ))
                .with_state(db.clone())
        }
    };
}