#[delete]
Expand description
The delete
procedural macro transforms an SQL DELETE
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
or no return value (void
).
§Syntax
ⓘ
use sqlx_template::delete;
#[delete(
sql = "DELETE FROM users WHERE id = :id",
debug = 100,
db = "sqlite"
)]
pub async fn remove_user(id: i32) -> u64 {}
§Attributes
-
sql
: Specifies the SQLDELETE
query to be executed. This can be:- A raw SQL query as a string (e.g.,
sql = "DELETE FROM user 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
orfile
keyword.
Constraints:
- The query must be a single SQL
DELETE
statement. - Named parameters (if exist) must be in the format
:<param_name>
and must correspond to the function’s parameters.
- A raw SQL query as a string (e.g.,
-
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, orNone
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::delete;
type RowAffected = u64;
#[delete(
sql = "DELETE FROM user WHERE name = :name",
debug = 100,
db = "sqlite"
)]
pub async fn delete_user(name: &str) -> RowAffected {}
#[delete(
sql = "DELETE FROM user WHERE name = :name",
debug = 0,
db = "sqlite"
)]
pub async fn delete_user_no_return(name: &str) {}