PacktPublishing / Building-Data-Science-Applications-with-FastAPI

Building Data Science Applications with FastAPI, Published by Packt
MIT License
299 stars 152 forks source link

Directory problems in Chapter 6 Alembic section #9

Open gitgithan opened 1 year ago

gitgithan commented 1 year ago

Book says run alembic revision --autogenerate -m "initial migration", implicitly saying run from the folder Building-Data-Science-Applications-with-FastAPI since alembic.ini is referencing script_location = chapter6/sqlalchemy_relationship/alembic instead of the default alembic.

However this will result in errors saying FAILED: No config file 'alembic.ini' found, or file has no '[alembic]' section.

What i needed to make this work was to specify the path of alembic.ini using -c option. alembic -c chapter6/sqlalchemy_relationship/alembic.ini revision --autogenerate -m "initial migration", same for alembic -c chapter6/sqlalchemy_relationship/alembic.ini upgrade head.

Another issue When I first follow along the book, i get a empty migration script

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    pass
    # ### end Alembic commands ###

I found this message (https://stackoverflow.com/a/67509934/8621823) explaining that if the table is already there, the migration script will be empty at those portions, so I deleted the sqlite database, and deleted all the migration scripts, tried again and it worked. I also had to delete the database because somewhere along the way, running alembic revision gave me ERROR [alembic.util.messaging] Can't locate revision identified by 'ca9e1b2549f3'. I'm guessing this revision was stored in the database, and it was looking for this revision under alembic/versions folder, which i had cleared.

Question

  1. What is the proper way to reproduce the book's instructions and generate a non-empty migration script? (I wonder if my explanation of Can't locate revision error is right, and whether deleting sqlite database and all the existing migration scripts is necessary)
  2. Book warns against renaming columns, what are some common workflows/scenarios with alembic assuming I don't delete the database? (doesn't feel right to delete, i did it just to reproduce the book). Would the scenario be someone adds new table/columns to a database through sqlalchemy's metadata object, which get's picked up by alembic revision command to add some new tables and columns under def upgrade in the migration script, to be applied with alembic upgrade head to change the database?
frankie567 commented 1 year ago

Alembic basically works this way:

So if you want to recreate an initial migration from scratch, you need to start with an empty database and delete all existing migrations.