Derive Macro SelectTemplate

Source
#[derive(SelectTemplate)]
{
    // Attributes available to this derive:
    #[table_name]
    #[debug_slow]
    #[tp_select_all]
    #[tp_select_one]
    #[tp_select_page]
    #[tp_select_stream]
    #[tp_select_count]
}
Expand description

SelectTemplate is a derive macro designed to automatically generate record retrieval functions based on sqlx. This macro creates various query methods for the struct it is applied to, returning records from the database, assuming that the columns in the database correspond to the fields in the struct.

§Attributes

SelectTemplate accepts the following attributes:

  • table_name: Specifies the name of the table in the database (mandatory).
  • debug_slow: Configures debug logs for the executed query:
    • If set to 0: Only logs the executed query.
    • If set to a value greater than 0: Only logs the query if the execution time exceeds the configured value (in milliseconds).
    • If not configured, no debug logs will be generated.
  • tp_select_all: Generates a function that returns all records as a Vec<T>. It has the following sub-attributes:
    • by: List of columns for the WHERE condition, used as function input (can be empty).
    • fn_name: The name of the generated function. If empty, the library will automatically generate a function name.
    • order: Adds an ORDER BY clause based on the specified columns and order (supports asc|desc, default is asc).
    • debug_slow: Configures debug logs for the executed query:
      • If set to 0: Only logs the executed query.
      • If set to a value greater than 0: Only logs the query if the execution time exceeds the configured value (in milliseconds).
      • If not configured, no debug logs will be generated.
  • tp_select_one: Similar to tp_select_all, but returns a single record as Option<T>.
  • tp_select_stream: Similar to tp_select_all, but returns an impl Stream<Item = T>.
  • tp_select_count: Similar to tp_select_all, but returns the count of records as i64.
  • tp_select_page: Similar to tp_select_all, but accepts offset and limit as inputs, and returns a tuple of all records and the total count.

The debug_slow attribute at the struct level has priority over the value in tp_select_*.

Additionally, the library will automatically generate the following default functions when SelectTemplate is derived:

  • find_all: Returns all records in the table.
  • count_all: Counts all records in the table.
  • find_page_all: Returns all records and the total count in the table based on pagination parameters.

§Example

use sqlx_template::SelectTemplate;
use sqlx::FromRow;

#[derive(SelectTemplate, FromRow)]
#[table_name = "users"]
#[tp_select_one(by = "id", fn_name = "find_user_by_id")]
#[tp_select_all(by = "id, email", order = "id desc", fn_name = "find_all_users")]
#[tp_select_count(by = "id", fn_name = "count_users_by_id")]
#[tp_select_page(by = "id", fn_name = "find_users_page")]
#[tp_select_stream(by = "email", order = "id desc, email", fn_name = "stream_users_by_email", debug_slow = -1)]
#[debug_slow = 1000]
pub struct User {
    #[auto]
    pub id: i32,
    pub email: String,
    pub password: String,
}

// Example usage:
// Find user by id
let user = User::find_user_by_id(&pool, 1).await?;
println!("Found user: {:?}", user);

// Find all users
let users = User::find_all_users(&pool, Some("example@example.com")).await?;
println!("All users: {:?}", users);

// Count users by id
let user_count = User::count_users_by_id(&pool, Some(1)).await?;
println!("User count: {}", user_count);

// Find users with pagination
let (users, total_count) = User::find_users_page(&pool, 0, 10).await?;
println!("Users: {:?}, Total count: {}", users, total_count);

// Stream users by email
let mut user_stream = User::stream_users_by_email(&pool, "example@example.com").await?;
while let Some(user) = user_stream.next().await {
    println!("Streamed user: {:?}", user);
}

In the example above:

  • table_name is set to “users”, specifying the table to query from.
  • tp_select_one generates a function named find_user_by_id to find a user by id.
  • tp_select_all generates a function named find_all_users to find all users by id and email, ordered by id in descending order.
  • tp_select_count generates a function named count_users_by_id to count users by id.
  • tp_select_page generates a function named find_users_page to find users with pagination by id.
  • tp_select_stream generates a function named stream_users_by_email to stream users by email, ordered by id in descending order and then by email, with debug logging if the query execution time exceeds the configured value.

§Note

This macro relies on sqlx, so you need to add sqlx to your [dependencies] in Cargo.toml and properly configure the database connection before using the generated query methods.