-
I couldn't find anything about optimistic locking in Diesel. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
You might want to add a few more details to your question what exactly you are looking for. Diesel provides several helpers to configure your transactions and also several helpers to configure which locks should be acquired. |
Beta Was this translation helpful? Give feedback.
-
Thanks for your response and sorry for the bevity, I assumed optimistic locking says it all. It's about maintaining a row version and producing an error when updating a record where the row version has changed in the database since the last read. It's about avoiding long running transactions for example when a web client loads a record to eventually update it. I came up with let db_movie = update(movie.find(db_movie.id))
.filter(sys_version.eq(db_movie.sys_version)) // << check if we have the most recent version
.set((
imdb_rating.eq(Some(BigDecimal::from(rating.rating))),
imdb_vote_count.eq(rating.vote_count),
sys_version.eq(sys_version + 1), // << increment on save
sys_updated_at.eq(diesel::dsl::now)
))
.returning(Movie::as_select())
.get_result::<Movie>(&mut conn)
.unwrap(); I haven't tested this code yet but I assume it would work as expected. So, if the result is empty then the update failed because the record in the database didn't have the expected I was curious if there are more efficient ways or direct support in Diesel where I can just add an attribute to the table that specifies the version column and Diesel takes care of the rest. |
Beta Was this translation helpful? Give feedback.
The query written there should work as written assuming the type mappings are correct.
As for the additional check: There is the
OptionalExtension::optional()
which turns aNotFound
error into aOption<T>
. That's likely the thing you want to use there.Otherwise there is no additional support for this in diesel. I also do not see why this should be something that's "directly" supported as there are just to many variables there (name of the version column, etc). You still would need to specify essentially the same information there instead of in the update statement, so this wouldn't become easier.