Search code examples
rustrust-diesel

How could I find a value using a column other than the primary key with Diesel?


I have a table of users and would like to perform a search using Diesel to ensure that the username is not already taken. The only way I've found to perform queries is to use the find() function, which uses the primary key. Is there another function that searches using other fields, similarly to SELECT * FROM users WHERE username = foo?

Here's my users table:

CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE users (
    user_id uuid PRIMARY KEY DEFAULT uuid_generate_v4() NOT NULL UNIQUE,
    username VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(60) NOT NULL
);

And here is the Rust struct I'm using:

#[derive(Queryable, AsChangeset, Deserialize, Serialize)]
#[table_name = "users"]
pub struct User {
    pub user_id: uuid::Uuid,
    pub username: String,
    pub password: String,
}

#[derive(Insertable, Deserialize, Serialize)]
#[table_name = "users"]
pub struct InsertableUser {
    pub username: String,
    pub password: String,
}

Solution

  • Diesel provides a general .filter method that let's you construct arbitrary complex where clauses. For your example query you look for something like:

    users::table.filter(users::username.eq("foo"))