Skills Agentes

Golang Database

Guía completa para acceso a bases de datos en Go: queries parametrizadas, scanning de structs, columnas NULLable, transacciones, aislamiento, connection pool y migraciones. No genera esquemas ni SQL de migración.

Reemplaza a: GORM/ent y otros ORMs

Solicitaread edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent askuserquestion
Estrellas
3k

en todo el repo

Actividad
49

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
3

últimos 90 días

Contexto
2.9k tok

118 tok en reposo

Paquete
6 archivos

44 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add samber/cc-skills-golang --skill golang-database --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Aplica queries parametrizadas, propagación de context y manejo explícito de sql.ErrNoRows en código Go de base de datos
  • Revisa o genera transacciones, niveles de aislamiento y SELECT FOR UPDATE
  • Configura el connection pool (SetMaxOpenConns, SetMaxIdleConns, etc.)
  • Audita código existente en busca de rows.Close() faltantes o queries sin parametrizar
  • Recomienda sqlx o pgx en lugar de ORMs para struct scanning y columnas NULLable

Úsalo cuando

  • Al escribir, revisar o depurar código Golang que interactúa con PostgreSQL, MariaDB, MySQL o SQLite
  • Para testing de base de datos
  • Para preguntas sobre database/sql, sqlx o pgx

No lo uses cuando

  • No genera esquemas de base de datos ni SQL de migraciones

Qué lo activa

Di cualquiera de estas frases y el agente debería cargar este skill.

  • Revisa este código Go que consulta PostgreSQL con sqlx
  • Ayúdame a escribir una transacción con SELECT FOR UPDATE en Go
  • ¿Cómo configuro el connection pool con pgx?
  • Detecta fugas de conexión por rows.Close() faltante en este archivo

SKILL.md

En inglés

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

Reproducido de samber/cc-skills-golang bajo licencia MIT. Leer esta página en markdown.

Archivos

6 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

Antes de instalar

Requiere el binario go y un proyecto Golang.

Detalles

Creador
samber
Categoría
Bases de datos
Licencia
MIT
Recursos incluidos
referencias
Código fuente
Ver SKILL.md

Etiquetas

Más de samber/cc-skills-golang

Este repo incluye 46 skills. Si instalas uno, normalmente ya tienes los demás.

Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters.

Costo de contexto al activarse
1.8k tok
Tamaño del paquete
5 archivos
Última actualización
hace 3 días
herramientas desarrollo

Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

Costo de contexto al activarse
3.3k tok
Tamaño del paquete
10 archivos
Última actualización
hace 28 días
testing qa

Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez.

Costo de contexto al activarse
3.8k tok
Tamaño del paquete
4 archivos
Última actualización
hace 20 días
herramientas desarrollo

Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
9 archivos
Última actualización
el mes pasado
herramientas desarrollo

Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración.

Costo de contexto al activarse
4.4k tok
Tamaño del paquete
6 archivos
Última actualización
el mes pasado
testing qa

Inyección de dependencias en Golang con samber/do: contenedores de servicios, gestión de ciclo de vida, scopes, health checks, apagado ordenado y organización en módulos.

Costo de contexto al activarse
2.3k tok
Tamaño del paquete
4 archivos
Última actualización
hace 22 días
herramientas desarrollo

Skills relacionados

Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

Costo de contexto al activarse
3.3k tok
Tamaño del paquete
10 archivos
Última actualización
hace 28 días
testing qa

Desarrollo de aplicaciones CLI en Go: estructura de comandos, flags, configuración por capas, versión embebida, exit codes, señales, completions y testing con cobra, viper o urfave/cli.

Costo de contexto al activarse
2.6k tok
Tamaño del paquete
14 archivos
Última actualización
hace 3 meses
herramientas desarrollo

Convenciones de estilo en Golang: longitud y corte de líneas, declaración de variables, claridad del control de flujo y cuándo los comentarios ayudan u estorban.

Costo de contexto al activarse
2.5k tok
Tamaño del paquete
3 archivos
Última actualización
el mes pasado
herramientas desarrollo