SaveChanges
ant snapshots each entity it loads. SaveChanges compares every tracked entity with its snapshot and writes the differences: one UPDATE per changed entity, with only the changed columns, plus any inserts and deletes.
Update what you loaded
user, err := db.Users.Find(ctx, id)
if err != nil {
return err
}
user.Age++
err = db.SaveChanges(ctx)
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
Only the changed column is written, so a value someone else changed meanwhile isn't overwritten by your stale copy. With no changes, no statement is sent.
A zero value is a change like any other:
user.Age = 0
user.Bio = nil
err = db.SaveChanges(ctx)
// UPDATE "users" SET "age" = $1, "bio" = $2, "updated_at" = $3 WHERE "users"."id" = $4
A write through a pointer counts too.
What counts as a change
Comparison is reflect.DeepEqual with adjustments, so values that are equal in the database don't produce an UPDATE:
- A float
NaNequalsNaN. - Times are equal when they are the same instant, in any zone and at any depth, such as inside an
sql.Null[time.Time]orant.UnixTime. - An edit inside a decoded JSON value is seen, including a key set in a
map[string]anyor an element changed in a[]any. niland empty stay different, as NULL and''are in the database.
For a value where deep equality is wrong, see custom comparers.
Save several entities
SaveChanges covers everything the context tracks, with parents before children on insert and children first on delete.
user.Age = 30
post.Title = "Edited"
err := db.SaveChanges(ctx)
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
// UPDATE "posts" SET "title" = $1, "updated_at" = $2 WHERE "posts"."id" = $3
New entities are batched into one INSERT per table and fill in their keys:
err := ant.Add(ctx, db, &User{Name: "N1", Email: "n1@example.com"})
err = ant.Add(ctx, db, &User{Name: "N2", Email: "n2@example.com"})
err = db.SaveChanges(ctx)
// INSERT INTO "users" ("created_at", "updated_at", "name", "email", "age", "bio")
// VALUES ($1, $2, $3, $4, $5, $6), ($7, $8, $9, $10, $11, $12) RETURNING "id"
What is tracked
All, First, Single and Find track their results, and so do Insert and the rows an Include loads. All returns pointers, so changes in a range count.
users, err := db.Users.All(ctx)
for _, user := range users {
user.Age = 50
}
err = db.SaveChanges(ctx)
These aren't tracked, so changing them saves nothing:
| Results of | Why |
|---|---|
Each | It yields values, one at a time |
Column, Omit | Their zero fields aren't real values |
NoTracking | You asked |
ant.Raw, FromRaw, Project, Select | They aren't whole entities |
One transaction, all or nothing
SaveChanges always runs in a transaction, or in a savepoint when it is called inside one. If any statement fails, nothing is saved.
first := &User{Name: "N1", Email: "n1@example.com"}
second := &User{Name: "N2", Email: "alice@example.com"} // taken
err := ant.Add(ctx, db, first)
err = ant.Add(ctx, db, second)
err = db.SaveChanges(ctx)
// ERROR: duplicate key value violates unique constraint "users_email_key" (SQLSTATE 23505)
After a failure the entities are as they were before the call:
- Keys the save generated are cleared, so
first.IDandsecond.IDare 0 again, not the ids of rows that were rolled back. db.HasChanges(ctx)is still true.
Fix the cause and call SaveChanges again to insert both users with new keys.
first := &User{Name: "N1", Email: "n1@example.com"}
second := &User{Name: "N2", Email: "alice@example.com"} // taken
err := ant.Add(ctx, db, first)
err = ant.Add(ctx, db, second)
err = db.SaveChanges(ctx) // fails, nothing saved, first.ID == 0
second.Email = "n2@example.com"
err = db.SaveChanges(ctx) // inserts both
A save that failed on a deadlock or serialization conflict can run again by itself.
When SaveChanges runs inside a transaction that later rolls back, the tracker takes the save back too.
ant.WithoutAutoTx() turns off the transaction SaveChanges and Insert open for themselves, so a failure partway leaves the earlier statements in place. Use it only when you manage transactions yourself.
Changed or removed since it was loaded
An UPDATE or DELETE that finds no row means someone else removed the row or, with a version column, changed it. SaveChanges returns ant.ErrConcurrency and writes nothing.
session := ant.Session(db)
user, err := session.Users.Find(ctx, id)
// another request deletes the user here
user.Age = 5
err = session.SaveChanges(ctx)
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
// err: ant: row was changed or removed since it was loaded: User 7
if errors.Is(err, ant.ErrConcurrency) {
// reload and try again, or tell the caller
}
Changing a primary key on a tracked entity returns ant.ErrKeyChanged. Add a new entity and remove the old one.
Is anything pending?
HasChanges plans the save that SaveChanges would make, without writing anything or changing any entity.
user.Age = 60
has, err := db.HasChanges(ctx)
// has is true
It also sees a post appended to, removed from, or moved between loaded relations. See changing relations.
Preview a save
ant.DryRun runs a function in a transaction, rolls it back, and returns every statement it ran.
statements, err := ant.DryRun(ctx, ant.Session(db), func(tx *AppDB) error {
user, err := tx.Users.Find(ctx, id)
if err != nil {
return err
}
user.Age = 99
return tx.SaveChanges(ctx)
})
for _, s := range statements {
fmt.Println(s.SQL)
}
// SELECT ... FROM "users" WHERE "users"."id" = $1 LIMIT $2
// SAVEPOINT ant_sp_1
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3
// RELEASE SAVEPOINT ant_sp_1
Entities loaded inside stay in the tracker with their edits, so pass a throwaway session.
One instance per row
A context holds one instance per row, so a later query returns the same pointer, with your unsaved changes.
first, err := db.Users.Find(ctx, id)
first.Age = 70
again, err := db.Users.Where(ant.Eq(&Users.ID, id)).Single(ctx)
fmt.Println(first == again, again.Age) // true 70
A bulk Update doesn't touch tracked entities. Reload picks up database changes, and they become the new baseline.
Turning it off
NoTracking opts one query out, in any position in the chain. WithTracking(false) turns tracking off for a whole context.
db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn, ant.WithTracking(false))
session := ant.Session(db, ant.WithTracking(true))
A context with tracking off never grows and is safe to share between goroutines. Tracking lives in the sessions that save.
Custom comparers
b.Comparer replaces deep equality for one field, such as a list whose order means nothing.
type Tagged struct {
ID int64
Items ant.JSON[[]string]
}
func (Tagged) Configure(b *ant.ModelBuilder[Tagged]) {
b.Comparer(&Taggeds.Items, sameItems)
}
func sameItems(a, b ant.JSON[[]string]) bool {
return slices.Equal(slices.Sorted(slices.Values(a.V)), slices.Sorted(slices.Values(b.V)))
}
var Taggeds = ant.Fields[Tagged]()
A tracker keeps growing until it is cleared, and a tracking context serves one operation at a time. Use a session per unit of work.
See it tested: tests/features/change_tracking/save_changes_test.go