sqlalchemy / alembic

A database migrations tool for SQLAlchemy.
MIT License
2.76k stars 241 forks source link

refactor: make drop_constraint() constraint_name Optional #1424

Closed JudeDavis1 closed 7 months ago

JudeDavis1 commented 7 months ago

Alembic generates drop_constraint in migration files, sometimes with None as the constraint_name. The current type is str, but alembic still puts None. To stop Mypy from complaining, this parameter needs to be an optional.

CaselIT commented 7 months ago

Hi,

I'm not sure how that drop constraint would succeed when run in the db with specifying a name? Like what would op.drop_constraint(None, 'some_table') do?

@zzzeek Is the above supposed to succeed on some db?

zzzeek commented 7 months ago

nope it's not. if None is generated there from alembic, the migration needs to be corrected. typing doing its job

CaselIT commented 7 months ago

@JudeDavis1 autogenerate is setting none since when creating a constraint a name is not generally needed, so it's optional in the sqlalchemy model.

To properly remove that you will need to find what's the name that was given to it looking in the db with a tool like dbeaver or using the sqlalchemy inspector were constraint names are returned for most databases.

Thanks in any case!

JudeDavis1 commented 7 months ago

nope it's not. if None is generated there from alembic, the migration needs to be corrected. typing doing its job

@zzzeek @CaselIT If this was the case, I would expect there to at least be an error/warning saying something.

CaselIT commented 7 months ago

Well the documentation of autogenerate specify that autogenerate produces "candidate" migrations to review and modify manually, so I think this is covered by that.

I don't think a warning should be raised for this, but guess a log indicating that one or more constraint / indexes do not have a name and the drop command should be updated could be added (assuming one is not already issued)

@zzzeek do you think it would be useful or cause too much noise?

zzzeek commented 7 months ago

@zzzeek @CaselIT If this was the case, I would expect there to at least be an error/warning saying something.

there is in fact an error raised, which is when you try to run the migration, it will raise at that point. alembic's autogenerate feature only generates so-called "candidate" Python code and it does not have a layer of error checking within the rendering phase.

Overall, here are all the places that the None condition could be caught:

While users frequently want this feature, "autogenerate" is not intended to be an invisible step in an otherwise fully automatic process to generate diffs and upgrade a database. Manually reviewing the code is required, we dont promise transparently correct migrations and we dont raise within the render phase, as it's not necessary.