I have a certain model where I want to add a unique constraint on two columns, id and name, so that entries with the same id and name cannot be created. However, if an entry with the same id and name has previously been deleted (softly), I don't want an UniqueConstraintError to be thrown.
The model is defined as:
import { Model, DataTypes, Sequelize } from 'sequelize';
interface myModelAttributes {
id: number,
name: string,
deletedAt: string,
createdAt: string,
updatedAt: string,
}
module.exports = (sequelize: Sequelize) => {
class myModel extends Model<myModelAttributes>
implements myModelAttributes {
declare id: number;
declare name: string;
declare deletedAt: string;
declare createdAt: string;
declare updatedAt: string;
}
myModel.init({
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
},
deletedAt: {
type: DataTypes.DATE,
allowNull: true,
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
},
updatedAt: {
type: DataTypes.DATE,
allowNull: false,
},
}, {
sequelize,
modelName: 'myModel',
paranoid: true,
timestamps: true,
});
return myModel;
};
and I added a migration for this constraint:
module.exports = {
up: async (queryInterface) => {
await queryInterface.addConstraint('myModel', {
fields: ['name', 'id'],
type: 'unique',
});
},
down: async (queryInterface) => {
await queryInterface.addConstraint('myModel', ['name', 'id']);
},
};
This works for preventing duplicate entries, but I want to extend it to ignore deleted records (where deletedAt !== null). How can I go about this?