Imagine that I have the following table:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
name VARCHAR NOT NULL UNIQUE
)
And the following Rust structs:
#[derive(Debug, Queryable, Selectable, Insertable)]
#[diesel(table_name = crate::schema::users)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct User {
id: i32,
created_at: SystemTime,
updated_at: SystemTime,
name: String,
}
#[derive(Insertable)]
#[diesel(table_name = crate::schema::users)]
#[diesel(check_for_backend(diesel::pg::Pg))]
pub struct NewUser {
name: String
}
I want to be able to call a function that either create or get the user with the following name. So if the user does not exists it creates it, and if the user already exists it returns that record. For that I thought I could use the diesel method on_conflict_do_nothing() as follow:
pub fn create_or_get(&self, user_name: &String) -> QueryResult<User> {
use self::schema::users::dsl::*;
let new_user = NewUser::from(user_name.clone());
let conn = &mut self.pool.get().unwrap();
diesel::insert_into(users).values(&new_user).on_conflict_do_nothing().returning(User::as_returning()).get_result(conn)
}
But I am getting Err.NotFound when the name is already in the database. Any idea what am I doing wrong?