Sequelize Paranoid 옵션

twoStones·2022년 7월 24일
0

sequelize

목록 보기
3/3

시퀄라이즈는 paranoid tables 컨셉을 지원.
paranoid table은 레코드를 삭제할 때 실제로 삭제하지 않고 deletedAt 컬럼에 timestamp 값을 넣는다. hard-deletion이 아닌 soft-deletion.

모델에 paranoid 옵션 추가

class Post extends Model {}
Post.init({ /* attributes here */ }, {
  sequelize,
  paranoid: true, // 이 옵션을 주면 된다 

  // 다른 이름으로 할 수도 있다
  deletedAt: 'destroyTime'
});
  • timestamp 옵션이 false로 되어 있으면 paranoid 옵션은 동작하지 않는다

삭제

await Post.destroy({
  where: {
    id: 1
  }
});

// UPDATE "posts" 
//    SET "deletedAt"=[timestamp] 
//  WHERE "deletedAt" IS NULL AND "id" = 1
  • destroy 메소드를 호출하면 soft-deletion이 발생
await Post.destroy({
  where: {
    id: 1
  },
  force: true
});
// DELETE FROM "posts" WHERE "id" = 1
  • model에 paranoid 옵션이 있지만 destroy 메서드 호출 시 force 속성의 값을 true로 주면 강제로 삭제 가능

soft 삭제 복구(Restoring)

// Example showing the instance `restore` method
// We create a post, soft-delete it and then restore it back
const post = await Post.create({ title: 'test' });
console.log(post instanceof Post); // true
await post.destroy();
console.log('soft-deleted!');
await post.restore();
console.log('restored!');

// Example showing the static `restore` method.
// Restoring every soft-deleted post with more than 100 likes
await Post.restore({
  where: {
    likes: {
      [Op.gt]: 100
    }
  }
});

findAll()과 findByPk() 에서 paranoid 옵션

await Post.findByPk(123); // This will return `null` if the record of id 123 is soft-deleted
await Post.findByPk(123, { paranoid: false }); // This will retrieve the record

await Post.findAll({
  where: { foo: 'bar' }
}); // This will not retrieve soft-deleted records

await Post.findAll({
  where: { foo: 'bar' },
  paranoid: false
}); // This will also retrieve soft-deleted records
  • findAll(), findByPk() 함수는 소프트 삭제된 레코드를 조회하지 않는다. 그런데 paranoid:false 옵션을 주면 소프트 삭제된 레코드도 조회한다
profile
일단 작성

0개의 댓글