Python for Entrepreneurs Transcripts
Chapter: Accessing databases from Python: SQLAlchemy ORM
Lecture: Concept: Unit of Work Design Pattern
0:02 You've seen one of the key foundational design patterns
0:05 in SQLAlchemy is this concept of unit of work.
0:09 The way it works is you create a unit of work,
0:12 you make a bunch of changes to a variety of entities,
0:14 they can come from the same table
0:16 here they are coming from three separate tables, customer, supplier orders,
0:19 you make a bunch of changes, inserts, updates and deletes.
0:22 And then, we can either commit all of those changes
0:25 or none of those changes, as a single unit of work.
0:28 So this is the concept, how does it look in code?
0:31 Remember we created the db session factory class to manage all these details for us.
0:37 And here is kind of what was in that global init section,
0:40 so remember, we create one and only one engine per connection string,
0:44 so we have our engine, and then in order to get a hold of one of these sessions
0:48 is we are going to need a session factory or session maker as they call it.
0:52 We are going to create this instance, of a session factory,
0:56 again, there is a one to one mapping between the factory and the engine
0:59 and there is only one engine so there is only one of these factories.
1:03 But we are then going to use this to create these sessions
1:06 over and over and over, so do you see it here, this is only done once.
1:10 But then as you interact with the data,
1:12 you are going to go through these cycles of creating a unit of work,
1:14 doing the work and then committing or abandon it.
1:17 So we always start by calling the session factory, to create the session,
1:21 we make a variety of changes, maybe we want to add a query,
1:25 maybe add some more data, and then when we are finally finished,
1:28 we want to save those two adds and maybe we queried some objects
1:32 and actually updated them by just changing their properties,
1:35 we want to push all those changes back to the database, we say session.commit.
1:39 If you don't want to commit the session, don't, nothing will happen.