resource-model-macro 0.1.0

Proc-macro that generates CRUD structs, sqlx repositories, migrations, and an Axum REST API from a YAML spec
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
use crate::spec::{EntitySpec, RelationSpec, Spec};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

fn map_type(ty: &str) -> TokenStream {
    match ty {
        "uuid" => quote! { uuid::Uuid },
        "string" | "text" => quote! { String },
        "int" => quote! { i32 },
        "bigint" => quote! { i64 },
        "float" => quote! { f64 },
        "bool" => quote! { bool },
        _ => unreachable!("unsupported type '{}' should have been caught by validation", ty),
    }
}

fn to_snake_case(s: &str) -> String {
    let mut result = String::new();
    for (i, c) in s.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            result.push('_');
        }
        result.extend(c.to_lowercase());
    }
    result
}

pub fn generate(spec: &Spec) -> TokenStream {
    let crud_trait = generate_crud_trait();
    let migrate_fn = generate_migrate(spec);
    let api = spec.config.api;

    let entities: Vec<TokenStream> = spec
        .entities
        .iter()
        .map(|entity| {
            let relations: Vec<&RelationSpec> = spec
                .relations
                .iter()
                .filter(|r| r.source == entity.name)
                .collect();
            generate_entity(entity, &relations, spec, api)
        })
        .collect();

    let api_module = if api {
        generate_api(spec)
    } else {
        quote! {}
    };

    quote! {
        #crud_trait
        #migrate_fn
        #(#entities)*
        #api_module
    }
}

fn map_sql_type(ty: &str) -> &'static str {
    match ty {
        "uuid" => "UUID",
        "string" | "text" => "TEXT",
        "int" => "INTEGER",
        "bigint" => "BIGINT",
        "float" => "DOUBLE PRECISION",
        "bool" => "BOOLEAN",
        _ => unreachable!(),
    }
}

fn generate_migrate(spec: &Spec) -> TokenStream {
    let drop_stmts: Vec<String> = spec
        .entities
        .iter()
        .rev()
        .map(|e| format!("DROP TABLE IF EXISTS {} CASCADE", e.table))
        .collect();

    let create_stmts: Vec<String> = spec
        .entities
        .iter()
        .map(|entity| {
            let mut cols = Vec::new();

            cols.push(format!(
                "{} {} PRIMARY KEY",
                entity.id.name,
                map_sql_type(&entity.id.ty)
            ));

            for f in &entity.fields {
                let mut col = format!("{} {}", f.name, map_sql_type(&f.ty));
                if f.required {
                    col.push_str(" NOT NULL");
                }
                if f.unique {
                    col.push_str(" UNIQUE");
                }
                if let Some(ref refs) = f.references {
                    let target = spec
                        .entities
                        .iter()
                        .find(|e| e.name == refs.entity)
                        .unwrap();
                    col.push_str(&format!(" REFERENCES {}({})", target.table, refs.field));
                }
                cols.push(col);
            }

            format!(
                "CREATE TABLE {} (\n  {}\n)",
                entity.table,
                cols.join(",\n  ")
            )
        })
        .collect();

    let all_sql: Vec<&String> = drop_stmts.iter().chain(create_stmts.iter()).collect();

    let exec_calls: Vec<TokenStream> = all_sql
        .iter()
        .map(|sql| {
            quote! {
                sqlx::query(#sql).execute(pool).await?;
            }
        })
        .collect();

    quote! {
        pub async fn migrate(pool: &sqlx::PgPool) -> Result<(), sqlx::Error> {
            #(#exec_calls)*
            Ok(())
        }
    }
}

fn generate_crud_trait() -> TokenStream {
    quote! {
        #[async_trait::async_trait]
        pub trait CrudRepository: Send + Sync {
            type Entity: Send + Sync;
            type Create: Send + Sync;
            type Update: Send + Sync;

            async fn create(&self, input: Self::Create) -> Result<Self::Entity, sqlx::Error>;
            async fn find_by_id(&self, id: uuid::Uuid) -> Result<Option<Self::Entity>, sqlx::Error>;
            async fn list(&self) -> Result<Vec<Self::Entity>, sqlx::Error>;
            async fn update(&self, id: uuid::Uuid, input: Self::Update) -> Result<Option<Self::Entity>, sqlx::Error>;
            async fn delete(&self, id: uuid::Uuid) -> Result<bool, sqlx::Error>;
        }
    }
}

fn generate_entity(
    entity: &EntitySpec,
    relations: &[&RelationSpec],
    spec: &Spec,
    api: bool,
) -> TokenStream {
    let name = format_ident!("{}", entity.name);
    let create_name = format_ident!("Create{}", entity.name);
    let update_name = format_ident!("Update{}", entity.name);
    let repo_trait_name = format_ident!("{}Repository", entity.name);
    let repo_struct_name = format_ident!("Sqlx{}Repository", entity.name);
    let table = &entity.table;

    let id_ident = format_ident!("{}", entity.id.name);
    let id_type = map_type(&entity.id.ty);

    // ── struct fields ──────────────────────────────────────────────────
    let entity_fields: Vec<TokenStream> = std::iter::once(quote! { pub #id_ident: #id_type })
        .chain(entity.fields.iter().map(|f| {
            let fname = format_ident!("{}", f.name);
            let ftype = map_type(&f.ty);
            if f.required {
                quote! { pub #fname: #ftype }
            } else {
                quote! { pub #fname: Option<#ftype> }
            }
        }))
        .collect();

    let create_fields: Vec<TokenStream> = entity
        .fields
        .iter()
        .map(|f| {
            let fname = format_ident!("{}", f.name);
            let ftype = map_type(&f.ty);
            if f.required {
                quote! { pub #fname: #ftype }
            } else {
                quote! { pub #fname: Option<#ftype> }
            }
        })
        .collect();

    let update_fields: Vec<TokenStream> = entity
        .fields
        .iter()
        .map(|f| {
            let fname = format_ident!("{}", f.name);
            let ftype = map_type(&f.ty);
            quote! { pub #fname: Option<#ftype> }
        })
        .collect();

    // ── derives (conditionally include ToSchema) ───────────────────────
    let entity_derive = if api {
        quote! { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow, utoipa::ToSchema)] }
    } else {
        quote! { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, sqlx::FromRow)] }
    };

    let create_derive = if api {
        quote! { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] }
    } else {
        quote! { #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] }
    };

    let update_derive = if api {
        quote! { #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, utoipa::ToSchema)] }
    } else {
        quote! { #[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)] }
    };

    // ── SQL strings ────────────────────────────────────────────────────
    let all_col_names: Vec<&str> = std::iter::once(entity.id.name.as_str())
        .chain(entity.fields.iter().map(|f| f.name.as_str()))
        .collect();
    let col_list = all_col_names.join(", ");
    let placeholders: String = (1..=all_col_names.len())
        .map(|i| format!("${i}"))
        .collect::<Vec<_>>()
        .join(", ");

    let insert_sql = format!(
        "INSERT INTO {table} ({col_list}) VALUES ({placeholders}) RETURNING {col_list}"
    );

    let select_one_sql = format!(
        "SELECT {col_list} FROM {table} WHERE {} = $1",
        entity.id.name
    );

    let select_all_sql = format!(
        "SELECT {col_list} FROM {table} ORDER BY {}",
        entity.id.name
    );

    let set_clauses: Vec<String> = entity
        .fields
        .iter()
        .enumerate()
        .map(|(i, f)| format!("{name} = COALESCE(${p}, {name})", name = f.name, p = i + 2))
        .collect();
    let update_sql = format!(
        "UPDATE {table} SET {} WHERE {} = $1 RETURNING {col_list}",
        set_clauses.join(", "),
        entity.id.name
    );

    let delete_sql = format!("DELETE FROM {table} WHERE {} = $1", entity.id.name);

    // ── bind chains ────────────────────────────────────────────────────
    let insert_binds: Vec<TokenStream> = entity
        .fields
        .iter()
        .map(|f| {
            let fname = format_ident!("{}", f.name);
            quote! { .bind(&input.#fname) }
        })
        .collect();

    let update_binds: Vec<TokenStream> = entity
        .fields
        .iter()
        .map(|f| {
            let fname = format_ident!("{}", f.name);
            quote! { .bind(&input.#fname) }
        })
        .collect();

    // ── relation methods ───────────────────────────────────────────────
    let (rel_trait_methods, rel_impl_methods) = generate_relation_methods(relations, spec);

    quote! {
        #entity_derive
        pub struct #name {
            #(#entity_fields,)*
        }

        #create_derive
        pub struct #create_name {
            #(#create_fields,)*
        }

        #update_derive
        pub struct #update_name {
            #(#update_fields,)*
        }

        #[async_trait::async_trait]
        pub trait #repo_trait_name:
            CrudRepository<Entity = #name, Create = #create_name, Update = #update_name>
        {
            #(#rel_trait_methods)*
        }

        #[derive(Clone)]
        pub struct #repo_struct_name {
            pool: sqlx::PgPool,
        }

        impl #repo_struct_name {
            pub fn new(pool: sqlx::PgPool) -> Self {
                Self { pool }
            }
        }

        #[async_trait::async_trait]
        impl CrudRepository for #repo_struct_name {
            type Entity = #name;
            type Create = #create_name;
            type Update = #update_name;

            async fn create(&self, input: Self::Create) -> Result<Self::Entity, sqlx::Error> {
                sqlx::query_as::<_, #name>(#insert_sql)
                    .bind(uuid::Uuid::new_v4())
                    #(#insert_binds)*
                    .fetch_one(&self.pool)
                    .await
            }

            async fn find_by_id(&self, id: uuid::Uuid) -> Result<Option<Self::Entity>, sqlx::Error> {
                sqlx::query_as::<_, #name>(#select_one_sql)
                    .bind(id)
                    .fetch_optional(&self.pool)
                    .await
            }

            async fn list(&self) -> Result<Vec<Self::Entity>, sqlx::Error> {
                sqlx::query_as::<_, #name>(#select_all_sql)
                    .fetch_all(&self.pool)
                    .await
            }

            async fn update(&self, id: uuid::Uuid, input: Self::Update) -> Result<Option<Self::Entity>, sqlx::Error> {
                sqlx::query_as::<_, #name>(#update_sql)
                    .bind(id)
                    #(#update_binds)*
                    .fetch_optional(&self.pool)
                    .await
            }

            async fn delete(&self, id: uuid::Uuid) -> Result<bool, sqlx::Error> {
                let result = sqlx::query(#delete_sql)
                    .bind(id)
                    .execute(&self.pool)
                    .await?;
                Ok(result.rows_affected() > 0)
            }
        }

        #[async_trait::async_trait]
        impl #repo_trait_name for #repo_struct_name {
            #(#rel_impl_methods)*
        }
    }
}

fn generate_relation_methods(
    relations: &[&RelationSpec],
    spec: &Spec,
) -> (Vec<TokenStream>, Vec<TokenStream>) {
    let mut trait_methods = Vec::new();
    let mut impl_methods = Vec::new();

    for rel in relations {
        let method = format_ident!("{}", rel.name);
        let target_entity = spec.entities.iter().find(|e| e.name == rel.target).unwrap();
        let target_type = format_ident!("{}", rel.target);
        let fk_param = format_ident!("{}", rel.foreign_key);

        let target_col_list: String = std::iter::once(target_entity.id.name.as_str())
            .chain(target_entity.fields.iter().map(|f| f.name.as_str()))
            .collect::<Vec<_>>()
            .join(", ");

        match rel.kind.as_str() {
            "has_many" => {
                let sql = format!(
                    "SELECT {target_col_list} FROM {} WHERE {} = $1 ORDER BY {}",
                    target_entity.table, rel.foreign_key, target_entity.id.name
                );

                trait_methods.push(quote! {
                    async fn #method(&self, #fk_param: uuid::Uuid)
                        -> Result<Vec<#target_type>, sqlx::Error>;
                });

                impl_methods.push(quote! {
                    async fn #method(&self, #fk_param: uuid::Uuid)
                        -> Result<Vec<#target_type>, sqlx::Error>
                    {
                        sqlx::query_as::<_, #target_type>(#sql)
                            .bind(#fk_param)
                            .fetch_all(&self.pool)
                            .await
                    }
                });
            }
            "belongs_to" => {
                let sql = format!(
                    "SELECT {target_col_list} FROM {} WHERE {} = $1",
                    target_entity.table, target_entity.id.name
                );

                trait_methods.push(quote! {
                    async fn #method(&self, #fk_param: uuid::Uuid)
                        -> Result<Option<#target_type>, sqlx::Error>;
                });

                impl_methods.push(quote! {
                    async fn #method(&self, #fk_param: uuid::Uuid)
                        -> Result<Option<#target_type>, sqlx::Error>
                    {
                        sqlx::query_as::<_, #target_type>(#sql)
                            .bind(#fk_param)
                            .fetch_optional(&self.pool)
                            .await
                    }
                });
            }
            _ => {}
        }
    }

    (trait_methods, impl_methods)
}

// ── API generation (when config.api = true) ────────────────────────────

fn generate_api(spec: &Spec) -> TokenStream {
    let error_type = generate_api_error();

    let mut all_handlers = Vec::new();
    let mut route_registrations = Vec::new();

    for entity in &spec.entities {
        let has_many_rels: Vec<&RelationSpec> = spec
            .relations
            .iter()
            .filter(|r| r.source == entity.name && r.kind == "has_many")
            .collect();

        let (handlers, routes) = generate_entity_api(entity, &has_many_rels, spec);
        all_handlers.push(handlers);
        route_registrations.extend(routes);
    }

    quote! {
        pub mod resource_api {
            use super::*;

            #error_type

            #(#all_handlers)*

            pub fn router() -> utoipa_axum::router::OpenApiRouter<sqlx::PgPool> {
                utoipa_axum::router::OpenApiRouter::new()
                    #(#route_registrations)*
            }
        }
    }
}

fn generate_entity_api(
    entity: &EntitySpec,
    has_many_relations: &[&RelationSpec],
    _spec: &Spec,
) -> (TokenStream, Vec<TokenStream>) {
    let name = format_ident!("{}", entity.name);
    let create_name = format_ident!("Create{}", entity.name);
    let update_name = format_ident!("Update{}", entity.name);
    let repo_struct = format_ident!("Sqlx{}Repository", entity.name);
    let table = &entity.table;
    let entity_lower = to_snake_case(&entity.name);

    let list_fn = format_ident!("list_{}", table);
    let create_fn = format_ident!("create_{}", entity_lower);
    let get_fn = format_ident!("get_{}", entity_lower);
    let update_fn = format_ident!("update_{}", entity_lower);
    let delete_fn = format_ident!("delete_{}", entity_lower);

    let api_path = format!("/api/{}", table);
    let api_path_id = format!("/api/{}/{{id}}", table);
    let tag = table.to_string();

    let list_desc = format!("List all {}", table);
    let create_desc = format!("Create {}", entity_lower);
    let get_desc = format!("Get {} by ID", entity_lower);
    let update_desc = format!("Update {}", entity_lower);
    let delete_desc = format!("Delete {}", entity_lower);

    let crud_handlers = quote! {
        #[utoipa::path(
            get,
            path = #api_path,
            responses((status = 200, description = #list_desc, body = Vec<#name>)),
            tag = #tag
        )]
        pub async fn #list_fn(
            axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
        ) -> Result<axum::Json<Vec<#name>>, ApiError> {
            let repo = #repo_struct::new(pool);
            repo.list().await.map(axum::Json).map_err(ApiError::Internal)
        }

        #[utoipa::path(
            post,
            path = #api_path,
            request_body = #create_name,
            responses((status = 201, description = #create_desc, body = #name)),
            tag = #tag
        )]
        pub async fn #create_fn(
            axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
            axum::Json(input): axum::Json<#create_name>,
        ) -> Result<(axum::http::StatusCode, axum::Json<#name>), ApiError> {
            let repo = #repo_struct::new(pool);
            repo.create(input)
                .await
                .map(|e| (axum::http::StatusCode::CREATED, axum::Json(e)))
                .map_err(ApiError::Internal)
        }

        #[utoipa::path(
            get,
            path = #api_path_id,
            params(("id" = uuid::Uuid, Path, description = "Record ID")),
            responses(
                (status = 200, description = #get_desc, body = #name),
                (status = 404, description = "Not found")
            ),
            tag = #tag
        )]
        pub async fn #get_fn(
            axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
            axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
        ) -> Result<axum::Json<#name>, ApiError> {
            let repo = #repo_struct::new(pool);
            repo.find_by_id(id)
                .await
                .map_err(ApiError::Internal)?
                .map(axum::Json)
                .ok_or(ApiError::NotFound)
        }

        #[utoipa::path(
            put,
            path = #api_path_id,
            params(("id" = uuid::Uuid, Path, description = "Record ID")),
            request_body = #update_name,
            responses(
                (status = 200, description = #update_desc, body = #name),
                (status = 404, description = "Not found")
            ),
            tag = #tag
        )]
        pub async fn #update_fn(
            axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
            axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
            axum::Json(input): axum::Json<#update_name>,
        ) -> Result<axum::Json<#name>, ApiError> {
            let repo = #repo_struct::new(pool);
            repo.update(id, input)
                .await
                .map_err(ApiError::Internal)?
                .map(axum::Json)
                .ok_or(ApiError::NotFound)
        }

        #[utoipa::path(
            delete,
            path = #api_path_id,
            params(("id" = uuid::Uuid, Path, description = "Record ID")),
            responses(
                (status = 204, description = #delete_desc),
                (status = 404, description = "Not found")
            ),
            tag = #tag
        )]
        pub async fn #delete_fn(
            axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
            axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
        ) -> Result<axum::http::StatusCode, ApiError> {
            let repo = #repo_struct::new(pool);
            if repo.delete(id).await.map_err(ApiError::Internal)? {
                Ok(axum::http::StatusCode::NO_CONTENT)
            } else {
                Err(ApiError::NotFound)
            }
        }
    };

    let mut routes = vec![
        quote! { .routes(utoipa_axum::routes!(#list_fn, #create_fn)) },
        quote! { .routes(utoipa_axum::routes!(#get_fn, #update_fn, #delete_fn)) },
    ];

    let mut rel_handlers = Vec::new();
    for rel in has_many_relations {
        let rel_fn_name = format_ident!("get_{}_{}", entity_lower, rel.name);
        let target_type = format_ident!("{}", rel.target);
        let rel_method = format_ident!("{}", rel.name);
        let rel_path = format!("/api/{}/{{id}}/{}", table, rel.name);
        let rel_desc = format!("Get {} for {}", rel.name, entity_lower);

        rel_handlers.push(quote! {
            #[utoipa::path(
                get,
                path = #rel_path,
                params(("id" = uuid::Uuid, Path, description = "Parent record ID")),
                responses((status = 200, description = #rel_desc, body = Vec<#target_type>)),
                tag = #tag
            )]
            pub async fn #rel_fn_name(
                axum::extract::State(pool): axum::extract::State<sqlx::PgPool>,
                axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
            ) -> Result<axum::Json<Vec<#target_type>>, ApiError> {
                let repo = #repo_struct::new(pool);
                repo.#rel_method(id).await.map(axum::Json).map_err(ApiError::Internal)
            }
        });

        routes.push(quote! { .routes(utoipa_axum::routes!(#rel_fn_name)) });
    }

    let all = quote! {
        #crud_handlers
        #(#rel_handlers)*
    };

    (all, routes)
}

fn generate_api_error() -> TokenStream {
    quote! {
        pub enum ApiError {
            NotFound,
            Internal(sqlx::Error),
        }

        impl axum::response::IntoResponse for ApiError {
            fn into_response(self) -> axum::response::Response {
                match self {
                    Self::NotFound => (
                        axum::http::StatusCode::NOT_FOUND,
                        axum::Json(serde_json::json!({"error": "not found"})),
                    )
                        .into_response(),
                    Self::Internal(e) => {
                        eprintln!("database error: {e}");
                        (
                            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
                            axum::Json(serde_json::json!({"error": "internal server error"})),
                        )
                            .into_response()
                    }
                }
            }
        }
    }
}