Backend with Golang

MySQL - Transaction

아직개구리 2023. 5. 9. 17:18

Transaction 

- sequential group of statements, queries, or operations such as select, insert, update or delete to perform as a one signle work unit that can be committed or rolled back. 

- database 와 application 사이의 데이터 거래에 있어서 안전성을 높이기 위한 방법. 

 

만약에 transaction 이 여러개의 modifications을 만든다면 두가지의 결과가 나타날 수 있다. 

  1. transaction이 commit 되었을 때, 모든 modification이 성공하거나 
  2. transaction이 rollback 되었을 때, 모든 modification이 실행되지 않거나. 

Transaction 의 특성 

  1. Atomicity : 하나의 트랜잭션 단위 안에 있는 모든 statement 나 operations가 성공적으로 끝나는 것을 보장한다. 하나라도 failed한다면, 모든 트랜잭션은 aborted되고, 이전 state로 돌아간다. 
  2. Consistency:  database 가 state를 오직 transaction이 성공적으로 commit되었을 때만 바꾼다는 것을 보장한다. data를 보호하기 위한 방법이다. 
  3. Isolation: 이 특성은 transaction unit의 각각의 operation이 독립적으로 실행된다는 것을 의미한다. 
  4. Durability: committed transaction들의 결과는 영원히 유지되는 것을 보장한다. 만약 system이 crash되거나 failed되더라도. 

COMMIT example & ROLLBACK example

Commit: 

우리가 transaction을 사용하기를 원할 때, SQL statement를 logical portion으로 나눠야한다. 그리고 나서 data가 commit되어야 하는지, rollback되어야 하는지 결정할 수 있다. 

commit statement를 사용해서 transaction을 complete할 수 있다. 

START TRANSACTION;

SELECT @income:=MAX(income) FROM employees;

INSERT INTO employees(emp_id, emp_name, emp_age),
VALUES (111, 'kim', 45);

INSERT INTO orders(order_id, prod_name, order_num, order_date)
VALUES (6, 'Printer', 5654, '2020-01-10');

COMMIT;

Rollback: 

첫번째 세션에서  change 를 만들어도, commit이나 rollback statement 가 없기 때문에 change에 대한 record를 가지고 있을 수 있다. commit, rollback을 하면 record가 없어진다. 

START TRANSACTION; 

DELETE FROM Orders; 
-- 이때 다른 session에서 SELECT * FROM Orders;를 실행하면, 모든 데이터가 그대로 있다. 

ROLLBACK;

SELECT * FROM Orders;

 * 모든 statement 를 되돌릴 수 있는 것은 아니다. DDL command (Data Definition Language)는 되돌릴 수 없다. 예시로는 such as CREATE, ALTER, or DROP database as well as CREATE, UPDATE, or DROP tables or stored routines. 가 있다. 

 

 

Reference 

1. https://www.javatpoint.com/mysql-transaction#:~:text=A%20transaction%20in%20MySQL%20is,be%20committed%20or%20rolled%20back. 

'Backend with Golang' 카테고리의 다른 글

[Concurrency-2] Chapter 3 channel 전까지  (0) 2023.06.12
[Concurrency-1] Concurrency가 왜 어려운가?  (1) 2023.05.28
Docker-compose.yml 파일 작성하기 (TBU)  (0) 2023.05.09
Go: JSON  (0) 2023.05.03
Goroutine  (0) 2023.05.01