Skip to content

Latest commit

Β 

History

History
65 lines (55 loc) Β· 2.48 KB

transaction-acid.md

File metadata and controls

65 lines (55 loc) Β· 2.48 KB

νŠΈλžœμž­μ…˜μ˜ ACID 속성에 λŒ€ν•œ μ„€λͺ…κ³Ό μ€‘μš”μ„±

Atomicity (μ›μžμ„±)

νŠΈλžœμž­μ…˜μ˜ λͺ¨λ“  연산은 μ „λΆ€ μ‹€ν–‰λ˜κ±°λ‚˜ μ „ν˜€ μ‹€ν–‰λ˜μ§€ μ•Šμ•„μ•Ό ν•©λ‹ˆλ‹€ (All or Nothing).

μ˜ˆμ‹œ: κ³„μ’Œ 이체 νŠΈλžœμž­μ…˜

BEGIN TRANSACTION;
    UPDATE account SET balance = balance - 1000 WHERE user_id = 'sender';
    UPDATE account SET balance = balance + 1000 WHERE user_id = 'receiver';
COMMIT;

이 경우 두 μ—…λ°μ΄νŠΈ 쿼리 쀑 ν•˜λ‚˜λΌλ„ μ‹€νŒ¨ν•˜λ©΄ 전체가 λ‘€λ°±λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€. μ†‘κΈˆμžμ˜ κ³„μ’Œμ—μ„œ 돈이 λΉ μ Έλ‚˜κ°”λŠ”λ° 수취인의 κ³„μ’Œμ— μž…κΈˆλ˜μ§€ μ•ŠλŠ” 상황은 μžˆμ–΄μ„œλŠ” μ•ˆ λ©λ‹ˆλ‹€.

Consistency (일관성)

νŠΈλžœμž­μ…˜μ΄ μ™„λ£Œλœ 후에도 λ°μ΄ν„°λ² μ΄μŠ€κ°€ μΌκ΄€λœ μƒνƒœλ₯Ό μœ μ§€ν•΄μ•Ό ν•©λ‹ˆλ‹€. λͺ¨λ“  λ°μ΄ν„°λŠ” 정해진 κ·œμΉ™μ„ λ§Œμ‘±ν•΄μ•Ό ν•©λ‹ˆλ‹€.

μ˜ˆμ‹œ: 재고 관리 μ‹œμŠ€ν…œ

BEGIN TRANSACTION;
    UPDATE inventory SET quantity = quantity - 10 WHERE product_id = 1;
    INSERT INTO orders (product_id, quantity) VALUES (1, 10);
COMMIT;

μž¬κ³ λŠ” μ ˆλŒ€ λ§ˆμ΄λ„ˆμŠ€κ°€ 될 수 μ—†λ‹€λŠ” κ·œμΉ™μ΄ μžˆλ‹€λ©΄, 이 νŠΈλžœμž­μ…˜μ€ μž¬κ³ κ°€ 10개 미만일 λ•Œ μ‹€ν–‰λ˜μ§€ μ•Šμ•„μ•Ό ν•©λ‹ˆλ‹€.

Isolation (격리성)

λ™μ‹œμ— μ‹€ν–‰λ˜λŠ” νŠΈλžœμž­μ…˜λ“€μ€ μ„œλ‘œ 영ν–₯을 λ―ΈμΉ˜μ§€ μ•Šκ³  λ…λ¦½μ μœΌλ‘œ μˆ˜ν–‰λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.

μ˜ˆμ‹œ: λ™μ‹œ μ£Όλ¬Έ 처리

-- Transaction 1
BEGIN TRANSACTION;
    SELECT quantity FROM inventory WHERE product_id = 1 FOR UPDATE;
    -- quantity: 5
    UPDATE inventory SET quantity = quantity - 3 WHERE product_id = 1;
COMMIT;

-- Transaction 2 (λ™μ‹œ μ‹€ν–‰)
BEGIN TRANSACTION;
    SELECT quantity FROM inventory WHERE product_id = 1 FOR UPDATE;
    -- Transaction 1이 μ™„λ£Œλ  λ•ŒκΉŒμ§€ λŒ€κΈ°
    -- quantity: 2
    UPDATE inventory SET quantity = quantity - 2 WHERE product_id = 1;
COMMIT;

Durability (지속성)

νŠΈλžœμž­μ…˜μ΄ μ„±κ³΅μ μœΌλ‘œ μ™„λ£Œ(컀밋)된 ν›„μ—λŠ” ν•΄λ‹Ή κ²°κ³Όκ°€ 영ꡬ적으둜 보μž₯λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.

μ˜ˆμ‹œ: μ£Όλ¬Έ 데이터 보쑴

BEGIN TRANSACTION;
    INSERT INTO orders (id, user_id, total_amount) VALUES (1, 'user1', 50000);
    INSERT INTO order_items (order_id, product_id, quantity) VALUES (1, 100, 2);
COMMIT;

μ‹œμŠ€ν…œμ΄ κ°‘μžκΈ° μ€‘λ‹¨λ˜λ”λΌλ„, μ»€λ°‹λœ μ£Όλ¬Έ λ°μ΄ν„°λŠ” λ³΄μ‘΄λ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.

격리 μˆ˜μ€€μ— λ”°λ₯Έ μ£Όμ˜μ‚¬ν•­

격리성은 λ‹€μŒκ³Ό 같은 레벨둜 κ΅¬λΆ„λ©λ‹ˆλ‹€:

  1. READ UNCOMMITTED
  2. READ COMMITTED
  3. REPEATABLE READ
  4. SERIALIZABLE