I use sqlx to communicate with my Postgres database. I'm trying to abstract the database communication with a Repository pattern. Aslo, with this abstraction I would like to share the database transaction between repositories using Unit Of Work pattern. The only problem that I have I don't know how to share the sqlx
transaction between those repositories without explicitly providing transaction
in save
arguments (e.g. repository_x.save(entity, transaction)
). I would like to create and share transactions in uow
(unit of work) abstraction.
I want to achieve something like this
struct CommandHandler {
unit_of_work: UnitOfWork
}
impl CommandHandler {
pub fn handle(&self, &command: Command) {
let repository_a = self.unit_of_work.repository_a();
let repository_b = self.unit_of_work.repository_b();
let entity_a = repository_a.get_by_id(command.id);
let entity_b = repository_b.get_by_id(entity_a.id);
unit_of_work.start_transaction();
repository_a.save(entity_a);
repository_b.save(entity_b);
unit_of_work.commit_transaction();
}
}
Does anyone know what the implementation of the unit_of_work
struct would look like to execute the above example?