Token导航 LogoToken导航

Agent Skill · 开发

building-with-sqlalchemy-orm(使用 sqlalchemy orm 构建)

building-with-sqlalchemy-orm 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

building-with-sqlalchemy-orm 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为接触敏感数据;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 12,952。

总安装 1,071周安装 46GitHub Stars 158下载 375核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:building-with-sqlalchemy-orm(使用 sqlalchemy orm 构建)
来源仓库:https://github.com/panaversity/agentfactory
仓库路径:skills/building-with-sqlalchemy-orm
安装命令:
npx skills add https://github.com/panaversity/agentfactory --skill building-with-sqlalchemy-orm
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/panaversity/agentfactory --skill building-with-sqlalchemy-orm

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

building-with-sqlalchemy-orm 用于构建基于 SQLAlchemy ORM 2.0+ 的生产级数据库应用。适用于 PostgreSQL 通用模式和 Neon 无服务器环境的开发场景。提供数据库模型定义、连接管理和查询优化等核心能力。使用前需确认项目现有模型结构、数据库配置和连接模式。

建议参考官方文档和最佳实践以确保实现符合项目规范。

来源仓库内路径:skills/building-with-sqlalchemy-orm

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/panaversity/agentfactory --skill building-with…;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要接触敏感数据,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

building-with-sqlalchemy-orm 怎么安装?

在终端执行 npx skills add https://github.com/panaversity/agentfactory --skill building-with-sqlalchem…。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

building-with-sqlalchemy-orm 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

building-with-sqlalchemy-orm 需要什么权限?

权限级别是接触敏感数据。该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

building-with-sqlalchemy-orm 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

building-with-sqlalchemy-orm 用的人多吗?

公开数据是累计安装 1,071 次,近一周安装 46 次,下载 375 次,GitHub 158 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

building-with-sqlalchemy-orm 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 需要接触敏感数据,装到常用环境前要先评估影响面。
  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 环境里有大量密钥、凭证,不方便给第三方 Skill 读取的人。
  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
building-with-sqlalchemy-orm

使用 sqlalchemy orm 构建 · 本页

1,071158接触敏感数据未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

Building with SQLAlchemy ORM

Build production-grade database applications with SQLAlchemy ORM 2.0+, generic PostgreSQL patterns, and Neon-specific serverless considerations.

Before Implementation

Gather context to ensure successful implementation:

SourceGather
CodebaseExisting models, database setup, connection patterns
ConversationStudent's specific use case (what they're building), constraints
Skill ReferencesDomain patterns from references/ (API docs, best practices, architecture)
User GuidelinesProject conventions, proficiency level

Only ask student for THEIR requirements (domain expertise is embedded in this skill).


Persona

You are a Python database architect with production experience building applications with SQLAlchemy ORM. You understand both the generic PostgreSQL patterns (applicable everywhere) and Neon-specific serverless considerations (autoscaling, scale-to-zero, branching). You've built multi-table applications with proper transaction handling, relationships, and connection pooling.


When to Use

  • Building database models from requirements (defining tables as Python classes)
  • Implementing CRUD operations safely with transactions
  • Managing relationships between tables (foreign keys, joins)
  • Querying data with filters, ordering, and complex joins
  • Connecting to PostgreSQL or Neon with proper configuration
  • Teaching database fundamentals to beginners learning persistence

Core Concepts

1. Models as Classes (ORM Abstraction)

SQLAlchemy maps Python classes to database tables:

from sqlalchemy import Column, Integer, String, Float, ForeignKey
from sqlalchemy.orm import declarative_base

Base = declarative_base()

class Expense(Base):
    __tablename__ = 'expenses'

    id = Column(Integer, primary_key=True)
    description = Column(String(200))
    amount = Column(Float)
    category_id = Column(Integer, ForeignKey('categories.id'))

Why this matters: You write Python. SQLAlchemy generates SQL. You don't write SQL by hand.

2. Sessions as Transactions (Unit of Work)

A session groups database operations into an atomic transaction:

with Session(engine) as session:
    new_expense = Expense(description="Groceries", amount=45.50, category_id=1)
    session.add(new_expense)
    session.commit()  # All or nothing

Why this matters: If anything fails, nothing is committed. Guarantees database consistency.

3. Relationships (Foreign Keys as Navigation)

Define relationships in Python instead of manual joins:

class Category(Base):
    __tablename__ = 'categories'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    expenses = relationship("Expense", back_populates="category")

class Expense(Base):
    __tablename__ = 'expenses'
    id = Column(Integer, primary_key=True)
    category = relationship("Category", back_populates="expenses")

Usage:

category = session.query(Category).first()
print(category.expenses)  # All expenses in this category

4. Queries (Filtering, Ordering, Joining)

Construct queries safely without writing raw SQL:

# Filter: expenses > $50
expensive = session.query(Expense).filter(Expense.amount > 50).all()

# Order: sorted by amount descending
sorted_expenses = session.query(Expense).order_by(Expense.amount.desc()).all()

# Join: expenses with their categories
results = session.query(Expense, Category).join(Category).all()

5. Neon Connection Specifics

Neon is serverless PostgreSQL with auto-scaling and branching. Key differences:

  • Connection string: postgresql+psycopg2://user:pass@host/dbname?sslmode=require
  • Always use SSL: ?sslmode=require (Neon enforces this)
  • Environment variables: Store credentials in .env (never hardcode)
  • Auto-pause: Neon pauses compute when idle—connection pools help with this

Decision Logic

ScenarioPatternWhy
First database modelSingle table, one Column typeSimplest mental model before relationships
Need to link dataUse relationship() + ForeignKeyORM handles complex joins for you
Many concurrent requestsConnection pooling with pool_sizeNeon scales compute; pooling maximizes it
Data consistency criticalTransactions with try/exceptRollback on error; guarantees atomicity
Want to scale to zeroNeon serverless + pool with echo_poolAuto-pause when idle; wake on first request
Debugging queriesEnable echo=True in engineSee generated SQL

Workflow: Building Budget Tracker

Step 1: Define Models

from sqlalchemy import create_engine, Column, Integer, String, Float, DateTime, ForeignKey, func
from sqlalchemy.orm import declarative_base, relationship, Session
from datetime import datetime

Base = declarative_base()

class Category(Base):
    __tablename__ = 'categories'
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True)
    expenses = relationship("Expense", back_populates="category")

class Expense(Base):
    __tablename__ = 'expenses'
    id = Column(Integer, primary_key=True)
    description = Column(String(200))
    amount = Column(Float)
    date = Column(DateTime, default=datetime.utcnow)
    category_id = Column(Integer, ForeignKey('categories.id'))
    category = relationship("Category", back_populates="expenses")

Step 2: Create Engine and Tables

import os
from dotenv import load_dotenv

load_dotenv()

# Connection string from environment
DATABASE_URL = os.getenv("DATABASE_URL")
# Format: postgresql+psycopg2://user:password@host/dbname?sslmode=require

engine = create_engine(DATABASE_URL)
Base.metadata.create_all(engine)

Step 3: Implement CRUD

def create_expense(session, description, amount, category_id):
    """Create a new expense."""
    try:
        expense = Expense(
            description=description,
            amount=amount,
            category_id=category_id
        )
        session.add(expense)
        session.commit()
        return expense
    except Exception as e:
        session.rollback()
        print(f"Error creating expense: {e}")
        return None

def read_expenses(session, category_id=None):
    """Read expenses, optionally filtered by category."""
    query = session.query(Expense)
    if category_id:
        query = query.filter(Expense.category_id == category_id)
    return query.all()

def update_expense(session, expense_id, amount=None, description=None):
    """Update an expense."""
    expense = session.query(Expense).filter(Expense.id == expense_id).first()
    if expense:
        if amount is not None:
            expense.amount = amount
        if description is not None:
            expense.description = description
        session.commit()
        return expense
    return None

def delete_expense(session, expense_id):
    """Delete an expense."""
    expense = session.query(Expense).filter(Expense.id == expense_id).first()
    if expense:
        session.delete(expense)
        session.commit()
        return True
    return False

Step 4: Query with Relationships

# Get all expenses for a category
category = session.query(Category).filter_by(name="Food").first()
print(category.expenses)  # Uses relationship

# Total spent by category
totals = session.query(
    Category.name,
    func.sum(Expense.amount).label('total')
).join(Expense).group_by(Category.name).all()

for name, total in totals:
    print(f"{name}: ${total:.2f}")

Step 5: Handle Transactions Safely

def transfer_expense(session, expense_id, new_category_id):
    """Move expense to different category (must succeed fully or not at all)."""
    try:
        expense = session.query(Expense).filter(Expense.id == expense_id).first()
        if not expense:
            raise ValueError(f"Expense {expense_id} not found")

        expense.category_id = new_category_id
        session.commit()
        return True
    except Exception as e:
        session.rollback()
        print(f"Transaction failed, rolled back: {e}")
        return False

Step 6: Connect to Neon

Environment file (.env):

DATABASE_URL=postgresql+psycopg2://user:password@ep-ABC123.neon.tech/dbname?sslmode=require

Connection with pool configuration:

from sqlalchemy.pool import QueuePool

engine = create_engine(
    DATABASE_URL,
    poolclass=QueuePool,
    pool_size=5,
    max_overflow=10,
    pool_pre_ping=True,  # Verify connections before use
    echo=False  # Set to True for debugging
)

MCP Integration

To connect SQLAlchemy database operations to AI agents:

# Define an MCP tool that the agent can use
def query_expenses_by_category(category_name: str) -> list:
    """Agent can ask: 'How much did I spend on groceries?'"""
    with Session(engine) as session:
        return session.query(Expense).join(Category).filter(
            Category.name == category_name
        ).all()

def summarize_spending(start_date, end_date) -> dict:
    """Agent can generate reports."""
    with Session(engine) as session:
        return session.query(
            Category.name,
            func.sum(Expense.amount).label('total'),
            func.count(Expense.id).label('count')
        ).join(Expense).filter(
            Expense.date.between(start_date, end_date)
        ).group_by(Category.name).all()

Register these as MCP tools so the agent (Budget Manager) can use them.


Safety & Guardrails

NEVER

  • ❌ Hardcode credentials in Python files
  • ❌ Skip error handling around transactions
  • ❌ Trust user input without validation
  • ❌ Commit secrets to git
  • ❌ Skip connection pooling for production

ALWAYS

  • ✅ Use environment variables for connection strings (.env file)
  • ✅ Wrap transactions in try/except blocks with rollback
  • ✅ Validate and sanitize all user input before database operations
  • ✅ Use session.commit() explicitly (never auto-commit)
  • ✅ Use session.rollback() on errors
  • ✅ Enable pool_pre_ping=True to check connection health
  • ✅ Use ?sslmode=require with Neon (enforced anyway)

Common Mistakes

MistakeImpactFix
Forgetting session.commit()Changes not savedAlways call commit() or use context manager
Not rolling back on errorPartial data in databaseWrap in try/except with rollback()
Hardcoding credentialsSecurity breachUse environment variables
No connection poolingNeon compute scaling inefficientSet pool_size parameter
Raw user input in queriesSQL injectionUse parameterized queries (ORM does this)

Budget Tracker Example (Complete)

See references/budget-tracker-complete.py for a fully working Budget Tracker application with:

  • Model definitions
  • Database setup
  • CRUD functions
  • Transaction handling
  • Neon connection
  • Example usage

Troubleshooting

ProblemCauseSolution
ModuleNotFoundError: No module named 'sqlalchemy'Not installedpip install sqlalchemy or uv add sqlalchemy
ModuleNotFoundError: No module named 'psycopg2'PostgreSQL driver missingpip install psycopg2-binary or uv add psycopg2-binary
OperationalError: could not connect to serverWrong connection string or Neon offlineCheck DATABASE_URL format, verify Neon project is running
IntegrityError: duplicate key valueInserting duplicate unique fieldCheck if value already exists, use update instead
ForeignKeyError: could not create foreign keyCategory doesn't existCreate category first, or use valid category_id
Queries are slowNo indexes, missing relationshipsCheck references/architecture.md for indexing patterns

Resources

平台分布

Codex

33.57%
按下载量换算126

Claude

29.2%
按下载量换算110

Cursor

18.85%
按下载量换算71

Gemini CLI

10.59%
按下载量换算40

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

接触敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills