go-database
Go database operations - SQL, ORMs, transactions, migrations
What this skill does
# Go Database Skill
Production database patterns with Go including SQL, ORMs, and data access layer design.
## Overview
Best practices for database operations covering connection pooling, transactions, migrations, and query optimization.
## Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| database | string | yes | - | Database: "postgres", "mysql", "sqlite" |
| orm | string | no | "sqlx" | ORM: "none", "sqlx", "gorm" |
| pool_size | int | no | 25 | Max open connections |
## Core Topics
### Connection Setup
```go
func NewDB(dsn string) (*sqlx.DB, error) {
db, err := sqlx.Connect("postgres", dsn)
if err != nil {
return nil, fmt.Errorf("connect: %w", err)
}
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
db.SetConnMaxIdleTime(1 * time.Minute)
if err := db.Ping(); err != nil {
return nil, fmt.Errorf("ping: %w", err)
}
return db, nil
}
```
### Repository Pattern
```go
type UserRepository struct {
db *sqlx.DB
}
func (r *UserRepository) FindByID(ctx context.Context, id int64) (*User, error) {
var user User
err := r.db.GetContext(ctx, &user,
`SELECT id, name, email, created_at FROM users WHERE id = $1`, id)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUserNotFound
}
return nil, fmt.Errorf("find user %d: %w", id, err)
}
return &user, nil
}
func (r *UserRepository) Create(ctx context.Context, user *User) error {
query := `INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, created_at`
return r.db.QueryRowxContext(ctx, query, user.Name, user.Email).
Scan(&user.ID, &user.CreatedAt)
}
```
### Transactions
```go
func (r *OrderRepository) CreateOrder(ctx context.Context, order *Order, items []OrderItem) error {
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("begin: %w", err)
}
defer tx.Rollback()
// Insert order
err = tx.QueryRowxContext(ctx,
`INSERT INTO orders (user_id, total) VALUES ($1, $2) RETURNING id`,
order.UserID, order.Total).Scan(&order.ID)
if err != nil {
return fmt.Errorf("insert order: %w", err)
}
// Insert items
stmt, err := tx.PreparexContext(ctx,
`INSERT INTO order_items (order_id, product_id, quantity, price) VALUES ($1, $2, $3, $4)`)
if err != nil {
return fmt.Errorf("prepare: %w", err)
}
defer stmt.Close()
for _, item := range items {
if _, err := stmt.ExecContext(ctx, order.ID, item.ProductID, item.Quantity, item.Price); err != nil {
return fmt.Errorf("insert item: %w", err)
}
}
return tx.Commit()
}
```
### Migrations (goose)
```sql
-- +goose Up
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users(email);
-- +goose Down
DROP TABLE users;
```
## Retry Logic
```go
func (r *Repository) withRetry(ctx context.Context, fn func() error) error {
backoff := []time.Duration{100*time.Millisecond, 500*time.Millisecond, 2*time.Second}
for i := 0; i <= len(backoff); i++ {
err := fn()
if err == nil {
return nil
}
// Only retry on transient errors
if !isRetryable(err) {
return err
}
if i < len(backoff) {
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoff[i]):
}
}
}
return fmt.Errorf("max retries exceeded")
}
func isRetryable(err error) bool {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
return pgErr.Code == "40001" || pgErr.Code == "40P01" // serialization/deadlock
}
return false
}
```
## Unit Test Template
```go
func TestUserRepository_FindByID(t *testing.T) {
db := setupTestDB(t)
repo := &UserRepository{db: db}
// Setup
user := &User{Name: "Test", Email: "[email protected]"}
err := repo.Create(context.Background(), user)
require.NoError(t, err)
// Test
found, err := repo.FindByID(context.Background(), user.ID)
require.NoError(t, err)
assert.Equal(t, user.Name, found.Name)
// Test not found
_, err = repo.FindByID(context.Background(), 99999)
assert.ErrorIs(t, err, ErrUserNotFound)
}
```
## Troubleshooting
### Failure Modes
| Symptom | Cause | Fix |
|---------|-------|-----|
| Connection refused | Pool exhausted | Increase pool, fix leaks |
| Slow queries | Missing index | Run EXPLAIN ANALYZE |
| Deadlock | Competing tx | Review lock ordering |
### Debug Commands
```bash
# Check active connections
SELECT * FROM pg_stat_activity WHERE datname = 'mydb';
# Analyze query
EXPLAIN ANALYZE SELECT * FROM users WHERE email = '[email protected]';
```
## Usage
```
Skill("go-database")
```
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.