Skip to main content

Select

Struct Select 

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

A SELECT query builder.

Provides a fluent API for building SELECT queries with type-safe column references and conditions.

Implementations§

Source§

impl<M: Model> Select<M>

Source

pub fn new() -> Self

Create a new SELECT query for the model’s table.

Source

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

Select specific columns.

Source

pub fn filter(self, expr: Expr) -> Self

Add a WHERE condition.

Source

pub fn or_filter(self, expr: Expr) -> Self

Add an OR WHERE condition.

Source

pub fn order_by(self, order: OrderBy) -> Self

Add ORDER BY clause.

Source

pub fn join(self, join: Join) -> Self

Add a JOIN clause.

Source

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

Set LIMIT.

Source

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

Set OFFSET.

Source

pub fn group_by(self, cols: &[&str]) -> Self

Add GROUP BY columns.

Source

pub fn having(self, expr: Expr) -> Self

Add HAVING condition.

Source

pub fn distinct(self) -> Self

Make this a DISTINCT query.

Source

pub fn for_update(self) -> Self

Add FOR UPDATE lock.

Source

pub fn eager(self, loader: EagerLoader<M>) -> Self

Configure eager loading for relationships.

§Example
let heroes = select!(Hero)
    .eager(EagerLoader::new().include("team"))
    .all_eager(cx, &conn)
    .await?;
Source

pub async fn all_eager<C: Connection>( self, cx: &Cx, conn: &C, ) -> Outcome<Vec<M>, Error>

Execute the query with eager loading and return hydrated models.

This method fetches the parent models along with their eagerly loaded relationships in a single query using JOINs. Results are deduplicated by primary key to handle one-to-many JOINs.

§Note

Currently, this method parses parent models from aliased columns and deduplicates by primary key. Full hydration of Related<T> and RelatedMany<T> fields requires macro support and is tracked separately. The JOIN query is still valuable as it:

  • Fetches all data in a single query (avoiding N+1)
  • Returns related data that can be accessed via row.subset_by_prefix()
§Example
let heroes = select!(Hero)
    .eager(EagerLoader::new().include("team"))
    .all_eager(cx, &conn)
    .await?;
Source

pub fn build(&self) -> (String, Vec<Value>)

Build the SQL query and parameters.

Source

pub fn into_exists(self) -> Expr

Convert this SELECT query to an EXISTS expression.

Creates an Expr::Exists that can be used in WHERE clauses of other queries. For performance, the SELECT is automatically optimized to SELECT 1 when generating the EXISTS subquery.

§Example
// Find customers who have at least one order
let has_orders = Select::<Order>::new()
    .filter(Expr::raw("orders.customer_id = customers.id"))
    .into_exists();

let customers = Select::<Customer>::new()
    .filter(has_orders)
    .all(cx, &conn)
    .await?;

// Generates: SELECT * FROM customers WHERE EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.id)
Source

pub fn into_not_exists(self) -> Expr

Convert this SELECT query to a NOT EXISTS expression.

Creates an Expr::Exists (negated) that can be used in WHERE clauses. For performance, the SELECT is automatically optimized to SELECT 1.

§Example
// Find customers with no orders
let has_no_orders = Select::<Order>::new()
    .filter(Expr::raw("orders.customer_id = customers.id"))
    .into_not_exists();

let customers = Select::<Customer>::new()
    .filter(has_no_orders)
    .all(cx, &conn)
    .await?;

// Generates: SELECT * FROM customers WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = customers.id)
Source

pub fn into_lateral_join( self, alias: impl Into<String>, join_type: JoinType, on: Expr, ) -> Join

Convert this SELECT into a LATERAL JOIN.

Creates a Join with lateral: true that can be added to another query. The subquery can reference columns from the outer query.

Supported by PostgreSQL (9.3+) and MySQL (8.0.14+). Not supported by SQLite.

§Arguments
  • alias - Required alias for the lateral subquery
  • join_type - The join type (typically Left or Inner)
  • on - ON condition (use Expr::raw("TRUE") for implicit TRUE)
§Example
// Get top 3 recent orders per customer
let recent_orders = Select::<Order>::new()
    .filter(Expr::raw("orders.customer_id = customers.id"))
    .order_by(OrderBy::desc("date"))
    .limit(3)
    .into_lateral_join("recent_orders", JoinType::Left, Expr::raw("TRUE"));

let query = Select::<Customer>::new().join(recent_orders);
Source

pub async fn all<C: Connection>( self, cx: &Cx, conn: &C, ) -> Outcome<Vec<M>, Error>

Execute the query and return all matching rows as models.

Source

pub async fn first<C: Connection>( self, cx: &Cx, conn: &C, ) -> Outcome<Option<M>, Error>

Execute the query and return the first matching row.

Source

pub async fn one<C: Connection>(self, cx: &Cx, conn: &C) -> Outcome<M, Error>

Execute the query and return exactly one row, or error.

Source

pub async fn count<C: Connection>( self, cx: &Cx, conn: &C, ) -> Outcome<u64, Error>

Execute the query and return the count of matching rows.

Source

pub async fn exists<C: Connection>( self, cx: &Cx, conn: &C, ) -> Outcome<bool, Error>

Check if any rows match the query.

Trait Implementations§

Source§

impl<M: Clone + Model> Clone for Select<M>

Source§

fn clone(&self) -> Select<M>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<M: Debug + Model> Debug for Select<M>

Source§

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

Formats the value using the given formatter. Read more
Source§

impl<M: Model> Default for Select<M>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<M> Freeze for Select<M>

§

impl<M> RefUnwindSafe for Select<M>
where M: RefUnwindSafe,

§

impl<M> Send for Select<M>

§

impl<M> Sync for Select<M>

§

impl<M> Unpin for Select<M>
where M: Unpin,

§

impl<M> UnwindSafe for Select<M>
where M: 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
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> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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<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