[TIL_Carrotww] 74 - 22/12/16

유형석·2022년 12월 16일
0

TIL

목록 보기
87/138
post-thumbnail

📝Carrotww의 코딩 기록장

🧲 transction

  • Transaction
    트랜잭션은 DB의 데이터 삽입, 수정, 삭제를 징행할 때 성공 실패를 분명히 하고 상호 독립적이며 일관되게 처리하는 기능.

🧲 django transction

🔍 django 에서는 기본적으로 auto commit을 지원하여 성공 시 DB에 commit, 실패 시 자동으로 rollback 시킨다.

atomic(using=None, savepoint=True, durable=False)

위 코드로 트랜잭션이 시작된다. 3번째 인자인 durable은 django 3.2 버전에서 추가된 기능이다.

복수의 쿼리를 실행시켜 이를 모두 성공 또는 실패로 처리해야 한다면 atomic 이란 기능을 사용하면 되는데,
데코레이터와 with 두 가지 방식이 있다.

🧲 데코레이터

@transaction.atomic()
def test():
    Article.objects.filter(id=1).update(title='decorator')
    Workshop.objects.filter(id=1).update(content='decorator')

함수 위에 decorator를 써주면 된다.

🧲 with 문

with transaction.atomic():
 	Article.objects.filter(id=1).update(title='decorator')
    Workshop.objects.filter(id=1).update(content='decorator')

두 가지 같은 기능이며 Article이 수정되고 Workshop이 실패한다면 Article은 rollback이 진행된다.

  • 기본적인 사용 방식
from django.db import DatabaseError, transaction

obj = MyModel(active=False)
obj.active = True
try:
    with transaction.atomic():
        obj.save()
except DatabaseError:
    obj.active = False

위 코드에서 Django 트랜잭션 관리
1. 가장 바깥쪽 atomic 들어갈때 트랜잭션 활성화
2. 내부 atomic 블록에 들어갈 때, savepoint 생성
3. 내부 블록을 종료할 때, savepoint 해제 - 성공했을 경우
rollback - 실패했을 경우 진행
4. try-except 블록을 빠져나갈 때,
트랜잭션을 성공했을 경우 commit
실패했을 경우 - rollback

atomic 두 번째 인자

atomic의 두 번째 인자는 savepoint를 허용할 지 설정해주는 것으로 False로 설정하게 되면 savepoint 생성을 비활성화 할 수 있다.
savepoint를 허용하지 않아도 트랜잭션에 의해 무결성을 보장할 수 있지만, 에러 핸들링이 멈추게 되어 과도한 savepoint로 오버헤드가 많이 발생하는 것이 아니라면 건들지 않는것이 좋다.

profile
Carrot_hyeong

0개의 댓글