docs/models/optimistic-locking.mdx
import Tabs from '@theme/Tabs'; import TabItem from '@theme/TabItem';
Sequelize has built-in support for optimistic locking through a model instance version count.
Whenever Sequelize needs to modify the model,
it will make sure that the version count on the model instance is equal to the version count in the database.
If the counts are different, an OptimisticLockError will be thrown.
Optimistic locking is disabled by default and can be enabled by using the @Version decorator on the attribute of your model
that should be used as the version count.
import { InferCreationAttributes, InferAttributes, Model, CreationOptional } from '@sequelize/core';
import { Version } from '@sequelize/core/decorators-legacy';
class User extends Model<InferAttributes<User>, InferCreationAttributes<User>> {
// highlight-next-line
@Version
declare version: CreationOptional<number>;
}
import { Model } from '@sequelize/core';
import { Version } from '@sequelize/core/decorators-legacy';
class User extends Model {
// highlight-next-line
@Version
version;
}