Building Data-Driven Web Apps with Flask and SQLAlchemy Transcripts
Chapter: Using SQLAlchemy
Lecture: Concept: Unit of work

Login or purchase this course to watch this video and the rest of the course contents.
0:00 One of the core concepts of SQLAlchemy is this Unit Of Work. Let's dig into that. The Unit Of Work is a design pattern
0:09 that allows ORMs and other data-access frameworks to put a bunch of work together and then at the very end decide to go and interact with the database
0:19 decide now we're going to actually save this data within a single transaction. So here we have a bunch of different tables
0:28 customers, suppliers, and orders. They're all providing entities into this operation this unit of work. So maybe we have a couple of customers
0:36 one supplier, and one order. We've also maybe allocated some new one like we did with package and we're inserting that into the database.
0:43 And maybe we've changed things about the supplier we're updating those in the database. And the order is canceled so we're calling delete on that.
0:52 All that gets kind of queued up in this unit of work. And then I'll call commit in SQLAlchemy syntax and that pushes all those changes
1:01 which are tracked by the unit of work the so-called dirty records the things that need to be inserted the things that need to be deleted
1:08 the things that need to be updated and so on. So we can use these unit of works like that and the way we create them are with these sessions.
1:16 So we've seen that we create these engines and the engine gives us this session factory that was all encapsulated within our db_session class.
1:27 We do this once and then every time we want to interact with the database we create one of these sessions.
1:33 So we come over here and we call that session factory it gives us a unit of work which is often called a session kind of treat this like a transaction
1:42 a bunch of stuff happens in memory then it's committed. Maybe we add something, maybe we do some more queries
1:48 maybe that tells us what we've got to do to add some more. We could make changes to the results of those queries
1:53 either updates or deletes. Other than the query there's not actually been any interaction with the database.
2:00 This add doesn't actually add it to the database it just queues it up to be added. When you call commit that commits the entire unit of work.
2:09 Don't want to commit it? Don't, then nothing will happen in the database there will be no changes to your data.
2:15 And that's how the unit of work pattern appears and is used in SQLAlchemy through this session factory and then committing it.

Talk Python's Mastodon Michael Kennedy's Mastodon