0

I have an existing app which uses SQLAlchemy for DB access. It works well.

Now I want to introduce DB migrations, and I read alembic is the recommended way. Basically I want to start with the "current DB state" (not empty DB!) as revision 0, and then track further revisions going forward.

So I installed alembic (version 1.7.3) and put

from my_project.db_tables import Base
target_metadata = Base.metadata

into my env.py. The Base is just standard SQLAlchemy Base = sqlalchemy.ext.declarative.declarative_base() within my project (again, which works fine).

Then I ran alembic revision --autogenerate -m "revision0", expecting to see an upgrade() method that gets me to the current DB state from an empty DB. Or maybe an empty upgrade(), since it's the first revision, I don't know.

Instead, the upgrade() method is full of op.drop_index and op.drop_table calls, while downgrade() is all op.create_index and op.create_table. Basically the opposite of what I expected.

Any idea what's wrong? What's the recommended way to "initialize" migrations from an existing DB state?

user124114
  • 8,372
  • 11
  • 41
  • 63
  • possibly related: https://stackoverflow.com/a/69132288/2144390 – Gord Thompson Oct 07 '21 at 21:20
  • 1
    also related: https://stackoverflow.com/q/52121596/2144390 – Gord Thompson Oct 07 '21 at 21:37
  • @GordThompson Thanks. The first link is not relevant (I don't use upper case). The second link might be – clearly even the first step there fails: `alembic revision --autogenerate` creates a monstrous file, as described in the OP. Still not sure what to do though. – user124114 Oct 08 '21 at 07:13

1 Answers1

0

OK, I figured it out.

The existing production DB has lots of stuff that alembic revision --autogenerate is not picking up on. That's why its generated migration scripts are full of op.drops in upgrade(), and op.creates in downgrade().

So I'll have to manually clean up the generated scripts every time. Or automate this cleanup Python script cleanup somehow programmatically, outside of Alembic.

user124114
  • 8,372
  • 11
  • 41
  • 63