Compare repository, query generator and ORM boundaries
Compare repository, query generator and ORM boundaries
A repository exposes domain operations instead of raw database mechanics. Handwritten SQL offers explicit control; query generators can produce typed Go methods from SQL and schema; object-relational mappers (ORMs) map models to database operations and often automate query construction. These are choices inside the repository. No third-party generator or ORM is installed.
package main
import ( "context" "database/sql" "database/sql/driver" "errors" "fmt" "io")
// fixtureDriver is a teaching double, not a SQL engine.type fixtureDriver struct{}type fixtureConn struct{ mode string }type fixtureTx struct{}type fixtureRows struct { values [][]driver.Value fail bool index int}
func (fixtureDriver) Open(name string) (driver.Conn, error) { if name == "offline" { return nil, errors.New("fixture offline") } return &fixtureConn{mode: name}, nil}func (c *fixtureConn) Prepare(string) (driver.Stmt, error) { return nil, errors.New("prepare not implemented in fixture")}func (c *fixtureConn) Close() error { return nil }func (c *fixtureConn) Begin() (driver.Tx, error) { return &fixtureTx{}, nil }func (c *fixtureConn) Ping(ctx context.Context) error { return ctx.Err() }func (t *fixtureTx) Commit() error { return nil }func (t *fixtureTx) Rollback() error { return nil }func (c *fixtureConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) { if err := ctx.Err(); err != nil { return nil, err } switch q { case "SELECT name FROM books WHERE id = ?": if len(args) != 1 { return nil, errors.New("one argument required") } if args[0].Value == int64(7) { return &fixtureRows{values: [][]driver.Value{{"Go"}}}, nil } return &fixtureRows{}, nil case "SELECT name FROM books": return &fixtureRows{values: [][]driver.Value{{"Go"}, {nil}}, fail: c.mode == "broken"}, nil default: return nil, errors.New("unsupported fixture query") }}func (c *fixtureConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) { if err := ctx.Err(); err != nil { return nil, err } if q != "UPDATE books SET name = ? WHERE id = ?" || len(args) != 2 { return nil, errors.New("unsupported fixture update") } if args[1].Value == int64(7) { return driver.RowsAffected(1), nil } return driver.RowsAffected(0), nil}func (r *fixtureRows) Columns() []string { return []string{"name"} }func (r *fixtureRows) Close() error { return nil }func (r *fixtureRows) Next(dest []driver.Value) error { if r.index == len(r.values) { if r.fail { return errors.New("fixture stream interrupted") } return io.EOF } copy(dest, r.values[r.index]) r.index++ return nil}func must(err error) { if err != nil { panic(err) }}func openFixture(mode string) *sql.DB { db, err := sql.Open("bytemind-fixture", mode) must(err) return db}func init() { sql.Register("bytemind-fixture", fixtureDriver{}) }
type BookReader interface { FindName(context.Context, int) (string, error)}type SQLBooks struct{ db *sql.DB }
func (r SQLBooks) FindName(ctx context.Context, id int) (string, error) { var name string err := r.db.QueryRowContext(ctx, "SELECT name FROM books WHERE id = ?", id).Scan(&name) return name, err}
type MemoryBooks map[int]string
func (r MemoryBooks) FindName(ctx context.Context, id int) (string, error) { if err := ctx.Err(); err != nil { return "", err } v, ok := r[id] if !ok { return "", sql.ErrNoRows } return v, nil}func title(ctx context.Context, r BookReader, id int) (string, error) { return r.FindName(ctx, id) }func main() { db := openFixture("ready") defer db.Close() name, err := title(context.Background(), SQLBooks{db}, 7) must(err) fmt.Println(name)}The consumer uses BookReader without knowing the SQL or pool. Production repositories can translate sql.ErrNoRows into a domain error; here it is retained for comparison. Keep transaction ownership explicit across multiple operations.
Expected output:
GoTest with a substitute
package main
import ( "context" "database/sql" "errors" "fmt")
type BookReader interface { FindName(context.Context, int) (string, error)}type SQLBooks struct{ db *sql.DB }
func (r SQLBooks) FindName(ctx context.Context, id int) (string, error) { var name string err := r.db.QueryRowContext(ctx, "SELECT name FROM books WHERE id = ?", id).Scan(&name) return name, err}
type MemoryBooks map[int]string
func (r MemoryBooks) FindName(ctx context.Context, id int) (string, error) { if err := ctx.Err(); err != nil { return "", err } v, ok := r[id] if !ok { return "", sql.ErrNoRows } return v, nil}func title(ctx context.Context, r BookReader, id int) (string, error) { return r.FindName(ctx, id) }func main() { r := MemoryBooks{7: "Go"} name, err := title(context.Background(), r, 7) fmt.Println(name, err == nil) _, err = title(context.Background(), r, 8) fmt.Println(errors.Is(err, sql.ErrNoRows))}A read-only memory map tests consumer behavior but not SQL correctness, isolation or constraints. Generated code catches some type mismatches but still needs integration tests; an ORM may hide expensive queries such as N+1 reads. Compare actual SQL, migrations, tracing, transactions and workload measurements.
Expected output:
Go truetrueTry it locally
Use the memory repository with a canceled context. Verify the consumer receives context.Canceled.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Database 09: Compare repository, query generator and ORM boundaries
Check the lesson objective before moving on.
What does a repository interface separate?
What is still needed with generators or ORM?