0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · 강의

트랜잭션 및 데이터 조작

Mnesia 테이블에서 원자적 트랜잭션을 수행하여 분산 노드 전반의 데이터 일관성을 보장합니다.

트랜잭션 및 데이터 조작은(는) CoddyKit의 무료 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Mnesia Needs Transactions

Imagine managing important data like bank transfers. You wouldn't want money to leave one account without arriving in another, right?

This "all or nothing" principle is crucial for data consistency, and it's where transactions come in. Mnesia uses transactions to group multiple database operations into a single, atomic unit.

An atomic transaction either fully completes all its operations, or if any part fails, all changes are rolled back. This ensures your data remains consistent and reliable.

The Core: `mnesia:transaction`

In Mnesia, you perform transactional operations using the mnesia:transaction/1 function. It takes an anonymous function (a fun) as its argument.

All Mnesia read and write operations that need to be atomic must be placed inside this fun. If the fun executes successfully, the changes are committed. If an error occurs or mnesia:abort/1 is called, all changes are rolled back.

Let's see its basic structure:

-module(example_transaction).
-export([main/0]).

main() ->
    mnesia:start(),
    {atomic, _Result} = mnesia:transaction(fun() ->
        % Mnesia operations go here
        io:format("Inside the transaction!~n"),
        ok
    end),
    io:format("Transaction completed.~n"),
    mnesia:stop().

Preparing Data for Transactions

Before we can manipulate data, we need a Mnesia table. Let's define a simple person record and create a table for it. This setup will be used in our transaction examples.

Remember, mnesia:create_table/2 is usually called once when your application starts up for the first time.

-module(mnesia_table_setup).
-export([main/0]).
-record(person, {id, name, age}).

main() ->
    % Ensure Mnesia is started on this node
    mnesia:create_schema([node()]),
    mnesia:start(),
    % Create table if it doesn't exist
    case mnesia:create_table(person, [{attributes, record_info(fields, person)}]) of
        {atomic, ok} -> io:format("Table 'person' created successfully.~n");
        {aborted, {already_exists, person}} -> io:format("Table 'person' already exists.~n");
        Error -> io:format("Error creating table: ~p~n", [Error])
    end,
    mnesia:stop().

Adding & Updating Records

Inside a transaction, you use mnesia:write/1 to store or update records. If a record with the same primary key (the first field in our person record, id) already exists, it will be updated. Otherwise, a new record is inserted.

Let's add a new person to our table. Remember to start Mnesia first!

-module(write_example).
-export([main/0]).
-record(person, {id, name, age}).

main() ->
    % Ensure Mnesia is started and table exists (simplified setup)
    mnesia:create_schema([node()]),
    mnesia:start(),
    mnesia:create_table(person, [{attributes, record_info(fields, person)}]),
    mnesia:wait_for_tables([person], 5000),

    % Write a new person record
    Person1 = #person{id = 1, name = "Alice", age = 30},
    {atomic, ok} = mnesia:transaction(fun() ->
        mnesia:write(Person1)
    end),
    io:format("Wrote: ~p~n", [Person1]),

    mnesia:stop().

Fetching Records Transactionally

To retrieve data inside a transaction, use mnesia:read/1. It takes a record or a record key (like {person, 1}) and returns a list of matching records. If no record is found, it returns [] (an empty list).

Let's read the person we just added. We'll combine writing and reading in a single transaction for a fuller example.

-module(read_example).
-export([main/0]).
-record(person, {id, name, age}).

main() ->
    mnesia:create_schema([node()]),
    mnesia:start(),
    mnesia:create_table(person, [{attributes, record_info(fields, person)}]),
    mnesia:wait_for_tables([person], 5000),

    Person1 = #person{id = 1, name = "Alice", age = 30},
    Person2 = #person{id = 2, name = "Bob", age = 25},

    {atomic, Result} = mnesia:transaction(fun() ->
        % Write two records
        mnesia:write(Person1),
        mnesia:write(Person2),
        % Read one of them
        mnesia:read({person, 1})
    end),
    io:format("Transaction result (read data): ~p~n", [Result]),

    mnesia:stop().

Modifying Data with Transactions

mnesia:write/1 handles both inserting new records and updating existing ones. To remove a record entirely, you use mnesia:delete/1, providing the full record or just its key.

Let's update Alice's age and then delete Bob from our Mnesia table, all within a single, consistent transaction.

-module(update_delete_example).
-export([main/0]).
-record(person, {id, name, age}).

main() ->
    mnesia:create_schema([node()]),
    mnesia:start(),
    mnesia:create_table(person, [{attributes, record_info(fields, person)}]),
    mnesia:wait_for_tables([person], 5000),

    % Ensure initial data for update/delete
    mnesia:transaction(fun() ->
        mnesia:write(#person{id = 1, name = "Alice", age = 30}),
        mnesia:write(#person{id = 2, name = "Bob", age = 25})
    end),

    io:format("--- Before transaction ---~n"),
    io:format("Alice: ~p~n", [mnesia:dirty_read({person, 1})]),
    io:format("Bob: ~p~n", [mnesia:dirty_read({person, 2})]),

    {atomic, _} = mnesia:transaction(fun() ->
        % Update Alice's age
        UpdatedAlice = #person{id = 1, name = "Alice", age = 31},
        mnesia:write(UpdatedAlice),
        % Delete Bob
        mnesia:delete({person, 2})
    end),

    io:format("--- After transaction ---~n"),
    io:format("Alice: ~p~n", [mnesia:dirty_read({person, 1})]),
    io:format("Bob: ~p~n", [mnesia:dirty_read({person, 2})]), % Should be []

    mnesia:stop().

Transaction Rollbacks in Action

The power of transactions lies in their atomicity. If any operation within the fun fails or you explicitly call mnesia:abort/1, Mnesia will roll back all changes made during that transaction.

This means your database state will revert to how it was before the transaction started, preventing partial updates and maintaining consistency.

-module(rollback_example).
-export([main/0]).
-record(person, {id, name, age}).

main() ->
    mnesia:create_schema([node()]),
    mnesia:start(),
    mnesia:create_table(person, [{attributes, record_info(fields, person)}]),
    mnesia:wait_for_tables([person], 5000),

    % Ensure Alice exists initially
    mnesia:transaction(fun() ->
        mnesia:write(#person{id = 1, name = "Alice", age = 30})
    end),
    io:format("Initial Alice: ~p~n", [mnesia:dirty_read({person, 1})]),

    % Attempt a transaction that will abort
    Result = mnesia:transaction(fun() ->
        mnesia:write(#person{id = 1, name = "Alice", age = 35}), % Update
        mnesia:write(#person{id = 3, name = "Charlie", age = 22}), % New record
        mnesia:abort("Something went wrong!") % Abort the transaction
    end),
    io:format("Transaction result: ~p~n", [Result]),

    io:format("Alice after aborted transaction: ~p~n", [mnesia:dirty_read({person, 1})]),
    io:format("Charlie after aborted transaction: ~p~n", [mnesia:dirty_read({person, 3})]),

    mnesia:stop().

`mnesia:sync_transaction/1` for Global Commit

While mnesia:transaction/1 ensures local atomicity, its return doesn't guarantee the transaction has committed on all Mnesia replicas in a distributed setup. For that, you use mnesia:sync_transaction/1.

mnesia:sync_transaction/1 blocks the caller until the transaction has been successfully committed on all nodes where the affected tables are resident. This is crucial for strong consistency guarantees in distributed systems.

Use it when you absolutely need to know that data is consistent across your entire cluster before proceeding.

-module(sync_transaction_example).
-export([main/0]).
-record(item, {id, name}).

main() ->
    % This example assumes a distributed Mnesia setup.
    % For a single node, it behaves like mnesia:transaction/1.
    mnesia:create_schema([node()]),
    mnesia:start(),
    mnesia:create_table(item, [{attributes, record_info(fields, item)}]),
    mnesia:wait_for_tables([item], 5000),

    Item = #item{id = 101, name = "Widget A"},

    io:format("Attempting sync_transaction...~n"),
    {atomic, ok} = mnesia:sync_transaction(fun() ->
        mnesia:write(Item)
    end),
    io:format("Item written and committed across all replicas: ~p~n", [Item]),

    mnesia:stop().

Transaction Knowledge Check

You've learned about Mnesia transactions and how to manipulate data atomically. Let's test your understanding!

Transactions: Your Data's Safety Net

In this lesson, you mastered Mnesia transactions, a cornerstone for building robust and reliable applications.

  • We learned that transactions provide atomicity, ensuring "all or nothing" data operations.
  • You practiced using mnesia:transaction/1 to group Mnesia operations.
  • We covered mnesia:write/1 for adding/updating, mnesia:read/1 for fetching, and mnesia:delete/1 for removing records.
  • We briefly touched upon mnesia:sync_transaction/1 for strong distributed consistency.

Next, we'll dive into configuring Mnesia for distributed operation, including data replication and fault-tolerant storage across a cluster.

자주 묻는 질문

“트랜잭션 및 데이터 조작” 강의는 무료인가요?

네 — “트랜잭션 및 데이터 조작” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.

“트랜잭션 및 데이터 조작”에서 뭘 배우나요?

Mnesia 테이블에서 원자적 트랜잭션을 수행하여 분산 노드 전반의 데이터 일관성을 보장합니다. 브라우저에서 직접 실행하는 실습 코드로 Erlang OTP: Distributed & Fault-Tolerant Systems Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Erlang OTP: Distributed & Fault-Tolerant Systems Programming을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Erlang OTP: Distributed & Fault-Tolerant Systems Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“트랜잭션 및 데이터 조작” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Mnesia 기초 및 스키마
  2. 트랜잭션 및 데이터 조작
  3. 분산 Mnesia 및 복제
  4. Mnesia 인덱싱과 쿼리 최적화
← Erlang OTP: Distributed & Fault-Tolerant Systems Programming(으)로 돌아가기