Derive Macro UpdateTemplate

Source
#[derive(UpdateTemplate)]
{
    // Attributes available to this derive:
    #[table_name]
    #[tp_update]
    #[debug_slow]
}
Expand description

UpdateTemplate is a derive macro designed to automatically generate record update functions based on sqlx. This macro creates update methods for the struct it is applied to, reducing repetitive code and improving the readability and maintainability of your code. It assumes that the columns in the database correspond to the fields in the struct.

§Attributes

UpdateTemplate accepts the following attributes:

  • table_name: Specifies the name of the table in the database (mandatory).
  • tp_update: The main configuration for generating the update function, with the following sub-attributes:
    • by: List of columns that will be the update condition, will be the function’s input (mandatory and non-empty).
    • on: List of columns that will be updated. If empty, all columns will be updated.
    • fn_name: The name of the generated function. If empty, the library will automatically generate a function name.
    • op_lock: The name of the column to apply optimistic locking (optional).
    • returning: if set = true, generated function will return the newly updated record (feature postgres only)
    • debug_slow: Configures debug logs for the executed query:
      • If 0: Only logs the executed query.
      • If > 0: Only logs the query if the execution time exceeds the configured value (in milliseconds).
      • If not configured, no debug logs will be generated.
  • debug_slow: Configures debug logs for the executed query, with priority given to the value in tp_update.

§Example

use sqlx_template::UpdateTemplate;

#[derive(UpdateTemplate, sqlx::FromRow)]
#[table_name = "users"]
#[tp_update(by = "id", op_lock = "version", fn_name = "update_user")]
#[tp_update(by = "id", on = "email, password", fn_name = "update_user_password")]
#[debug_slow = 1000]
pub struct User {
    pub id: i32,
    pub email: String,
    pub password: String,
    pub version: i32
}

In the example above:

  • table_name is set to “users”, specifying the table to update.
  • The first tp_update generates a function named update_user to update record, using id as the condition and applying optimistic locking on the version column.
  • The second tp_update generates a function named update_user_password to update both email and password columns, using id as the condition.
  • debug_slow is set to 1000 milliseconds, meaning only queries taking longer than 1 second will be logged for debugging.

§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 update methods.