golang-database
Skill3.4k starsChanged 2 months agoMITView on GitHub
Comprehensive guide for Go database access — parameterized queries, struct scanning, NULLable columns, transactions, isolation levels, SELECT FOR UPDATE, connection pool, batch processing, context propagation, and migration tooling. Use when writing, reviewing, or debugging Golang code that interacts with PostgreSQL, MariaDB, MySQL, or SQLite; for database testing; or for questions about database/sql, sqlx, or pgx. Does NOT generate database schemas or migration SQL.
- Installs packages
4 other projects use a version of this, 2 of them edited.
Trending
Quiet since October.about the whole repository
Most recently taken up by
- rzisso/golang-skillsword for word, first seen Sep 16, 2026
- jkeddari/go-skillstheir own version, first seen Jul 19, 2026
- alexastrum/skledited, first seen Jun 12, 2026
- guynhsichngeodiec/cc-skills-golangedited, first seen Apr 7, 2026
Who's talking about samber/cc-skills-golang
- @golangch.bsky.social“A collection of Golang agentic skills that works #golang github.com/samber/cc-s...”Bluesky · Jul 16, 2026 · 10 likes
- @samber.bsky.social“My Go skill set: github.com/samber/cc-skills-golang npx skills add samber/cc-skills-golang Open to …”Bluesky · Mar 23, 2026 · 6 likes
- LobsterTrap/lola“[FEATURE] - Cherry Pick Skills”GitHub · May 6, 2026 · 3 reactions
- @golangch.bsky.social“Claude Code Skills for production-ready Golang projects #golang github.com/samber/cc-s...”Bluesky · Mar 29, 2026 · 3 likes
- A Hacker News story“A collection of 35 Golang Agent Skills”Hacker News · Mar 23, 2026 · 3 points
The biggest 5 of 45 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 45
Talked about on GitHub, Bluesky and Hacker News (45 times).
On GitHub · 41
- May 6, 2026[FEATURE] - Cherry Pick Skills — LobsterTrap/lola3 reactions · 1 comment
- Jul 16, 2026Skills with nested metadata maps are silently dropped during discovery — charmbracelet/crush1 reaction
- Mar 30, 2026[SUBMISSION] cc-skills-golang — ProSkillsMD/proskills1 reaction · 1 comment
- Oct 4, 2026claude-code-plugins.github.samber.cc-skills-golang: init at 2.0.0 — sudosubin/agents.nix0 reactions
- Oct 1, 2026agent-skills.github.samber.cc-skills-golang: init at 2.0.0 — sudosubin/agents.nix0 reactions
36 more on GitHub
- Sep 23, 2026Update skill: /samber-golang-structs-interfaces (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-spf13-viper (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-benchmark (medium risk) — aiskillstore/marketplacesays it tested it0 reactions
- Sep 23, 2026Update skill: /samber-golang-pkg-go-dev (high risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-samber-ro (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-uber-fx (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-stretchr-testify (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-swagger (safe risk) — aiskillstore/marketplace0 reactions
- Sep 23, 2026Update skill: /samber-golang-stay-updated (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-spf13-cobra (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-cli (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-lint (medium risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-samber-slog (medium risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-modernize (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-samber-lo (safe risk) — aiskillstore/marketplace0 reactions
- Sep 6, 2026Update skill: /samber-golang-documentation (safe risk) — aiskillstore/marketplace0 reactions
- Sep 5, 2026corpus tier3 cites an id with no path: the largest source's provenance handle cannot be followed — jonhill90/agent-estate0 reactions · 1 comment
- Sep 3, 2026chore: sync upstream skills (auto) — marcioaltoe/skills0 reactions
- Sep 2, 2026chore: sync upstream skills (auto) — marcioaltoe/skills0 reactions
- Aug 19, 2026add `samber` golang skills — greenbone/opensight-golang-libraries0 reactions · 4 comments
- Jul 17, 2026fix: import skills with nested metadata and surface parse errors — gridctl/gridctl0 reactions
- Jul 17, 2026fix: skill import fails on nested metadata frontmatter with misleading 'no SKILL.md files found' error — gridctl/gridctl0 reactions
- Jul 16, 2026chore: sync upstream skills — marcioaltoe/skills0 reactions
- Jul 3, 2026New skill: /samber-golang-performance (safe risk) — aiskillstore/marketplace0 reactions
- Jul 1, 2026New skill: /samber-golang-error-handling (low risk) — aiskillstore/marketplace0 reactions
- Jul 1, 2026New skill: /samber-golang-code-style (low risk) — aiskillstore/marketplace0 reactions
- Jun 26, 2026Integrate samber/cc-skills-golang: install full general-purpose set + full-list reminder at plan & each scenario — ArcadeAI/safeword0 reactions · 3 comments
- Jun 26, 2026[FEATURE] Add Golang skills selectively — inference-gateway/cli0 reactions
- Jun 24, 2026chore(skills): sync upstream skills — marcioaltoe/skills0 reactions
- Jun 7, 2026feature/naming-linting-testing-skills — joekhosbayar/go-mightysays it tested it0 reactions
- May 22, 2026🔐 ci: pin + sandbox the skills install in claude-review.yml — martinciu/ccpulse0 reactions
- May 21, 2026🔐 ci: pin or sandbox the unpinned npx skills install in claude-review.yml — martinciu/ccpulse0 reactions · 1 comment
- Apr 25, 2026Audit candidate: samber/cc-skills-golang — xiaolai/nlpm0 reactions · 3 comments
- Mar 30, 2026[Resource]: cc-skills-golang — hesreallyhim/awesome-claude-code0 reactions · 1 comment
- Mar 29, 2026golang skills — sushichan044/dotfiles0 reactions
- Mar 22, 2026Add a claude code skills for Golang — jqueryscript/awesome-claude-code0 reactions
On Bluesky · 3
- Jul 16, 2026A collection of Golang agentic skills that works #golang github.com/samber/cc-s... — @golangch.bsky.social10 likes and reposts
- Mar 23, 2026My Go skill set: github.com/samber/cc-skills-golang npx skills add samber/cc-skills-golang Open to contributions. If you're building skills… — @samber.bsky.social6 likes and reposts
- Mar 29, 2026Claude Code Skills for production-ready Golang projects #golang github.com/samber/cc-s... — @golangch.bsky.social3 likes and reposts · 1 reply
On Hacker News · 1
- Mar 23, 2026A collection of 35 Golang Agent Skills3 points · 2 comments
Other versions4 projects use a version of this.
Word for word · 1
- rzisso/golang-skills★ 0100% same
Edited · 2
- alexastrum/skl★ 1099% same
- guynhsichngeodiec/cc-skills-golang★ 096% same
Wrote their own version · 1
- jkeddari/go-skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository46 other files it gives its agents.
- CLAUDE.mdCLAUDE.md
- golang-benchmarkSkill
- golang-cliSkill
- golang-code-styleSkill
- golang-concurrencySkill
- golang-contextSkill
- golang-continuous-integrationSkill
- golang-data-structuresSkill
- golang-dependency-injectionSkill
- golang-dependency-managementSkill
- golang-design-patternsSkill
- golang-documentationSkill
- golang-error-handlingSkill
- golang-google-wireSkill
- golang-goplsSkill
- golang-graphqlSkill
- golang-grpcSkill
- golang-how-toSkill
- golang-lintSkill
- golang-modernizeSkill
- golang-namingSkill
- golang-observabilitySkill
- golang-performanceSkill
- golang-pkg-go-devSkill
- golang-popular-librariesSkill
- golang-project-layoutSkill
- golang-refactoringSkill
- golang-safetySkill
- golang-samber-doSkill
- golang-samber-hotSkill
- golang-samber-loSkill
- golang-samber-moSkill
- golang-samber-oopsSkill
- golang-samber-roSkill
- golang-samber-slogSkill
- golang-securitySkill
- golang-spf13-cobraSkill
- golang-spf13-viperSkill
- golang-stay-updatedSkill
- golang-stretchr-testifySkill
- golang-structs-interfacesSkill
- golang-swaggerSkill
- golang-testingSkill
- golang-troubleshootingSkill
- golang-uber-digSkill
- golang-uber-fxSkill
The file
We split this skill into the rules it gives an agent
9 rules. 5 are common, 0 are distinctive, and 4 are very specific to this project.
5
Common
Most of the 3 edited versions we read keep these.
0
Distinctive
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Common: line 35
When using sqlx or pgx, refer to the library's official documentation and code examples for current API signatures.
- Very specific: line 44
NEVER use db.Query for statements that don't return rows — Query returns *Rows which must be closed.
- Very specific: line 46
Use
SELECT ... FOR UPDATE: when reading data you intend to modify — prevents race conditions - Common: line 47
Set custom isolation levels: when default READ COMMITTED is insufficient (e.g., serializable for financial operations)
- Common: line 98
Never interpolate column names from user input.
- Very specific: line 112
Use db:"column_name" tags for sqlx, pgx.CollectRows with pgx.RowToStructByName for pgx.
- Very specific: line 179
Always use the *Context method variants to propagate deadlines and cancellation:
- Common: line 208
Use an external migration tool.
- Common: line 220
Do not rely on triggers, views, materialized views, stored procedures, or row-level security in application code — they create invisible …
“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
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-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-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 fasterFor 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-securityskill for SQL injection prevention patterns - → See
samber/cc-skills-golang@golang-contextskill for context propagation to database operations - → See
samber/cc-skills-golang@golang-error-handlingskill for database error wrapping patterns - → See
samber/cc-skills-golang@golang-testingskill for database integration test patterns
References
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

