golang-database
CLAWHUB · Unverified
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.
- 62
- Rank
- 84
- Safety
- 1.5k
- Downloads
About
What it does, and when to use it.
Capability contract not published. No trust telemetry is available yet. 1.5K downloads reported by the source. Last updated 10/10/2026.
Avoid when
- Contract metadata is missing or unavailable for deterministic execution.
Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing
Public facts
Every fact links back to the source it came from.
- Vendor
- Clawhubvendor · Oct 10, 2026
- Protocol compatibility
- OpenClawcompatibility · Oct 10, 2026
- Adoption signal
- 1.5K downloadsadoption · Oct 10, 2026
- Latest release
- 1.3.0release · Aug 20, 2026
- Handshake status
- UNKNOWNsecurity
What changed
Newest first. Only changes that point at a source are listed.
Release 1.3.0release
golang-database v1.3.0 - Added explicit path scoping to only apply to Go (*.go) files. - Updated compatibility metadata to include Codex and similar harnesses. - Changed homepage emoji from "🗄️" to "🗄". - Removed the skill-card.md file for a cleaner skill package.
Observed Aug 20, 2026 · source
Install and run
Setup complexity: low.
clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-database- Install using `clawhub skill install s173arkhs3131fq5jf769qq75583hdgt:golang-database` in an isolated environment before connecting it to live workloads.
- No published capability contract is available yet, so validate auth and request/response behavior manually.
- Review the upstream CLAWHUB listing at https://clawhub.ai/samber/golang-database before using production credentials.
Contract: missing
curl -s "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-database/snapshot"
Run-check
$0.02 USD1 measured facts are behind this paywall: success rate and latency, uptime and estimated cost, when not to use it, how to call it, benchmark scores.
Agents pay $0.02 in USDC. A card payment is $0.50, the smallest a card allows.
Documentation
CLAWHUB
144,579 characters of source documentation, loaded on request.
Extracted files
5 files captured from the source.
SKILL.md
---
name: golang-database
description: "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."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
author: samber
version: "1.3.0"
openclaw:
emoji: "🗄"
homepage: https://github.com/samber/cc-skills-golang
requires:
bins:
- go
install: []
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent AskUserQuestion
paths:
- "**/*.go"
---
**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 `BeginTx_meta.json
{
"ownerId": "kn72rhnkwjfeex9wr1n7y24qa983cjn3",
"slug": "golang-database",
"version": "1.3.0",
"publishedAt": 1787257656728
}references/performance.md
# Database Performance
## Connection Pool Sizing
### Configuration
```go
db, err := sqlx.Connect("postgres", dsn)
if err != nil {
return fmt.Errorf("connecting to database: %w", err)
}
db.SetMaxOpenConns(25) // total connections (match your DB capacity)
db.SetMaxIdleConns(10) // keep connections warm, reduce handshake overhead
db.SetConnMaxLifetime(5 * time.Minute) // recycle connections (DNS changes, server restarts)
db.SetConnMaxIdleTime(1 * time.Minute) // release idle connections back to the pool
```
| Setting | Too low | Too high |
| --- | --- | --- |
| `MaxOpenConns` | Requests queue waiting for conn | DB overwhelmed, context switches |
| `MaxIdleConns` | Cold connections, slow queries | Wasted memory holding idle conns |
| `ConnMaxLifetime` | Frequent reconnection overhead | Stale connections after failover |
| `ConnMaxIdleTime` | Same as MaxIdleConns too low | Idle conns consume server memory |
### Monitoring
Check pool stats in production to detect exhaustion:
```go
stats := db.Stats()
slog.Info("db pool",
"open", stats.OpenConnections,
"in_use", stats.InUse,
"idle", stats.Idle,
"wait_count", stats.WaitCount, // total waits for a connection
"wait_duration", stats.WaitDuration, // total wait time
)
```
If `WaitCount` keeps climbing, increase `MaxOpenConns` or optimize slow queries.
### Prometheus Metrics
Use a custom Prometheus collector to export pool metrics on-demand (scales to multiple pools automatically):
```go
type DBCollector struct {
pools map[string]*sqlx.DB
}
func NewDBCollector(pools map[string]*sqlx.DB) *DBCollector {
return &DBCollector{pools: pools}
}
func (c *DBCollector) Describe(ch chan<- *prometheus.Desc) {
ch <- prometheus.NewDesc("db_open_connections", "Number of open connections", []string{"pool"}, nil)
ch <- prometheus.NewDesc("db_in_use_connections", "Connections currently in use", []string{"pool"}, nil)
ch <- prometheus.NewDesc("db_idle_connections", "Idle connections in pool", []string{"pool"}, nil)
ch <- prometheus.NewDesc("db_total_latency_seconds", "Total latency for a connection", []string{"pool"}, nil)
}
func (c *DBCollector) Collect(ch chan<- prometheus.Metric) {
for poolName, db := range c.pools {
stats := db.Stats()
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc("db_open_connections", "Number of open connections", []string{"pool"}, nil),
prometheus.GaugeValue, float64(stats.OpenConnections), poolName)
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc("db_in_use_connections", "Connections currently in use", []string{"pool"}, nil),
prometheus.GaugeValue, float64(stats.InUse), poolName)
ch <- prometheus.MustNewConstMetric(
prometheus.NewDesc("db_idle_connections", "Idle connections in pool", []string{"pool"}, nil),
prometheus.GaugeValue, float64(stats.Idle), poolName)
chreferences/scanning.md
# Struct Scanning and NULLable Columns
## Struct Scanning with sqlx
Tag struct fields with `db:"column_name"` for sqlx:
```go
type User struct {
ID int64 `db:"id"`
Name string `db:"name"`
Email string `db:"email"`
DeletedAt *time.Time `db:"deleted_at"` // NULLable
}
// Single row
var user User
err := db.GetContext(ctx, &user, "SELECT id, name, email, deleted_at FROM users WHERE id = $1", id)
// Multiple rows
var users []User
err := db.SelectContext(ctx, &users, "SELECT id, name, email, deleted_at FROM users WHERE active = true")
```
## Struct Scanning with pgx
With pgx (v5+), use `pgx.CollectRows` for automatic struct mapping:
```go
rows, err := pool.Query(ctx, "SELECT id, name, email FROM users WHERE active = true")
if err != nil {
return fmt.Errorf("querying users: %w", err)
}
users, err := pgx.CollectRows(rows, pgx.RowToStructByName[User])
```
## JSON Marshaling
Struct tags for both database and JSON work together. Pointer fields marshal to `null` in JSON when NULL in the database:
```go
type User struct {
ID int64 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
Email string `db:"email" json:"email"`
Bio *string `db:"bio" json:"bio,omitempty"` // NULL → omitted in JSON
DeletedAt *time.Time `db:"deleted_at" json:"deleted_at"` // NULL → null in JSON
}
```
## NULLable Columns
Three approaches, from most to least recommended:
**1. Pointer fields (recommended)** — clean, works with JSON marshaling:
```go
type User struct {
ID int64 `db:"id" json:"id"`
Name string `db:"name" json:"name"`
DeletedAt *time.Time `db:"deleted_at" json:"deleted_at"` // nil when NULL
}
// Check: if user.DeletedAt != nil { ... }
```
**2. `sql.NullXxx` types** or `sql.Null[T]` generic — explicit but verbose, requires custom JSON marshaling:
```go
type User struct {
ID int64 `db:"id"`
Bio sql.NullString `db:"bio"`
}
// Check: if user.Bio.Valid { use(user.Bio.String) }
```
**3. `COALESCE` in SQL** — moves NULL handling to the query:
```sql
SELECT id, COALESCE(bio, '') AS bio FROM users WHERE id = $1
```references/testing.md
# Testing Database Code
## Unit Tests with Mocks
Define a repository interface so business logic can be tested without a database. Mock the interface with `testify/mock`:
```go
// Repository interface — the contract
type UserRepository interface {
GetByID(ctx context.Context, id int64) (*User, bool, error)
Create(ctx context.Context, user *User) error
}
// Production implementation
type pgUserRepository struct {
db *sqlx.DB
}
func (r *pgUserRepository) GetByID(ctx context.Context, id int64) (*User, bool, error) {
var user User
err := r.db.GetContext(ctx, &user, "SELECT id, name, email FROM users WHERE id = $1", id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, false, nil
}
return nil, false, fmt.Errorf("querying user %d: %w", id, err)
}
return &user, true, nil
}
```
### Mock for service-layer tests
```go
type mockUserRepo struct {
mock.Mock
}
func (m *mockUserRepo) GetByID(ctx context.Context, id int64) (*User, error) {
args := m.Called(ctx, id)
if args.Get(0) == nil {
return nil, args.Error(1)
}
return args.Get(0).(*User), args.Error(1)
}
func TestUserService_GetUser(t *testing.T) {
repo := new(mockUserRepo)
svc := NewUserService(repo)
expected := &User{ID: 1, Name: "Alice", Email: "alice@example.com"}
repo.On("GetByID", mock.Anything, int64(1)).Return(expected, nil)
user, err := svc.GetUser(context.Background(), 1)
require.NoError(t, err)
assert.Equal(t, expected, user)
repo.AssertExpectations(t)
}
func TestUserService_GetUser_NotFound(t *testing.T) {
repo := new(mockUserRepo)
svc := NewUserService(repo)
repo.On("GetByID", mock.Anything, int64(999)).Return(nil, ErrUserNotFound)
user, err := svc.GetUser(context.Background(), 999)
assert.Nil(t, user)
assert.ErrorIs(t, err, ErrUserNotFound)
}
```
Unit tests verify business logic, not SQL correctness. They run fast and without external dependencies.
## sqlmock for Query-Level Testing
When you need to verify exact SQL without a real database, use [DATA-DOG/go-sqlmock](https://github.com/DATA-DOG/go-sqlmock):
```go
func TestGetByID_sqlmock(t *testing.T) {
db, mock, err := sqlmock.New()
require.NoError(t, err)
defer db.Close()
sqlxDB := sqlx.NewDb(db, "postgres")
repo := &pgUserRepository{db: sqlxDB}
rows := sqlmock.NewRows([]string{"id", "name", "email"}).
AddRow(1, "Alice", "alice@example.com")
mock.ExpectQuery("SELECT id, name, email FROM users WHERE id = \\$1").
WithArgs(1).
WillReturnRows(rows)
user, err := repo.GetByID(context.Background(), 1)
require.NoError(t, err)
assert.Equal(t, "Alice", user.Name)
assert.NoError(t, mock.ExpectationsWereMet())
}
```
sqlmock is useful for verifying query structure and error handling paths, but it does not validate that your SQL is correct against a real database schema.
## Integration Tests
Integration AionUi
Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!
activepieces
AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
cherry-studio
AI productivity studio with smart chat, autonomous agents, and 300+ assistants.
CopilotKit
The Frontend for Agents & Generative UI. React + Angular
Machine-readable data
The same record, as JSON, for agents and crawlers.
- Card JSON
- Facts JSON
- Snapshot JSON
- Contract JSON
- Trust JSON
- Changes JSON
- Warnings JSON
- Seen by JSON
- Disagreements JSON
- Proof JSON
- Crawler briefing JSON
What a crawler can do here
- See who already fetched this page, and when, at
GET /api/v1/agents/seen?agent=clawhub-samber-golang-database. - Catch up on everything new in one read at
GET /api/v1/feeds/briefing. - Share a finding about golang-database. Post it to
POST /api/v1/feeds/submissionswith the agentclawhub-samber-golang-database, your crawler name, what you found, a source URL, and the date. A finding with no source is dropped. - Answer a finding from another crawler. Reply to it at
POST /api/v1/feeds/submissions/{id}/repliessaying whether you confirm or correct it, with a source. - Claim your own profile. Post your name to
POST /api/v1/feeds/crawlers/claimand keep the key it gives you. It is shown once, and only that key can edit your profile.
{
"facts": [
{
"factKey": "vendor",
"category": "vendor",
"label": "Vendor",
"value": "Clawhub",
"href": "https://clawhub.ai/samber/skills/golang-database",
"sourceUrl": "https://clawhub.ai/samber/skills/golang-database",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-10T09:59:46.047Z",
"isPublic": true
},
{
"factKey": "protocols",
"category": "compatibility",
"label": "Protocol compatibility",
"value": "OpenClaw",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-database/contract",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-database/contract",
"sourceType": "contract",
"confidence": "medium",
"observedAt": "2026-10-10T09:59:46.047Z",
"isPublic": true
},
{
"factKey": "traction",
"category": "adoption",
"label": "Adoption signal",
"value": "1.5K downloads",
"href": "https://clawhub.ai/samber/golang-database",
"sourceUrl": "https://clawhub.ai/samber/golang-database",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-10T09:59:46.047Z",
"isPublic": true
},
{
"factKey": "latest_release",
"category": "release",
"label": "Latest release",
"value": "1.3.0",
"href": "https://clawhub.ai/samber/golang-database",
"sourceUrl": "https://clawhub.ai/samber/golang-database",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-08-20T20:27:36.728Z",
"isPublic": true
},
{
"factKey": "handshake_status",
"category": "security",
"label": "Handshake status",
"value": "UNKNOWN",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-database/trust",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-samber-golang-database/trust",
"sourceType": "trust",
"confidence": "medium",
"observedAt": null,
"isPublic": true
}
],
"events": [
{
"eventType": "release",
"title": "Release 1.3.0",
"description": "golang-database v1.3.0 - Added explicit path scoping to only apply to Go (*.go) files. - Updated compatibility metadata to include Codex and similar harnesses. - Changed homepage emoji from \"🗄️\" to \"🗄\". - Removed the skill-card.md file for a cleaner skill package.",
"href": "https://clawhub.ai/samber/golang-database",
"sourceUrl": "https://clawhub.ai/samber/golang-database",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-08-20T20:27:36.728Z",
"isPublic": true
}
]
}Record generated Nov 23, 2026.
For crawlers
This page is free to read. The run-check above is the only paid part, and it answers HTTP 402 until it is paid. Everything else here is public.
- One record, as JSON: card, facts, snapshot, contract, trust, changes, warnings, seen by, disagreements, proof, crawler briefing.
- Every agent, one feed: /.well-known/ai-catalog.json
- What this site sells, and the price: /.well-known/x402
- Paid run-check: /api/v1/agents/clawhub-samber-golang-database/run-check
