Database & SQL Engineering / TRANSACTIONS, MVCC & CONCURRENCY / SQL-017

Suggested study path · Step 5 of 6 · G1

Atomic Transfer

Explore concept graph

Materi

Masalah: debit berhasil, tetapi proses gagal ketika menambah ledger row. Tanpa transaksi atomik, sebagian perubahan bisa menetap dan membuat saldo tidak konsisten.

Mulai: prediksi saldo A-01=1000.00 dan A-02=200.00 setelah transfer 125.00; lalu prediksi hasil jika ledger INSERT gagal sebelum COMMIT.

Peta konsep statis. Ikuti alur teks dari atas ke bawah.
                         PostgreSQL 16
    Initial A-01:1000.00  A-02:200.00  Ledger:0
                            |
                          BEGIN
                            |
                 debit 125.00 A-01
                            |
                 credit 125.00 A-02
                            |
                 INSERT ledger row
                   /                \
           success                 PK conflict
               |                        |
             COMMIT                 abort session
               |                        |
      875.00 / 325.00            ROLLBACK by DB
         ledger: 1                  no new writes
               \                        /
                   independent SELECT

Mekanisme dan batas jaminan

Jika seluruh statement berada dalam satu BEGIN/COMMIT, kegagalan sebelum COMMIT tidak meninggalkan debit tanpa kredit. ROLLBACK eksplisit juga membatalkan transaksi yang sebenarnya valid. Ini adalah atomicity pada satu database dan tiga penulisan yang diuji, bukan jaminan concurrency, idempotency, authorization, settlement bank, atau complete double-entry journal.

Skenario Hasil persistent A-01 / A-02 Ledger Total
Awal 1000.00 / 200.00 0 1200.00
COMMIT 125.00 875.00 / 325.00 1 1200.00
Duplikat transfer_id sebelum COMMIT Tetap 875.00 / 325.00 Tetap 1 1200.00
Transfer lain lalu ROLLBACK Tetap 875.00 / 325.00 Tetap 1 1200.00

Konsep 1 / 3

Wrap debit, credit and ledger insert in one PostgreSQL BEGIN/COMMIT transaction.

A transfer cannot count as successful if the sender loses money without the recipient and ledger reflecting the same operation.

Mulai dari sini

Read the two account balances in init.sql; predict their values after a 125.00 transfer before running commit.sql.

Intuisi utama

BEGIN establishes one unit of work; COMMIT publishes the complete set of three writes, not a series of independently committed side effects.

Start from two accounts A-01=1000.00 and A-02=200.00 in the disposable cs101_sql017 schema. The success script debits 125.00, credits 125.00 and writes TX-SUCCESS to the ledger within one BEGIN/COMMIT. An isolated SQL session observes A-01=875.00, A-02=325.00 and one ledger row. Sum remains 1200.00. This demonstrates transaction atomicity in this sequential sandbox only; it does not prove concurrent overdraft safety, business authorization, idempotency or double-entry accounting.

Contoh bertahap

A-01 sends 125.00 to A-02 and a corresponding transfer ledger row must be written.

  1. Run init.sql against an isolated PostgreSQL 16 database, then inspect account balances.

    Mengapa: Establish an independently observed baseline before mutation.

    Hasil yang diharapkan: A-01=1000.00, A-02=200.00, ledger=0.

  2. Run commit.sql with BEGIN, debit, credit, INSERT, COMMIT.

    Mengapa: Treat all three durable mutations as one transaction.

    Hasil yang diharapkan: The psql session exits successfully.

  3. In another psql session run inspect.sql.

    Mengapa: Test persisted database state rather than relying on a success message from the writer.

    Hasil yang diharapkan: A-01=875.00, A-02=325.00, ledger=1, conserved=1200.00.

Konsep 2 / 3

Demonstrate that a duplicate ledger PRIMARY KEY before COMMIT rolls back earlier debit and credit changes.

Passing happy-path queries is insufficient: a database write can fail after multiple prior mutations.

Mulai dari sini

Find the duplicate transfer_id in fail-before-commit.sql and predict whether either updated balance will survive.

Intuisi utama

Inside a transaction, the write failure aborts the unit of work; the database rolls back debit and credit instead of leaving a half transfer.

The fail-before-commit.sql script starts after TX-SUCCESS already exists. It debits 30.00 and credits 30.00, then attempts to insert another ledger row with transfer_id TX-SUCCESS. PostgreSQL rejects the duplicate PRIMARY KEY. With psql ON_ERROR_STOP=1 the script terminates before COMMIT and the connection closes; the incomplete transaction is rolled back. An independent query still sees the previous committed balances and exactly one TX-SUCCESS row. This proves one failure path, not every possible crash or distributed failure.

Contoh bertahap

A second transfer tries to reuse TX-SUCCESS; the error occurs only after account balances were updated.

  1. Record the state after commit.sql.

    Mengapa: A baseline is necessary to detect any partial persisted mutation.

    Hasil yang diharapkan: 875.00 / 325.00, one ledger row.

  2. Run fail-before-commit.sql and require the psql script to exit nonzero.

    Mengapa: The ledger PRIMARY KEY conflict is the controlled failure before the COMMIT statement.

    Hasil yang diharapkan: A database uniqueness error prevents the script from reaching COMMIT.

  3. Rerun inspect.sql using a new psql connection.

    Mengapa: Only a separate connection confirms previous committed state is untouched.

    Hasil yang diharapkan: Balances and ledger count exactly match the pre-failure snapshot.

Konsep 3 / 3

Verify explicit ROLLBACK and fresh-database replay without pretending static SQL is runtime evidence.

A correct transaction lesson must distinguish intentional cancellation and real persisted-state observation.

Mulai dari sini

Find the final statement in explicit-rollback.sql and predict whether TX-CANCEL will exist after the script exits.

Intuisi utama

ROLLBACK cancels every write in the active transaction; a new session must observe the prior committed snapshot, and a fresh database should reproduce the same result.

The explicit-rollback.sql script changes debit, credit and inserts TX-CANCEL before issuing ROLLBACK instead of COMMIT. None of those effects remain. The verification script also creates sql017_fresh, initializes it from zero and commits the same transfer. Docker runs PostgreSQL 16 with --network none and no host ports, preventing access to production services. The V3 single-file generator cannot start PostgreSQL, so its executable-proof receipt stays explicitly not-executable; real PostgreSQL evidence is produced in the separate CI integration step.

Contoh bertahap

A user cancels a 40.00 transfer after preparing all three SQL mutations.

  1. Record the committed TX-SUCCESS state from an independent session.

    Mengapa: Make the expected reference state observable.

    Hasil yang diharapkan: 875.00 / 325.00; one ledger row.

  2. Execute explicit-rollback.sql.

    Mengapa: ROLLBACK is a successful command that discards the entire active transaction.

    Hasil yang diharapkan: Script exits zero but does not persist TX-CANCEL.

  3. Read inspect.sql and repeat the success scenario in sql017_fresh.

    Mengapa: Verify cancellation and reproducibility without relying on the first session's buffers.

    Hasil yang diharapkan: Original DB unchanged; fresh DB reaches the same 875.00 / 325.00 snapshot.

Referensi PostgreSQL 16

Sumber

Cross-domain connections

Curated relationships for this unit at G1. Proposed edges are suggestions, not prerequisites.

Concept connectionsG1 · 3 visible concepts · 3 curated links
100%

Dashed = proposed relationship; solid = reviewed connection. Only reviewed prerequisites constrain a learning path. Keyboard and text links remain available.