Building Data-Driven Web Apps with Pyramid and SQLAlchemy Transcripts
Chapter: Using SQLAchemy
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:08 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 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 we get, so 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, right? 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:15 So we've seen that we create these engines and the engine gives us this session factoring. That was all encapsulated within our DBSession class.
1:26 We do this once, right? 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
1:40 kind of treat this like a transaction. 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 either updates or delete.
1:55 All of that work has not interacted with the database. In fact, other than the query there's not actually been any interaction with the database.
2:04 This add doesn't actually add it to the database. It just queues it up to be added and when you call commit that commits the entire unit of work.
2:13 Don't want to commit it? Don't, nothing will happen in the database. There will be no changes to your data.
2:19 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