Thuta Learning
ရှာဖွေရန်
IntermediateData & Databasesbeginner

Transactions နှင့် Savepoints

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • Transactions နှင့် Savepoints concept ကို နားလည်ရှင်းပြနိုင်ရန်
  • နမူနာ SQL/command ကို ကိုယ်တိုင် run ပြီး output စစ်နိုင်ရန်
  • Tutorial Platform project နှင့် production scenario တွင် အသုံးချနိုင်ရန်

နားလည်ထားရမယ့် အချက်

Transaction က command များစွာကို atomic unit တစ်ခုအဖြစ်ပေါင်းပါတယ်။ အားလုံးအောင်မြင်မှ `COMMIT` လုပ်ပြီး error ဖြစ်လျှင် `ROLLBACK` လုပ်ပါတယ်။ Savepoint က transaction တစ်ခုလုံးမဖျက်ဘဲ အလယ်အဆင့်တစ်ခုသို့ပြန်နိုင်စေပါတယ်။ Transaction ကိုကြာကြာဖွင့်ထားရင် locks၊ dead tuples cleanup နဲ့ connection usage ကိုထိခိုက်နိုင်ပါတယ်။

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Enrollment row ဖန်တီးပြီး initial progress rows ထည့်တာကို transaction တစ်ခုအတွင်းလုပ်မယ်။ Duplicate enrollment error ဖြစ်လျှင် partial progress rows မကျန်ရပါဘူး။ Application transaction က external email/API call ကို rollback မလုပ်နိုင်တာကြောင့် outbox/idempotency pattern လိုအပ်နိုင်ပါတယ်။

အတူတူ စမ်းရေးကြည့်မယ်

sql
CREATE TABLE IF NOT EXISTS app.lesson_progress (
  enrollment_id bigint NOT NULL REFERENCES app.enrollments(enrollment_id) ON DELETE CASCADE,
  lesson_id bigint NOT NULL REFERENCES app.lessons(lesson_id) ON DELETE CASCADE,
  completed boolean NOT NULL DEFAULT false,
  completed_at timestamptz,
  PRIMARY KEY (enrollment_id, lesson_id)
);

BEGIN;

WITH new_enrollment AS (
  INSERT INTO app.enrollments (user_id, tutorial_id)
  VALUES (1, 1)
  RETURNING enrollment_id, tutorial_id
)
INSERT INTO app.lesson_progress (enrollment_id, lesson_id)
SELECT e.enrollment_id, l.lesson_id
FROM new_enrollment e
JOIN app.lessons l USING (tutorial_id);

COMMIT;
-- On any unrecoverable error: ROLLBACK;
You should see
Enrollment နှင့် progress setup တစ်ခုလုံးအောင်မြင်မည် သို့မဟုတ် တစ်ခုမှမကျန်ဘဲ rollback ဖြစ်မည်။

၅ မိနစ် စမ်းကြည့်

Account balance transfer table နှစ်ခု update လုပ်သော transaction ရေးပြီး အလယ်မှာ error တမင်ထည့်ကာ rollback စစ်ပါ။

သတိလေးတစ်ချက်

Transaction ဖွင့်ပြီး user input သို့ network call ကိုစောင့်ခြင်းက lock time ကိုမလိုအပ်ဘဲရှည်စေပါတယ်။

PostgreSQL — TransactionsPostgreSQL Global Development Group

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Transaction ဖွင့်ပြီး user input သို့ network call ကိုစောင့်ခြင်းက lock time ကိုမလိုအပ်ဘဲရှည်စေပါတယ်။
  • နမူနာ code ကို production data ပေါ် တိုက်ရိုက်မစမ်းဘဲ local/test database နှင့် recoverable backup ပေါ်တွင် အရင်အတည်ပြုပါ။

လေ့ကျင့်ခန်း

Account balance transfer table နှစ်ခု update လုပ်သော transaction ရေးပြီး အလယ်မှာ error တမင်ထည့်ကာ rollback စစ်ပါ။

You'll know it worked when: Enrollment နှင့် progress setup တစ်ခုလုံးအောင်မြင်မည် သို့မဟုတ် တစ်ခုမှမကျန်ဘဲ rollback ဖြစ်မည်။

Transactions နှင့် Savepoints | Thuta Learning