Golang Database
This AI agent writes and audits Go database code using raw SQL (no ORMs), generating repository functions and transaction wrappers by first scanning the codebase for existing patterns, or debugging code by checking for missing `rows.Close()`, unparameterized queries, and absent context propagation.
How to Install
git clone --depth 1 https://github.com/samber/cc-skills-golang.git && cp cc-skills-golang/skills/golang-database ~/.claude/skills/SKILL.md -rPersona: 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-databaseskill 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
- Use sqlx or pgx, not ORMs — ORMs hide SQL, generate unpredictable queries, and make debugging harder
- Queries MUST use parameterized placeholders — NEVER concatenate user input into SQL strings
- Context MUST be passed to all database operations — use
*Contextmethod variants (QueryContext,ExecContext,GetContext) sql.ErrNoRowsMUST be handled explicitly — distinguish "not found" from real errors usingerrors.Is- Rows MUST be closed after iteration —
defer rows.Close()immediately afterQueryContextcalls - NEVER use
db.Queryfor statements that don't return rows —Queryreturns*Rowswhich must be closed; if you forget, the connection leaks back to the pool. Usedb.Execinstead - Use transactions for multi-statement operations — wrap related writes in
BeginTxx/Commit - Use
SELECT ... FOR UPDATEwhen reading data you intend to modify — prevents race conditions - Set custom isolation levels when default READ COMMITTED is insufficient (e.g., serializable for financial operations)
- Handle NULLable columns with pointer fields (
*string,*int) orsql.NullXxxtypes - Connection pool MUST be configured —
SetMaxOpenConns,SetMaxIdleConns,SetConnMaxLifetime,SetConnMaxIdleTime - Use external tools for migrations — golang-migrate or Flyway, never hand-rolled or AI-generated migration SQL
- Batch operations in reasonable sizes — not row-by-row (too many round trips), not millions at once (locks and memory)
- 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
- 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-se
Details
| Category | Coding → generation |
| Source | samber/cc-skills-golang |
| SKILL.md | View on GitHub → |
| Repo Stars | ★ 2.3K |
| Est. per Skill | 51 (shared across 44 skills from this repo) |
| Difficulty | Intermediate |
| Risk Level | N/A |
Related Skills
Works Well With
Skills from the same repository — often designed to work together