Skip to content

Commit

Permalink
Making "Locking" section in "Advanced Query" more elaborate (#725)
Browse files Browse the repository at this point in the history
* Making "Locking" section in "Advanced Query" more elaborate

* Revert yarn changes
  • Loading branch information
dogenkigen authored Dec 19, 2023
1 parent a46343c commit c3a991d
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions pages/docs/advanced_query.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,28 +43,40 @@ db.Session(&gorm.Session{QueryFields: true}).Find(&user)
// SELECT `users`.`name`, `users`.`age`, ... FROM `users`
```

## Locking (FOR UPDATE)
## Locking

GORM supports different types of locks, for example:

```go
db.Clauses(clause.Locking{Strength: "UPDATE"}).Find(&users)
// SELECT * FROM `users` FOR UPDATE
```
The above statement will lock the selected rows for the duration of the transaction. This can be used in scenarios where you are preparing to update the rows and want to prevent other transactions from modifying them until your transaction is complete.

The `Strength` can be also set to `SHARE` which locks the rows in a way that allows other transactions to read the locked rows but not to update or delete them.
```go
db.Clauses(clause.Locking{
Strength: "SHARE",
}).Find(&users)
// SELECT * FROM `users` FOR SHARE OF `users`
```
The `Table` option can be used to specify the table to lock. This is useful when you are joining multiple tables and want to lock only one of them.
```go
db.Clauses(clause.Locking{
Strength: "SHARE",
Table: clause.Table{Name: clause.CurrentTable},
}).Find(&users)
// SELECT * FROM `users` FOR SHARE OF `users`

```
Options can be provided like `NOWAIT` which tries to acquire a lock and fails immediately with an error if the lock is not available. It prevents the transaction from waiting for other transactions to release their locks.
```go
db.Clauses(clause.Locking{
Strength: "UPDATE",
Options: "NOWAIT",
}).Find(&users)
// SELECT * FROM `users` FOR UPDATE NOWAIT
```

Refer [Raw SQL and SQL Builder](sql_builder.html) for more detail
Another option can be `SKIP LOCKED` which skips over any rows that are already locked by other transactions. This is useful in high concurrency situations where you want to process rows that are not currently locked by other transactions.

## SubQuery

Expand Down

0 comments on commit c3a991d

Please sign in to comment.