#[derive(DeleteTemplate)]
{
// Attributes available to this derive:
#[table_name]
#[tp_delete]
#[debug_slow]
}
Expand description
DeleteTemplate is a derive macro designed to automatically generate record deletion functions
based on sqlx. This macro creates delete methods for the struct it is applied to, returning
the number of records deleted.
It assumes that the columns in the database correspond to the fields in the struct.
§Attributes
DeleteTemplate 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.
- If set to
tp_delete: The main configuration for generating the delete function, with the following sub-attributes:by: List of columns that will be the delete condition, will be the function’s input (mandatory and non-empty).fn_name: The name of the generated function. If empty, the library will automatically generate a function name.returning: If set to true, the generated function will return the deleted record (only enabled with thepostgresfeature).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.
- If set to
The debug_slow attribute at the struct level has priority over the value in tp_delete.
§Example
use sqlx_template::DeleteTemplate;
#[derive(DeleteTemplate, sqlx::FromRow)]
#[table_name = "users"]
#[tp_delete(by = "id", fn_name = "delete_user", returning = true)]
#[tp_delete(by = "id")]
pub struct User {
pub id: i32,
pub email: String,
pub password: String,
}
// Delete a user record by id
let user = User { id: 1, email: "john.doe@example.com".to_string(), password: "password123".to_string() };
let rows_affected = User::delete_by_id(&user.id, &pool).await?;
println!("Rows affected: {}", rows_affected);
// If the `postgres` feature is enabled and `returning` is set to true
#[cfg(feature = "postgres")]
let deleted_user = User::delete_user(&user.id, &pool).await?;
println!("Deleted user: {:?}", deleted_user);In the example above:
table_nameis set to “users”, specifying the table to delete from.- The first
tp_deletegenerates a function nameddelete_userto delete a record based on theidcolumn and return the deleted record (with thepostgresfeature enabled). debug_slowis 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 delete methods.