sql-macros-derive 0.5.0

Auto generate sql queries for CRUD on sqlx
Documentation
//! `SqlInsertManyColumns`: for callers who already have the batch built
//! column-wise (one `Vec<T>` per field) rather than row-wise — skips
//! `SqlInsertMany`'s transpose-and-clone step entirely (see
//! `model::unnest_collect_tokens`), binding each field's `Vec` straight
//! into `UNNEST(...)`. Otherwise identical to `SqlInsertMany`: same
//! `return_type`/`return_fields`, same compile-time-checked `UNNEST`
//! query, same `#[table(pg_type = "...")]` requirement for anything
//! `model::unnest_array_type` can't map to a Postgres type automatically
//! (it also tries a `Vec<T>` field's inner `T`, so the same auto-detected
//! types work here too), and the same upsert design as `SqlInsertMany`:
//! a bare `#[table(upsert)]` field gets its own `upsert_by_<field>`
//! method, a struct-level `#[table(upsert = method_name(field1, field2,
//! ...))]` gets an additional method with that exact name (no `_many`
//! suffix needed — unlike `SqlInsertMany`, this derive can never coexist
//! with `SqlInsert`/`SqlInsertMany` on the same struct, since they
//! require incompatible field types: scalar vs. `Vec<T>`). `insert_many`
//! itself is always generated, always plain — never `ON CONFLICT`,
//! regardless of how many fields are marked.
//!
//! No length check across the column `Vec`s — if they're different
//! lengths, `UNNEST` zips them, padding the short ones with `NULL` up to
//! the longest. A `NOT NULL` column turns that into a loud database
//! error; a nullable one won't, so mismatched lengths there are the
//! caller's own responsibility to get right.

use quote::quote;

use crate::model::{self, TableModel};

struct InsertManyColumnsContext<'a> {
    table_name: &'a str,
    column_names: String,
    placeholders: String,
    all: Vec<&'a model::Column>,
    return_type: Option<&'a syn::Type>,
    return_fields: Option<&'a str>,
}

fn generate_method(
    ctx: &InsertManyColumnsContext<'_>,
    method_name: &syn::Ident,
    targets: &[&model::Column],
) -> proc_macro2::TokenStream {
    let InsertManyColumnsContext {
        table_name,
        column_names,
        placeholders,
        all,
        return_type,
        return_fields,
    } = ctx;
    let bind_args = model::self_bind_ref_tokens(all);
    let first_ident = &all[0].ident;

    let query = format!("INSERT INTO {table_name} ({column_names})\nSELECT * FROM UNNEST({placeholders})");
    let query = match model::upsert_clause(all, targets) {
        Some(clause) => format!("{query}{clause}"),
        None => query,
    };
    let returning = return_fields.unwrap_or("*");

    if let Some(return_type) = return_type {
        let query = format!("{query}\nRETURNING {returning}");
        let doc = model::sql_doc(&query);
        quote! {
            #[doc = #doc]
            pub async fn #method_name<'e, E>(&self, executor: E) -> Result<Vec<#return_type>, sqlx::Error>
            where
                E: sqlx::PgExecutor<'e>,
            {
                if self.#first_ident.is_empty() {
                    return Ok(Vec::new());
                }

                let objects = sqlx::query_as!(#return_type, #query, #bind_args)
                    .fetch_all(executor)
                    .await?;
                Ok(objects)
            }
        }
    } else {
        let doc = model::sql_doc(&query);
        quote! {
            #[doc = #doc]
            pub async fn #method_name<'e, E>(&self, executor: E) -> Result<sqlx::any::AnyQueryResult, sqlx::Error>
            where
                E: sqlx::PgExecutor<'e>,
            {
                if self.#first_ident.is_empty() {
                    return Ok(Default::default());
                }

                let result = sqlx::query!(#query, #bind_args).execute(executor).await?;
                Ok(result.into())
            }
        }
    }
}

pub fn expand(model: &TableModel) -> darling::Result<proc_macro2::TokenStream> {
    let struct_name = &model.struct_name;

    let all: Vec<&model::Column> = model.columns.iter().collect();
    let placeholders = model::unnest_placeholders(&all)?;

    let ctx = InsertManyColumnsContext {
        table_name: &model.table_name,
        column_names: model.column_names(),
        placeholders,
        all,
        return_type: model.return_type.as_ref(),
        return_fields: model.return_fields.as_deref(),
    };

    let mut errors = darling::Error::accumulator();
    let mut methods = Vec::new();

    // `insert_many()` — always generated, always plain (no `ON CONFLICT`).
    let default_method_name = syn::Ident::new("insert_many", struct_name.span());
    methods.push(generate_method(&ctx, &default_method_name, &[]));

    // One `upsert_by_<field>` method per bare-`#[table(upsert)]` field.
    for column in model.upsert_targets() {
        let method_name = syn::Ident::new(&format!("upsert_by_{}", column.ident), column.ident.span());
        methods.push(generate_method(&ctx, &method_name, &[column]));
    }

    // Struct-level composite upsert, e.g. `#[table(upsert =
    // mark_done(user_id, todo_id))]` — additional method, bare name (no
    // collision possible, see module doc).
    if let Some(customs) = errors.handle(model.custom_upsert_methods()) {
        for custom in customs {
            methods.push(generate_method(&ctx, &custom.method_name, &custom.targets));
        }
    }

    errors.finish()?;

    Ok(quote! {
        impl #struct_name {
            #(#methods)*
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::quote as q;

    fn parse(tokens: proc_macro2::TokenStream) -> syn::DeriveInput {
        syn::parse2(tokens).expect("failed to parse test struct")
    }

    #[test]
    fn binds_fields_directly_with_no_transpose() {
        let input = parse(q! {
            #[table(name = "users")]
            struct CreateUserColumns {
                email: Vec<String>,
                is_active: Vec<bool>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(!tokens.contains(".clone()"));
        assert!(!tokens.contains("items"));
        assert!(tokens.contains("fn insert_many <"));
        assert!(tokens.contains(
            "INSERT INTO users (email, is_active)\\nSELECT * FROM UNNEST($1::text[],$2::bool[])"
        ));
        assert!(tokens.contains("self . email"));
        assert!(tokens.contains("self . is_active"));
    }

    #[test]
    fn no_column_length_check_generated() {
        // Deliberate: mismatched-length column `Vec`s are the caller's
        // own responsibility — `UNNEST` just pads the short one with
        // `NULL`, which a `NOT NULL` column already turns into a loud
        // database error on its own.
        let input = parse(q! {
            struct CreateUserColumns {
                email: Vec<String>,
                is_active: Vec<bool>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(!tokens.contains("Configuration"));
        assert!(!tokens.contains(". len ()"));
    }

    #[test]
    fn unrecognized_column_type_without_pg_type_is_a_spanned_error() {
        let input = parse(q! {
            struct CreateUserColumns { role: Vec<Role> }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let err = expand(&model).unwrap_err();
        assert!(err.to_string().contains("don't know the Postgres type"));
    }

    #[test]
    fn nullable_column_vec_option_detects_its_type_and_binds_with_as_cast() {
        // Full expand(), not just `unnest_array_type` in isolation —
        // same reasoning as the row-wise test in `insert_many.rs`, but
        // for the columns-already-built shape: `Vec<Option<i32>>`
        // instead of `Option<i32>`.
        let input = parse(q! {
            struct CreateUserColumns {
                email: Vec<String>,
                priority: Vec<Option<i32>>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(tokens.contains("UNNEST($1::text[],$2::int4[])"));
        assert!(tokens.contains("& self . priority as _"));
    }

    #[test]
    fn pg_type_override_detected_through_vec_wrapper() {
        let input = parse(q! {
            struct CreateUserColumns {
                #[table(as_type = "role!: Role", pg_type = "role")]
                role: Vec<Role>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(tokens.contains("UNNEST($1::role[])"));
        assert!(tokens.contains("self . role as _"));
    }

    #[test]
    fn plain_insert_many_has_no_on_conflict_clause() {
        let input = parse(q! {
            struct CreateUserColumns { email: Vec<String> }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(!tokens.contains("ON CONFLICT"));
    }

    #[test]
    fn bare_upsert_field_generates_its_own_upsert_by_method() {
        let input = parse(q! {
            struct CreateUserColumns {
                #[table(upsert)]
                email: Vec<String>,
                is_active: Vec<bool>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(tokens.contains("fn insert_many <"));
        assert!(tokens.contains("fn upsert_by_email"));
        assert!(tokens.contains("ON CONFLICT (email) DO UPDATE SET is_active=EXCLUDED.is_active"));
    }

    #[test]
    fn insert_only_field_is_excluded_from_the_upsert_set_clause() {
        let input = parse(q! {
            struct CreateUserColumns {
                #[table(upsert)]
                email: Vec<String>,
                #[table(insert_only)]
                created_by: Vec<i32>,
                is_active: Vec<bool>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(tokens.contains("ON CONFLICT (email) DO UPDATE SET is_active=EXCLUDED.is_active"));
        assert!(!tokens.contains("created_by=EXCLUDED.created_by"));
    }

    #[test]
    fn two_bare_upsert_fields_generate_two_independent_methods() {
        let input = parse(q! {
            struct AddMemberColumns {
                #[table(upsert)]
                org_id: Vec<i32>,
                #[table(upsert)]
                user_id: Vec<i32>,
                role: Vec<String>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(tokens.contains("fn upsert_by_org_id"));
        assert!(tokens.contains("ON CONFLICT (org_id) DO UPDATE SET user_id=EXCLUDED.user_id, role=EXCLUDED.role"));
        assert!(tokens.contains("fn upsert_by_user_id"));
        assert!(tokens.contains("ON CONFLICT (user_id) DO UPDATE SET org_id=EXCLUDED.org_id, role=EXCLUDED.role"));
    }

    #[test]
    fn composite_upsert_generates_an_additional_named_method() {
        let input = parse(q! {
            #[table(upsert = insert_or_update_members(org_id, user_id))]
            struct AddMemberColumns {
                org_id: Vec<i32>,
                user_id: Vec<i32>,
                role: Vec<String>,
            }
        });
        let model = TableModel::from_derive_input(&input).unwrap();
        let tokens = expand(&model).unwrap().to_string();
        assert!(tokens.contains("fn insert_many <"));
        assert!(tokens.contains("fn insert_or_update_members <"));
        assert!(tokens.contains("ON CONFLICT (org_id, user_id) DO UPDATE SET role=EXCLUDED.role"));
    }
}