Keeping SQL Out of Your Business Logic
Somewhere in a Go codebase near you, there is a function called ProcessOrder. It checks stock, calculates discounts, sends an email, and, in the middle of it all, contains a raw SQL string with a JOIN that nobody on the team fully understands. It's like finding a plumber's wrench inside a wedding cake. Both are useful, but not together.
The repository pattern is how we keep the wrench in the toolbox. In this article we'll build repositories properly: what they should do, what they should refuse to do, how to design their interfaces, how to handle errors and transactions, and how to test them.
What a repository is and isn't
A repository is a collection-like object that hides how data is stored. From the outside, it looks like a tidy shelf: "give me the user with this email," "save this order," "list the products in this category." Whether the shelf is backed by PostgreSQL, a cache, or a very patient intern with a notebook is none of the caller's business.
What a repository does:
- Reads and writes data
- Translates between database rows and your domain structs
- Translates database errors into errors your app understands
What it does not do:
- Make business decisions ("is this customer eligible for a discount?")
- Know about HTTP, JSON, or Gin
- Send emails, charge cards, or call other services
A useful gut check: if the method name includes a verb like Approve, Calculate, or Notify, it probably doesn't belong in a repository. Repository verbs are boring: Create, Find, Update, Delete, List, Count.
Step one: define the interface where it's used
In Go, interfaces are satisfied implicitly. A type doesn't declare "I implement this." It just has the right methods. This leads to a lovely design habit: define the interface next to the code that needs it, and keep it small.
// internal/service/order_service.go
package service
type OrderStore interface {
Create(ctx context.Context, order *domain.Order) error
FindByID(ctx context.Context, id uint) (*domain.Order, error)
ListByUser(ctx context.Context, userID uint, limit, offset int) ([]domain.Order, error)
}
Notice we name it by role (OrderStore), list only what the order service genuinely uses, and put it in the service package. Some teams keep interfaces in the repository package instead, as we did in the first article, and that's perfectly workable too. The deeper principle is the same: the consumer states its needs, and the implementation rises to meet them.
Also notice context.Context as the first parameter. This isn't decoration. It lets callers set timeouts and cancel work. If a user closes their browser mid-request, the context is cancelled and your database query can stop wasting time on someone who's gone. Pass it through every layer, always.
Step two: the implementation
// internal/repository/order_repository.go
package repository
type orderRepository struct {
db *gorm.DB
}
func NewOrderRepository(db *gorm.DB) *orderRepository {
return &orderRepository{db: db}
}
func (r *orderRepository) Create(ctx context.Context, o *domain.Order) error {
if err := r.db.WithContext(ctx).Create(o).Error; err != nil {
return fmt.Errorf("creating order: %w", err)
}
return nil
}
func (r *orderRepository) FindByID(ctx context.Context, id uint) (*domain.Order, error) {
var o domain.Order
err := r.db.WithContext(ctx).Preload("Items").First(&o, id).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, domain.ErrOrderNotFound
}
return nil, fmt.Errorf("finding order %d: %w", id, err)
}
return &o, nil
}
Two habits are doing heavy lifting here.
WithContext(ctx) attaches the context to the query, so cancellation and deadlines work.
Error translation. Look at what happens when GORM returns ErrRecordNotFound. The repository converts it into domain.ErrOrderNotFound, an error that belongs to your application. Why? Because the service shouldn't need to import GORM just to ask "was it missing?" If you ever swap databases, only the repository changes, and every errors.Is(err, domain.ErrOrderNotFound) elsewhere keeps working. The repository is a customs officer: foreign errors get stamped into local currency at the border.
Where do the domain errors live?
A small file, no dependencies:
// internal/domain/errors.go
package domain
import "errors"
var (
ErrOrderNotFound = errors.New("order not found")
ErrUserNotFound = errors.New("user not found")
ErrEmailTaken = errors.New("email already registered")
)
These are sentinel errors, named values you compare against with errors.Is. Because they live in the domain package, which everything is allowed to import, no layer has to reach sideways into another layer's internals to understand a failure.
Mapping between models and domain structs
In small projects, one struct often serves as both your GORM model and your domain object. That's fine. But as projects grow, you may feel friction: the database wants tags and join tables, the business logic wants clean types. One answer is to keep two structs and convert between them inside the repository:
// database shape (private to the repository package)
type orderModel struct {
ID uint `gorm:"primaryKey"`
UserID uint `gorm:"index"`
Total int64
Status string
CreatedAt time.Time
}
func (m orderModel) toDomain() domain.Order {
return domain.Order{
ID: m.ID,
UserID: m.UserID,
Total: m.Total,
Status: domain.OrderStatus(m.Status),
CreatedAt: m.CreatedAt,
}
}
Is this extra work? Yes. Is it always worth it? No. If your domain struct is a plain struct with GORM tags and nobody is bothered, keep one. Add the second only when the two shapes really begin to diverge. Don't build a customs office for a country with no trade.
Listing, filtering, and pagination
Lists are where repositories earn their keep. Here's a listing method with pagination and an optional filter:
type OrderFilter struct {
UserID *uint
Status *string
}
func (r *orderRepository) List(ctx context.Context, f OrderFilter, limit, offset int) ([]domain.Order, error) {
q := r.db.WithContext(ctx).Model(&orderModel{})
if f.UserID != nil {
q = q.Where("user_id = ?", *f.UserID)
}
if f.Status != nil {
q = q.Where("status = ?", *f.Status)
}
var models []orderModel
err := q.Order("created_at DESC").
Limit(limit).
Offset(offset).
Find(&models).Error
if err != nil {
return nil, fmt.Errorf("listing orders: %w", err)
}
out := make([]domain.Order, len(models))
for i, m := range models {
out[i] = m.toDomain()
}
return out, nil
}
The trick is the filter struct. Instead of ten methods like ListByUser, ListByUserAndStatus, ListByStatus, you get one flexible method, and pointer fields mean "not specified." This keeps the interface small while allowing combinations. Notice that Order("created_at DESC") is here, so the sort order is stable. A list without an ORDER BY returns rows in whatever order the database feels like, which is a fine foundation for flaky tests and confused users.
Always cap limit. Somebody will eventually request limit=10000000. Clamp it in the service or the handler, because your repository can't tell a legitimate request from a sleepy cat on the keyboard.
Transactions without leaking GORM
Here's a genuinely tricky design question. Suppose placing an order must create the order and reduce stock, atomically. A transaction spans two repositories, but the service shouldn't know about *gorm.DB or tx.Begin().
There are a few approaches. A clean one is a small transaction runner interface:
// internal/service
type TxManager interface {
WithinTx(ctx context.Context, fn func(ctx context.Context) error) error
}
The implementation, in the repository layer, starts a GORM transaction and stashes it in the context:
type ctxKey struct{}
type txManager struct{ db *gorm.DB }
func (m *txManager) WithinTx(ctx context.Context, fn func(ctx context.Context) error) error {
return m.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
return fn(context.WithValue(ctx, ctxKey{}, tx))
})
}
// inside every repository, pick the right handle
func dbFrom(ctx context.Context, fallback *gorm.DB) *gorm.DB {
if tx, ok := ctx.Value(ctxKey{}).(*gorm.DB); ok {
return tx
}
return fallback.WithContext(ctx)
}
Each repository method then starts with dbFrom(ctx, r.db). If a transaction is in progress, it uses it. If not, it uses the regular connection. The service just writes:
err := s.tx.WithinTx(ctx, func(ctx context.Context) error {
if err := s.stock.Reserve(ctx, item.ProductID, item.Qty); err != nil {
return err
}
return s.orders.Create(ctx, order)
})
If either step fails, everything rolls back. The service expresses what must be atomic, and the repository layer decides how. Is this pattern more elaborate than a beginner project needs? Absolutely. For a small app, simply having one repository method that does both steps inside its own transaction is fine. Reach for the TxManager when business logic genuinely spans several repositories.
Don't let the repository grow a brain
The most common repository sin is business logic creep. It starts innocently:
func (r *orderRepository) CreateIfStockAvailable(...) // hmm
func (r *orderRepository) ApplyDiscount(...) // uh oh
func (r *orderRepository) MarkAsPaidAndNotify(...) // no. Absolutely not.
Each one makes the repository smarter and the service dumber, and soon your rules are hiding in SQL where nobody looks for them. When you're tempted to add one, ask: "Is this about how data is stored, or what the business wants?" Storage goes in the repository. Wants go in the service.
There's one honest gray area: operations that need database-level atomicity, like UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0. The rule ("can't sell what you don't have") is business, but the mechanism is a conditional write that must happen in a single statement to be safe. It's fine for the repository to offer DecrementStock returning a "not enough stock" error. The service decides when to call it and what to do with the answer.
Testing repositories
Services can be tested with fake repositories. But how do you test the repository itself? The honest answer: against a real database. A repository's entire job is to talk to Postgres correctly, so mocking Postgres would test your mock, a proud and useless achievement.
Practical options:
- A throwaway Postgres in Docker (we'll set up Docker in a later article), started before the test run
-
testcontainers-go, which spins up a real database per test run, then discards it - A transaction per test that rolls back at the end, so tests don't contaminate each other
A small example:
func TestOrderRepository_FindByID_NotFound(t *testing.T) {
db := setupTestDB(t) // connects, migrates
repo := NewOrderRepository(db)
_, err := repo.FindByID(context.Background(), 999)
if !errors.Is(err, domain.ErrOrderNotFound) {
t.Fatalf("expected ErrOrderNotFound, got %v", err)
}
}
Keep these tests focused: does Create persist? Does FindByID return related items? Does the not-found error translate? Do filters combine correctly? Don't test GORM itself. It has its own tests.
Common mistakes
Returning *gorm.DB or builders upward. If a method hands back a half-built query for the service to finish, the service now speaks GORM. Return finished results.
One giant repository. A Repository struct with 60 methods is a junk drawer. Split by aggregate: users, orders, products.
Swallowing errors. return nil, nil on failure is a trap, because the caller gets no result and no error and a nil pointer is waiting down the road. Return real errors.
Forgetting context. A query without context can't be cancelled, so slow requests pile up long after clients have left.
Reaching for generic repositories too early. A Repository[T] with Create, Find, and Delete looks elegant, but real queries rarely fit it. Start concrete. Generalize if repetition truly hurts.
Quick recap
- Repositories store and fetch. They don't decide.
- Define small interfaces where they're used, and pass
context.Contexteverywhere. - Translate database errors into domain errors at the boundary.
- Use filter structs and stable ordering for lists, and cap limits.
- Keep transactions in the repository layer, exposing only an abstraction to services if you need cross-repository atomicity.
- Test repositories against a real database, and services against fakes.
Top comments (0)