Transactions & Data Manipulation
Perform atomic transactions on Mnesia tables, ensuring data consistency across distributed nodes.
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().All lessons in this course
- Mnesia Fundamentals & Schema
- Transactions & Data Manipulation
- Distributed Mnesia & Replication
- Mnesia Indexing & Query Optimization