본문 바로가기
Database/mysql

[MYSQL/Database] TCL(Transaction Control Laguage)

by JINJINC 2023. 4. 11.
728x90
반응형

 TCL ( Transaction Control Language)

- DCL(Data Control Language)의 Commit과 Rollback을 따로 분리하여 TCL이라고 한다.

- 하나의 작업단위 : 전부 성공 또는 전부 취소  <예> A은행 -> B은행 : 10만원 이체

- REDO 로그를 사용해서 과거의 데이터를 최신 데이터 쪽으로 흐르게 하는 것을 '롤 포워드(roll-forward)'라고 한다.
  반대로, UNDO 정보를 사용해서 변경을 취소(과거의 상태로 되돌린다)하는 것을 '롤백(rollback)'이라고 한다.

- 트랜잭션의 특징(ACID)

 

  • 원자성(Atomicity) : The entire transation takes place at once or doesn't happen at all.                 
  •  일관성(Consistency) : The database must be consistent before and after the transation.
  •  독립성(Isolation) : Mutiple Transation occur independently without interference.
  • 영구성(Durability) : The changes of a successful transation occurs even if the system failure occurs.

처음 MYSQL을 설치하면 AUTOCOMMIT이 1로 설정되어 있어서 ROLLBACK 이 안된다 .
그래서AUTOCOMMIT을 0으로 설정한 쿼리를 ROLLBACK하여 구성 함

 

0. 연습용 테이블 생성
create table t1(id int, name varchar(30));

insert into t1 values(1, '홍길동');
insert into t1 values(2, '서길동');
insert into t1 values(3, '남길동');
insert into t1 values(4, '북길동');
select * from t1;

1. 롤백이 가능하도록 autocommit을 0으로 설정

SET autocommit = 0;
SET SQL_SAFE_UPDATES=0;

2. ROLLBACK & COMMIT 연습

- ROLLBACK

데이터베이스의 상태를 트랜잭션 수행하기 이전 상태로 되돌릴 수 있다.

단 트랜잭션이 Commit 되지 않은 상태여야 한다.

- COMMIT

트랜잭션의 결과를 확정시킨다.

이 명령을 실행하고 나서는 롤백으로 이전 시점으로 복구할 수 없다.

 

start transaction;
delete from t1 where id = 1;
delete from t1 where id = 2;
delete from t1 where id = 3;
select * from t1;

rollback;  -- rollback 성공
select * from t1;


delete from t1 where id = 1;
delete from t1 where id = 2;
delete from t1 where id = 3;
commit;
rollback;  -- rollback 실패
select * from t1;

3. SAVEPOINT

트랜잭션 중에 포인트를 지정하고 해당 상태로 되돌아 갈 수 있는 기능을 제공한다.

drop table t1
create table t1(id int, name varchar(30));

insert into t1 values(1, '홍길동');
insert into t1 values(2, '서길동');
insert into t1 values(3, '남길동');
insert into t1 values(4, '북길동');
select * from t1;
commit;  -- 실행 여러번 하기

start transaction;

savepoint a;
delete from t1 where id = 1;
select * from t1;

savepoint b;
delete from t1 where id = 2;
select * from t1;

rollback to b;
select * from t1;

rollback to a;
select * from t1;

commit;  -- 실행 여러번 하기

ROLLBACK A로 가게되면 B의 내용은 없던 것으로 돌아간다. 

728x90
반응형

댓글