Python for Entrepreneurs Transcripts
Chapter: Accessing databases from Python: SQLAlchemy ORM
Lecture: Concept: Unit of Work Design Pattern

Login or purchase this course to watch this video and the rest of the course contents.
0:02 You've seen one of the key foundational design patterns in SQLAlchemy is this concept of unit of work. The way it works is you create a unit of work,
0:13 you make a bunch of changes to a variety of entities, they can come from the same table
0:17 here they are coming from three separate tables, customer, supplier orders, you make a bunch of changes, inserts, updates and deletes.
0:23 And then, we can either commit all of those changes or none of those changes, as a single unit of work.
0:29 So this is the concept, how does it look in code? Remember we created the db session factory class to manage all these details for us.
0:38 And here is kind of what was in that global init section, so remember, we create one and only one engine per connection string,
0:45 so we have our engine, and then in order to get a hold of one of these sessions
0:49 is we are going to need a session factory or session maker as they call it. We are going to create this instance, of a session factory,
0:57 again, there is a one to one mapping between the factory and the engine and there is only one engine so there is only one of these factories.
1:04 But we are then going to use this to create these sessions over and over and over, so do you see it here, this is only done once.
1:11 But then as you interact with the data, you are going to go through these cycles of creating a unit of work,
1:15 doing the work and then committing or abandon it. So we always start by calling the session factory, to create the session,
1:22 we make a variety of changes, maybe we want to add a query, maybe add some more data, and then when we are finally finished,
1:29 we want to save those two adds and maybe we queried some objects and actually updated them by just changing their properties,
1:36 we want to push all those changes back to the database, we say session.commit. If you don't want to commit the session, don't, nothing will happen.


Talk Python's Mastodon Michael Kennedy's Mastodon