joesan
joesan

Reputation: 15385

Scala Asynchronous Database Calls

I'm currently using Slick 3.x.x which is completely asynchronous in all its calls to the database. Let's say, I have a table that has some sort of versioning. Every time I create a new entry from an already existing entry (i.e. updating a given entry), I have to make sure that I increment the version number.

How can I make sure in this asynchronous world of database communications that I can maintain data integrity? In my case with versioning, I would first do a select for the max version which would give me back a Future and then I use the result of this Future, increment 1 and issue a create command!

It could very well be possible that thread 1 started with select max version and paused for a while, thread 2 catering to a new request could run the select for max version and increment and write the new record in the database. Now thread1 comes back and tries to so the same process, but only to result in the fact that thread1 would overwrite what thread2 wrote in the database.

It could be that I might end up having multiple duplicates because the order in which multiple futures might be run might differ!

Upvotes: 2

Views: 299

Answers (1)

Steve Waldman
Steve Waldman

Reputation: 14073

The asynchrony with which your application manages its interaction with the database doesn't alter the semantics of database transactions. if you want atomic, consistent sequences of operations, then you want a database transaction. Slick offers a "combinator" called transactionally which will force a sequence of operations to run within a database transaction.

Upvotes: 3

Related Questions