Skip to main content

cruxmont_embedded_pg_test_macro/
lib.rs

1extern crate proc_macro;
2use proc_macro::TokenStream;
3use proc_macro2::Span;
4use quote::quote;
5use syn::{ItemFn, LitStr, parse_macro_input};
6use uuid::Uuid;
7
8#[proc_macro_attribute]
9pub fn embedded_pg_test(_attr: TokenStream, item: TokenStream) -> TokenStream {
10    let input_fn = parse_macro_input!(item as ItemFn);
11
12    // Get the function name
13    let func_name = &input_fn.sig.ident;
14    let stmts = &input_fn.block.stmts; // Vec<Stmt>
15
16    let db_tag = Uuid::new_v4().simple().to_string(); // "c0a801e6be7d470691ed7d087b4e1bfd"
17    let env_name = format!("DATABASE_URL_{}", db_tag); // "DATABASE_URL_c0a801e6be7d…"
18    let env_lit = LitStr::new(&env_name, Span::call_site()); // `syn::LitStr` → "DATABASE_URL_c0…"
19    let db_name = LitStr::new(&db_tag, Span::call_site());
20
21    let expanded = quote! {
22        #[test]
23        fn #func_name() {
24            use sqlx::Executor;
25            use tokio::runtime::Builder;
26
27            // create an embedded postgres DB
28            let settings = postgresql_embedded::Settings {
29                version: postgresql_embedded::VersionReq::parse("=16.4.0").expect("parse postgres version"),
30                ..Default::default()
31            };
32            let mut db = postgresql_embedded::PostgreSQL::new(settings);
33            let db_handle = std::sync::Arc::new(std::sync::Mutex::new(db));
34            let db_handle_ref = db_handle.clone();
35
36            let rt = Builder::new_current_thread()
37                .enable_all()
38                .build()
39                .expect("create Tokio runtime");
40
41            // create the DB in the core DB
42            rt.block_on(async move {
43                let mut db_ref = db_handle_ref.lock().expect("Lock the Mutex");
44                db_ref.setup().await.expect("setup DB");
45                db_ref.start().await.expect("start DB");
46                db_ref.create_database(#db_name).await.expect("start DB");
47                let url: String = db_ref.settings().url(#db_name);
48
49                // set the environment variables for the DB
50                unsafe {
51                    std::env::set_var(#env_lit, url);
52                    std::env::set_var("DB_MAX_CONNECTIONS", "1");
53                }
54            });
55
56            let test_result = rt.block_on(async {
57                // define the DB pool which is std::sync::LazyLock<sqlx::Pool<sqlx::Postgres>> inner = Pool<sqlx::Postgres>
58                cruxmont::pg_pool::define_pg_pool!(SQLX_POSTGRES_TEST_POOL, #env_lit, "DB_MAX_CONNECTIONS");
59
60                struct TestDbHandle;
61
62                impl cruxmont::dal::connections::sqlx_postgres::YieldPostGresPool for TestDbHandle {
63                    fn yield_pool() -> &'static sqlx::Pool<sqlx::Postgres> {
64                        &*SQLX_POSTGRES_TEST_POOL
65                    }
66                }
67
68                // execute the testing code
69                let handle = tokio::spawn(async {
70                    #(#stmts)*
71                });
72                // handle.await   // → Result<Result<(), _>, JoinError>
73                let result = handle.await; // Await the handle
74                SQLX_POSTGRES_TEST_POOL.close().await; // Close the pool after awaiting
75                result // Return the handle's result
76            });
77
78            // rt.block_on(async move {
79            //     let mut db_ref = db_handle.lock().expect("Lock the Mutex");
80            //     db_ref.drop_database(#db_name).await.expect("drop DB");
81            //     db_ref.stop().await
82            // });
83            test_result.unwrap();
84        }
85    };
86    TokenStream::from(expanded)
87}