multi_query

Attribute Macro multi_query 

Source
#[multi_query]
Expand description

The multi_query procedural macro transforms a series of SQL queries with named parameters into an asynchronous function that interacts with the database. It provides various features, including debugging options, and is designed to handle multiple SQL statements with no return value (void).

§Syntax

use sqlx_template::multi_query;

#[multi_query(
    sql = "UPDATE users SET active = true WHERE id = :id",
    debug = 100,
    db = "sqlite"
)]
pub async fn activate_user(id: i32) {}

§Attributes

  • sql: Specifies the SQL queries to be executed. This can be:

    • A raw SQL query as a string (e.g., sql = "BEGIN; UPDATE user SET age = :age WHERE name = :name; COMMIT;").
    • A path to a file containing the SQL queries (e.g., file = "path/to/queries.sql").
    • The queries directly as a string without the sql or file keyword.

    Constraints:

    • The queries can contain multiple SQL statements.
    • Named parameters (if exist) must be in the format :<param_name> and must correspond to the function’s parameters.
  • debug: Controls the debug behavior of the macro. It can be:

    • An integer value. If not provided, the default is no debugging.
    • 0: Prints the queries before execution.
    • Greater than 0: Prints the queries and execution time if it exceeds the specified number of milliseconds.

§Function Signature

The macro generates an asynchronous function with the following characteristics:

  • The function signature remains unchanged (e.g., pub async fn <function_name>).
  • The function parameters are preserved in their original order.
  • An additional parameter for the database connection is required.

§Return Types

The macro only supports the void return type:

  • Void:
    • : Returns nothing.

§Example Usage

use sqlx_template::multi_query;

#[multi_query(
    sql = "BEGIN; UPDATE user SET age = :age WHERE name = :name; DELETE FROM session WHERE user_name = :name; COMMIT;",
    debug = 100,
    db = "sqlite"
)]
pub async fn update_user_and_clear_sessions(name: &str, age: i32) {}

#[multi_query(
    sql = "INSERT INTO user (name, age) VALUES (:name, :age); INSERT INTO log (user_name, action) VALUES (:name, 'created')",
    debug = 0,
    db = "sqlite"
)]
pub async fn insert_user_with_log(name: &str, age: i32) {}