Search code examples
databasepostgresqlrustrust-diesel

Check if a certain database-entry already exists in DIesel/Rust


I'm currently developing a database in Rust using the Diesel-Framework.

My task is to check if an entry in the table already exists by comparing the primary key.

Im generating the primary key using the Uuid-Crate:

let extension = ".png".to_string();
let primary_key = Uuid::parse_str(&extension).unwrap();

If the primary key does not exist yet, I want to insert a new entry into the database. On the other hand if there is already a primary key existing with the same Uuid, I dont want to insert into the database.

Now Im looking for a proper way to manage this task - I thought about using the find-function but Im not sure how to do it yet.


Solution

  • In case were UUID is the primary key your bdd engine will return a uniq constraint violation error when an already existing UUID is inserted, you can get the same behavior on any row by adding a uniq constraint on it. You shoulde take a look to the postgres doc