Skip to main content

Entity states

SaveChanges writes each tracked entity according to its state. ant sets the state on load, insert and edit. Set it yourself for a struct that didn't come from a query.

These calls take a ctx, return an error and claim the tracker, so call them on a session that no other goroutine is using.

The states​

StateMeansNext SaveChanges
ant.DetachedNot trackedNothing
ant.AddedNewINSERT
ant.UnchangedMatches what was loadedNothing
ant.ModifiedDiffers from what was loadedUPDATE
ant.DeletedMarked for removalDELETE

Insert on the next save​

ant.Add marks a new entity. Adding several and saving once batches them into one INSERT per table.

newUser := &User{Name: "Dana", Email: "dana@example.com"}

err := ant.Add(ctx, db, newUser)
err = db.SaveChanges(ctx)
// INSERT INTO "users" ("created_at", "updated_at", "name", "email", "age", "bio")
// VALUES ($1, $2, $3, $4, $5, $6) RETURNING "id"

Delete on the next save​

err := ant.Remove(ctx, db, user)
err = db.SaveChanges(ctx)
// DELETE FROM "users" WHERE "users"."id" = $1

Remove on an entity that was added and never saved cancels the insert and writes nothing.

Track a row you already know​

ant.Attach tracks an entity as it is, assuming it matches the database. Later edits save only the changed columns. Use it for a value from your own cache or a previous request.

err := ant.Attach(ctx, db, existing)

existing.Age = 32

err = db.SaveChanges(ctx)
// UPDATE "users" SET "age" = $1, "updated_at" = $2 WHERE "users"."id" = $3

Write every column​

ant.MarkModified is for a struct with no known earlier values, such as a request body. The next save writes every column the struct holds, and stamps updated_at with the current time, as any update does, so a body that left it out doesn't store the zero time. The same goes for an entity TrackGraph decides is Modified.

err := ant.MarkModified(ctx, db, disconnect)
err = db.SaveChanges(ctx)
// UPDATE "users" SET "updated_at" = $1, "name" = $2, "email" = $3, "age" = $4, "bio" = $5
// WHERE "users"."id" = $6

A field the body left out is written as its zero value, so use it only when the struct is the whole row.

Stop tracking​

err := ant.Detach(ctx, db, user) // forget this entity and its unsaved changes
err = db.ClearTracked(ctx) // forget everything

Look at what the tracker knows​

ant.Entry returns a snapshot of one entity's state, taken under the claim. It doesn't change when the entity does.

entry, err := ant.Entry(ctx, db, user)

fmt.Println(entry.State()) // Modified
fmt.Println(entry.Changed()) // [Age]

dirty := ant.IsDirty(entry, &Users.Age)
before, err := ant.Original(entry, &Users.Age)

An untracked entity is Detached, and Original on it returns ant.ErrNotTracked.

ant.Tracked[User](ctx, db) lists the tracked entities of one type, oldest first. db.DebugTracked(ctx) returns the tracker as text:

text, err := db.DebugTracked(ctx)
// User {1} Modified Age

Save a tree from outside​

ant.TrackGraph tracks a tree from outside, like a request body. Your function decides each entity's state, and HasKey is true when the entity already has a key.

err := ant.TrackGraph(ctx, db, incoming, func(n ant.GraphNode) ant.State {
if n.HasKey {
return ant.Modified
}

return ant.Added
})

err = db.SaveChanges(ctx)
// UPDATE "users" SET ... WHERE "users"."id" = $6
// UPDATE "posts" SET ... WHERE "posts"."id" = $5
// INSERT INTO "posts" (...) VALUES (...) RETURNING "id"

Foreign keys are filled in as it walks, so the new post above gets its user's key. Returning ant.Detached skips an entity and everything below it. A Modified entity writes every column, as MarkModified does.