← 返回 Skills 市场
samber

Golang Database

作者 Samuel Berthe · GitHub ↗ · v1.1.2 · MIT-0
cross-platform ✓ 安全检测通过
269
总下载
0
收藏
0
当前安装
3
版本数
在 OpenClaw 中安装
/install golang-database
功能描述
Comprehensive guide for Go database access. Covers parameterized queries, struct scanning, NULLable column handling, error patterns, transactions, isolation...
使用说明 (SKILL.md)

Persona: You are a Go backend engineer who writes safe, explicit, and observable database code. You treat SQL as a first-class language — no ORMs, no magic — and you catch data integrity issues at the boundary, not deep in the application.

Modes:

  • Write mode — generating new repository functions, query helpers, or transaction wrappers: follow the skill's sequential instructions; launch a background agent to grep for existing query patterns and naming conventions in the codebase before generating new code.
  • Review/debug mode — auditing or debugging existing database code: use a sub-agent to scan for missing rows.Close(), un-parameterized queries, missing context propagation, and absent error checks in parallel with reading the business logic.

Community default. A company skill that explicitly supersedes samber/cc-skills-golang@golang-database skill takes precedence.

Go Database Best Practices

Go's database/sql provides a solid foundation for database access. Use sqlx or pgx on top of it for ergonomics — never an ORM.

When using sqlx or pgx, refer to the library's official documentation and code examples for current API signatures.

Best Practices Summary

  1. Use sqlx or pgx, not ORMs — ORMs hide SQL, generate unpredictable queries, and make debugging harder
  2. Queries MUST use parameterized placeholders — NEVER concatenate user input into SQL strings
  3. Context MUST be passed to all database operations — use *Context method variants (QueryContext, ExecContext, GetContext)
  4. sql.ErrNoRows MUST be handled explicitly — distinguish "not found" from real errors using errors.Is
  5. Rows MUST be closed after iteration — defer rows.Close() immediately after QueryContext calls
  6. NEVER use db.Query for statements that don't return rows — Query returns *Rows which must be closed; if you forget, the connection leaks back to the pool. Use db.Exec instead
  7. Use transactions for multi-statement operations — wrap related writes in BeginTxx/Commit
  8. Use SELECT ... FOR UPDATE when reading data you intend to modify — prevents race conditions
  9. Set custom isolation levels when default READ COMMITTED is insufficient (e.g., serializable for financial operations)
  10. Handle NULLable columns with pointer fields (*string, *int) or sql.NullXxx types
  11. Connection pool MUST be configured — SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTime
  12. Use external tools for migrations — golang-migrate or Flyway, never hand-rolled or AI-generated migration SQL
  13. Batch operations in reasonable sizes — not row-by-row (too many round trips), not millions at once (locks and memory)
  14. Never create or modify database schemas — a schema that looks correct on toy data can create hotspots, lock contention, or missing indexes under real production load. Schema design requires understanding of data volumes, access patterns, and production constraints that AI does not have
  15. Avoid hidden SQL features — do not rely on triggers, views, materialized views, stored procedures, or row-level security in application code

Library Choice

Library Best for Struct scanning PostgreSQL-specific
database/sql Portability, minimal deps Manual Scan No
sqlx Multi-database projects StructScan No
pgx PostgreSQL (30-50% faster) pgx.RowToStructByName Yes (COPY, LISTEN, arrays)
GORM/ent Avoid Magic Abstracted away

Why NOT ORMs:

  • Unpredictable query generation — N+1 problems you cannot see in code
  • Magic hooks and callbacks (BeforeCreate, AfterUpdate) make debugging harder
  • Schema migrations coupled to application code
  • Learning the ORM API is harder than learning SQL, and the abstraction leaks

Parameterized Queries

// ✗ VERY BAD — SQL injection vulnerability
query := fmt.Sprintf("SELECT * FROM users WHERE email = '%s'", email)

// ✓ Good — parameterized (PostgreSQL)
var user User
err := db.GetContext(ctx, &user, "SELECT id, name, email FROM users WHERE email = $1", email)

// ✓ Good — parameterized (MySQL)
err := db.GetContext(ctx, &user, "SELECT id, name, email FROM users WHERE email = ?", email)

Dynamic IN clauses

query, args, err := sqlx.In("SELECT * FROM users WHERE id IN (?)", ids)
if err != nil {
    return fmt.Errorf("building IN clause: %w", err)
}
query = db.Rebind(query) // adjust placeholders for your driver
err = db.SelectContext(ctx, &users, query, args...)

Dynamic column names

Never interpolate column names from user input. Use an allowlist:

allowed := map[string]bool{"name": true, "email": true, "created_at": true}
if !allowed[sortCol] {
    return fmt.Errorf("invalid sort column: %s", sortCol)
}
query := fmt.Sprintf("SELECT id, name, email FROM users ORDER BY %s", sortCol)

For more injection prevention patterns, see the samber/cc-skills-golang@golang-security skill.

Struct Scanning and NULLable Columns

Use db:"column_name" tags for sqlx, pgx.CollectRows with pgx.RowToStructByName for pgx. Handle NULLable columns with pointer fields (*string, *time.Time) — they work cleanly with both scanning and JSON marshaling. See Scanning Reference for examples of all approaches.

Error Handling

func GetUser(id string) (*User, error) {
    var user User

    err := db.GetContext(ctx, &user, "SELECT id, name FROM users WHERE id = $1", id)
    if err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, ErrUserNotFound // translate to domain error
        }
        return nil, fmt.Errorf("querying user %s: %w", id, err)
    }

    return &user, nil
}

or:

func GetUser(id string) (u *User, exists bool, err error) {
    var user User

    err := db.GetContext(ctx, &user, "SELECT id, name FROM users WHERE id = $1", id)
    if err != nil {
        if errors.Is(err, sql.ErrNoRows) {
            return nil, false, nil // "no user" is not a technical error, but a domain error
        }
        return nil, false, fmt.Errorf("querying user %s: %w", id, err)
    }

    return &user, true, nil
}

Always close rows

rows, err := db.QueryContext(ctx, "SELECT id, name FROM users")
if err != nil {
    return fmt.Errorf("querying users: %w", err)
}
defer rows.Close() // prevents connection leaks

for rows.Next() {
    // ...
}
if err := rows.Err(); err != nil { // always check after iteration
    return fmt.Errorf("iterating users: %w", err)
}

Common database error patterns

Error How to detect Action
Row not found errors.Is(err, sql.ErrNoRows) Return domain error
Unique constraint Check driver-specific error code Return conflict error
Connection refused err != nil on db.PingContext Fail fast, log, retry with backoff
Serialization failure PostgreSQL error code 40001 Retry the entire transaction
Context canceled errors.Is(err, context.Canceled) Stop processing, propagate

Context Propagation

Always use the *Context method variants to propagate deadlines and cancellation:

// ✗ Bad — no context, query runs until completion even if client disconnects
db.Query("SELECT ...")

// ✓ Good — respects context cancellation and timeouts
db.QueryContext(ctx, "SELECT ...")

For context patterns in depth, see the samber/cc-skills-golang@golang-context skill.

Transactions, Isolation Levels, and Locking

For transaction patterns, isolation levels, SELECT FOR UPDATE, and locking variants, see Transactions.

Connection Pool

db.SetMaxOpenConns(25)              // limit total connections
db.SetMaxIdleConns(10)              // keep warm connections ready
db.SetConnMaxLifetime(5 * time.Minute)  // recycle stale connections
db.SetConnMaxIdleTime(1 * time.Minute)  // close idle connections faster

For sizing guidance and formulas, see Database Performance.

Migrations

Use an external migration tool. Schema changes require human review with understanding of data volumes, existing indexes, foreign keys, and production constraints.

Recommended tools:

  • golang-migrate — CLI + Go library, supports all major databases
  • Flyway — JVM-based, widely used in enterprise environments
  • Atlas — modern, declarative schema management

Migration SQL should be written and reviewed by humans, versioned in source control, and applied through CI/CD pipelines.

Avoid Hidden SQL Features

Do not rely on triggers, views, materialized views, stored procedures, or row-level security in application code — they create invisible side effects and make debugging impossible. Keep SQL explicit and visible in Go where it can be tested and version-controlled.

Schema Creation

This skill does NOT cover schema creation. AI-generated schemas are often subtly wrong — missing indexes, incorrect column types, bad normalization, or missing constraints. Schema design requires understanding data volumes, access patterns, query profiles, and business constraints. Use dedicated database tooling and human review.

Deep Dives

  • Transactions — Transaction boundaries, isolation levels, deadlock prevention, SELECT FOR UPDATE
  • Testing Database Code — Mock connections, integration tests with containers, fixtures, schema setup/teardown
  • Database Performance — Connection pool sizing, batch processing, indexing strategy, query optimization
  • Struct Scanning — Struct tags, NULLable column handling, JSON marshaling patterns

Cross-References

  • → See samber/cc-skills-golang@golang-security skill for SQL injection prevention patterns
  • → See samber/cc-skills-golang@golang-context skill for context propagation to database operations
  • → See samber/cc-skills-golang@golang-error-handling skill for database error wrapping patterns
  • → See samber/cc-skills-golang@golang-testing skill for database integration test patterns

References

安全使用建议
This skill appears to do what it says: a best-practices guide for Go database code that only needs the Go toolchain. Before enabling it, consider: (1) the skill instructs agents to scan your repository (grep/analysis) — if you want to limit automatic scanning, control when the skill is invoked; (2) example code references TEST_DATABASE_URL and other integration/test patterns — do not run examples against production databases; (3) always review generated code or suggestions before committing (examples are opinionated: prefers sqlx/pgx and pointer-based nullable handling). If you need stricter control, disable autonomous invocation or review the skill's SKILL.md in your environment first.
功能分析
Type: OpenClaw Skill Name: golang-database Version: 1.1.2 The golang-database skill bundle is a comprehensive guide for writing secure and efficient Go database code. It explicitly prioritizes security by mandating parameterized queries to prevent SQL injection and provides detailed instructions on resource management, such as closing database rows and propagating contexts. The SKILL.md and reference files (e.g., transactions.md, testing.md) contain standard engineering best practices without any evidence of malicious intent, data exfiltration, or harmful prompt injection.
能力评估
Purpose & Capability
The name/description (Go DB best practices) matches the contents and required binary (go). Examples and references are about sqlx/pgx/database/sql and testing; there are no unrelated environment variables, binaries, or install steps requested.
Instruction Scope
SKILL.md is prescriptive about code patterns (parameterized queries, context propagation, transaction patterns, connection pools) and explicitly refuses schema/migration generation. It also instructs agents to launch background/sub-agents to grep and scan the codebase for patterns (rows.Close, unparameterized queries). That behavior is appropriate for a code-review/code-generation helper but does grant the agent broad read access to the repository and the ability to run analysis tooling — reviewers should be aware the skill will examine project files when invoked.
Install Mechanism
Instruction-only skill with no install spec and no downloads. This minimizes disk writes and arbitrary code execution risk.
Credentials
The skill declares no required env vars or credentials. Example/test snippets mention TEST_DATABASE_URL and references to Prometheus collectors (example code), but these are illustrative and not requested as required secrets by the skill itself.
Persistence & Privilege
always:false (no forced inclusion). The skill may be invoked autonomously by agents (platform default), but it does not request elevated persistent privileges or modify other skills' configs.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install golang-database
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /golang-database 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.1.2
- Version bumped to 1.1.2. - Added `AskUserQuestion` to the `allowed-tools` in metadata, enabling interactive prompts. - Updated the metadata version to reflect the new release. - No changes made to the instructions or best practices content.
v1.1.1
- Updated version to 1.1.1 and metadata accordingly. - Minor formatting changes: normalized whitespace and added quotes to the description field in SKILL.md. - No changes to technical content or behavior.
v1.1.0
golang-database v1.1.0 - Expanded documentation to comprehensively cover parameterized queries, struct scanning, NULLable handling, error patterns, transactions, isolation levels, SELECT FOR UPDATE, connection pooling, batch processing, context propagation, and migration tools. - Clarified library choices (`database/sql`, `sqlx`, `pgx`), and strongly advised against ORMs. - Added explicit step-by-step best practices for working with Go and major SQL databases. - Introduced clear instructions for safe use of dynamic SQL elements (IN clauses, column names). - Updated skill persona and operation modes for writing, reviewing, or debugging database code. - Enforced that this skill does not generate database schemas or migration SQL, and restricts schema modifications to external tools only.
元数据
Slug golang-database
版本 1.1.2
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 3
常见问题

Golang Database 是什么?

Comprehensive guide for Go database access. Covers parameterized queries, struct scanning, NULLable column handling, error patterns, transactions, isolation... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 269 次。

如何安装 Golang Database?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install golang-database」即可一键安装,无需额外配置。

Golang Database 是免费的吗?

是的,Golang Database 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Golang Database 支持哪些平台?

Golang Database 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Golang Database?

由 Samuel Berthe(@samber)开发并维护,当前版本 v1.1.2。

💬 留言讨论