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
0:02 is this Unit of Work.
0:04 Let's dig into that.
0:05 The unit of work is a design pattern
0:07 that allows ORMs and other data access frameworks
0:11 to put a bunch of work together
0:14 and then at the very end
0:15 decide to go and interact with the database.
0:18 Decide, now, we're going to actually
0:21 save this data within a single transaction.
0:24 So here we have a bunch of different tables
0:27 customers, suppliers, and orders.
0:29 They're all providing entities into this operation
0:32 this unit of work.
0:34 So maybe we have a couple customers
0:35 one supplier, and one order.
0:37 We've also maybe allocated some new one
0:39 like we did with package
0:40 and we're inserting that into the database.
0:42 And maybe we've changed things about the supplier.
0:45 We're updating those in the database.
0:47 And the order is canceled, so we're calling delete on that.
0:51 All that gets kind of queued up in this unit of work
0:54 and then we get, so I'll call commit in SQLAlchemy syntax
0:58 and that pushes all those changes
1:00 which are tracked by the unit of work
1:02 the so-called dirty records, right?
1:04 The things that need to be inserted
1:06 the things that need to be deleted
1:07 the things that need to be updated, and so on.
1:09 So we can use these unit of works like that.
1:11 And the way we create them are with these sessions.
1:14 So we've seen that we create these engines
1:19 and the engine gives us this session factoring.
1:21 That was all encapsulated within our DBSession class.
1:25 We do this once, right?
1:27 And then, every time we want to interact with the database
1:30 we create one of these sessions.
1:32 So we come over here and we call that session factory
1:34 it gives us a unit of work, which is often called a session
1:39 kind of treat this like a transaction.
1:41 A bunch of stuff happens in memory, then it's committed.
1:44 Maybe we add something, maybe we do some more queries
1:47 maybe that tells us what we've got to do to add some more
1:49 we could make changes to the results of those queries
1:52 either updates or delete.
1:54 All of that work has not interacted with the database.
1:58 In fact, other than the query
2:00 there's not actually been any interaction with the database.
2:03 This add doesn't actually add it to the database.
2:06 It just queues it up to be added
2:08 and when you call commit
2:10 that commits the entire unit of work.
2:12 Don't want to commit it?
2:14 Don't, nothing will happen in the database.
2:16 There will be no changes to your data.
2:18 And that's how the unit of work pattern appears
2:21 and is used in SQLAlchemy
2:23 through this session factory, and then committing it.