Building data-driven web apps with Flask and SQLAlchemy Transcripts
Chapter: Database migrations with Alembic
Lecture: Concept: auto-generating changes

Login or purchase this course to watch this video and the rest of the course contents.
0:00 The best way to use a Alembic I think
0:02 is to let SQLAlchemy at least pre-build
0:06 the various revision changes for you
0:08 and then you can edit them still if you like.
0:11 In order to do that, you have to edit
0:12 the env.py file, and you have to set
0:15 the target metadata to the SQLAlchemyBase.metadata
0:19 and just like before, it is super important
0:21 that that SQLAlchemyBase thing
0:23 sees all of your various models.
0:26 That means you have to do some form of import
0:28 like this from pypi.data import *
0:32 or something to that effect, to make sure
0:34 that everything is loaded up.
0:36 But adding these two things will connect
0:38 SQLAlchemy and Alembic so that Alembic can
0:41 use your models to generate revisions
0:44 and that is way, way sweeter.
0:47 So just simply setting this target metadata
0:50 is all we have to do to connect
0:51 our ORM models to Alembic.
0:53 And then to make a change, we just add
0:55 the auto generate, like we had before
0:58 but now we say auto generate this change.
1:00 It's going to go detect the various changes
1:03 and then it's going to create another one of these files.
1:06 We open up that file and now it's better.
1:08 We have this little section in upgrade.
1:10 Instead of pass, it says these were auto generated
1:13 by Alembic, please review them
1:15 and if you're happy just leave them
1:18 or if you need to, make changes.
1:21 Nothing happens when you auto generate this
1:23 but it generates the file as it can guess
1:25 and then you edit it to do what it needs.
1:28 Finally, you just apply it again
1:31 and it's going to apply that auto generated
1:33 revision change, rather than the one
1:35 you had to manually write, and that's Alembic.
1:38 A very nice way to keep evolving
1:41 your database structure, along with
1:43 the evolution of your SQLAlchemy models
1:47 and for the most part making that automatic.