Skip to content

Move migration logic to alembic env.py and add CLI wrappers - #7742

Merged
FarhanAliRaza merged 25 commits into
mainfrom
claude/focused-wozniak-n9s0x3
Nov 10, 2026
Merged

FarhanAliRaza merged 25 commits into
mainfrom
claude/focused-wozniak-n9s0x3

Conversation

@masenf

@masenf masenf commented Nov 5, 2026 •

Copy link
Copy Markdown
Collaborator

Type of change

  • New feature (non-breaking change which adds functionality)
  • Bug fix (non-breaking change which fixes an issue)
  • This change requires a documentation update

Closes #1396. Part of #6245.

Description

This PR moves the migration logic out of reflex.model into a generated alembic/env.py. The reflex db commands become thin wrappers over the alembic command line, and the bare alembic command works on the same environment.

reflex/.templates/alembic/env.py (installed by reflex db init, owned by the app):

  • Imports the app to register the models, and reads db_url from rxconfig.py. The sqlalchemy.url in alembic.ini is not used.
  • Under alembic revision --autogenerate and alembic check, it also evaluates the pages, so a model that only a page imports is compared. alembic upgrade does not evaluate the pages.
  • Carries a column's Python-side default into the migration as a server default.
  • Skips empty autogenerated revisions.

reflex/utils/migrations.py (new): run(), init(), install_env(), script_directory(), evaluate_pages(), load_app(), is_legacy_env(), update_legacy_env() and describe_error().

reflex db commands (reflex/reflex.py):

  • init runs alembic init and applies a first autogenerated revision. If alembic/env.py is missing, it writes the file from the template.
  • migrate, makemigrations and status run alembic upgrade head, alembic revision --autogenerate and alembic history --indicate-current.
  • init and makemigrations evaluate every page first. migrate evaluates them after the upgrade and before the schema check.
  • Without db_url, or before reflex db init, the commands log an error and exit with status 1.

Apps from earlier releases: a stock env.py (it has target_metadata = None) is replaced with the template on the next reflex db command or migrate() call. The old file is kept as env.old, and the existing revisions are kept.

Bug fixes:

  • After a reflex run writes the stateful-pages marker, reflex db makemigrations no longer writes op.drop_table for a model that only a page imports.
  • The schema check after reflex db migrate and at app startup no longer reports false "Detected database schema changes".

Deprecations

reflex.model.alembic_autogenerate, get_migration_history and format_revision, and the matching rx.Model class methods, still work. They call console.deprecate (deprecated in 0.10.2, removed in 1.0.0). alembic_autogenerate now runs through env.py and ignores its connection argument.

Test plan

  • New 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, legacy env.py update, the bare alembic command line, error reporting, and exit status 1 without a database.
  • docs/database/overview.md documents the new workflow.

View guided diff Turn on auto-fix

`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
@masenf
masenf requested review from a team and Alek99 as code owners November 5, 2026 00:44
@masenf masenf added roadmap https://github.com/reflex-dev/reflex/issues/2727 breaking Public API facing change considered for minor release bump pre-v1.0 labels Nov 5, 2026
@greptile-apps

greptile-apps Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[High impact] The PR appears safe to merge; no new actionable issues were found.

Summary

Moves migration setup into an app-owned alembic/env.py and makes the database commands wrap Alembic.

  • Reflex and Alembic use one app-aware migration setup.
  • Database comparisons now include models imported only by pages.
  • Older apps keep their migration history when Reflex replaces the stock environment.
  • Database commands explain missing setup and return a failing status.
  • The old migration helpers remain available but now point callers to Alembic commands.

Reviews (23) · Last reviewed commit: "Drop the db exit-status test that the mi..." · Reviewed by Greptile

Comment thread reflex/.templates/alembic/env.py Resolved
Comment thread reflex/model.py Resolved
Comment thread reflex/utils/migrations.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread tests/units/utils/test_migrations.py Resolved
Comment thread reflex/.templates/alembic/env.py Resolved
Comment thread news/+alembic-cli-wrappers.breaking.md Resolved
Comment thread reflex/.templates/alembic/env.py Resolved
Comment thread reflex/.templates/alembic/env.py Resolved
Comment thread tests/units/utils/test_migrations.py Resolved
Comment thread reflex/model.py Resolved
Comment thread reflex/utils/migrations.py Resolved
Comment thread docs/database/overview.md Resolved
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
@codspeed

codspeed Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Merging this PR will regress 1 benchmark

1 warning

⚠️ 15 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

⚡ 1 improved benchmark
❌ 1 regressed benchmark
✅ 146 untouched benchmarks

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ test_process_event_burst_independent_tokens[1] 2.7 ms 2.9 ms -4.27%
⚡ test_route_matching[1000] 50.6 µs 47.7 µs +5.9%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing claude/focused-wozniak-n9s0x3 (4fd2ed7) with main (8ba7568)

Open in CodSpeed

…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
Comment thread reflex/.templates/alembic/env.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread reflex/.templates/alembic/env.py Resolved
`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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread reflex/utils/prerequisites.py Resolved
claude and others added 2 commits November 5, 2026 19:32
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
Comment thread reflex/utils/migrations.py Resolved
`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
Comment thread tests/units/utils/test_migrations.py Resolved
@FarhanAliRaza FarhanAliRaza added the on deck PRs lined up to review / merge next label Nov 6, 2026
@masenf

masenf commented Nov 6, 2026

Copy link
Copy Markdown
Collaborator Author

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
Comment thread reflex/reflex.py Resolved
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
Comment thread reflex/reflex.py Resolved
`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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread docs/database/overview.md Resolved
Comment thread docs/database/overview.md Resolved
claude and others added 2 commits November 8, 2026 19:56
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
Comment thread reflex/.templates/alembic/env.py Resolved
Comment thread news/+alembic-cli-wrappers.breaking.md Resolved
…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
Comment thread reflex/model.py Resolved
`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

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread reflex/model.py Resolved
@FarhanAliRaza
FarhanAliRaza merged commit d8e3984 into main Nov 10, 2026
167 of 168 checks passed
@FarhanAliRaza
FarhanAliRaza deleted the claude/focused-wozniak-n9s0x3 branch November 10, 2026 16:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking Public API facing change considered for minor release bump pre-v1.0 on deck PRs lined up to review / merge next roadmap https://github.com/reflex-dev/reflex/issues/2727

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remove misleading alembic configuration

3 participants