sqlalchemy-data-access

Database access rules for SQLAlchemy 2.0, a Python library for working with databases, using asynchronous sessions. They cover queries, parameter binding, security, and performance.

In plain words
What is it for?
Use them when writing async database reads, dynamic filters, primary-key lookups, ORM code, or database-related service helpers.
Why use it?
They help agents write modern database queries safely and avoid SQL injection, outdated APIs, and inefficient access patterns.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/e-gov/cursor-prompts/sqlalchemy-data-access
Clone the repo
git clone --depth 1 https://github.com/e-gov/cursor-prompts
Per session 1,197 This file is loaded in full into every session.
When invoked 1,197 The same file — it is already loaded in full.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.01197 $0.01197
Opus 5 $0.00598 $0.00598
Sonnet 5 $0.00239 $0.00239
Haiku 4.5 $0.00120 $0.00120

Measured 2d ago against content hash 773e41377d4e, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

sqlalchemy-data-access scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

rules/python-fastapi/sqlalchemy-data-access.mdc · 75 lines

How it starts

The opening of the file, as written. The whole thing — 75 lines — stays where its author put it; the contents beside it link to each section on GitHub.

SQLAlchemy 2.0 Async Data Access

Context

  • Applies to database access in services and helpers using AsyncSession (see your project’s database module and get_db / session dependency).
  • SQL injection, parameterized access, least privilege DB users: mdc:rules/common/security.mdc (Input Validation — ORMs/parameterization). This rule is the SQLAlchemy 2.0 async expression of those requirements in this repo.
  • Migrations vs runtime: schema changes via Alembic as separate deploy steps — mdc:rules/common/component-technical-standards.mdc (Database & Data Management).

Core style (SQLAlchemy 2.0)

  • Use select() with await session.execute(...), then scalar_one(), scalar_one_or_none(), scalars().all(), or await session.scalar(select(...)) as appropriate.
  • Use session.get(Model, pk) for primary-key lookups when you want identity-map behavior.
  • Do not use legacy Session.query() on async sessions.
  • Prefer ORM entities and Column expressions in where / order_by; build dynamic filters by composing sqlalchemy.and_ / or_ and Condition objects — not by concatenating SQL.

Parameter binding and dynamic SQL

  • Never concatenate raw SQL with user-controlled strings — see mdc:rules/common/security.mdc. Use Core/ORM expressions so values are bound as parameters.
  • For LIKE / ILIKE with untrusted fragments, bind literals safely, for example:
    • column.ilike(func.concat("%", literal(user_fragment), "%"))
      (pattern often lives in a small helper such as _author_filter on a service module).
  • For dynamic ORDER BY, use an allowlist of column attributes (like SORTABLE_FIELDS + getattr(Model, field)), not raw strings from the client.

Reads and shape of queries

  • Pagination: Prefer limit / offset (or keyset pagination for very large tables). Run a separate count() query when the API needs total hits, as in paged list endpoints — avoid loading the full table to count rows.
  • Counts: select(func.count()).select_from(Model).where(...) (or func.count(Model.id)) rather than len((await session.scalars(select(Model))).all()).
  • Columns: Use select(Model.col1, Model.col2) when you intentionally need a narrow projection; map rows explicitly.
  • N+1: If you add relationships, load them in the same round trip with selectinload() / joinedload() on the outer select(), or use a single statement with joins — do not access unloaded collections in a loop without an eager-load strategy.
  • Large result sets: Never load unbounded all() for user-facing endpoints without limit. For batch jobs that scan many rows, use chunked queries (keyset/limit loops) or SQLAlchemy streaming APIs supported by your installed version, and keep transactions short.

Read the full file on GitHub · 75 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 75 lines · 1,197 tokens per session scan A 773e41377d4e

Subscribe to this mod's changes

sqlalchemy-data-access is a cursor rule published in the GitHub repository e-gov/cursor-prompts (34 stars, last pushed 4mo ago), licensed MIT. It adds 1,197 tokens to every session, about $0.0060 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.