Skip to main content

Query

Struct Query 

Source
pub struct Query<'a> { /* private fields */ }
Expand description

A query object with bind parameters.

Implementations§

Source§

impl<'a> Query<'a>

Source

pub const MAX_PARAMETERS: usize = 2100

The largest number of parameters SQL Server accepts in one statement.

A statement carrying more is rejected by the server with “The incoming request has too many parameters. The server supports a maximum of 2100 parameters.” — which arrives only after the whole batch has been sent.

This matters most for an IN list or a multi-row INSERT, where the count comes from the length of a collection rather than from the SQL text: the limit is reached by data volume, at run time, on a batch that may be larger than any that was tested. Split such a batch into chunks of at most MAX_PARAMETERS / parameters_per_row items.

§Example
// A three-column INSERT: three parameters per row.
let rows_per_statement = Query::MAX_PARAMETERS / 3;
assert_eq!(rows_per_statement, 700);
Source

pub fn new(sql: impl Into<Cow<'a, str>>) -> Self

Construct a new query object with the given SQL. If the SQL is parameterized, the given number of parameters must be bound to the object before executing.

The sql can define the parameter placement by annotating them with @PN, where N is the index of the parameter, starting from 1.

Source

pub fn bind(&mut self, param: impl IntoSql<'a> + 'a)

Bind a new parameter to the query. Must be called exactly as many times as there are parameters in the given SQL. Otherwise the query will fail on execution.

Source

pub fn bind_iter( &mut self, params: impl IntoIterator<Item = impl IntoSql<'a> + 'a>, )

Bind every item of an iterator, in order.

Equivalent to calling bind once per item. Pairs with placeholders to build an IN list, where the number of parameters is only known at runtime.

§Example
let ids = vec![1i32, 2, 3];

let sql = format!(
    "SELECT name FROM users WHERE id IN ({})",
    Query::placeholders(1, ids.len()),
);

let mut query = Query::new(sql);
query.bind_iter(ids);

assert_eq!(query.param_count(), 3);
Source

pub fn param_count(&self) -> usize

How many parameters have been bound so far.

Useful for checking against MAX_PARAMETERS before executing a statement whose parameter count is decided at runtime.

Source

pub fn placeholders(first: usize, count: usize) -> String

Build a @P1, @P2, … placeholder list for count parameters, numbered from first.

SQL Server has no array parameter, so an IN list must name one placeholder per value, and IN (@P1) bound to a comma-separated string matches nothing rather than failing. Generating the list is the only way to write such a query, and this does it without a format loop at every call site.

first is 1-based, matching the @P1 numbering Query::new documents.

§Example
assert_eq!(Query::placeholders(1, 3), "@P1, @P2, @P3");

// Continuing after parameters that are already bound.
assert_eq!(Query::placeholders(4, 2), "@P4, @P5");

A count of zero yields an empty string. IN () is a syntax error, so a caller with nothing to match on should skip the query rather than build one:

let ids: Vec<i32> = Vec::new();
assert!(Query::placeholders(1, ids.len()).is_empty());
Source

pub async fn execute<S>(self, client: &mut Client<S>) -> Result<ExecuteResult>
where S: AsyncRead + AsyncWrite + Unpin + Send,

Executes SQL statements in the SQL Server, returning the number rows affected. Useful for INSERT, UPDATE and DELETE statements. See Client#execute for a simpler API if the parameters are statically known.

§Example
let mut query = Query::new("INSERT INTO ##Test (id) VALUES (@P1), (@P2), (@P3)");

query.bind("foo");
query.bind(2i32);
query.bind(String::from("bar"));

let results = query.execute(&mut client).await?;
Source

pub async fn query<'b, S>( self, client: &'b mut Client<S>, ) -> Result<QueryStream<'b>>
where S: AsyncRead + AsyncWrite + Unpin + Send,

Executes SQL statements in the SQL Server, returning resulting rows. Useful for SELECT statements. See Client#query for a simpler API if the parameters are statically known.

§Example
let mut query = Query::new("SELECT @P1, @P2, @P3");

query.bind(1i32);
query.bind(2i32);
query.bind(3i32);

let stream = query.query(&mut client).await?;

Trait Implementations§

Source§

impl<'a> Debug for Query<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for Query<'a>

§

impl<'a> RefUnwindSafe for Query<'a>

§

impl<'a> Send for Query<'a>

§

impl<'a> Sync for Query<'a>

§

impl<'a> Unpin for Query<'a>

§

impl<'a> UnsafeUnpin for Query<'a>

§

impl<'a> UnwindSafe for Query<'a>

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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