Now liveThe Skillselion MCP - thousands of ranked skills, loaded into your agent mid-task. No install.Get it →
samber avatar

Golang Database

  • 34.1k installs
  • 2.8k repo stars
  • Updated July 27, 2026
  • samber/cc-skills-golang

golang-database is an agent skill for safe Go SQL access with sqlx or pgx, parameterized queries, transactions, and connection pooling.

About

The golang-database skill v1.2.1 guides explicit SQL-first Go data access using database/sql with sqlx or pgx, never ORMs. Fifteen best-practice rules require parameterized placeholders, context on all QueryContext and ExecContext calls, explicit sql.ErrNoRows handling, defer rows.Close, transactions for multi-statement writes, SELECT FOR UPDATE when modifying read data, custom isolation levels for financial cases, pointer or sql.Null types for nullable columns, tuned connection pools, external migration tools, and batch sizing discipline. It forbids AI-generated schema design and hidden SQL features like triggers or stored procedures in application code. Library comparison favors pgx for PostgreSQL performance, sqlx for multi-database struct scanning, and warns against GORM magic and N+1 queries. Write mode follows sequential instructions with background greps for existing query patterns. Review mode parallel-scans for missing rows.Close, string-concat SQL, and absent context propagation. Cross-references link golang-context, golang-security, and golang-continuous-integration skills.

  • Fifteen rules for parameterized SQL, context propagation, transactions, pooling, and explicit ErrNoRows handling.
  • Recommends sqlx or pgx on database/sql and explicitly avoids ORMs like GORM and ent.
  • Requires SELECT FOR UPDATE and custom isolation levels when race-sensitive reads precede writes.
  • Forbids AI-generated schemas and hidden SQL features such as triggers and stored procedures.
  • Write and review modes with parallel scans for missing rows.Close and concatenated SQL strings.

Golang Database by the numbers

  • 34,101 all-time installs (skills.sh)
  • +530 installs in the week ending Jul 28, 2026 (Skillselion tracking)
  • Ranked #12 of 923 Databases skills by installs in the Skillselion catalog
  • Security screen: LOW risk (skills.sh audit)
  • Data as of Jul 28, 2026 (Skillselion catalog sync)
At a glance

golang-database capabilities & compatibility

Capabilities
parameterized query patterns · context aware database operations · transaction and isolation guidance · connection pool configuration · null column and errnorows handling
Use cases
database · api development
From the docs

What golang-database says it does

Use sqlx or pgx, not ORMs
retag-ops/docs-cache/skill_samber_cc-skills-golang_golang-database.md
Never create or modify database schemas
retag-ops/docs-cache/skill_samber_cc-skills-golang_golang-database.md
npx skills add https://github.com/samber/cc-skills-golang --skill golang-database

Add your badge

Show developers this skill is listed on Skillselion. Paste this into your README.

Listed on Skillselion
Installs34.1k
repo stars2.8k
Security audit3 / 3 scanners passed
Last updatedJuly 27, 2026
Repositorysamber/cc-skills-golang

How do I write Go database code without SQL injection, connection leaks, or ORM unpredictability?

Write safe Go database code with sqlx or pgx, parameterized queries, transactions, pooling, NULL handling, and context propagation.

Who is it for?

Go backend engineers working with PostgreSQL, MySQL, MariaDB, or SQLite via database/sql ecosystems.

Skip if: Skip when generating database schemas or migration SQL, which this skill explicitly forbids.

When should I use this skill?

Writing repositories, debugging connection leaks, handling NULL columns, or configuring pool limits.

What you get

Explicit parameterized queries with context, proper row closing, transactions, and tuned pools.

  • Safe repository functions
  • Transaction wrappers
  • Pool configuration guidance

By the numbers

  • Metadata version 1.2.1 with fifteen numbered best-practice rules.
  • Library table compares database/sql, sqlx, pgx, and discouraged ORMs.

Files

SKILL.mdMarkdownGitHub ↗

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 BeginTxx/Commit 8. Use `SELECT ... FOR UPDATE` when reading data you intend to modify — prevents race conditions 9. Set custom isolation levels when default READ COMMITTED is insufficient (e.g., serializable for financial operations) 10. Handle NULLable columns with pointer fields (*string, *int) or sql.NullXxx types 11. Connection pool MUST be configured — SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTime 12. Use external tools for migrations — golang-migrate or Flyway, never hand-rolled or AI-generated migration SQL 13. Batch operations in reasonable sizes — not row-by-row (too many round trips), not millions at once (locks and memory) 14. 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 15. Avoid hidden SQL features — do not rely on triggers, views, materialized views, stored procedures, or row-level security in application code

Library Choice

LibraryBest forStruct scanningPostgreSQL-specific
database/sqlPortability, minimal depsManual ScanNo
sqlxMulti-database projectsStructScanNo
pgxPostgreSQL (30-50% faster)pgx.RowToStructByNameYes (COPY, LISTEN, arrays)
GORM/entAvoidMagicAbstracted 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

ErrorHow to detectAction
Row not founderrors.Is(err, sql.ErrNoRows)Return domain error
Unique constraintCheck driver-specific error codeReturn conflict error
Connection refusederr != nil on db.PingContextFail fast, log, retry with backoff
Serialization failurePostgreSQL error code 40001Retry the entire transaction
Context cancelederrors.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 faster

For 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](./references/transactions.md) — Transaction boundaries, isolation levels, deadlock prevention, SELECT FOR UPDATE
  • [Testing Database Code](./references/testing.md) — Mock connections, integration tests with containers, fixtures, schema setup/teardown
  • [Database Performance](./references/performance.md) — Connection pool sizing, batch processing, indexing strategy, query optimization
  • [Struct Scanning](./references/scanning.md) — Struct tags, NULLable column handling, JSON marshaling patterns

Cross-References

  • → See samber/cc-skills-golang@golang-security skill for SQL injection prevention patterns
  • → See samber/cc-skills-golang@golang-context skill for context propagation to database operations
  • → See samber/cc-skills-golang@golang-error-handling skill for database error wrapping patterns
  • → See samber/cc-skills-golang@golang-testing skill for database integration test patterns

References

Related skills

How it compares

Explicit SQL-first Go database guide, not an ORM tutorial or schema generator.

FAQ

Who is golang-database for?

Go backend engineers using sqlx or pgx for PostgreSQL, MySQL, MariaDB, or SQLite access.

When should I use golang-database?

When writing parameterized queries, transactions, pool config, or reviewing database code for leaks and injection.

Is golang-database safe to install?

Review the Security Audits panel on this page before installing in production.

Databasesdatabases

This week in AI coding

Five minutes, every Monday - the tools, releases and tactics for developers.

unsubscribe anytime.