Mnesia 기초 및 스키마
Mnesia의 아키텍처와 테이블 유형을 이해하고 분산 데이터를 위한 스키마를 정의하는 방법을 학습합니다.
Mnesia 기초 및 스키마은(는) CoddyKit의 무료 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Welcome to Mnesia!
Mnesia is Erlang's built-in distributed database. It's designed for high availability, fault tolerance, and soft real-time systems, making it perfect for concurrent Erlang applications.
Think of Mnesia as a powerful, embedded database that seamlessly integrates with Erlang's concurrency model.
Mnesia's Core Strengths
Mnesia offers key features that align perfectly with Erlang's philosophy:
- Distributed: It can span across multiple Erlang nodes.
- Transactional: Guarantees atomicity, consistency, isolation, and durability (ACID) for data operations.
- Fault-Tolerant: Automatically handles node failures and data replication.
- Hybrid Storage: Supports both in-memory and disk-based tables.
Starting Mnesia
Before you can use Mnesia, you need to start the Mnesia application and then the Mnesia database manager. This is a common first step when working with Mnesia.
Try running this simple example:
-module(mnesia_lesson_start).
-export([run/0]).
run() ->
% 1. Start the Mnesia application
application:start(mnesia),
io:format("Mnesia application started.~n"),
% 2. Start the Mnesia database manager
mnesia:start(),
io:format("Mnesia database started successfully!~n"),
% Clean up (important for simple runnable examples)
mnesia:stop(),
application:stop(mnesia),
ok.What is a Mnesia Schema?
A Mnesia schema defines the overall structure of your Mnesia database. It specifies which tables exist, their properties, and how they are stored across different nodes.
The schema itself is stored in a special Mnesia table called mnesia_schema.
Creating the Schema
The schema must be created once for the entire Mnesia system (cluster of nodes). You use mnesia:create_schema/1, passing a list of node names that will participate in the Mnesia system.
Here's how to create a schema for a single node:
-module(mnesia_lesson_schema).
-export([run/0]).
run() ->
application:start(mnesia),
% Create schema for the current node
case mnesia:create_schema([node()]) of
ok -> io:format("Mnesia schema created.~n");
{error, {already_exists, _}} ->
io:format("Schema already exists. (This is fine if run before)~n");
Error -> io:format("Error creating schema: ~p~n", [Error])
end,
application:stop(mnesia),
ok.Mnesia Table Fundamentals
Mnesia stores data in tables, similar to a relational database. Each table has a name and a set of attributes (columns).
- Tables are dynamic and can be created or deleted at runtime.
- They can be replicated across multiple nodes for fault tolerance.
- Mnesia supports different storage types for tables.
Understanding Table Types
Mnesia offers various table types to suit different needs:
ram_copies: Data is stored only in RAM. Fastest access, but data is lost if the node crashes.disc_copies: Data is stored in RAM and also replicated to disk. Provides persistence and good performance.disc_only_copies: Data is stored only on disk. Slower access, but uses less RAM and is persistent.
Choosing the right type depends on your data's persistence and performance requirements.
Defining Tables with Records
In Erlang, Mnesia tables are typically defined using records. A record declaration specifies the table's name (the record's name) and its attributes (the record's fields).
For example, a #user{} record would define a user table with specific fields like id, name, and email.
Creating Your First Table
Let's combine what we've learned! This example will start Mnesia, ensure a schema exists, define a user record, and then create a user table with disc_copies storage.
Run this to see a complete Mnesia setup for a basic table!
-module(mnesia_lesson_create_table).
-export([run/0]).
% Define the user record for our table
-record(user, {id, name, email}).
run() ->
% 1. Start the Mnesia application
application:start(mnesia),
io:format("Mnesia application started.~n"),
% 2. Create schema (if it doesn't exist)
case mnesia:create_schema([node()]) of
ok -> io:format("Mnesia schema created.~n");
{error, {already_exists, _}} ->
io:format("Schema already exists (skipping creation).~n");
Error -> io:format("Error creating schema: ~p~n", [Error])
end,
% 3. Start the Mnesia database manager
mnesia:start(),
io:format("Mnesia database started.~n"),
% 4. Create the 'user' table
% Options: [{disc_copies, [node()]}] means persistent table on this node
case mnesia:create_table(user, [{disc_copies, [node()]}]) of
{atomic, ok} ->
io:format("Table 'user' created successfully (disc_copies).~n");
{aborted, {already_exists, user}} ->
io:format("Table 'user' already exists (skipping creation).~n");
Error ->
io:format("Error creating table: ~p~n", [Error])
end,
% Give Mnesia a moment
timer:sleep(100),
% 5. Stop Mnesia and the application
mnesia:stop(),
application:stop(mnesia),
io:format("Mnesia stopped.~n"),
ok.Quick Check
Which Mnesia table type stores data only in memory and loses it if the node crashes or restarts?
Mnesia Fundamentals Recap
Great job! You've taken your first steps into Mnesia. We covered:
- What Mnesia is and its core features.
- How to start Mnesia and initialize its schema.
- The concept of Mnesia tables and their definition using Erlang records.
- The different table types:
ram_copies,disc_copies, anddisc_only_copies.
Next, we'll dive into performing atomic transactions and manipulating data within these tables!
자주 묻는 질문
“Mnesia 기초 및 스키마” 강의는 무료인가요?
네 — “Mnesia 기초 및 스키마” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의 전체를 잠금 해제할 수 있습니다. Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“Mnesia 기초 및 스키마”에서 뭘 배우나요?
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개 중 1번째 강의입니다.
“Mnesia 기초 및 스키마” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Erlang OTP: Distributed & Fault-Tolerant Systems Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Mnesia 기초 및 스키마
- 트랜잭션 및 데이터 조작
- 분산 Mnesia 및 복제
- Mnesia 인덱싱과 쿼리 최적화