PreparedQuery

Struct PreparedQuery 

Source
pub struct PreparedQuery<F> { /* private fields */ }
Expand description

A prepared query builder that supports named placeholders.

PreparedQuery allows you to use named placeholders (:name) in your SQL templates instead of positional placeholders (?). It avoids self-referential lifetime issues by storing the SQL template, placeholder order, and binder function separately, and constructing the actual Query on each execution.

§Type Parameters

  • F - A binder function that binds values to placeholders. Must work with any lifetime 'q.

§Examples

use sqlx::MySqlPool;
use sqlx_named_bind::PreparedQuery;

let user_id = 42;
let name = "John Doe";

let mut query = PreparedQuery::new(
    "INSERT INTO users (user_id, name) VALUES (:user_id, :name)",
    |q, key| match key {
        ":user_id" => q.bind(user_id),
        ":name" => q.bind(name),
        _ => q,
    }
)?;

let result = query.execute(&pool).await?;
println!("Inserted {} rows", result.rows_affected());

§Using with Transactions

use sqlx::{MySqlPool, Transaction, MySql};
use sqlx_named_bind::PreparedQuery;

let mut tx: Transaction<MySql> = pool.begin().await?;

let mut query = PreparedQuery::new(
    "UPDATE users SET name = :name WHERE user_id = :user_id",
    |q, key| match key {
        ":user_id" => q.bind(vec![1, 2, 3]),
        ":name" => q.bind("Jane Doe"),
        _ => q,
    }
)?;

query.execute(&mut *tx).await?;
tx.commit().await?;

Implementations§

Source§

impl<F> PreparedQuery<F>
where F: for<'q> FnMut(Q<'q>, &str) -> Q<'q>,

Source

pub fn new<T>(template: T, binder: F) -> Result<Self>
where T: Into<String>,

Creates a new PreparedQuery from an SQL template and binder function.

The SQL template can contain named placeholders in the format :name. The binder function will be called for each placeholder in the order they appear.

§Arguments
  • template - SQL query template with named placeholders (e.g., :user_id)
  • binder - Function that binds values to placeholders based on their names
§Errors

Returns an error if the SQL template cannot be parsed (invalid regex pattern).

§Examples
use sqlx_named_bind::PreparedQuery;

let query = PreparedQuery::new(
    "SELECT * FROM users WHERE id = :id",
    |q, key| match key {
        ":id" => q.bind(42),
        _ => q,
    }
)?;
Source

pub async fn execute<'e, E>(&mut self, executor: E) -> Result<MySqlQueryResult>
where E: Executor<'e, Database = MySql>,

Executes the prepared query using the provided executor.

This method constructs a fresh Query on each call, avoiding self-referential lifetime issues. It works with any SQLx Executor implementation, including MySqlPool, Transaction, and others.

§Arguments
  • executor - Any SQLx executor (pool, transaction, etc.)
§Returns

Returns the MySQL query result containing information about affected rows, last insert ID, etc.

§Errors

Returns an error if the database query fails.

§Examples
use sqlx::MySqlPool;
use sqlx_named_bind::PreparedQuery;

let mut query = PreparedQuery::new(
    "DELETE FROM users WHERE id = :id",
    |q, key| match key {
        ":id" => q.bind(42),
        _ => q,
    }
)?;

let result = query.execute(&pool).await?;
println!("Deleted {} rows", result.rows_affected());

Auto Trait Implementations§

§

impl<F> Freeze for PreparedQuery<F>
where F: Freeze,

§

impl<F> RefUnwindSafe for PreparedQuery<F>
where F: RefUnwindSafe,

§

impl<F> Send for PreparedQuery<F>
where F: Send,

§

impl<F> Sync for PreparedQuery<F>
where F: Sync,

§

impl<F> Unpin for PreparedQuery<F>
where F: Unpin,

§

impl<F> UnwindSafe for PreparedQuery<F>
where F: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more