Skip to main content

Optimistic concurrency

Without a check, the second of two saves of the same row overwrites the first. A version field makes the second save fail.

Add a version field​

ant:"version" marks a signed integer field as the row's version. It starts at 1 and goes up by one with every write. A version of any other type, such as uint32, a string or a pointer, is refused when the context opens; use a token for a value you manage.

type Page struct {
ID int64
Title string
Slug string `ant:"unique"`
Version int64 `ant:"version"`
}

A save changes the row only if it still has the version you loaded:

a, err := db.Pages.Find(ctx, id)

a.Title = "first"
err = db.SaveChanges(ctx)
// UPDATE "pages" SET "title" = $1, "version" = $2
// WHERE "pages"."id" = $3 AND "pages"."version" = $4
// -- $1 = "first", $2 = 2, $3 = 1, $4 = 1

If no row matches, the row changed or was deleted since you loaded it. The save returns ant.ErrConcurrency and writes nothing.

Detect a collision​

The second of two sessions to save loses:

one, two := ant.Session(db), ant.Session(db)

a, err := one.Pages.Find(ctx, id)
b, err := two.Pages.Find(ctx, id)

a.Title = "first"
err = one.SaveChanges(ctx) // fine

b.Title = "second"
err = two.SaveChanges(ctx) // ant.ErrConcurrency

Handle a conflict​

The error is an *ant.ConcurrencyError, naming the model and key. Reload the row, then let the user retry.

err := db.SaveChanges(ctx)

var conflict *ant.ConcurrencyError

if errors.As(err, &conflict) {
fmt.Println(conflict.Model, conflict.Key)

return db.Pages.Reload(ctx, page)
}

A handler maps it to a 409:

func save(w http.ResponseWriter, r *http.Request) {
err := db.SaveChanges(r.Context())

if errors.Is(err, ant.ErrConcurrency) {
http.Error(w, "someone else changed this page, reload and try again", http.StatusConflict)

return
}
}

Every write moves the version​

Every write to a versioned row moves its version on by one, so an earlier copy cannot save over it.

WriteVersion
SaveChangesChecked, then moved on
Delete through SaveChangesChecked: DELETE ... WHERE id = $1 AND version = $2
Bulk UpdateMoved on, not checked
Soft delete and RestoreMoved on, and checked through SaveChanges
Upsert, InsertMany with a conflict, MergeMoved on when the row exists; a new row starts at 1
Unlinking a child from a to-many relationMoved on
_, err := db.Pages.Where(ant.Eq(&Pages.Slug, "home")).Update(ctx, ant.Set(&Pages.Title, "Home"))
// UPDATE "pages" SET "title" = $1, "version" = ("version" + $2) WHERE "pages"."slug" = $3

The version belongs to ant. Naming it in a bulk Update, in an upsert's DoUpdate or Set, or in a Merge assignment is an error, returned before any SQL runs:

_, err := db.Pages.Where(ant.Eq(&Pages.Slug, "home")).Update(ctx, ant.Set(&Pages.Version, int64(1)))
// ant: Page.Version is a version, which ant moves on by itself; leave it out

Upsert a copy you loaded​

An Upsert of an entity with a non-zero version is treated as a copy of a stored row: its update applies only while the stored row has that version, otherwise it returns a ConcurrencyError. A zero version is a new entity, so the version moves on without a check.

mine := &Page{Slug: "home", Title: "mine", Version: loaded.Version}

wrote, err := db.Pages.Upsert(ctx, mine, ant.OnConflict(&Pages.Slug))
// INSERT INTO "pages" ("title", "slug", "version") VALUES ($1, $2, $3)
// ON CONFLICT ("slug") DO UPDATE
// SET "title" = "excluded"."title", "version" = ("pages"."version" + 1)
// WHERE "pages"."version" = $4
// RETURNING "id", "title", "slug", "version"
wrote, err := db.Pages.Upsert(ctx, &Page{Slug: "home", Title: "new"}, ant.OnConflict(&Pages.Slug))
// INSERT INTO "pages" ("title", "slug", "version") VALUES ($1, $2, $3)
// ON CONFLICT ("slug") DO UPDATE
// SET "title" = "excluded"."title", "version" = ("pages"."version" + 1)
// RETURNING "id", "title", "slug", "version"

InsertMany with a conflict moves versions on but cannot check them, because it cannot tell a row's own version from the 1 it stamps on a new row.

MySQL and MariaDB have no condition on ON DUPLICATE KEY UPDATE. There, ant writes each assignment as col = CASE WHEN version = ? THEN new ELSE col END, so a stale copy changes nothing and the zero affected rows give ErrConcurrency. ant reads the affected-row count, so leave the driver's clientFoundRows off (the default). See databases.

Two copies of one row in one save​

If a save writes two instances of the same versioned row, the version carries forward from the first write to the second, so the second does not fail.

A token you manage​

ant:"token" works like a version, but the value is yours, such as an ETag. A NULL token compares correctly.

type Stock struct {
ID int64
Quantity int
ETag *string `ant:"token"`
}