Skip to content

Type to search extensions

SQLAlchemy LSP

v0.1.2

Language server for SQLAlchemy and Alembic: diagnostics, completion, hover, navigation

Updated 4 months ago
459 downloads 4 stars Repository ↗

sqlalchemy-lsp

A language server for SQLAlchemy ORM and Alembic, plus a check command that runs the same diagnostics in CI. It ships as one Rust binary and works in any editor that speaks LSP. It runs next to your regular Python language server and only handles what is specific to SQLAlchemy and Alembic.

Features

Diagnostics 51 checks: model and table structure, columns and types, foreign keys, relationships, legacy APIs, ORM extensions, Alembic migration history
Quick fixes per-finding fixes marked safe or unsafe, plus "fix all" (source.fixAll.sqlalchemy) for the safe ones
Completions FK strings, relationship() and mapped_column() arguments and values, cascade tokens, __table_args__ columns, model constructor keywords, Alembic op.* calls, table and column names inside string arguments such as secondary="..." and primaryjoin="..."
Hover model, column, relationship and FK cards, cascade tokens, back_populates counterparts, Alembic revision ids, table and column names in op.* calls
Navigation go to definition, find references and rename for models, columns, relationships and FK targets; revision ids in down_revision and depends_on
Code lens per model: incoming FKs, relationships and migrations that mention it; per migration: head or child count
Document links FK strings, relationship targets and op.* table names link to the model
Inlay hints resolved FK targets, relationship types, the database column name when it differs from the attribute, the model behind a table name in migrations
Signature help model constructors and relationship()
Symbols Alembic revisions in the workspace symbol picker
Schema ER diagram of the workspace (Mermaid, Graphviz or ASCII), the whole schema or one model's neighborhood, and a Mermaid graph of the migration history
Diagnostics delivery pushed after every change, plus document and workspace pull diagnostics

The server indexes the whole workspace, so a foreign key, relationship or base class in another file resolves the same way as one in the same file. Positions are negotiated as UTF-8 or UTF-16.

Diagnostics

Every code below is on by default except the ones marked off. Codes marked off are enabled through select.

Code Name Default
SQLA-W101 missing-tablename on
SQLA-E102 duplicate-tablename on
SQLA-E103 duplicate-column on
SQLA-W104 missing-primary-key on
SQLA-E105 table-arg-column-not-found on
SQLA-H106 unnamed-constraint on
SQLA-H107 no-naming-convention on
SQLA-W201 nullable-not-optional on
SQLA-H202 optional-without-nullable on
SQLA-W203 mutable-default on
SQLA-W204 default-and-server-default off
SQLA-H205 naive-datetime on
SQLA-H206 unbounded-string (needs target_dialect) on
SQLA-I207 missing-column-comment off
SQLA-E301 unknown-fk-table on
SQLA-E302 fk-column-not-found on
SQLA-W303 fk-type-mismatch on
SQLA-W304 ambiguous-foreign-keys on
SQLA-W305 composite-fk-no-foreign-keys on
SQLA-E401 rel-target-not-found on
SQLA-W402 back-populates-mismatch on
SQLA-W403 back-populates-not-found on
SQLA-W404 uselist-mismatch on
SQLA-W405 target-mismatch on
SQLA-H406 missing-fk-for-relationship on
SQLA-H407 unique-missing-one-to-one on
SQLA-W408 unknown-cascade on
SQLA-W409 orphan-without-delete on
SQLA-H410 circular-relationship on
SQLA-W411 missing-remote-side on
SQLA-H412 secondary-with-data-columns on
SQLA-W413 non-collection-mapped on
SQLA-H414 lazy-select-scalar off
SQLA-H415 lazy-joined-collection on
SQLA-H416 viewonly-write off
SQLA-W501 legacy-backref on
SQLA-W502 legacy-declarative-base on
SQLA-I503 legacy-query-api on
SQLA-W504 missing-mapped-annotation on
SQLA-I505 import-alias on
SQLA-I506 missing-repr off
SQLA-H601 hybrid-without-expression on
SQLA-H602 association-proxy-misconfigured off
SQLA-H603 validates-without-include-removes on
SQLA-W701 broken-migration-chain on
SQLA-W702 multiple-heads on
SQLA-H703 unknown-migration-table on
SQLA-W704 null-constraint-name on
SQLA-I705 model-table-never-migrated off
SQLA-I706 model-column-never-migrated off
SQLA-W901 unused-noqa on

The letter after SQLA- is the default severity: E error, W warning, H hint, I info. The first digit is the family, so SQLA-3xx selects every foreign-key check.

Installation

uv tool install sqlalchemy-lsp

Or with pip:

pip install sqlalchemy-lsp

Pre-built binaries for Linux, macOS and Windows are on the releases page. Arch users can install sqlalchemy-lsp from the AUR.

macOS binaries are unsigned. After downloading, clear the Gatekeeper quarantine flag once:

xattr -d com.apple.quarantine sqlalchemy-lsp-macos-aarch64

Configuration

Standard projects need no configuration. To change behavior, add a [tool.sqlalchemy-lsp] section to pyproject.toml or create sqlalchemy-lsp.toml at the project root. When both exist, pyproject.toml wins key by key.

# sqlalchemy-lsp.toml

# Limit indexing to these paths (default: the whole workspace)
# model_paths = ["app/models"]
# alembic_path = "migrations"

# Enables dialect-specific checks such as SQLA-H206
# target_dialect = "mysql"

# log_level = "info"
# log_file = "/tmp/sqlalchemy-lsp.log"

[diagnostics]
# Codes, families (SQLA-3xx) or presets (all, none, recommended)
# select = ["recommended", "SQLA-I506"]
ignore = ["SQLA-H406"]

[diagnostics.severity]
"SQLA-W303" = "error"

# Per-path settings, applied on top of [diagnostics]
[[overrides]]
includes = ["migrations/**"]
diagnostics.ignore = ["SQLA-H703"]

Without alembic_path, migrations are picked up from any versions/ (or versions_*/) directory.

To silence a line, add # noqa: SQLA-W303 (one or more codes) or a bare # noqa (every SQLA finding on that line). # noqa: file anywhere in a file silences the whole file. A # noqa: SQLA-... that matches nothing is reported as SQLA-W901. A bare # noqa is never reported, because other linters use it too.

CLI

# Run diagnostics
sqlalchemy-lsp check .
sqlalchemy-lsp check app/models/ --select SQLA-3xx --ignore SQLA-H406
sqlalchemy-lsp check --reporter json      # also: full, json-lines, grouped, github, gitlab, junit, pylint

# Apply safe fixes, or all fixes with --unsafe
sqlalchemy-lsp check --fix
sqlalchemy-lsp check --fix --unsafe

# ER schema: the whole workspace, or one model and its neighbors
sqlalchemy-lsp schema --format mermaid
sqlalchemy-lsp schema --model User --hops 2 --output user.mmd

# Finding counts per code
sqlalchemy-lsp stats --output-format json

check exits 1 when it reports findings (0 with --exit-zero) and 2 on a usage or configuration error. It reads the same configuration as the server and reports the same findings.

Editor setup

Zed

Open the extensions panel (Cmd+Shift+X), search for sqlalchemy-lsp and install it. It activates for Python files.

To control the order of language servers, add this to ~/.config/zed/settings.json:

{
  "languages": {
    "Python": { "language_servers": ["sqlalchemy-lsp", "..."] }
  }
}

Helix

Merge editors/helix/languages.toml into ~/.config/helix/languages.toml.

Neovim

Requires Neovim 0.11 or later. Use the snippet from editors/neovim/sqlalchemy_lsp.lua or add this to your init.lua:

vim.lsp.config('sqlalchemy_lsp', {
  cmd = { 'sqlalchemy-lsp', 'lsp', '--stdio' },
  filetypes = { 'python' },
  root_markers = { 'pyproject.toml', 'sqlalchemy-lsp.toml', 'alembic.ini', '.git' },
})
vim.lsp.enable('sqlalchemy_lsp')

The schema and migration graph are available as code actions; the server opens the result in a new buffer.

Other editors

The server speaks standard LSP over stdio:

sqlalchemy-lsp lsp --stdio

It also handles the sqlalchemy.showSchema command (an optional format string, or { model, hops, format }) and sqlalchemy.showMigrationGraph. Both return the diagram as text.

License

MIT