SKILL·5878CD

go-database

eduardo-sl
更新于 8 days ago
64
9
64
在 GitHub 上查看
designdata

关于

This Claude Skill provides Go developers with database implementation patterns including connection management, transactions, migrations, and ORM usage (sqlc/GORM/ent). Use it for database access, SQL queries, prepared statements, and repository patterns in Go services. It specifically excludes in-memory structures, SQL security, and query performance profiling which are covered by other skills.

快速安装

Claude Code

推荐
主要方式
npx skills add eduardo-sl/go-agent-skills -a claude-code
插件命令备选方式
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 克隆备选方式
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-database

在 Claude Code 中复制并粘贴此命令以安装该技能

技能文档

Go Database Patterns

Database access is where most Go services spend their complexity budget. Get connection management, transactions, and query patterns right.

Detailed reference material, loaded on demand:

  • references/query-patterns.md — full query/scan/rows patterns, null handling, N+1 avoidance, connection-leak examples.
  • references/tooling.md — repository pattern implementation, sqlc annotated queries, migration tooling and rules.

Read a reference file only when the summary below is not enough.

1. Connection Management

Configure the pool explicitly — the default is unbounded connections:

func OpenDB(dsn string) (*sql.DB, error) {
    db, err := sql.Open("postgres", dsn)
    if err != nil {
        return nil, fmt.Errorf("open db: %w", err)
    }

    db.SetMaxOpenConns(25)
    db.SetMaxIdleConns(10)
    db.SetConnMaxLifetime(5 * time.Minute)
    db.SetConnMaxIdleTime(1 * time.Minute)

    if err := db.PingContext(context.Background()); err != nil {
        return nil, fmt.Errorf("ping db: %w", err)
    }

    return db, nil
}
SettingGuideline
MaxOpenConnsMatch your DB's max connections / number of app instances
MaxIdleConns40-50% of MaxOpenConns
ConnMaxLifetime5-10 minutes (prevents stale connections behind load balancers)
ConnMaxIdleTime1-2 minutes

2. Query Rules

  1. Parameterized queries only — string concatenation into SQL is an injection vulnerability, no exceptions.
  2. Always pass context — use the *Context variants (QueryContext, QueryRowContext, ExecContext) so queries respect cancellation and timeouts.
  3. defer rows.Close() immediately after the error check, and check rows.Err() after the iteration loop.
  4. Handle sql.ErrNoRows explicitly with errors.Is, mapping it to a domain error like ErrUserNotFound.
var user User
err := db.QueryRowContext(ctx,
    "SELECT id, name, email FROM users WHERE id = $1", id,
).Scan(&user.ID, &user.Name, &user.Email)

if errors.Is(err, sql.ErrNoRows) {
    return nil, ErrUserNotFound
}
if err != nil {
    return nil, fmt.Errorf("get user %s: %w", id, err)
}

Multi-row iteration patterns: references/query-patterns.md.

3. Transactions

Use a helper that guarantees rollback on error:

func WithTx(ctx context.Context, db *sql.DB, fn func(tx *sql.Tx) error) error {
    tx, err := db.BeginTx(ctx, nil)
    if err != nil {
        return fmt.Errorf("begin tx: %w", err)
    }

    if err := fn(tx); err != nil {
        if rbErr := tx.Rollback(); rbErr != nil {
            return fmt.Errorf("rollback failed: %v (original: %w)", rbErr, err)
        }
        return err
    }

    if err := tx.Commit(); err != nil {
        return fmt.Errorf("commit tx: %w", err)
    }
    return nil
}

Set isolation explicitly for critical operations: sql.TxOptions{Isolation: sql.LevelSerializable}.

4. Structure and Tooling

  • Repository pattern: define the interface at the consumer side, implement it with concrete database access, map driver errors to domain errors at this boundary.
  • sqlc: prefer it for raw-SQL projects — generates type-safe Go from annotated SQL, catching query/schema mismatches at build time.
  • Migrations: use a tool (goose, golang-migrate, atlas), one migration per change, forward-only in production, with down SQL, run as a separate step — not at server startup.

Implementations and examples: references/tooling.md.

5. Common Pitfalls

  • Null columns: use sql.NullString/sql.NullInt64 or pointer fields (*string, nil = SQL NULL). Scanning NULL into a plain string errors at runtime.
  • N+1 queries: a query inside a loop over query results. Replace with a JOIN or a batch query (WHERE id = ANY($1)).
  • Connection leaks: any early return between Query and defer rows.Close() leaks a connection from the pool.

Worked examples of each pitfall: references/query-patterns.md.

Verification Checklist

  1. Connection pool configured with explicit limits (MaxOpenConns, MaxIdleConns, lifetimes)
  2. All queries use parameterized placeholders, never string concatenation
  3. All QueryContext results have defer rows.Close() immediately after error check
  4. rows.Err() checked after row iteration loop
  5. sql.ErrNoRows handled explicitly with errors.Is
  6. Transactions use a helper that guarantees rollback on error
  7. Context propagated to all database calls (*Context variants)
  8. Nullable columns use sql.NullString / sql.NullInt64 or pointer types
  9. No N+1 query patterns — use JOINs or batch queries
  10. Migrations are versioned, reversible, and run separately from app startup

GitHub 仓库

eduardo-sl/go-agent-skills
路径: skills/(data)/go-database
0
FAQ

常见问题

什么是 go-database Skill?

go-database 是一个 Claude Skill,作者为 eduardo-sl。Skill 将 Claude 按需加载的说明和资源打包,让 Claude 无需额外提示即可执行与 go-database 相关的任务。

如何安装 go-database?

使用本页的安装命令:将 go-database 作为插件添加到 Claude Code,或将其仓库克隆到 skills 目录,然后重启 Claude 以加载该 Skill。

go-database 属于哪个分类?

go-database 属于元分类。

go-database 可以免费使用吗?

可以。go-database 已收录在 AIMCP,可免费安装。

相关推荐技能

content-collections

Content Collections 是一个 TypeScript 优先的构建工具,可将本地 Markdown/MDX 文件转换为类型安全的数据集合。它专为构建博客、文档站和内容密集型 Vite+React 应用而设计,提供基于 Zod 的自动模式验证。该工具涵盖从 Vite 插件配置、MDX 编译到生产环境部署的完整工作流。

查看技能
polymarket

这个Claude Skill为开发者提供完整的Polymarket预测市场开发支持,涵盖API调用、交易执行和市场数据分析。关键特性包括实时WebSocket数据流,可监控实时交易、订单和市场动态。开发者可用它构建预测市场应用、实施交易策略并集成实时市场预测功能。

查看技能
creating-opencode-plugins

该Skill帮助开发者创建OpenCode插件,用于接入命令、文件、LSP等25+种事件。它提供了插件结构、事件API规范和JavaScript/TypeScript实现模式,适合需要拦截操作、扩展功能或自定义事件处理的场景。开发者可通过它快速构建响应式模块来增强OpenCode AI助手的能力。

查看技能
sglang

SGLang是一个专为LLM设计的高性能推理框架,特别适用于需要结构化输出的场景。它通过RadixAttention前缀缓存技术,在处理JSON、正则表达式、工具调用等具有重复前缀的复杂工作流时,能实现极速生成。如果你正在构建智能体或多轮对话系统,并追求远超vLLM的推理性能,SGLang是理想选择。

查看技能