DB10 - Transcation
Transactions 트랜잭션
- Concept and examples
개념과 예시 - Levels of transactions
트랜잭션의 수준
Transactions 트랜잭션
1) A transaction 트랜잭션
- An indivisible “unit” of program execution that accesses and updates dat안a items
데이터 항목에 접근하고 업데이트하는 프로그램 실행의 불가분한 "단위"- Indivisible: Either execute entirely or not at all
불가분성: 전부 실행하거나 전혀 실행되지 않음
- Indivisible: Either execute entirely or not at all
- A collection of operations that form a single logical unit of work
하나의 논리적 작업 단위를 형성하는 연산들의 모음 - Consists of a sequence of query and/or update statements
쿼리 및/또는 업데이트 문장의 시퀀스로 구성됨
2) Why transactions? 왜 트랜잭션이 필요한가?
- Database systems are normally being accessed by many users or processes at the same time
데이터베이스 시스템은 보통 여러 사용자나 프로세스에 의해 동시에 접근됨- Both queries and modifications
쿼리와 수정 둘 다
- Both queries and modifications
- Unlike operating systems, which support interaction of processes, a DMBS needs to keep processes from troublesome interactions
프로세스 간의 상호작용을 지원하는 운영체제와 달리, DBMS는 문제를 일으키는 상호작용을 방지해야 함
3) E.g., Bank 예: 은행
4) C.f., File management in an OS
참고: 운영체제의 파일 관리
- An OS allows two people to edit a document at the same time. If both write, one’s changes get lost
운영체제는 두 사람이 동시에 문서를 편집할 수 있게 하지만, 둘 다 쓰면 한 사람의 변경 사항이 손실될 수 있음
5) A transaction consists of a sequence of query and/or update statements and is a "unit" of work
트랜잭션은 쿼리 및/또는 업데이트 문장의 시퀀스로 구성되며, "작업 단위"임
- To address both atomicity and serialization, group database operations into transactions
원자성과 직렬화를 보장하기 위해 데이터베이스 작업을 트랜잭션으로 묶음 - A transaction is a collection of one or more operations on DB that must be executed atomically
트랜잭션은 원자적으로 실행되어야 하는 하나 이상의 DB 연산으로 구성됨 - Transactions are executed in a serializable manner
트랜잭션은 직렬 가능하게 실행됨
6) Transaction = process involving database queries and/or modification
트랜잭션 = 데이터베이스 쿼리 및/또는 수정이 포함된 프로세스
- A transaction begins implicitly when an SQL statement is executed (the SQL standard)
트랜잭션은 SQL 문이 실행될 때 암묵적으로 시작됨 (SQL 표준) - The transaction must end with one of the following statements:
트랜잭션은 아래의 문장 중 하나로 끝나야 함- Commit work: The updates performed by the transaction become permanent in the database
Commit work: 트랜잭션이 수행한 업데이트가 데이터베이스에 영구적으로 반영됨 - Rollback work: All the updates performed by the SQL statements in the transaction are undone
Rollback work: 트랜잭션 내의 SQL 문이 수행한 모든 업데이트가 취소됨
- Commit work: The updates performed by the transaction become permanent in the database
7) Transactions could be formed by explicit programmer controls
트랜잭션은 프로그래머의 명시적 제어로 구성될 수 있음
- START TRANSACTION;
...
COMMIT; or ROLLBACK;
8) START TRANSACTION statement is to declare that the guarded queries are of a group of operations that must be executed atomically
START TRANSACTION 문은 보호되는 쿼리들이 반드시 원자적으로 실행되어야 하는 작업 그룹임을 선언함
- Each SQL statement that does not belong to any transaction explicitly is a transaction with the single statement
트랜잭션에 명시적으로 속하지 않은 각 SQL 문은 그 자체로 하나의 트랜잭션임
9) COMMIT or ROLLBACK declares the end of a transaction
COMMIT 또는 ROLLBACK은 트랜잭션의 종료를 선언함
- COMMIT causes a transaction to complete
COMMIT은 트랜잭션을 완료시킴- The database modifications are now permanent in the database
데이터베이스 수정 내용이 이제 영구적으로 반영됨
- The database modifications are now permanent in the database
- ROLLBACK ends the transaction by aborting
ROLLBACK은 트랜잭션을 중단시키며 종료함- No effects on the database
데이터베이스에는 아무런 영향도 없음 - Failures like division by 0 or a constraint violation can also cause rollback, even if the programmer does not request it
0으로 나누기나 제약 조건 위반 같은 실패도, 프로그래머가 요청하지 않아도 롤백을 발생시킴
- No effects on the database
10) E.g., Bank 예: 은행
- START TRANSACTION;
- START TRANSACTION; UPDATE accounts SET balance = balance + 100 WHERE accNo = 456; UPDATE accounts SET balance = balance - 100 WHERE accNo = 123; COMMIT; COMMIT;
A Transaction Example 트랜잭션 예시
- START TRANSACTION;
SELECT @A:=SUM(salary) FROM instructor WHERE dept_name='Comp. Sci.';
UPDATE budget_summary SET summary=@A WHERE dept_name='Comp. Sci.';
COMMIT;
- C.f., Session variable - @var_name
- Usages 사용 예시
- SET @var_name = value or SET @var_name := value
- @var_name := value in a SELECT clause
- Declaration is not required
선언이 필요하지 않음 - Data type: Defined at the assignment
데이터 타입: 할당 시점에 정의됨 - Scope: Until the end of the current session
범위: 현재 세션이 끝날 때까지
- Usages 사용 예시
Another Transaction Example 또 다른 트랜잭션 예시
- SELECT * FROM sales_history
- START TRANSACTION;
- DELETE FROM sales_history;
- SELECT * FROM sales_history;
- ROLLBACK;
SELECT * FROM sales_history; SELECT * FROM sales_history;
A Competing Scenario 경쟁 시나리오
- Example: Interacting process
예: 상호작용하는 프로세스
- Assume a usual Sells(store, chocobar, price) relation, and suppose that Joe’s Store sells only Snickers for $1.00 and Twix for $1.50
일반적인 Sells(store, chocobar, price) 관계가 있다고 가정하고, Joe의 Store에서는 Snickers를 $1.00, Twix를 $1.50에만 판다고 가정하자 - Sally is querying Sells for the highest and lowest price Joe charges
Sally는 Joe가 받는 가장 높은 가격과 가장 낮은 가격을 Sells에서 쿼리함 - Joe decides to stop selling Snickers and Twix, but to sell only M&M's at $2.00
Joe는 Snickers와 Twix 판매를 중단하고, 대신 M&M's만 $2.00에 팔기로 결정함
(1) Sally’s Program Sally의 프로그램
- Sally executes the following two SQL statements called (min) and (max) to help us remember what they do
Sally는 아래의 두 SQL 문을 실행하는데, 이를 (min)과 (max)라고 부름- (max) SELECT MAX(price) FROM Sells WHERE store = ’Joe’’s Store’;
- (min) SELECT MIN(price) FROM Sells WHERE store = ’Joe’’s Store’;
(2) Joe’s Program Joe의 프로그램
- At about the same time, Joe executes the following steps: (del) and (ins)
거의 같은 시점에 Joe는 아래 단계들을 실행함: (del)과 (ins)- (del) DELETE FROM Sells WHERE store = ’Joe’’s Store’;
- (ins) INSERT INTO Sells VALUES(’Joe’’s Store’, ’M&M's’, 2.00);
(3) Interleaving of Statements 문장들의 얽힘
- Although (max) must come before (min), and (del) must come before (ins), there are no other constraints on the order of these statements
(max)는 (min)보다 먼저 오고, (del)은 (ins)보다 먼저 와야 하지만, 이 외에는 순서에 대한 제약이 없음- Unless we group Sally’s and/or Joe’s statements into transactions
단, Sally와/또는 Joe의 문장을 트랜잭션으로 묶지 않는 한
- Unless we group Sally’s and/or Joe’s statements into transactions
(4) Strange interleaving 이상한 얽힘
- Suppose the steps execute in the order (max)(del)(ins)(min)
단계들이 (max)(del)(ins)(min) 순서로 실행되었다고 가정하자- Joe’s Prices: {1.00, 1.50} {1.00, 1.50} {2.00}
Joe의 가격: {1.00, 1.50} {1.00, 1.50} {2.00} - Statement: (max) (del) (ins) (min)
실행된 문장: (max) (del) (ins) (min) - Result: 1.50 2.00
결과: 1.50 2.00
- Joe’s Prices: {1.00, 1.50} {1.00, 1.50} {2.00}
- Sally sees MAX < MIN
Sally는 MAX < MIN인 결과를 보게 됨
(5) Fixing the Problem by Using Transactions 트랜잭션을 사용해 문제 해결하기
- If we group Sally’s statements (max)(min) into one transaction, then she cannot see the previous inconsistency
Sally의 문장 (max)(min)을 하나의 트랜잭션으로 묶으면, 이전의 불일치를 볼 수 없음 - She sees Joe’s prices at some fixed time
Sally는 Joe의 가격을 고정된 시점에서만 보게 됨- Either before or after he changes prices, or in the middle, but the MAX and MIN are computed from the same prices
가격 변경 전, 후 또는 중간이더라도 MAX와 MIN은 동일한 가격에서 계산됨
- Either before or after he changes prices, or in the middle, but the MAX and MIN are computed from the same prices
(6) Another Problem: Rollback, 또 다른 문제: 롤백
- Suppose Joe executes (del)(ins), not as a transaction, but after executing these statements, thinks better of it and issues a ROLLBACK statement
Joe가 (del)(ins)를 트랜잭션으로 실행하지 않고 실행 후 마음이 바뀌어 ROLLBACK을 수행한다고 가정하자 - If Sally executes her statements after Joe’s (ins) but before the rollback, she sees a value, 2.00, that never existed in the database
Sally가 Joe의 (ins) 이후, ROLLBACK 이전에 자신의 문장을 실행하면 데이터베이스에 실제로 존재하지 않는 값 2.00을 보게 됨
(7) Solution 해결책
- If Joe executes (del)(ins) as a transaction, its effect cannot be seen by others until the transaction executes COMMIT
Joe가 (del)(ins)를 트랜잭션으로 실행하면, COMMIT이 실행될 때까지 그 영향은 다른 사람에게 보이지 않음 - If the transaction executes ROLLBACK instead, then its effects can never be seen
트랜잭션이 대신 ROLLBACK을 실행하면, 그 영향은 결코 다른 사람에게 보이지 않음
ACID Properties ACID 속성
- ACID properties ACID 속성
- Atomic: Either fully executed or rolled back as if it never occurred
원자성: 전부 실행되거나, 전혀 일어나지 않은 것처럼 롤백됨- The all-or-none property
전부 아니면 전혀 없는 특성
- The all-or-none property
- Consistent: All database constraints should be preserved
일관성: 모든 데이터베이스 제약 조건이 보존되어야 함 - Isolated: Isolation from concurrent transactions – It appears to the user as if only one process executes at a time
고립성: 동시 실행되는 트랜잭션으로부터의 고립 – 사용자에게는 오직 하나의 프로세스만 실행되는 것처럼 보임- DBMS must ensure that transactions operate properly without interference from other concurrently executing statements
DBMS는 다른 동시 실행 문장의 간섭 없이 트랜잭션이 올바르게 작동하도록 보장해야 함
- DBMS must ensure that transactions operate properly without interference from other concurrently executing statements
- Durable: Effects of a process survive a crash
지속성: 프로세스의 결과가 충돌 후에도 유지됨- The results of transactions must persist in the system
트랜잭션의 결과는 시스템에 지속적으로 남아야 함
- The results of transactions must persist in the system
States of a Transaction 트랜잭션의 상태
- A transaction must be in one of the following states:
트랜잭션은 아래 상태 중 하나여야 함
- Active: Initial state; transactions stay in this state while executing
Active: 초기 상태; 트랜잭션이 실행 중인 상태 - Partially committed: After the final statement has been executed
Partially committed: 마지막 문장이 실행된 후 상태 - Failed: After the discovery that normal execution can no longer proceed
Failed: 정상 실행이 더 이상 불가능하다고 판단된 후 상태 - Aborted: After the transaction has been rolled back and the database has been restored
Aborted: 트랜잭션이 롤백되고 데이터베이스가 복원된 상태 - Committed: After successful completion
Committed: 성공적으로 완료된 후 상태
A Toy Example
간단한 예제
- T1 : A 계좌에서 50원 빼고, B 계좌에 50원 추가
- read(A) :
A := A - 50;
write(A);
read(B);
B := B + 50;
write(B);
- read(A) :
- T1 : A의 10%만큼을 temp에 저장하고, 그만큼 A에서 빼고 B에 더함
- T2: read(A);
temp := A * 0.1;
A := A - temp;
write(A);
read(B);
B := B + temp;
write(B);
- T2: read(A);
A Toy Example 간단한 예제
- 가정 : A가 100, B가 50
- 두 슬라이드의 차이점은:
- 첫 번째 슬라이드: 세 번째 시나리오에서 T₁의 write(A) 후에 T₂가 read(B)를 먼저 실행
- 두 번째 슬라이드: 세 번째 시나리오에서 T₁이 read(B), B := B + 50, write(B), commit을 먼저 완료한 후 T₂가 read(B)를 실행
Serializable Behaviors 직렬 가능 행동
- When there are more than one operations overlap in time, affecting the same data source
동시에 여러 연산이 중첩되어 같은 데이터 소스에 영향을 미칠 때
- Each operation could perform correctly
각 연산은 올바르게 수행될 수 있음 - While the global result might not be correct
그러나 전체 결과는 올바르지 않을 수 있음
- SQL allows the programmer to state that certain operations must be serializable with respect to other operations
SQL은 프로그래머가 특정 연산이 다른 연산과 직렬 가능해야 한다고 명시할 수 있게 함
- Operations must behave "as if" they were run serially – one at a time, with no overlap
- 연산은 직렬로 실행되는 것처럼, 하나씩 순차적으로 실행되는 것처럼 동작해야 함
Agenda 목차
- Transactions 트랜잭션
- Concept and examples 개념과 예시
- Levels of transactions 트랜잭션의 수준
Read-Only Transactions 읽기 전용 트랜잭션
- SET TRANSACTION READ ONLY;
START TRANSACTION;
…
COMMIT; or ROLLBACK; - Declare that the coming transaction reads data from the database, but never writes
이후 트랜잭션이 데이터베이스에서 데이터를 읽기만 하고, 쓰지는 않는다고 선언함- By default, a transaction is set as READ WRITE
기본적으로 트랜잭션은 READ WRITE로 설정됨
- By default, a transaction is set as READ WRITE
- READ ONLY is useful to increase the parallelism of read-only transactions, compared to the regular (read & write) transactions
READ ONLY는 일반 트랜잭션(읽기 및 쓰기)과 비교해 읽기 전용 트랜잭션의 병렬성을 높이는데 유용함
Isolation Levels of Transactions 트랜잭션의 고립 수준
- SET TRANSACTION ISOLATION LEVEL <level>;
START TRANSACTION;
…
COMMIT; or ROLLBACK; - Declare kinds of interferences (by other transactions) allowed for a transaction
트랜잭션에서 허용되는 다른 트랜잭션의 간섭 종류를 선언함- Declare the level of "locking" (enforcing limits on access to) data
데이터에 대한 "잠금" 수준을 선언함 (접근 제한을 강제함) - Tradeoffs: Concurrency ⇌ Data integrity
트레이드오프: 동시성 ⇌ 데이터 무결성
- Declare the level of "locking" (enforcing limits on access to) data
- SQL supports four isolation levels (i.e., <level>)
- SQL은 네 가지 고립 수준을 지원함 (<level>)
- SERIALIZABLE (level 3)
- REPEATABLE READ (level 2)
- the default isolation level in MySQL
MySQL의 기본 고립 수준
- the default isolation level in MySQL
- READ COMMITTED (level 1)
- READ UNCOMMITTED (level 0)
- Higher isolation level ⇒ more data integrity
고립 수준이 높을수록 ⇒ 데이터 무결성이 높아짐 - Lower isolation level ⇒ more concurrency; higher throughput
고립 수준이 낮을수록 ⇒ 더 높은 동시성; 더 높은 처리량
Possible Issues 발생 가능한 문제
- Phantom read 팬텀 리드
- Same SELECT queries in the same transaction can have different results by 'INSERT' in another committed transaction
동일 트랜잭션의 SELECT 쿼리가 다른 커밋된 트랜잭션의 'INSERT'에 의해 다른 결과를 반환함
- Same SELECT queries in the same transaction can have different results by 'INSERT' in another committed transaction
- Nonrepeatable read 반복 불가능한 읽기
- Same SELECT queries in the same transaction can have different results by 'UPDATE' or 'DELETE' in another committed transaction
동일 트랜잭션의 SELECT 쿼리가 다른 커밋된 트랜잭션의 'UPDATE' 또는 'DELETE'에 의해 다른 결과를 반환함
- Same SELECT queries in the same transaction can have different results by 'UPDATE' or 'DELETE' in another committed transaction
- Dirty read 더러운 읽기
- Read dirty data that is written by an ongoing transaction (not committed yet)
진행 중인 트랜잭션(아직 커밋되지 않은)의 데이터를 읽음
- Read dirty data that is written by an ongoing transaction (not committed yet)
Isolation Levels of Transactions 트랜잭션의 고립 수준
1. SERIALIZABLE transactions
SERIALIZABLE 트랜잭션
- A serializable transaction must behave with respect to other transactions as if they were executed one by one without any parallel execution (i.e., serially)
SERIALIZABLE 트랜잭션은 다른 트랜잭션과 함께 실행될 때, 마치 하나씩 순차적으로 실행되는 것처럼 동작해야 함- While a serializable transaction runs, all data it accesses are locked (other parallel transactions cannot modify nor insert)
SERIALIZABLE 트랜잭션이 실행되는 동안, 접근하는 모든 데이터는 잠금됨 (다른 병렬 트랜잭션은 수정이나 삽입 불가)
- While a serializable transaction runs, all data it accesses are locked (other parallel transactions cannot modify nor insert)
- Serializable is the most strict transaction isolation level – guarantees the highest level of data integrity
SERIALIZABLE은 가장 엄격한 트랜잭션 고립 수준으로, 최고의 데이터 무결성을 보장함 - May slow down the transaction handling performance
트랜잭션 처리 성능을 저하시킬 수 있음
2. REPEATABLE READ transactions
REPEATABLE READ 트랜잭션
- A repeatable read transaction must see for multiple executions of the same query that a tuple in the first result also appears at the later results
REPEATABLE READ 트랜잭션은 같은 쿼리를 여러 번 실행할 때 첫 결과의 튜플이 나중에도 계속 나타나야 함 - A repeatable read transaction must be isolated from the other transaction committed concurrently
REPEATABLE READ 트랜잭션은 동시에 커밋된 다른 트랜잭션으로부터 고립되어야 함- A repeatable read transaction only accesses data that has been committed before it starts
REPEATABLE READ 트랜잭션은 시작 전에 커밋된 데이터만 접근함
- A repeatable read transaction only accesses data that has been committed before it starts
- The second and the subsequence results of the same query may have phantom reads
같은 쿼리의 두 번째 및 이후 결과는 팬텀 리드를 가질 수 있음- Other parallel transactions may insert new tuples in a middle of a transaction, while not changing the existing tuples
다른 병렬 트랜잭션이 트랜잭션 중간에 새로운 튜플을 삽입할 수 있지만, 기존 튜플은 변경하지 않음
- Other parallel transactions may insert new tuples in a middle of a transaction, while not changing the existing tuples
3. READ COMMITTED transactions
READ COMMITTED 트랜잭션
- A read committed transaction must see for multiple executions of the same query that a tuple in the first result also appears at the later results
READ COMMITTED 트랜잭션은 같은 쿼리를 여러 번 실행할 때 첫 결과의 튜플이 나중에도 계속 나타나야 함 - A read-committed transaction must read the databases that are committed
READ COMMITTED 트랜잭션은 커밋된 데이터만 읽음 - The second and the subsequence results of the same query may have nonrepeatable reads
같은 쿼리의 두 번째 및 이후 결과는 반복 불가능한 읽기를 가질 수 있음- Other parallel transactions may commit changes in a middle of a transaction, while not changing the existing tuples
다른 병렬 트랜잭션이 트랜잭션 중간에 변경을 커밋할 수 있지만, 기존 튜플은 변경하지 않음
- Other parallel transactions may commit changes in a middle of a transaction, while not changing the existing tuples
READ UNCOMMITTED transactions
READ UNCOMMITTED 트랜잭션
- A read-uncommitted transaction may read dirty data, the data written by a transaction that has not yet committed
READ UNCOMMITTED 트랜잭션은 아직 커밋되지 않은 트랜잭션의 더러운 데이터를 읽을 수 있음- A dirty data may disappear if its writer transaction aborts
작성자 트랜잭션이 중단되면 더러운 데이터는 사라질 수 있음
- A dirty data may disappear if its writer transaction aborts
- A careful use of dirty read allows fast processing of transactions
더러운 읽기를 신중히 사용하면 트랜잭션 처리 속도를 높일 수 있음 - Practically there is no isolation; recommended not to use
사실상 고립성이 없으며, 사용을 권장하지 않음
Possible Issues in Different Isolation Levels
다른 고립 수준에서의 발생 가능한 문제
Isolation level | Phantom read | Nonrepeatable read | Dirty read |
SERIALIZABLE | Not allowed | Not allowed | Not allowed |
REPEATABLE READ | Possible | Not allowed | Not allowed |
READ COMMITTED | Possible | Possible | Not allowed |
READ UNCOMMITTED | Possible | Possible | Possible |
격리 수준 | 팬텀 리드 | 반복 불가능한 읽기 | 더티 리드 |
SERIALIZABLE (직렬화) | 허용되지 않음 | 허용되지 않음 | 허용되지 않음 |
REPEATABLE READ (반복 읽기) | 가능 | 허용되지 않음 | 허용되지 않음 |
READ COMMITTED (읽기 커밋됨) | 가능 | 가능 | 허용되지 않음 |
READ UNCOMMITTED (읽기 미커밋됨) | 가능 | 가능 | 가능 |