Python-powered chat apps with Twilio and SendGrid Transcripts
Chapter: Appendix: Using SQLAlchemy
Lecture: Concept: Unit of work
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:08 that allows ORMs and other data-access frameworks
0:12 to put a bunch of work together
0:14 and then at the very end decide to go
0:16 and interact with the database
0:18 decide now we're going to actually
0:22 save this data within a single transaction.
0:25 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 of 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 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
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:15 So we've seen that we create these engines
1:19 and the engine gives us this session factory
1:21 that was all encapsulated within our db_session class.
1:26 We do this once
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:35 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 deletes. Other than the query
1:56 there's not actually been any interaction with the database.
1:59 This add doesn't actually add it to the database
2:02 it just queues it up to be added.
2:03 When you call commit
2:05 that commits the entire unit of work.
2:08 Don't want to commit it?
2:10 Don't, then nothing will happen in the database
2:12 there will be no changes to your data.
2:14 And that's how the unit of work pattern appears
2:17 and is used in SQLAlchemy
2:19 through this session factory and then committing it.