Attribute Macro update

Source
#[update]
Expand description

The update procedural macro transforms an SQL UPDATE query with named parameters into an asynchronous function that interacts with the database. It provides various features, including debugging options and support for returning the number of affected rows.

§Syntax

use sqlx_template::update;

#[update(
    sql = "UPDATE users SET active = :active WHERE id = :id",
    db = "postgres",
    debug = 100
)]
pub async fn update_user_status(id: i32, active: bool) -> u64 {}

§Attributes

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

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

    Constraints:

    • The query must be a single SQL UPDATE statement.
    • 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 query before execution.
    • Greater than 0: Prints the query 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 supports the following return type based on the SQL query:

  • Single Record:

    • T: Returns a single record, which must be present. If no record is found, an error is returned.
    • Option<T>: Returns a single record if present, or None if no record is found.
  • Multiple Records:

    • Vec<T>: Returns all matching records as a vector.
  • Asynchronous Stream:

    • Stream<T>: Returns an asynchronous stream of records.
  • Paged Records:

    • Page<T>: Returns paginated results. Requires an additional parameter for pagination (e.g., impl Into<(i64, i32, bool)>). The function returns a tuple (Vec<T>, Option<i64>), where the vector contains the paginated records, and the optional value represents the total number of records if requested.
  • Scalar Value:

    • Scalar<T>: Returns a single scalar value from the query.
  • Affected Rows:

    • RowAffected: Returns the number of affected rows.
  • Void:

    • : Returns nothing.

§Example Usage

use sqlx_template::update;

type RowAffected = u64;

#[update(
    sql = "UPDATE user SET age = :age WHERE name = :name",
    db = "postgres",
    debug = 100
)]
pub async fn update_user_age(name: &str, age: i32) -> RowAffected {}