Skip to main content

Locks and hints

A lock holds rows until the transaction ends, so use locks inside a Tx.

Lock a row for update​

Read the row with ForUpdate, change it, and save in the same transaction. Others who try to lock or write the row wait.

err := db.Tx(ctx, func(tx *AppDB) error {
user, err := tx.Users.Where(ant.Eq(&Users.ID, id)).ForUpdate().Single(ctx)
// SELECT ... FROM "users" WHERE "users"."id" = $1 LIMIT $2 FOR UPDATE
if err != nil {
return err
}

user.Age++

return tx.SaveChanges(ctx)
})
MethodMeansSQL
ForUpdate()Lock for writing. Others waitFOR UPDATE
ForShare()Lock against writers. Other readers are fineFOR SHARE
NoWait()Fail at once on a locked rowNOWAIT
SkipLocked()Leave locked rows outSKIP LOCKED

NoWait and SkipLocked follow ForUpdate or ForShare. ForUpdate is always sent to the primary, even with replicas.

Count, Exists, Page's total and the aggregates such as SumOf run without the lock, which PostgreSQL refuses on an aggregate, so one locked query can be counted and read. With IncludeJoined, the lock is FOR UPDATE OF the query's own table, so the joined parent stays unlocked; MariaDB has no OF, and locks both.

Claim jobs from a queue​

SkipLocked lets each worker claim a row nobody else holds.

err := db.Tx(ctx, func(tx *AppDB) error {
job, err := tx.Jobs.OrderBy(&Jobs.ID).ForUpdate().SkipLocked().First(ctx)
// SELECT ... FROM "jobs" ORDER BY "jobs"."id" LIMIT $1 FOR UPDATE SKIP LOCKED
if err != nil {
return err
}

job.Done = true

return tx.SaveChanges(ctx)
})

When no row is free, First returns ant.ErrNotFound.

Row locks depend on the database. PostgreSQL and MySQL have them all, MariaDB has ForUpdate only, and SQLite and SQL Server return ant.ErrUnsupported. See databases.

Add an optimizer hint​

Hint writes an optimizer hint before the statement. PostgreSQL ignores hints without the pg_hint_plan extension.

users, err := db.Users.Query().Hint("SeqScan(users)").All(ctx)
// /*+ SeqScan(users) */ SELECT ... FROM "users"

MySQL and MariaDB read the hint right after SELECT, so ant writes it there: SELECT /*+ ... */ .... SQLite and SQL Server see the hint as a comment.

Tag a query​

Tag adds a comment to the SQL, to find a query in database logs.

users, err := db.Users.Where(ant.Gt(&Users.Age, 18)).Tag("dashboard: adults").All(ctx)
// /* dashboard: adults */ SELECT ... FROM "users" WHERE "users"."age" > $1

Tag and Hint can't be broken out of. ant puts a space between the characters of */ or /* in the text, so */ DROP TABLE users; /* is written as * / DROP TABLE users; / *.