Matterholt
2024-05-06
Building an app a database changes are inevitable. Alembic is light weight tool for database migrations mainly used with SQLAlchemy . What it basically does will apply git like tracking to the database. Alembic will give Django like database migrations to python applications and allow the dev to see changes made over time. The benefit of tracking the history of the database will allow teammates have the most current changes and if there is any issue the database can be rolled back the previous version. The feature of t
running though the process to understand what is going on
generate a file to implement changes to the database, bash alembic revision -m "create events table"
this will generate a file in the directory: alembic/version.
define what are the changes are going to be in the upgrade function
def upgrade(): op.create_table( “events”, sa.Column(“id”, sa.Integer, primary_key=True), sa.Column(“title”,sa.String(), nullable=False), sa.Column(“event_type”, sa.String(), nullable=False)
)``` 3. define how database should be rolled back to.
def downgrade():
op.drop_table(events)
alembic upgrade head
.alembic current
-> check current database state
alembic history
-> check history of database
alembic show 'rev-hash'
-> more detail on alembic revision
alembic downgrade -1
-> down grade to previous db revision
alembic updgrade +1
-> down grade to next db revision
alembic downgrade base
-> down grade to initial db
Setting up the sqlalchemy models file, fist is a simple stand alone. to get the concepts down
sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
metadata = Base.metadata
Letting alembic know to check and compare the models metadata. which is the way alembic know the changes made to the database modles
target_metadata = Base.metadata
Now in the shell Run alembic revision --autogenerate -m "make something happen"
.
once executed then in the directory alembic/version/{generated file}. That file can be open up and the upgrade/downgrade function should have the model sqlalchemy model table.
If all looks good and any changes are edited, then run alembic upgrade head
to confirm
sqlite3 something.db
> .tables
> .schema events
https://www.kimsereylam.com/sqlalchemy/2019/10/18/get-started-with-alembic.html