0Pricing
Erlang OTP: Distributed & Fault-Tolerant Systems Programming · درس

أساسيات Mnesia والمخطط

تعرّف على بنية Mnesia وأنواع الجداول وكيفية تعريف مخططات لبياناتك الموزعة

أساسيات Mnesia والمخطط درس مجاني في Erlang OTP: Distributed & Fault-Tolerant Systems Programming على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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, and disc_only_copies.

Next, we'll dive into performing atomic transactions and manipulating data within these tables!

الأسئلة الشائعة

هل درس «أساسيات Mnesia والمخطط» مجاني؟

نعم — نص درس «أساسيات Mnesia والمخطط» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Erlang OTP: Distributed & Fault-Tolerant Systems Programming، انتقل إلى CoddyKit PRO. تتضمن دورة Erlang OTP: Distributed & Fault-Tolerant Systems Programming 4 دروس في المجموع.

ماذا ستتعلم في «أساسيات Mnesia والمخطط»؟

تعرّف على بنية Mnesia وأنواع الجداول وكيفية تعريف مخططات لبياناتك الموزعة تتمرن على Erlang OTP: Distributed & Fault-Tolerant Systems Programming مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Erlang OTP: Distributed & Fault-Tolerant Systems Programming؟

لا تُشترط خبرة سابقة. Erlang OTP: Distributed & Fault-Tolerant Systems Programming على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «أساسيات Mnesia والمخطط»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Erlang OTP: Distributed & Fault-Tolerant Systems Programming هذا؟

نعم. كل درس في Erlang OTP: Distributed & Fault-Tolerant Systems Programming يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. أساسيات Mnesia والمخطط
  2. المعاملات ومعالجة البيانات
  3. Mnesia الموزعة والنسخ المتماثل
  4. فهرسة Mnesia وتحسين الاستعلامات
← العودة إلى Erlang OTP: Distributed & Fault-Tolerant Systems Programming