From 539ac9bcf9c69231e18f32a2805fd4413412ef8c Mon Sep 17 00:00:00 2001 From: Masen Furer Date: Fri, 3 May 2024 13:49:39 -0700 Subject: [PATCH] [REF-2658] Alembic should use batch mode for autogenerate Better support for column changes when using the default sqlite database. Only sqlite is affected by batch operations, other databases still use the same mechanisms they used before this change. See: https://alembic.sqlalchemy.org/en/latest/batch.html --- reflex/model.py | 1 + tests/test_model.py | 17 ++++++++++++----- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/reflex/model.py b/reflex/model.py index dcc971707b..c6c4a2a158 100644 --- a/reflex/model.py +++ b/reflex/model.py @@ -310,6 +310,7 @@ def run_autogenerate(rev, context): render_item=cls._alembic_render_item, process_revision_directives=writer, # type: ignore compare_type=False, + render_as_batch=True, # for sqlite compatibility ) env.run_migrations() changes_detected = False diff --git a/tests/test_model.py b/tests/test_model.py index accab52fe1..ee0336b373 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -96,18 +96,23 @@ class AlembicThing(Model, table=True): # type: ignore sqlmodel.SQLModel.metadata.clear() - # Create column t2 + # Create column t2, mark t1 as optional with default class AlembicThing(Model, table=True): # type: ignore - t1: str + t1: Optional[str] = "default" t2: str = "bar" Model.migrate(autogenerate=True) assert len(list(versions.glob("*.py"))) == 2 with reflex.model.session() as session: + session.add(AlembicThing(t2="baz")) + session.commit() result = session.exec(sqlmodel.select(AlembicThing)).all() - assert len(result) == 1 + assert len(result) == 2 + assert result[0].t1 == "foo" assert result[0].t2 == "bar" + assert result[1].t1 == "default" + assert result[1].t2 == "baz" sqlmodel.SQLModel.metadata.clear() @@ -120,8 +125,9 @@ class AlembicThing(Model, table=True): # type: ignore with reflex.model.session() as session: result = session.exec(sqlmodel.select(AlembicThing)).all() - assert len(result) == 1 + assert len(result) == 2 assert result[0].t2 == "bar" + assert result[1].t2 == "baz" # Add table class AlembicSecond(Model, table=True): # type: ignore @@ -158,8 +164,9 @@ class AlembicThing(Model, table=True): # type: ignore assert errctx.match(r"no such table: alembicsecond") # first table should still exist result = session.exec(sqlmodel.select(AlembicThing)).all() - assert len(result) == 1 + assert len(result) == 2 assert result[0].t2 == "bar" + assert result[1].t2 == "baz" sqlmodel.SQLModel.metadata.clear()