Mnesia
In the previous chapter, we reviewed Erlang Term Storage (ETS), which provides an excellent option for storing tuples of arbitrary data. In this chapter, we'll take a look at the Erlang module :mnesia
. Mnesia is a real-time distributed database management system (DBMS). Since it is integrated with Erlang, it will always be available without adding any third-party dependencies. Mnesia is quite powerful and rather flexible, making it an excellent choice for application prototyping.
We'll be working with Mnesia via Elixir. Recall from an earlier chapter (Erlang foundation) that Erlang modules can be called directly from Elixir by prefixing them with the colon ( : ) character, as in :mnesia
.
To begin using Mnesia we first define a schema. This is accomplished by the create_schema
function, which accepts a node as its only argument. Mnesia is easily scalable and can be distributed across several nodes. Let's create a schema using the current node:
iex> :mnesia.create_schema([node()])
:ok
What did we pass to
create_schema
? What isnode()
?
Quick aside: A node is an instance of the Erlang VM. Multiple isolated nodes can be created on a single machine and Erlang has facilities for communicating between them. We will discuss this more in detail when we reach the chapter on distribution.
Data in Mnesia is organized into tables where the table name is an atom. Similar to ETS, tables can have one of the following types:
:set
- default table type, not ordered, no duplicate keys:ordered_set
- the data is ordered by primary key:bag
- keys can be duplicates but records must be unique
ACID
Atomicity | Consistency | Isolation | Durability
Performance