Derive Macro InsertTemplate

Source
#[derive(InsertTemplate)]
{
    // Attributes available to this derive:
    #[table]
    #[auto]
    #[debug_slow]
    #[db]
}
Expand description

InsertTemplate is a derive macro designed to automatically generate record insert functions based on sqlx. This macro creates insert methods for the struct it is applied to, returning the number of new records added. It assumes that the columns in the database correspond to the fields in the struct.

§Attributes

InsertTemplate accepts the following attributes:

  • table: 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.
  • auto: Applied to fields that should be excluded from the insert statement, typically for auto-incrementing primary keys.
  • db: Specifies the target database type (e.g., #[db("postgres")], #[db("mysql")], #[db("sqlite")]).

Additionally, when using PostgreSQL (#[db("postgres")]), the library will generate an insert_return function that returns the newly inserted record.

§Example

use sqlx_template::InsertTemplate;
use sqlx::Pool;

#[derive(InsertTemplate, sqlx::FromRow)]
#[table("users")]
#[db("postgres")]
#[debug_slow = 1000]
pub struct User {
    #[auto]
    pub id: i32,
    pub email: String,
    pub password: String,
}

// Insert a new user record
let user = User { id: 0, email: "john.doe@example.com".to_string(), password: "password123".to_string() };
let rows_affected = User::insert(&user, &pool).await?;
println!("Rows affected: {}", rows_affected);

// With PostgreSQL database
#[derive(InsertTemplate, sqlx::FromRow, Debug)]
#[table("users")]
#[db("postgres")]
pub struct UserPg {
    #[auto]
    pub id: i32,
    pub email: String,
    pub password: String,
}

let user_pg = UserPg { id: 0, email: "john.doe@example.com".to_string(), password: "password123".to_string() };
let new_user = UserPg::insert_return(&user_pg, &pool).await?;
println!("New user: {:?}", new_user);

In the example above:

  • table is set to “users”, specifying the table to insert into. (mandatory).
  • debug_slow is set to 1000 milliseconds, meaning only queries taking longer than 1 second will be logged for debugging.
  • The id field is marked with #[auto], indicating that it should be excluded from the insert statement, typically for auto-incrementing primary keys.

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