Skip to content

feat(cli): SQLAlchemy models for scan, ER diagrams and N+1 (preview) - #199

Merged
FROWNINGdev merged 1 commit into
mainfrom
feat/sqlalchemy-models
Oct 31, 2026
Merged

FROWNINGdev merged 1 commit into
mainfrom
feat/sqlalchemy-models

Conversation

@FROWNINGdev

@FROWNINGdev FROWNINGdev commented Oct 31, 2026 •

Copy link
Copy Markdown
Owner

What

scan, list, describe, hover, er and nplusone, and the MCP tools list_apps, list_models, describe_model, find_relations, er_diagram and nplusone_scan, now read SQLAlchemy models alongside Django ones. Static, like the rest: ast only, nothing imported, no database.

Docs: docs/rules/sqlalchemy.md

Recognised

Style Mapped when
SQLAlchemy 2.0 descends from class Base(DeclarativeBase)
SQLAlchemy 1.x descends from declarative_base(), registry().generate_base(), @as_declarative(); or @registry.mapped
Flask-SQLAlchemy / Flask-AppBuilder descends from db.Model / FAB Model (auto snake_case table names)
SQLModel table=True (non-table parents lend fields)
  • Bases, __abstract__ classes and mixins are followed across files, including aliased imports from files with no SQLAlchemy in them (Superset's from superset_core... import Dashboard as CoreDashboard).
  • Table names: __tablename__, __table__, @declared_attr rules on the base (Prefect), Flask / SQLModel defaults, single-table inheritance.
  • ForeignKey columns are ER edges to the class mapped to the target table; relationship() attributes are listed apart with their lazy loader and shape; secondary= is a many-to-many through the association table, drawn once.

N+1

Loops over session.scalars(select(X)), execute(...).scalars(), session.query(X), X.query, paginate(), rows unpacked per entity, a single object's collection, nested loops and comprehensions. A relationship counts as loaded when the query's .options(...) names it (selectinload, joinedload, chains, defaultload, Load(), string paths, "*") or its loader is non-lazy. Collections are high, many-to-one medium (the identity map may answer). Unreadable options, queries rebound in a loop, writes, method calls, tests and Alembic revisions stay quiet.

Safety for Django users

  • scan_workspace(include_sqlalchemy=False) by default: drift, blast-radius, cascade, signals and suggest-indexes never see SQLAlchemy models.
  • The SQLAlchemy walk reads every file, so it runs only when there are no Django models or the project declares SQLAlchemy in a dependency file (≤ 2 levels deep). PostHog scan: 1.9 s, not 9 s.
  • Each N+1 detector gets its own ORM's models; Django's schema-less heuristics no longer run over SQLAlchemy code.

Fixed along the way: a models.py that is SQLAlchemy code without a Django import was read as Django models — 65 phantom models in Superset, 138 in Polar, 69 in Dispatch, 10 in Airflow, 8 in Redash.

Census

Project Models N+1 high / medium
Superset 39 0 / 0
Airflow 68 1 / 1
Prefect 35 0 / 0
Polar 172 0 / 0
Dispatch 76 1 / 2
Mealie 57 2 / 0
CTFd 48 3 / 2
Redash 20 0 / 0
FastAPI template 2 0 / 0

All 12 findings were checked by hand: each is a real query per row. ER builds in all five formats on every project. The six Django projects (NetBox, PostHog, authentik, Plane, paperless-ngx, Healthchecks) get no SQLAlchemy models, and their Django models and N+1 findings are unchanged.

Tests

test_sqlalchemy_parser.py (17) and test_sqlalchemy_nplusone.py (19); full suite 1091 passed, ruff and mypy clean.

Summary by CodeRabbit

  • New Features
    • Added preview support for scanning SQLAlchemy, SQLModel, and Flask-SQLAlchemy models with supported CLI and workspace tools.
    • Model listings, descriptions, and ER diagrams now include SQLAlchemy fields, relationships, and inherited data.
    • N+1 analysis now detects lazy SQLAlchemy relationship access in loops and suggests eager-loading options.
  • Bug Fixes
    • SQLAlchemy-only files are no longer misidentified as Django models.
  • Documentation
    • Added guidance on supported SQLAlchemy scanning and analysis.

scan, list, describe, hover, er and nplusone, and the MCP tools list_apps,
list_models, describe_model, find_relations, er_diagram and nplusone_scan,
now read SQLAlchemy models as well as Django ones. Static: ast only, no
import, no database.

- sqlalchemy_parser: SQLAlchemy 2.0 DeclarativeBase / Mapped[], 1.x
  declarative_base() / Column, Flask-SQLAlchemy db.Model, Flask-AppBuilder
  Model and SQLModel table=True classes. Bases, abstract classes and mixins
  are followed across files by import, including aliased imports from files
  with no SQLAlchemy in them. Table names from __tablename__, __table__,
  a declared_attr rule on the base, or the Flask / SQLModel defaults.
  ForeignKey columns become relations to the class mapped to the target
  table; relationship() attributes are kept apart with their lazy loader
  and shape (one or many); a secondary= relationship is also a
  ManyToManyField through the association table.
- ParsedModel gains orm, table_name and relationships (ParsedRelationship);
  only SQLAlchemy models add them to their JSON.
- scan_workspace(include_sqlalchemy=False): off by default, so drift,
  blast-radius, cascade, signals and suggest-indexes stay Django-only.
  The SQLAlchemy walk runs only when there are no Django models or the
  project declares SQLAlchemy in a dependency file (PostHog: 1.9s, not 9s).
- sqlalchemy_nplusone: loops over session.scalars(select(X)),
  execute().scalars(), session.query(X), X.query, paginate(), rows unpacked
  per entity, a single object's collection, nested loops and
  comprehensions. Loader options (selectinload, joinedload, subqueryload,
  immediateload, contains_eager, raiseload, noload, defaultload chains,
  Load(), string paths, "*") count as loaded; non-lazy relationship
  loaders are never reported. scan_all_nplusone runs each ORM's detector
  on its own models and keeps Django advice off SQLAlchemy code.
- Fixed: a models.py that is SQLAlchemy code without a Django import was
  read as Django models (65 phantom models in Superset, 138 in Polar, 69
  in Dispatch).
- er_formats: SQLAlchemy tables show mixin columns and their real primary
  key; DBML maps NO ACTION.
- workspace: alembic.ini or a sqlalchemy/sqlmodel dependency marks a
  project root for the MCP server.

Census: Superset, Airflow, Prefect, Polar, Dispatch, Mealie, CTFd, Redash
and the FastAPI template give 517 models and 12 N+1 findings (7 high,
5 medium), all real on review. The six Django projects give no SQLAlchemy
models and unchanged Django models and N+1 findings.
@coderabbitai

coderabbitai Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Caution

Review failed

The pull request is closed.

Walkthrough

This change adds static SQLAlchemy model scanning, model and ER output, and N+1 detection. CLI and MCP model operations include SQLAlchemy models, while Django-specific analyses remain Django-only.

Changes: SQLAlchemy support

Layer / File(s) Summary
Parse models and build workspace indexes
cli/django_orm_lens/models.py, cli/django_orm_lens/sqlalchemy_parser.py, cli/django_orm_lens/parser.py, cli/django_orm_lens/workspace.py, cli/tests/test_sqlalchemy_parser.py, CHANGELOG.md
The workspace recognizes SQLAlchemy projects and parses supported SQLAlchemy, SQLModel, and Flask model declarations, including cross-file inheritance and relationship metadata. SQLAlchemy-only files are excluded from Django model parsing.
Expose SQLAlchemy models in model and ER outputs
cli/django_orm_lens/cli.py, cli/django_orm_lens/mcp_server.py, cli/django_orm_lens/formatters.py, cli/django_orm_lens/er_formats.py, cli/tests/test_sqlalchemy_parser.py, docs/rules/README.md, docs/rules/sqlalchemy.md, CHANGELOG.md
CLI and MCP model operations include SQLAlchemy models. Model and ER output uses ORM-aware fields and relationship metadata, with tests and documentation covering the supported output.
Detect SQLAlchemy N+1 relationship access
cli/django_orm_lens/sqlalchemy_nplusone.py, cli/django_orm_lens/query_analyzer.py, cli/django_orm_lens/cli.py, cli/django_orm_lens/mcp_server.py, cli/django_orm_lens/ci_formats.py, cli/tests/test_sqlalchemy_nplusone.py, docs/rules/sqlalchemy.md
The SQLAlchemy detector scans recognized query-result loops for relationship access not covered by eager loading. CLI and MCP N+1 scans combine Django and SQLAlchemy findings.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant get_index
  participant scan_workspace
  participant scan_sqlalchemy_models
  CLI->>get_index: request SQLAlchemy-inclusive index
  get_index->>scan_workspace: root and include_sqlalchemy
  scan_workspace->>scan_sqlalchemy_models: scan eligible SQLAlchemy project
  scan_sqlalchemy_models-->>scan_workspace: parsed models and file count
  scan_workspace-->>get_index: combined workspace index
  get_index-->>CLI: workspace index
Loading
sequenceDiagram
  participant MCP
  participant scan_all_nplusone
  participant scan_sqlalchemy_nplusone
  participant scan_source
  MCP->>scan_all_nplusone: project root, index, and test option
  scan_all_nplusone->>scan_sqlalchemy_nplusone: scan SQLAlchemy files
  scan_sqlalchemy_nplusone->>scan_source: source file and model index
  scan_source-->>scan_sqlalchemy_nplusone: findings for the source
  scan_sqlalchemy_nplusone-->>scan_all_nplusone: SQLAlchemy findings
  scan_all_nplusone-->>MCP: combined N+1 findings
Loading

Suggested reviewers: nitjsefnie, jjordan0c

Merge Risk: Low · up to 6f6b8

The SQLAlchemy preview works for the main cases, but a few edge cases give wrong output. N+1 can report a false positive after a query is reassigned. MCP relation lookup can miss foreign keys inherited from mixins. Some SQLAlchemy projects may be rejected as non-Django workspaces. A third-party base class can be mistaken for a project model. These are small, targeted fixes that can be made before or shortly after merge.

- [ ] Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

ParsedModel,
WorkspaceIndex,
)
from .sqlalchemy_parser import declares_sqlalchemy, is_sqlalchemy_only_source
# project should not pay for: look only when there are no Django models
# or the project declares SQLAlchemy.
if include_sqlalchemy and (not found or declares_sqlalchemy(root_path)):
from .sqlalchemy_parser import scan_sqlalchemy_models
``backend/requirements.txt``). Lets a large Django project skip reading
every file in search of SQLAlchemy models it does not have.
"""
from .parser import BROAD_SKIP_DIRS


def _build_models(classes: list[_Class], modules: list[_Module]) -> list[ParsedModel]:
from .parser import _app_dir_for # local import: parser imports this module
(``versions/`` next to an ``env.py``): old revisions often declare
throwaway copies of the models for data migrations.
"""
from .parser import BROAD_SKIP_DIRS
@FROWNINGdev
FROWNINGdev merged commit e85cdf9 into main Oct 31, 2026
20 checks passed
@FROWNINGdev
FROWNINGdev deleted the feat/sqlalchemy-models branch October 31, 2026 09:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants