sqlalchemy
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "sqlalchemy" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-f96cb6b41e739e1ebc48b4aed9701a35074ccddf02704ed2c4f7b56d680c6862. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Work with databases in Python using SQLAlchemy — provide guidance and examples for setting up the Python ORM, defining database models, writing asynchronous database queries, managing migrations with Alembic, or choosing between SQLAlchemy and the Django ORM.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Software, accounts and paid services
- ```python
- Testing
- Not tested
Browse files
Frontmatter
name: sqlalchemy
description: >-
Work with databases in Python using SQLAlchemy. Use when a user asks to
set up a Python ORM, define database models, write async database queries,
manage migrations with Alembic, or choose between SQLAlchemy and Django ORM.
license: Apache-2.0
compatibility: 'Python 3.10+, PostgreSQL, MySQL, SQLite'
metadata:
author: terminal-skills
version: 1.0.0
category: data-ai
tags:
- sqlalchemy
- python
- orm
- database
- asyncSQLAlchemy
Overview
SQLAlchemy is the standard Python ORM and SQL toolkit. Version 2.0 introduces a modern, type-friendly API with async support. Define models as Python classes, write queries with the builder pattern, and manage schema changes with Alembic migrations.
Instructions
Step 1: Async Setup
# db.py — Async SQLAlchemy configuration
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncSession
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
from sqlalchemy import String, ForeignKey, DateTime, func
from datetime import datetime
DATABASE_URL = "postgresql+asyncpg://user:pass@localhost:5432/myapp"
engine = create_async_engine(DATABASE_URL, echo=False, pool_size=20)
async_session_maker = async_sessionmaker(engine, expire_on_commit=False)
class Base(DeclarativeBase):
pass
Step 2: Define Models
# models.py — SQLAlchemy 2.0 models with type hints
from db import Base
from sqlalchemy import String, ForeignKey, DateTime, Integer, Text, Boolean, func
from sqlalchemy.orm import Mapped, mapped_column, relationship
from datetime import datetime
class User(Base):
__tablename__ = "users"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
name: Mapped[str] = mapped_column(String(100))
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
role: Mapped[str] = mapped_column(String(20), default="member")
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
# Relationships
projects: Mapped[list["Project"]] = relationship(back_populates="owner", cascade="all, delete")
def __repr__(self) -> str:
return f"<User {self.email}>"
class Project(Base):
__tablename__ = "projects"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
name: Mapped[str] = mapped_column(String(100))
description: Mapped[str | None] = mapped_column(Text)
status: Mapped[str] = mapped_column(String(20), default="active")
owner_id: Mapped[str] = mapped_column(ForeignKey("users.id"))
task_count: Mapped[int] = mapped_column(Integer, default=0)
created_at: Mapped[datetime] = mapped_column(DateTime, server_default=func.now())
owner: Mapped["User"] = relationship(back_populates="projects")
tasks: Mapped[list["Task"]] = relationship(back_populates="project", cascade="all, delete")
class Task(Base):
__tablename__ = "tasks"
id: Mapped[str] = mapped_column(String(36), primary_key=True)
title: Mapped[str] = mapped_column(String(200))
status: Mapped[str] = mapped_column(String(20), default="todo")
project_id: Mapped[str] = mapped_column(ForeignKey("projects.id"))
assignee_id: Mapped[str | None] = mapped_column(ForeignKey("users.id"))
project: Mapped["Project"] = relationship(back_populates="tasks")
Step 3: Queries
# queries.py — Async query examples
from sqlalchemy import select, func, and_
from sqlalchemy.orm import selectinload
async def get_user_projects(db: AsyncSession, user_id: str):
"""Fetch user's projects with task counts."""
result = await db.execute(
select(Project)
.where(Project.owner_id == user_id, Project.status == "active")
.options(selectinload(Project.tasks)) # eager load to avoid N+1
.order_by(Project.created_at.desc())
)
return result.scalars().all()
async def get_project_stats(db: AsyncSession, project_id: str):
"""Aggregate task statistics for a project."""
result = await db.execute(
select(
Task.status,
func.count(Task.id).label("count"),
)
.where(Task.project_id == project_id)
.group_by(Task.status)
)
return {row.status: row.count for row in result.all()}
async def search_tasks(db: AsyncSession, query: str, project_id: str):
"""Full-text search in task titles."""
result = await db.execute(
select(Task)
.where(
and_(
Task.project_id == project_id,
Task.title.ilike(f"%{query}%"),
)
)
.limit(20)
)
return result.scalars().all()
Step 4: Alembic Migrations
# Initialize Alembic
pip install alembic
alembic init alembic
# Generate migration from model changes
alembic revision --autogenerate -m "add tasks table"
# Apply migrations
alembic upgrade head
# Rollback one step
alembic downgrade -1
Guidelines
- Use
Mappedtype hints (SQLAlchemy 2.0) — they provide IDE autocompletion and type safety. - Always use
selectinloadorjoinedloadfor relationships — prevents N+1 query problems. - Use
expire_on_commit=Falsefor async sessions — prevents lazy loading exceptions. - Alembic autogenerate detects most schema changes, but review migrations before applying.
- For simple projects, consider SQLModel (FastAPI creator's library) — simpler API, same engine.
Current listing version
1.0.0
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 SQLAlchemy 的完整使用指南,涵盖异步配置、模型定义、查询编写和 Alembic 迁移管理
- 适用于广泛受众的数据库操作需求,具有明确的实用价值
Highlights
- description 明确列出了使用场景,覆盖合理且边界清晰
Areas to improve
-
缺少 When to Use 章节 Reported severity: Minor
文档未明确说明何时使用此 Skill
Recommendation: 建议在 Overview 后添加 When to Use 章节,明确使用场景
-
缺少端到端完整示例 Reported severity: Minor
文档提供了代码片段,但缺少一个完整的端到端示例
Recommendation: 建议添加一个完整的端到端示例,展示从配置到查询的完整流程
Highlights
- 文档结构清晰,分步骤说明,包含端到端代码示例
- frontmatter 完整,单文件未超过 500 行
Highlights
- 工具来源明确,参数正确,覆盖了主要异常处理建议
- 不可逆操作(如迁移)有说明
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 145
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
```python
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.