Skip to main content

Query

Struct Query 

Source
pub struct Query<M: Model> { /* private fields */ }
Expand description

A query on one model’s table. Start it with Model::query() or Query::table(), then finish it with a terminal method such as get, first or insert.

Implementations§

Source§

impl<M: Model> Query<M>

Source

pub fn table() -> Self

Starts a query on the model’s table.

Source

pub fn where_eq(self, column: &str, value: impl Into<Value>) -> Self

Adds column = value. A NULL value becomes IS NULL, as in Laravel.

Source

pub fn or_where_eq(self, column: &str, value: impl Into<Value>) -> Self

Adds OR column = value.

Source

pub fn where_op( self, column: &str, op: Operator, value: impl Into<Value>, ) -> Self

Adds column <op> value. != with a NULL value becomes IS NOT NULL.

Source

pub fn or_where_op( self, column: &str, op: Operator, value: impl Into<Value>, ) -> Self

Adds OR column <op> value. != with a NULL value becomes IS NOT NULL.

Source

pub fn where_in<V: Into<Value>>( self, column: &str, values: impl IntoIterator<Item = V>, ) -> Self

Adds column IN (values). An empty list matches no rows, as in Laravel.

Source

pub fn or_where_in<V: Into<Value>>( self, column: &str, values: impl IntoIterator<Item = V>, ) -> Self

Adds OR column IN (values). An empty list matches no rows.

Source

pub fn where_null(self, column: &str) -> Self

Adds column IS NULL.

Source

pub fn or_where_null(self, column: &str) -> Self

Adds OR column IS NULL.

Source

pub fn where_not_null(self, column: &str) -> Self

Adds column IS NOT NULL.

Source

pub fn or_where_not_null(self, column: &str) -> Self

Adds OR column IS NOT NULL.

Source

pub fn where_group(self, f: impl FnOnce(Self) -> Self) -> Self

Adds a group of conditions joined by AND, in parentheses. The closure gets an empty query and adds its conditions to it, as Laravel’s where(fn) does:

ⓘ
.where_group(|q| q.where_eq("title", "a").or_where_eq("title", "b"))

Only where conditions are kept from the group; order_by, limit and the other settings are ignored. An empty group adds nothing.

Source

pub fn or_where_group(self, f: impl FnOnce(Self) -> Self) -> Self

Adds a group of conditions joined by OR, in parentheses. See where_group.

Source

pub fn order_by(self, column: &str, direction: Direction) -> Self

Adds a sort. Later calls sort within the earlier ones.

Source

pub fn select(self, columns: &[&str]) -> Self

Chooses the columns that get and first select. Without it, all columns are selected.

Source

pub fn limit(self, limit: u64) -> Self

Returns at most limit rows.

Source

pub fn offset(self, offset: u64) -> Self

Skips the first offset rows.

Source

pub fn for_update(self) -> Self

Locks the matching rows (SELECT ... FOR UPDATE). It applies to get, first, find, count and exists. In a transaction the lock lasts until it ends. On the pool it lasts only for the statement, in autocommit, as Laravel’s lockForUpdate() does. SQLite has no row locks, so the clause is left out there, as Laravel’s SQLite grammar does.

Source

pub async fn get<'a>(self, db: impl Executor<'a>) -> Result<Vec<M>, Error>
where M: DriverRows,

Returns every row that matches.

Source

pub async fn get_as<'a, T>(self, db: impl Executor<'a>) -> Result<Vec<T>, Error>
where T: DriverRows + Send + Unpin,

Returns every row that matches, decoded as T instead of the model. Use it with select to read some columns into a tuple or a struct that implements FromRow. The clauses are the same as get.

ⓘ
let titles = Post::query()
    .select(&["id", "title"])
    .get_as::<(i64, String)>(&db)
    .await?;
Source

pub async fn first_as<'a, T>( self, db: impl Executor<'a>, ) -> Result<Option<T>, Error>
where T: DriverRows + Send + Unpin,

Returns the first row decoded as T, in the order given by order_by. See get_as.

Source

pub async fn first<'a>(self, db: impl Executor<'a>) -> Result<Option<M>, Error>
where M: DriverRows,

Returns the first row in the order given by order_by. Without order_by there is no order, as with Laravel’s first, so call order_by when the row matters.

Source

pub async fn first_or_fail<'a>(self, db: impl Executor<'a>) -> Result<M, Error>
where M: DriverRows,

Returns the first row, or an error when none matches.

Source

pub async fn find<'a>( self, db: impl Executor<'a>, id: impl Into<Value>, ) -> Result<Option<M>, Error>
where M: DriverRows,

Returns the row with the given primary key, or None when there is none.

Source

pub async fn find_or_fail<'a>( self, db: impl Executor<'a>, id: impl Into<Value>, ) -> Result<M, Error>
where M: DriverRows,

Returns the row with the given primary key, or an error when there is none.

Source

pub async fn count<'a>(self, db: impl Executor<'a>) -> Result<i64, Error>

Counts the rows that match.

Source

pub async fn exists<'a>(self, db: impl Executor<'a>) -> Result<bool, Error>

Returns whether any row matches.

Source

pub async fn insert<'a>( self, db: impl Executor<'a>, values: &[(&str, Value)], ) -> Result<u64, Error>

Inserts one row and returns its auto-increment id. The columns must be in FILLABLE. On PostgreSQL the id comes from RETURNING on the primary key, so the primary key must be an integer column.

Source

pub async fn replace<'a>( self, db: impl Executor<'a>, values: &[(&str, Value)], ) -> Result<u64, Error>

Replaces the row that has the same unique key or primary key as values, or inserts the row when none has. Returns the rows affected, as the database reports them: MySQL gives 2 when a row was replaced, since it deletes the old row and inserts the new one, and SQLite gives 1.

This is Diesel’s replace_into, which issues REPLACE INTO on MySQL and SQLite. It is not Laravel’s upsert, which is INSERT ... ON DUPLICATE KEY UPDATE or ON CONFLICT. The old row is deleted, so its auto-increment id changes and columns not in values take their defaults. The columns must be in FILLABLE.

PostgreSQL has no REPLACE, and INSERT ... ON CONFLICT would keep the old row. So on PostgreSQL this returns Error::Unsupported.

Source

pub async fn update<'a>( self, db: impl Executor<'a>, values: &[(&str, Value)], ) -> Result<u64, Error>

Sets the columns on every matching row and returns how many rows matched. The columns must be in FILLABLE. Order and limit are ignored.

Source

pub async fn delete<'a>(self, db: impl Executor<'a>) -> Result<u64, Error>

Deletes every matching row and returns how many rows were deleted. Order and limit are ignored.

Auto Trait Implementations§

§

impl<M> !RefUnwindSafe for Query<M>

§

impl<M> !UnwindSafe for Query<M>

§

impl<M> Forget for Query<M>

§

impl<M> Freeze for Query<M>
where PhantomData<M>: Freeze,

§

impl<M> Move for Query<M>

§

impl<M> Send for Query<M>
where PhantomData<M>: Send,

§

impl<M> Sync for Query<M>
where PhantomData<M>: Sync,

§

impl<M> Unpin for Query<M>
where PhantomData<M>: Unpin,

§

impl<M> UnsafeUnpin for Query<M>

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

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

fn try_from(value: U) -> Result<T, !>

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