05 / 05

How would you design the data access layer of a Go service for testability and flexibility using the repository pattern?

Define a Repository interface per domain aggregate, implement with sql.DB, inject via constructor, and use sqlc for type-safe query generation. Tests use mock implementations or in-process SQLite.

Repository pattern
Design considerations
  1. 1

    sqlc generates type-safe Go functions from SQL queries — no reflection, full IDE support

  2. 2

    One repository interface per aggregate (User, Order, Product) — not one god repository

  3. 3

    Return domain errors (ErrNotFound) not database errors — decouple domain from persistence

  4. 4

    Integration tests use testcontainers-go for a real Postgres — unit tests use mocks

  5. 5

    Avoid leaking DB types (sql.NullString) into domain models — map at the repository layer