Sessions
A context that tracks changes serves one operation at a time. A session is a context on the same pool with a tracker of its own, so take one per request, per job, or per goroutine. Call ant.Open once at startup.
One per request
func rename(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
session := ant.Session(db)
user, err := session.Users.Find(ctx, id)
if err != nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
user.Name = "Alice B."
err = session.SaveChanges(ctx)
if err != nil {
http.Error(w, "could not save", http.StatusInternalServerError)
}
}
SELECT ... FROM "users" WHERE "users"."id" = $1 LIMIT $2
UPDATE "users" SET "name" = $1, "updated_at" = $2 WHERE "users"."id" = $3
Each session saves only its own changes, and many run at once. Observers registered on the root are shared. A session needs no closing.
A session shares the root's pool, so closing a session closes it for everyone. Close only the context from Open.
Keep the shared context out of tracking
ant.Open gives a context that tracks, so handlers that use it directly share one tracker (two operations at once). Open it with tracking off and turn tracking on in the sessions that save:
db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithTracking(false))
session := ant.Session(db, ant.WithTracking(true))
A session inherits the root's settings, so on a tracking-off root it has tracking off and SaveChanges has nothing to save.
Reads, bulk Update and Delete, and Insert don't touch a tracker, so a context with tracking off is safe to share between goroutines:
// A background job on the shared, tracking-off context.
func purge(ctx context.Context) error {
_, err := db.Posts.Where(ant.Eq(&Posts.Published, false)).Delete(ctx)
// DELETE FROM "posts" WHERE "posts"."published" = $1
return err
}
One exception: ant.Add and ant.Attach fill the tracker even when tracking is off. Once a tracking-off context holds an entity, it is no longer safe to share.
Two operations at once
Every load returns the tracker's one instance of a row, and Include writes the related rows into it. Two requests on one tracking context would load into the same entities while both change them: each would reset Alice's posts and append its own, so both would see the posts twice.
While one operation uses the tracker, another gets ant.ErrConcurrentUse at once instead of waiting.
// db tracks, and two requests call this at the same time.
user, err := db.Users.Include(&Users.Posts).Find(ctx, id)
if errors.Is(err, ant.ErrConcurrentUse) {
// the other request got the tracker first
}
Fix it with a session per goroutine, including parallel work inside one request:
var wg sync.WaitGroup
for _, id := range userIDs {
wg.Go(func() {
session := ant.Session(db, ant.WithTracking(true))
user, err := session.Users.Find(ctx, id)
if err != nil {
return
}
user.Age++
_ = session.SaveChanges(ctx)
})
}
wg.Wait()
What claims the tracker
| Operation | Claims |
|---|---|
Tracked reads: All, First, Single, Find (also from the identity map), Include | When tracking is on |
SaveChanges | Always |
Insert, Upsert, DeleteByID, Load, LoadMissing, Reload | When tracking is on, or the tracker holds anything |
ant.Add, Attach, Remove, MarkModified, Detach, TrackGraph, Tracked, Entry, ClearTracked, HasChanges, DebugTracked | Always |
Reads with NoTracking, Select, Project or ant.Raw, and bulk Update and Delete | Never |
Each of these takes the ctx you pass, which is how a nested call knows it belongs to the same operation. Chunk claims the tracker for one batch at a time, so the callback can run its own queries.
Hooks
A hook runs inside the operation that called it. Its queries must use the ctx the hook receives, which carries the operation's claim.
func (u *User) AfterLoad(ctx context.Context) error {
// ctx is the hook's: this query belongs to the load that called it
count, err := db.Posts.Where(ant.Eq(&Posts.UserID, u.ID)).Count(ctx)
if err != nil {
return err
}
_ = count
return nil
}
A query in a hook with any other context, such as context.Background(), looks like a second operation and fails with ErrConcurrentUse. Goroutines you start inside an operation with its context share the claim, so they must not use the tracker at the same time. See hooks.
See it tested: tests/features/change_tracking/concurrent_use_test.go
See it tested: tests/features/change_tracking/sessions_test.go