By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
The standard library ships database/sql, a pool plus an API. The driver itself is a separate module that registers itself when imported for its side effect (_ "github.com/jackc/pgx/v5/stdlib" for PostgreSQL, for example). Relay keeps the driver import in cmd/relayd only, so the rest of the code never depends on the database choice.
Every method you care about has a context variant: ExecContext, QueryContext, QueryRowContext. Use them and pass the request context, so a cancelled request releases its connection instead of finishing a query nobody wants. *sql.Row and *sql.Rows must be closed and checked: rows.Close() releases the connection, and rows.Err() reports iteration failures that Scan cannot.
A repository hides SQL behind an interface that the application defines. Handlers depend on store.Repository, not on *sql.DB; tests can implement the interface with an in-memory fake, and the production type owns the queries. This is the consumer-defined interface rule from step 10 applied to persistence.
package store
import (
"context"
"database/sql"
"fmt"
)
// Event is the storage shape; the API can map its own type onto it.
type Event struct {
ID int64
Service string
Level string
Status int
}
// Repository is what the application layer needs, not everything SQL can do.
type Repository interface {
Insert(ctx context.Context, event Event) error
CountByService(ctx context.Context) (map[string]int, error)
}
type SQLRepository struct {
db *sql.DB
}
func NewSQLRepository(db *sql.DB) *SQLRepository {
return &SQLRepository{db: db}
}
func (r *SQLRepository) Insert(ctx context.Context, event Event) error {
const query = `
INSERT INTO events (service, level, status)
VALUES ($1, $2, $3)`
if _, err := r.db.ExecContext(ctx, query, event.Service, event.Level, event.Status); err != nil {
return fmt.Errorf("insert event: %w", err)
}
return nil
}
func (r *SQLRepository) CountByService(ctx context.Context) (map[string]int, error) {
const query = `
SELECT service, COUNT(*)
FROM events
GROUP BY service`
rows, err := r.db.QueryContext(ctx, query)
if err != nil {
return nil, fmt.Errorf("count by service: %w", err)
}
defer rows.Close()
counts := map[string]int{}
for rows.Next() {
var service string
var count int
if err := rows.Scan(&service, &count); err != nil {
return nil, fmt.Errorf("scan count: %w", err)
}
counts[service] = count
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("iterate counts: %w", err)
}
return counts, nil
}
// Compile-time proof that the production type satisfies the interface.
var _ Repository = (*SQLRepository)(nil)sql.DB is a pool, so its limits are capacity planning. SetMaxOpenConns caps concurrent connections; SetMaxIdleConns keeps warm connections for reuse; SetConnMaxLifetime rotates connections so a load balancer or database restart does not strand them. PingContext on startup turns a misconfigured DSN into a clear boot failure instead of a 500 on the first request.
| Setting | Default | What to do |
|---|---|---|
SetMaxOpenConns | Unlimited | Set to the database's connection budget |
SetMaxIdleConns | 2 | Match or approach MaxOpenConns for steady traffic |
SetConnMaxLifetime | Unlimited | Rotate every 30-60 minutes |
PingContext | Not called | Check connectivity at startup |
| Transactions | Manual | BeginTx with the request context; always defer rollback |
| Migrations | Not included | Version them and run before deploying the new binary |
Key takeaways
database/sql is a pool and an API; the driver is a separately imported module.
Use the ...Context methods and pass the request context so cancellation releases connections.
Always close rows and check rows.Err(); Scan alone misses iteration failures.
Parameterize queries; never concatenate values into SQL.
Define a small repository interface in the application layer and keep SQL inside its implementation.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.