Repository navigation
Move migration logic to alembic env.py and add CLI wrappers - #7742
Conversation
`reflex db init` now runs `alembic init` with a template shipped in `reflex/.templates/alembic`: an `alembic.ini` without a database URL, an `env.py` that loads the app, takes `db_url` from rxconfig.py and carries the autogenerate hooks (sqlmodel import, server defaults for added columns, no empty revisions, batch mode), and a `script.py.mako`. The other commands delegate to alembic's own command line through `reflex.utils.migrations`: `migrate` is `upgrade head`, `makemigrations` is `revision --autogenerate`, `status` is `history --indicate-current`, and the startup schema check is `alembic check`. The custom EnvironmentContext code in `reflex.model` goes away; `migrate()` and `alembic_init()` stay as wrappers. Apps initialized by earlier releases carry alembic's stock env.py, which never loaded the app. The commands detect it and point at `reflex db init`, which then replaces env.py and script.py.mako while keeping the revisions. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
An earlier test can leave the reflex logger at INFO, so caplog then holds the "Created alembic.ini" line and an empty-text assertion depends on test order. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
The alembic.ini.mako and script.py.mako shipped with reflex were copies of alembic's own, so `reflex db init` now runs `alembic init` as is and installs the reflex env.py over the stock one, the same step the legacy upgrade takes. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
[High impact] The PR appears safe to merge; no new actionable issues were found. SummaryMoves migration setup into an app-owned
Reviews (23) · Last reviewed commit: "Drop the db exit-status test that the mi..." · Reviewed by Greptile |
There was a problem hiding this comment.
All reported issues were addressed across 12 files
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
Keeps the migration docs' upgrade note next to main's new create_all example. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
Merging this PR will regress 1 benchmark1 warning
Warning Please fix the performance issues or acknowledge them on CodSpeed. Performance Changes
Tip Investigate this regression by commenting Comparing |
…e first `reflex db init` on a legacy environment moves the previous env.py to env.old before installing the template. Autogenerate loads the app the way `reflex db makemigrations` always did, evaluating pages with compilation skipped, so models that pages or plugin route hooks import lazily are compared; the other commands still only import the app. `migrate(autogenerate=True)` applies pending scripts before autogenerating, as it did before, since alembic refuses to autogenerate against a database behind head. The docs no longer suggest `alembic upgrade --sql`, which batch migrations on sqlite cannot render offline, and state that env.py skips empty revisions for the alembic command line as well. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
There was a problem hiding this comment.
All reported issues were addressed across 8 files (changes from recent commits).
Requires human review: Auto-approval blocked because this review re-detected 1 unresolved issue already reported by Cubic.
View guided diff | Turn on auto-fix | Re-trigger cubic
`migrate()` and the `reflex db` commands replace a stock env.py from an earlier release with the template, keeping it as env.old, instead of only pointing at `reflex db init`: apps such as the rx-shout template call `rx.Model.migrate()` at import with the stock file, which the old in-process code never ran. The startup schema check still only logs the hint. Autogenerate restores REFLEX_SKIP_COMPILE after evaluating the pages, so a `migrate(autogenerate=True)` before the app's own compile no longer disables it. The env.py hooks accept alembic's revision argument type, which the minimum alembic version declares as an iterable too. The test project writes its sqlite URL in POSIX form, which Windows temp paths broke as a string literal. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
There was a problem hiding this comment.
All reported issues were addressed across 8 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
A `reflex db` command now runs alembic before the app is imported, so an app that calls `rx.Model.migrate()` at module level would start a second alembic run inside the first, and alembic's context proxy does not survive that: the inner run's exit strips the attributes the outer env.py still needs. env.py loads the app through `migrations.load_app()`, which also owns the compile flag restore, and `migrations.run()` skips a command issued during that import; the run already in progress applies the scripts. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
`migrate(autogenerate=True)` called at module level before `app = rx.App()` exists broke startup: env.py asked for the compiled app, which reads `app` from the module still being imported. The old helper only ever compared the registered models; only `reflex db init` and `makemigrations` evaluated the pages first. Those two commands do so again, before alembic runs, and env.py's `load_app()` is a plain import with the reentrancy guard. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
|
more fixes on the way based on out-of-band agentic testing |
Both commands loaded the app with the skip-compile flag, expecting that to evaluate the pages so models they import lazily are compared. Once a previous run has written `.web/backend/stateful_pages.json`, a skip-compile load evaluates only the routes the marker names, which for most apps is none, so a lazily imported model was missing from the metadata and autogenerate emitted `op.drop_table` for it. Reproduced on main and on released 0.10.1 as well. A dry-run compile evaluates every page and writes nothing to `.web`, so the commands use that instead. The regression test writes the marker before `init`, then checks that `makemigrations` with no change writes no revision. The test helper now also drops the app's submodules and its `rx.page` registrations between re-imports, which the new step needed. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8Dgk15CaSGqpobPeFDn
- The schema check after `reflex db migrate` and at app startup ran before the pages were evaluated, so a model that only a page imports always produced the "Detected database schema changes" warning. `get_compiled_app` now checks after the compile, and `reflex db migrate` evaluates the pages with a dry-run compile first, as `init` and `makemigrations` do. - With `db_url` unset, `migrate`, `makemigrations` and `status` failed inside alembic with "No 'script_location' key found in configuration". `check_db_initialized` now says that db_url is not configured and stops. - env.py applied alembic.ini's logging configuration whenever the reflex logger had no handlers, which reconfigured the root logger of any process calling `migrate()`. `migrations.run` now marks its own invocations and env.py applies `fileConfig` only under the `alembic` command line. The env.py update `migrate()` performs is logged as a warning, since such a process may show nothing less. - `reflex db init` writes env.py from the template when the file is missing, so an env.py edited by hand can be replaced by moving it aside; the docs say so, and that the `alembic` command line only imports the app module. - `alembic init` names each template file even with --quiet, because its ScriptDirectory is built without the command's messaging options. `migrations.init` redirects stdout while it runs. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8Dgk15CaSGqpobPeFDn
The db commands loaded the app with a full dry-run compile to get every page evaluated. That also ran the compile-time checks, such as the var dependency validation of the whole state tree, so a frontend problem unrelated to migrations stopped `reflex db`, and a state left behind by an earlier test module failed the migration tests in the full suite. With compilation skipped, `compile_app` now evaluates every page on a dry run, instead of only the routes the stateful-pages marker names, and writes no marker. The db commands use that through `_evaluate_pages()`: no rendering, no `.web` writes, no frontend validation. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8Dgk15CaSGqpobPeFDn
A page may query the database when evaluated, so against a schema that is behind its scripts the evaluation failed before the upgrade could run. The pages are evaluated after `upgrade head`, still ahead of the schema check that needs the models they import lazily. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
`ModelRegistry.get_metadata()` caches the metadata it merges when more than one model base is registered. `reflex db migrate` runs alembic before it evaluates the pages, so the schema check's run compared the database against the upgrade's view, missing the models the pages import lazily and warning about tables that are in fact current. env.py's `load_app()` now drops the cache, so each run sees every model registered so far. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
There was a problem hiding this comment.
All reported issues were addressed across 14 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
Only `reflex db init`, `reflex db makemigrations` and the schema check after `reflex db migrate` evaluate the pages before comparing the models; `reflex db status` never does. A hand-edited env.py is kept only while it no longer reads `target_metadata = None`, the line that marks the stock template, since any env.py still holding it is replaced and moved to env.old. The news fragment also said the lazily imported model was both "no longer missed" and "dropped". Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
…recated Review follow-ups on the env.py design: - env.py evaluates the pages for `alembic check` and `alembic revision --autogenerate`, as the `reflex db` commands do, so a model that only a page imports is no longer dropped from the generated revision. `alembic upgrade` leaves the pages alone, since a page may query the database it is about to migrate; `reflex db migrate` evaluates them after the upgrade for the same reason. The page evaluation moved from the CLI into `reflex.utils.migrations`, and the docs no longer describe a difference. - `reflex.model.alembic_autogenerate`, `get_migration_history` and `format_revision`, and the matching `rx.Model` class methods, are kept for a release with a deprecation warning instead of being removed. They run through the generated env.py now, so `alembic_autogenerate` ignores its `connection` argument. - The process-logging bugfix fragment is dropped: main never applied alembic.ini's logging settings from `migrate()`, only an earlier commit of this branch did. The sentence about the warning for the env.py update moved into the feature fragment, and the breaking fragment became a deprecation one. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
`alembic_autogenerate()` runs `alembic check` through env.py, so in an app initialized by an earlier release it met the stock env.py, which has no metadata and connects to the placeholder URL in alembic.ini. It now replaces that file first, keeping the backup and the warning `migrate()` already gives, through a helper both share. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
There was a problem hiding this comment.
All reported issues were addressed across 10 files (changes from recent commits).
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
Only `alembic_autogenerate` does; `get_migration_history` reads the revision and the scripts directly, and `format_revision` formats one. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
…tests The commands exit with status 1 since 3312599; these two tests still expected 0. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01ESN8DkLZoEJkNbL7bLtvXu
Type of change
Closes #1396. Part of #6245.
Description
This PR moves the migration logic out of
reflex.modelinto a generatedalembic/env.py. Thereflex dbcommands become thin wrappers over the alembic command line, and the barealembiccommand works on the same environment.reflex/.templates/alembic/env.py(installed byreflex db init, owned by the app):db_urlfrom rxconfig.py. Thesqlalchemy.urlin alembic.ini is not used.alembic revision --autogenerateandalembic check, it also evaluates the pages, so a model that only a page imports is compared.alembic upgradedoes not evaluate the pages.reflex/utils/migrations.py(new):run(),init(),install_env(),script_directory(),evaluate_pages(),load_app(),is_legacy_env(),update_legacy_env()anddescribe_error().reflex dbcommands (reflex/reflex.py):initrunsalembic initand applies a first autogenerated revision. Ifalembic/env.pyis missing, it writes the file from the template.migrate,makemigrationsandstatusrunalembic upgrade head,alembic revision --autogenerateandalembic history --indicate-current.initandmakemigrationsevaluate every page first.migrateevaluates them after the upgrade and before the schema check.db_url, or beforereflex db init, the commands log an error and exit with status 1.Apps from earlier releases: a stock
env.py(it hastarget_metadata = None) is replaced with the template on the nextreflex dbcommand ormigrate()call. The old file is kept asenv.old, and the existing revisions are kept.Bug fixes:
reflex runwrites the stateful-pages marker,reflex db makemigrationsno longer writesop.drop_tablefor a model that only a page imports.reflex db migrateand at app startup no longer reports false "Detected database schema changes".Deprecations
reflex.model.alembic_autogenerate,get_migration_historyandformat_revision, and the matchingrx.Modelclass methods, still work. They callconsole.deprecate(deprecated in 0.10.2, removed in 1.0.0).alembic_autogeneratenow runs throughenv.pyand ignores itsconnectionargument.Test plan
tests/units/utils/test_migrations.py: SQLModel and SQLAlchemy models, added and dropped columns and tables, callable defaults for existing rows, UTC datetimes, models that only a page imports, legacyenv.pyupdate, the barealembiccommand line, error reporting, and exit status 1 without a database.docs/database/overview.mddocuments the new workflow.