mirror of
https://github.com/ent/ent.git
synced 2026-05-22 09:31:45 +03:00
22 lines
719 B
Markdown
22 lines
719 B
Markdown
# [Optimistic Lock](https://en.wikipedia.org/wiki/Optimistic_concurrency_control) Using Hooks
|
|
|
|
In this example, we implement an optimistic locking mechanism using an `ent.Hook`.
|
|
|
|
The idea is to add to our schema a `version` field that holds the Unix time of when the latest update occurred.
|
|
When an `UpdateOne` operation is executed, the hook updates the `version` field with the new value and adds a predicate
|
|
to verify that the `version` wasn't updated by another process/transaction during the mutation.
|
|
|
|
An error is returned if the versions are mismatched, and the user should reload the entity and retry the mutation.
|
|
|
|
### Generate Assets
|
|
|
|
```console
|
|
go generate ./...
|
|
```
|
|
|
|
### Run Example
|
|
|
|
```console
|
|
go test
|
|
```
|