|
| 1 | +//! Reusable macros to generate common SQLx queries without boilerplate. |
| 2 | +//! |
| 3 | +//! These macros leverage `sqlx::QueryBuilder` so we don't need fully literal SQL |
| 4 | +//! at compile-time (which `query!`/`query_as!` require). |
| 5 | +
|
| 6 | +/// Define an async function that fetches a row by its `id` using `sqlx::QueryBuilder`. |
| 7 | +/// |
| 8 | +/// Parameters: |
| 9 | +/// - `fn_name`: function name to generate |
| 10 | +/// - `table_lit`: table name as a string literal, e.g. "score_metadata" |
| 11 | +/// - `RowType`: fully-qualified row type path |
| 12 | +/// - `columns_lit`: columns to select as a string literal |
| 13 | +/// |
| 14 | +/// Example: |
| 15 | +/// define_by_id!(find_by_id, "score_metadata", crate::models::score_metadata::types::ScoreMetadataRow, |
| 16 | +/// "id, skin, pause_count, started_at, ended_at, time_paused, score, accuracy, max_combo, perfect, count_300, count_100, count_50, count_miss, count_katu, count_geki, created_at"); |
| 17 | +#[macro_export] |
| 18 | +macro_rules! define_by_id { |
| 19 | + ( $fn_name:ident, $table_lit:literal, $RowType:path, $columns_lit:literal ) => { |
| 20 | + pub async fn $fn_name( |
| 21 | + pool: &sqlx::PgPool, |
| 22 | + id: i32, |
| 23 | + ) -> Result<Option<$RowType>, sqlx::Error> { |
| 24 | + let mut builder = sqlx::QueryBuilder::<sqlx::Postgres>::new("SELECT "); |
| 25 | + builder.push($columns_lit); |
| 26 | + builder.push(" FROM "); |
| 27 | + builder.push($table_lit); |
| 28 | + builder.push(" WHERE id = "); |
| 29 | + builder.push_bind(id); |
| 30 | + builder |
| 31 | + .build_query_as::<$RowType>() |
| 32 | + .fetch_optional(pool) |
| 33 | + .await |
| 34 | + } |
| 35 | + }; |
| 36 | +} |
| 37 | + |
| 38 | +/// Define an async INSERT function that returns the auto-generated `id` (i32). |
| 39 | +/// |
| 40 | +/// Parameters: |
| 41 | +/// - `fn_name`: function name to generate |
| 42 | +/// - `table_lit`: table name as a string literal |
| 43 | +/// - `RowType`: fully-qualified row type path of the input struct |
| 44 | +/// - field list: one or more identifiers which are taken from `row.field` in order |
| 45 | +/// |
| 46 | +/// Example: |
| 47 | +/// define_insert_returning_id!(insert, "score_metadata", crate::models::score_metadata::types::ScoreMetadataRow, |
| 48 | +/// skin, pause_count, started_at, ended_at, time_paused, score, accuracy, max_combo, perfect, count_300, count_100, count_50, count_miss, count_katu, count_geki); |
| 49 | +#[macro_export] |
| 50 | +macro_rules! define_insert_returning_id { |
| 51 | + ( $fn_name:ident, $table_lit:literal, $RowType:path, $($field:ident),+ $(,)? ) => { |
| 52 | + pub async fn $fn_name( |
| 53 | + pool: &sqlx::PgPool, |
| 54 | + row: $RowType, |
| 55 | + ) -> Result<i32, sqlx::Error> { |
| 56 | + let mut builder = sqlx::QueryBuilder::<sqlx::Postgres>::new("INSERT INTO "); |
| 57 | + builder.push($table_lit); |
| 58 | + builder.push(" ("); |
| 59 | + builder.push( stringify!($($field),+) ); |
| 60 | + builder.push(", created_at) VALUES ("); |
| 61 | + let mut separated = builder.separated(", "); |
| 62 | + $( separated.push_bind(row.$field); )+ |
| 63 | + separated.push("NOW()"); |
| 64 | + // let `separated` drop naturally; explicit drop is unnecessary |
| 65 | + builder.push(") RETURNING id"); |
| 66 | + |
| 67 | + let rec = builder.build().fetch_one(pool).await?; |
| 68 | + use sqlx::Row; |
| 69 | + let id: i32 = rec.try_get("id")?; |
| 70 | + Ok(id) |
| 71 | + } |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +// Internal helper to generate a placeholder list like "$1, $2, $3" |
| 76 | +// Note: sqlx::query! requires a fully literal SQL string. Building a dynamic |
| 77 | +// placeholder list within concat! isn't straightforward in macro_rules without |
| 78 | +// counting. Therefore, for portability across many Rust versions and to keep |
| 79 | +// things simple, prefer the `define_insert_returning_row!` variant where the |
| 80 | +// caller provides the RETURNING columns list. For returning id, we will emit a |
| 81 | +// concrete, explicit SQL through another macro. |
| 82 | + |
| 83 | +/// Define an async INSERT function that returns the full row using `QueryBuilder`. |
| 84 | +/// The caller provides the explicit RETURNING columns list literal. |
| 85 | +/// |
| 86 | +/// Parameters: |
| 87 | +/// - `fn_name`: function name to generate |
| 88 | +/// - `table_lit`: table name as a string literal |
| 89 | +/// - `RowType`: fully-qualified row type path to be returned |
| 90 | +/// - field list: one or more identifiers which are taken from `row.field` in order |
| 91 | +/// - `;` then `returning_columns_lit`: string literal of columns to return |
| 92 | +/// |
| 93 | +/// Example: |
| 94 | +/// define_insert_returning_row!(insert, "score", crate::models::score::types::ScoreRow, |
| 95 | +/// user_id, beatmap_id, score_metadata_id, replay_id, rate, hwid, mods, hash, rank, status; |
| 96 | +/// "id, user_id, beatmap_id, score_metadata_id, replay_id, rate, hwid, mods, hash, rank, status, created_at"); |
| 97 | +#[macro_export] |
| 98 | +macro_rules! define_insert_returning_row { |
| 99 | + ( $fn_name:ident, $table_lit:literal, $RowType:path, $($field:ident),+ ; $returning_columns_lit:literal ) => { |
| 100 | + pub async fn $fn_name( |
| 101 | + pool: &sqlx::PgPool, |
| 102 | + row: $RowType, |
| 103 | + ) -> Result<$RowType, sqlx::Error> { |
| 104 | + let mut builder = sqlx::QueryBuilder::<sqlx::Postgres>::new("INSERT INTO "); |
| 105 | + builder.push($table_lit); |
| 106 | + builder.push(" ("); |
| 107 | + builder.push( stringify!($($field),+) ); |
| 108 | + builder.push(", created_at) VALUES ("); |
| 109 | + let mut separated = builder.separated(", "); |
| 110 | + $( separated.push_bind(row.$field); )+ |
| 111 | + separated.push("NOW()"); |
| 112 | + // let `separated` drop naturally; explicit drop is unnecessary |
| 113 | + builder.push(") RETURNING "); |
| 114 | + builder.push($returning_columns_lit); |
| 115 | + |
| 116 | + builder |
| 117 | + .build_query_as::<$RowType>() |
| 118 | + .fetch_one(pool) |
| 119 | + .await |
| 120 | + } |
| 121 | + }; |
| 122 | +} |
0 commit comments