pub trait Selectable<DB: Backend> {
    type SelectExpression: Expression;

    fn construct_selection() -> Self::SelectExpression;
}
Expand description

Trait indicating that a record can be selected and queried from the database.

Types which implement Selectable represent the select clause of a SQL query. Use SelectableHelper::as_select() to construct the select clause. Once you called .select(YourType::as_select()) we enforce at the type system level that you use the same type to load the query result into.

The constructed select clause can contain arbitrary expressions coming from different tables. The corresponding derive provides a simple way to construct a select clause matching fields to the corresponding table columns.

Examples

If you just want to construct a select clause using an existing struct, you can use #[derive(Selectable)], See #[derive(Selectable)] for details.

use schema::users;

#[derive(Queryable, PartialEq, Debug, Selectable)]
struct User {
    id: i32,
    name: String,
}

let first_user = users.select(User::as_select()).first(connection)?;
let expected = User { id: 1, name: "Sean".into() };
assert_eq!(expected, first_user);

Alternatively, we can implement the trait for our struct manually.

use schema::users;
use diesel::prelude::{Queryable, Selectable};
use diesel::backend::Backend;

#[derive(Queryable, PartialEq, Debug)]
struct User {
    id: i32,
    name: String,
}

impl<DB> Selectable<DB> for User
where
    DB: Backend
{
    type SelectExpression = (users::id, users::name);

    fn construct_selection() -> Self::SelectExpression {
        (users::id, users::name)
    }
}

let first_user = users.select(User::as_select()).first(connection)?;
let expected = User { id: 1, name: "Sean".into() };
assert_eq!(expected, first_user);

Required Associated Types

The expression you’d like to select.

This is typically a tuple of corresponding to the table columns of your struct’s fields.

Required Methods

Construct an instance of the expression

Implementations on Foreign Types

Implementors