Skip to main content

Update and delete

Update and Delete write straight to the database without loading anything, and return how many rows they touched. To save changes to entities you've loaded, use SaveChanges.

Update​

Assignments are explicit, so zeros and nil are written.

n, err := db.Users.
Where(ant.Eq(&Users.ID, id)).
Update(ctx, ant.Set(&Users.Age, 0), ant.Set(&Users.Bio, nil))
// UPDATE "users" SET "age" = $1, "bio" = $2, "updated_at" = $3 WHERE "users"."id" = $4

UpdatedAt is set automatically unless you pass ant.Set(&Users.UpdatedAt, t). On a model with a version, the version is incremented:

// UPDATE "docs" SET "views" = ("docs"."views" + $1), "updated_at" = $2, "version" = ("version" + $3)
// WHERE "docs"."title" = $4

Assigning the version returns an error before the statement runs. Assigning the same field twice also returns an error naming it, because PostgreSQL and SQL Server refuse it and MySQL keeps the last.

Change a value relative to the row​

Inc and Dec run in the database, so concurrent writers don't lose updates:

_, err := db.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.Inc(&Users.Age, 1))
// UPDATE "users" SET "age" = ("users"."age" + $1), "updated_at" = $2 WHERE "users"."id" = $3

SetExpr assigns any expression, such as a function of another column:

_, err := db.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.SetExpr(&Users.Email, ant.Lower(&Users.Name)))
// UPDATE "users" SET "email" = LOWER("users"."name"), "updated_at" = $1 WHERE "users"."id" = $2
oldest := ant.SubExpr(db.Users.Where(), ant.Max(&Users.Age)).Expr()

_, err := db.Users.Where(ant.Eq(&Users.ID, id)).Update(ctx, ant.SetExpr(&Users.Age, oldest))
// UPDATE "users" SET "age" = (SELECT MAX("users"."age") FROM "users"), "updated_at" = $1
// WHERE "users"."id" = $2

On MySQL, a write whose subquery reads its own table is wrapped in a derived table, because MySQL refuses the plain form. See databases.

Delete​

n, err := db.Users.Where(ant.Lt(&Users.Age, 18)).Delete(ctx)
// DELETE FROM "users" WHERE "users"."age" < $1

On a model with soft deletes, this marks the rows instead of removing them.

Delete by relation​

Conditions can use relations, so no join is needed:

n, err := db.Users.Where(ant.HasNone(&Users.Posts)).Delete(ctx)
// DELETE FROM "users" WHERE NOT EXISTS (
// SELECT 1 FROM "posts" AS "ant_related" WHERE "ant_related"."user_id" = "users"."id")

Delete by key​

DeleteByID removes one row and returns ant.ErrNotFound if there is none.

err := db.Users.DeleteByID(ctx, id)
// DELETE FROM "users" WHERE "users"."id" = $1

The no-condition guard​

A bulk write with no condition returns ant.ErrNoCondition. Unfiltered opts out.

_, err := db.Users.Query().Delete(ctx) // ant.ErrNoCondition

n, err := db.Users.Unfiltered().Delete(ctx) // every row, on purpose
// DELETE FROM "users"

The guard also refuses conditions that can't exclude a row.

var none []string

_, err := db.Users.Where(ant.And()).Delete(ctx) // refused
_, err = db.Users.Where(ant.NotIn(&Users.Name, none...)).Delete(ctx) // refused

n, err := db.Users.Where(ant.In(&Users.Name, none...)).Delete(ctx) // fine: deletes nothing

A When that was skipped leaves the guard on too.

Limit a write​

Limit and Offset bound a bulk write. Add an ordering to choose which rows. SQL has no LIMIT on UPDATE or DELETE, so ant selects the rows by key in a subquery.

n, err := db.Users.Where(ant.Lt(&Users.Age, 18)).OrderBy(&Users.CreatedAt).Limit(100).Delete(ctx)
// DELETE FROM "users" WHERE "users"."id" IN (
// SELECT "users"."id" FROM "users" WHERE "users"."age" < $1
// ORDER BY "users"."created_at" LIMIT $2)

To purge in chunks, repeat until n is zero. Offset also works without Limit, on MySQL and MariaDB too.

Write through a derived source​

UPDATE and DELETE name only a table. When the query reads from From, FromCTE, a set operation (Union, Except and the rest), or Recursive, ant selects the matching rows by key in a subquery, so the source's conditions apply.

old := db.Users.Where(ant.Gt(&Users.Age, 60))

n, err := db.Users.Query().From(old).Update(ctx, ant.Inc(&Users.Age, 1))
// UPDATE "users" SET "age" = ("users"."age" + $1), "updated_at" = $2
// WHERE "users"."id" IN (SELECT "users"."id" FROM (
// SELECT ... FROM "users" WHERE "users"."age" > $3) AS "users")
old := db.Users.Where(ant.Gt(&Users.Age, 60))

n, err := db.Users.Query().FromCTE("old", old).Delete(ctx)
// DELETE FROM "users" WHERE "users"."id" IN (
// WITH "old" AS (SELECT ... FROM "users" WHERE "users"."age" > $1)
// SELECT "users"."id" FROM "old" AS "users")

The rules, each checked before anything runs:

Get the rows back​

UpdateReturning and DeleteReturning return what they touched, in the same statement. Support varies: see databases.

changed, err := db.Users.Where(ant.Gt(&Users.Age, 18)).UpdateReturning(ctx, ant.Inc(&Users.Age, 1))
// UPDATE "users" SET ... WHERE "users"."age" > $2 RETURNING "id", "created_at", ...

removed, err := db.Users.Where(ant.Eq(&Users.Name, "Bob")).DeleteReturning(ctx)
// DELETE FROM "users" WHERE "users"."name" = $1 RETURNING "id", "created_at", ...

Both apply the same no-condition guard.

Reloading an entity​

Reload replaces an entity's columns with what is stored now and discards unsaved changes. Relations are left alone.

_, err := db.Users.Where(ant.Eq(&Users.ID, user.ID)).Update(ctx, ant.Set(&Users.Age, 41))

err = db.Users.Reload(ctx, user)
// SELECT ... FROM "users" WHERE "users"."id" = $1
Bulk writes skip the model layer

Update and Delete run no hooks and no SaveInterceptor, because they load no entities, and a bulk update doesn't touch tracked structs. They do apply global filters, timestamps and the version.