How to add Queryable and Insertable simultaneously to diesel.rs entities
An issue that has occurred to me recently while using diesel.rs as an ORM for
rust, has been the inability to have Insertable
and Queryable
attributes
on structs
.
Why is that? Because Insertable
requires you to don’t have a property representing
the ID in order to auto-generate the primary key value with auto increment, but
Queryable
requires you to have a property named id
in order to make the entity,
ca va sans dire, Queryable
by ID
.
So the solution so far was explained here, in this issue on github.com https://github.com/diesel-rs/diesel/issues/1440 but I thought it was a bit too verbose in my opinion, and so I started thinking a bit.
And I think I found a very modern and simple solution, simply using a UUID
as
primary key, so that we would not need auto increment but would still be able to
generate IDs for our entities that would have a low chance of collision, how should
we implement that?
First of all we need to add the dependencies to our Cargo.toml
diesel = { version = "2.0.0", features = ["mysql", "r2d2", "chrono", "uuid"] }
uuid = {version = "1.1.2", features = ["v4", "serde"]}
And then update our entity and set the type for the id as a vector
#[derive(Insertable, Queryable, Identifiable, PartialEq, Debug)]
pub struct User {
pub id: Vec<u8>,
}
Which would then allow us to set the SQL type for the id of the entity as a BINARY
CREATE TABLE `users` (
`id` BINARY(36) PRIMARY KEY,
);
Easy peasy!