ORM Pattern Implementation in Go
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓ORM Pattern runs in O(1) time and O(n) space, in Go as in every other language.
- ✓database/sql plus a driver is the floor, and a real share of teams stop there with sqlx StructScan or sqlc-generated code and consider that the correct answer.
- ✓Errors are the review surface. Every gorm call returns *gorm.DB with the failure hidden in .Error, so the accepted form is if err := db.Preload("Legs").Find(&ships).Error; err != nil, never a bare chained call.
- ✓The Go trap: Updates given a struct silently discards every field equal to its zero value, because reflection cannot distinguish false from unset in a language without option types.
- ✓Preload is two statements, parents then children with an IN over the parent keys, and gorm builds the reverse index in Go; Joins is one statement with no index build but duplicates the parent columns once per child row.
What ORM Pattern actually is
ORM Pattern in Go: what you actually reach for
Go implementation
package freight
import (
"context"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type Shipment struct {
ID uint `gorm:"primaryKey"`
TrackingNo string `gorm:"uniqueIndex"`
Status string
Held bool
Legs []Leg // populated only when Preload asks for it
}
type Leg struct {
ID uint `gorm:"primaryKey"`
ShipmentID uint
Carrier string
}
func Manifest(ctx context.Context, dsn string) ([]Shipment, error) {
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
var ships []Shipment
// Two statements: SELECT shipments, then SELECT legs WHERE shipment_id IN (...)
if err := db.WithContext(ctx).Preload("Legs").Find(&ships).Error; err != nil {
return nil, err
}
s := &ships[0]
// Reflection cannot tell false from unset, so Held is dropped from this UPDATE.
if err := db.Model(s).Updates(Shipment{Status: "held", Held: false}).Error; err != nil {
return nil, err
}
// A map says what the struct could not. So would .Select("status", "held").
if err := db.Model(s).Updates(map[string]any{"status": "held", "held": false}).Error; err != nil {
return nil, err
}
return ships, nil
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Go-specific trap
Performance in Go, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Go type or library should I use for ORM Pattern?
database/sql plus a driver is the floor, and a real share of teams stop there with sqlx StructScan or sqlc-generated code and consider that the correct answer. The mapper most codebases import is gorm.io/gorm with a driver such as gorm.io/driver/postgres: struct tags for columns, Preload for has-many, Joins for belongs-to, WithContext for cancellation, and gorm.DeletedAt for soft deletes. entgo.io/ent is the other serious option and generates a typed client from a schema rather than reflecting over tags. Neither keeps an identity map.
What is the most common Go mistake when implementing ORM Pattern?
Updates given a struct silently discards every field equal to its zero value, because reflection cannot distinguish false from unset in a language without option types. db.Model(&s).Updates(Shipment{Status: "held", Held: false}) writes status and leaves held untouched, so clearing a bool, zeroing a counter or blanking a string all no-op while err stays nil. The remedies are map[string]any, an explicit .Select("held"), or pointer fields. The same reflection quietly appends deleted_at IS NULL to every query once a gorm.DeletedAt field exists.
How does ORM Pattern actually perform in Go?
Preload is two statements, parents then children with an IN over the parent keys, and gorm builds the reverse index in Go; Joins is one statement with no index build but duplicates the parent columns once per child row. Reflection is the tax that shows up in profiles: each scan resolves destination fields through reflect and grows the result slice, so half a million rows into structs measurably trails a generated Scan into fixed fields. Without an identity map, N loads of one row allocate N structs and N copies of its strings. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialMost AI and dev tools have a student plan. See which ones and how to claim them on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.