Repository
A repository is an interface that loads and stores domain values, hiding SQL (or another store). Handlers depend on the interface. Tests substitute a fake. The concrete type talks to database/sql.
Detailed Explanation
A handler that embeds SQL strings is hard to test and hard to migrate. A UserRepository with Find(ctx, id) (User, error) and Save(ctx, User) error is the seam. The HTTP package imports the interface (or defines a tiny one it needs). The postgres package implements it with *sql.DB.
Go flavour. The interface is small and belongs with the consumer, or in a domain package both import. Do not export a 30-method Repository "for everything." A UserStore with the three methods this service uses is enough. Implicit satisfaction means the SQL type does not import HTTP.
Not an ORM. A repository can call QueryRowContext and scan into a struct. It can wrap sqlx. It should not leak *sql.Rows to handlers. Transactions: either Save is one transaction, or you pass a Tx type the repository accepts — keep that decision in one place.
Fakes. An in-memory map[ID]User with a mutex is the test double. You do not need a mock generator for a three-method interface.
What it costs. An extra package and an extra type. That is cheap next to handlers that cannot run without Postgres. A repository that is a 1:1 mirror of every table with no domain language is busywork — then a *sql.DB on a small struct is enough.
Code Examples
package user
import "context"
type User struct {
ID string
Email string
}
type Store interface {
Find(ctx context.Context, id string) (User, error)
Save(ctx context.Context, u User) error
}type Memory struct {
m map[string]User
}
func (m *Memory) Find(_ context.Context, id string) (User, error) {
u, ok := m.m[id]
if !ok {
return User{}, errNotFound
}
return u, nil
}
var errNotFound = errString("not found")
type errString string
func (e errString) Error() string { return string(e) }Common Gotchas
A god-interface repository is unfakeable
split by use case.
Put `context.Context` on every method that I/O can cancel
Put `context.Context` on every method that I/O can cancel
The SQL implementation lives in `databases`; this term is the seam
The SQL implementation lives in `databases`; this term is the seam