flask-sqlalchemy 修改列属性后执行 migrate 不生效 ​



# 原代码
class TestModel(BaseModel):
__tablename__ = "test"

type = db.Column(db.String(255))
point_list = db.Column(db.String(256))


修改列属性后



class TestModel(BaseModel):
__tablename__ = "test"

type = db.Column(db.String(255))
point_list = db.Column(db.String(512))


执行 flask db migrate发现未检测到修改

在下面的migrations/env.py的函数中加了 compare_type=True, 再执行就可以检测到列修改了



def run_migrations_online():
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
compare_type=True, # 加了此行代码
**current_app.extensions['migrate'].configure_args
)

with context.begin_transaction():
context.run_migrations()