# Golang Database

> Standards for database interaction, connection pooling, and repository patterns in Golang. Use when implementing database access, connection pools, or repositories in Go. (triggers: internal/adapter/repository/**, database, sql, postgres, gorm, sqlc, pgx)

- Skill: `hoangnguyen0403/golang-database-2` (Agent Skill)
- Install (CLI): `npx skillmds@latest add hoangnguyen0403/golang-database-2`
- Raw SKILL.md: https://api.skillmd.com/api/skills/hoangnguyen0403/golang-database-2/raw
- Safety review: pending (external: skill-scanner PASS, skillspector PASS)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Data & Analytics
- Author: HoangNguyen0403 (https://skillmd.com/u/hoangnguyen0403)
- Updated: 2026-09-09
- Page: https://skillmd.com/skills/hoangnguyen0403/golang-database-2

---


# Golang Database Standards

## **Priority: P0 (CRITICAL)**

## Principles

- **Prefer Raw SQL/Builders over ORMs**: Go structs map well to SQL. ORMs (GORM) can obscure performance. Recommended: `sqlc` (type-safe SQL generation).
- **Repository Pattern**: Abstract DB access behind interfaces in `internal/port/` (e.g., `UserRepository`).
- **Connection Pooling**: Always configure `SetMaxOpenConns`, `SetMaxIdleConns`, `SetConnMaxLifetime`.
- **Transactions**: Logic requiring ACID MUST use transactions. Pass `context.Context` everywhere.

## Drivers

- **PostgreSQL**: `jackc/pgx` (Prefer `pgx/v5` for performance and features).
- **MySQL**: `go-sql-driver/mysql`.
- **SQLite**: `mattn/go-sqlite3` or `modernc.org/sqlite` (pure Go).

## Anti-Patterns

- **No global db var**: Inject DB connection via constructor; never use `var db *sql.DB`.
- **No bare queries**: Use `QueryContext`/`ExecContext`; bare queries ignore context timeouts.
- **No leaked rows**: Always `defer rows.Close()` and check `rows.Err()` after iteration.

## References

- [Repository Pattern Implementation](references/repository-pattern.md)
- [Connection Tuning](references/connection-tuning.md)


