#100DaysOfWeb in Python Transcripts
Chapter: Days 61-64: Database migrations
Lecture: Introduction to db migrations
0:00 Hello and welcome to our next 100 days project in our 100 days course. This time we're going to talk about SQLAlchemy database migrations.
0:10 Now, we've previously spoken about SQLAlchemy. It's a really great way to create classes they map to your database and you can work with Python objects
0:18 and just magically read and save those into read from save them into your database. However, that's the perfect starting from scratch story.
0:28 In practice, your code evolves over time. The chances that your SQLAlchemy classes which generated your database
0:35 will stay that way, the chance that you got that database structure exactly right the first time is very small. Right? Code evolves over time.
0:43 So in order to evolve our database along with our code using SQLAlchemy or other ORMs, like Django ORM you have to use this concept called migrations.
0:52 It's a database migration. It takes our database from one schema one shape, into another. And the goal of that is to keep our database
0:59 in sync with our ORM classes. So, what's the problem? Well, we're starting with our application in one form. We've made some changes, and we want to
1:09 run our code again, this time with a different database schema. Well, sometimes you can get away with the schema not matching exactly.
1:16 But generally what's going to happen is when you go to run your site you won't have this beautiful working application any more.
1:22 You're going to have this error page. SQLAlchemy exception, operational exception no such column, whatever it is. So, how do we fix this?
1:30 Well, we could by hand manually go in there and continuously change and evolve our database schema, that's one option.
1:38 Or, we can use some kind of package that will do that for us. So enter Alembic. Alembic is a database migration library created by Mike Bayer.
1:48 Mike Bayer is the same guy who created SQLAlchemy. So, those two go really well together as you can imagine. And the idea is, we're going to set up our
1:55 web application with Alembic tell it about our SQLAlchemy models tell it about our database and then we're going to say, "Alembic, keep our database
2:03 in sync with our code." And this is great because as we move from dev machine to dev machine maybe the database looks different
2:10 so we move from development to staging to production we might need to make different changes to those different databases to get them in sync.
2:17 And Alembic handles all of that for us. So throughout this chapter we're basically going to focus on using Alembic to make changes throughout our code
2:27 and keep our database in sync.