Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

sqlalchemy

БесплатноБез исполняемых скриптовНе проверен

SQLAlchemy Python ORM. Covers models, sessions, and queries. Use for Python database applications. USE WHEN: user mentions "sqlalchemy", "declarative_base"…

claude-dev-suiteот claude-dev-suite★ 51 звезда на GitHub

Об этом скилле

SQLAlchemy Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: sqlalchemy for comprehensive documentation.

When NOT to Use This Skill

  • TypeScript/Node.js Projects: Use prisma, drizzle, or typeorm skills
  • Django Applications: Use Django ORM documentation (not covered here)
  • Raw SQL Queries: Use database-query MCP server for direct SQL execution
  • NoSQL Databases: Use mongodb skill for MongoDB operations
  • FastAPI Specific: May need fastapi-expert for integration patterns
  • Database Design: Consult sql-expert or architect-expert for schema architecture
  • Other Python ORMs: Peewee, Pony ORM, Tortoise not supported by this skill

Model Definition

from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
from sqlalchemy.orm import relationship, DeclarativeBase
from datetime import datetime

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(100), nullable=False)
    email = Column(String(255), unique=True, nullable=False)
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)

    posts = relationship('Post', back_populates='author')

class Post(Base):
    __tablename__ = 'posts'

    id = Column(Integer, primary_key=True)
    title = Column(String(255), nullable=False)
    content = Column(String)
    author_id = Column(Integer, ForeignKey('users.id'))

    author = relationship('User', back_populates='posts')

Session Operations

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('postgresql://user:pass@localhost/db')
Session = sessionmaker(bind=engine)

# Create
with Session() as session:
    user = User(name='John', email='[email protected]')
    session.add(user)
    session.commit()

# Read
with Session() as session:
    users = session.query(User).all()
    user = session.query(User).filter_by(id=1).first()
    active_users = session.query(User).filter(User.is_active == True).all()

# Update
with Session() as session:
    user = session.query(User).filter_by(id=1).first()
    user.name = 'Jane'
    session.commit()

# Delete
with Session() as session:
    session.query(User).filter_by(id=1).delete()
    session.commit()

Async Support

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker

engine = create_async_engine('postgresql+asyncpg://user:pass@localhost/db')
async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def get_users():
    async with async_session() as session:
        result = await session.execute(select(User))
        return result.scalars().all()

Anti-Patterns

Anti-Pattern Why It's Bad Better Approach
Not closing sessions Connection leaks, pool exhaustion Use context managers (with Session())
Using session.query() in SQLAlchemy 2.0+ Deprecated, legacy API Use select() with session.execute()
No eager loading for relations N+1 query problem Use selectinload() or joinedload()
Hardcoded connection strings Security risk Use environment variables
Not configuring connection pool Connection issues, performance Set pool_size, max_overflow, pool_recycle
Using session.flush() without understanding Partial commits, confusion Use commit() for transactions
No pool_pre_ping in production Stale connections after DB restart Enable pool_pre_ping=True
Missing indexes on foreign keys Slow joins Add Index() to frequently joined columns
Using ORM for bulk operations Very slow for large datasets Use bulk_insert_mappings() or Core
Not handling IntegrityError Cryptic errors to users Catch and provide meaningful messages

Quick Troubleshooting

Issue Likely Cause Solution
"No module named 'sqlalchemy'" SQLAlchemy not installed Run pip install sqlalchemy
"Can't connect to server" Wrong DATABASE_URL or DB down Verify connection string, check DB status
"Table doesn't exist" Migrations not run Execute alembic upgrade head
"DetachedInstanceError" Accessing relation outside session Use joinedload() or keep session open
"IntegrityError: duplicate key" Unique constraint violation Check for existing record, handle error
"InvalidRequestError: SQL expression" Missing select() in 2.0 style Use select(Model) not session.query()
Slow queries N+1 problem, missing indexes Add eager loading, create indexes
Pool timeout Too many connections Increase pool_size, fix connection leaks
"Stale data" Session caching old data Call session.expire_all() or refresh objects
Alembic co
Полный SKILL.md на GitHub

Установить sqlalchemy в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Grep
Glob
Write
Edit

Вложенные файлы

quick-ref/models.mdquick-ref/queries.md

FAQ

Что делает скилл sqlalchemy?

SQLAlchemy Python ORM. Covers models, sessions, and queries. Use for Python database applications. USE WHEN: user mentions "sqlalchemy", "declarative_base", "DeclarativeBase", "Session", "Query", "relationship()", "alembic", asks about "python orm", "sqlalchemy models", "sqlalchemy async", "sqlalchemy relationships", "python database" DO NOT USE FOR: Node.js/TypeScript ORMs - use `prisma`, `drizzle`, or `typeorm` skills; Django ORM - use Django-specific resources; raw SQL - use `database-query` MCP; NoSQL - use `mongodb` skill; other Python ORMs (Peewee, Pony) - not supported

Как установить скилл sqlalchemy?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл sqlalchemy запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить sqlalchemy с