The following are some of the most important and attractive capabilities provided by Mnesia:
This Reference Manual describes the Mnesia API. This includes functions that define and manipulate Mnesia tables.
All functions in this Reference Manual can be used in any
combination with queries using the list comprehension notation.
For information about the query notation, see the
Data in Mnesia is organized as a set of tables. Each table has a name that must be an atom. Each table is made up of Erlang records. The user is responsible for the record definitions. Each table also has a set of properties. The following are some of the properties that are associated with each table:
If a table is of type
If a new item is inserted with the same key as an
existing record, the old record is overwritten. However,
if a table is of type
For information about the complete set of table properties
and their details, see
This Reference Manual uses a table of persons to illustrate various examples. The following record definition is assumed:
-record(person, {name,
age = 0,
address = unknown,
salary = 0,
children = []}),
The first record attribute is the primary key, or key for short.
The function descriptions are sorted in alphabetical order.
It is recommended to start to read about
Writing or deleting in transaction-context creates a local
copy of each modified record during the transaction. During
iteration, that is,
If possible, avoid writing or deleting records in the same transaction before iterating over the table.
Makes the transaction silently
return the tuple
A checkpoint is a consistent view of the system. A checkpoint can be activated on a set of tables. This checkpoint can then be traversed and presents a view of the system as it existed at the time when the checkpoint was activated, even if the tables are being or have been manipulated.
Returns
Calls
Executes the functional object
The code that executes inside the activity can
consist of a series of table manipulation functions, which are
performed in an
Short for
Calls
Short for
Calls
Calls
Calls
Calls
This function (
Mnesia forwards calls to the following functions:
to the corresponding:
Makes another copy of a table at the node
mnesia:add_table_copy(person, Node, disc_copies)
This function can also be used to add a replica of the
table named
Table indexes can be used whenever the user
wants to use frequently some other field than the key field
to look up records. If this other field has an associated
index, these lookups can occur in constant time
and space. For example, if your application wishes to use
field
mnesia:add_table_index(person, age)
Indexes do not come for free. They occupy space that is proportional to the table size, and they cause insertions into the table to execute slightly slower.
Returns a list of all keys in the table named
Calls the
The Mnesia tables can be manipulated without using transactions. This has some serious disadvantages, but is considerably faster, as the transaction manager is not involved and no locks are set. A dirty operation does, however, guarantee a certain level of consistency, and the dirty operations cannot return garbled records. All dirty operations provide location transparency to the programmer, and a program does not have to be aware of the whereabouts of a certain table to function.
Notice that it is more than ten times more efficient to read records dirty than within a transaction.
Depending on the application, it can be a good idea to use the dirty functions for certain operations. Almost all Mnesia functions that can be called within transactions have a dirty equivalent, which is much more efficient.
However, notice that there is a risk that the database can be left in an inconsistent state if dirty operations are used to update it. Dirty operations are only to be used for performance reasons when it is absolutely necessary.
Notice that calling (nesting)
Activates a new checkpoint covering all Mnesia tables,
including the schema, with maximum degree of redundancy, and
performs a backup using
The tables are backed up to external media using backup
module
Notice that this function must only be used to connect to newly started RAM nodes (N.D.R.S.N.) with an empty schema. If, for example, this function is used after the network has been partitioned, it can lead to inconsistent tables.
Notice that Mnesia can be connected to other
nodes than those returned in
For example:
mnesia:change_table_copy_type(person, node(), disc_copies)
Transforms the
This function can also be used to change the storage type
of the table named
The
Deletes all entries in the table
Creates a new database on disc. Various files are created in the local Mnesia directory of each node. Notice that the directory must be unique for each node. Two nodes must never share the same directory. If possible, use a local disc device to improve performance.
Notice that only nodes with disc are to be included in
Creates a Mnesia table called
At startup, Mnesia always loads
When accessing single attributes in a record, it is
not necessary, or even recommended, to hard code any
attribute names as atoms. Use construct
It is possible to have a replicated table of type
For example:
mnesia:create_table(table, [{ram_copies, [node()]}, {disc_only_copies, nodes()},
{storage_properties,
[{ets, [compressed]}, {dets, [{auto_save, 5000}]} ]}])
Notice that currently
For example, the following call creates the
mnesia:create_table(person,
[{ram_copies, [N1, N2]},
{attributes, record_info(fields, person)}]).
If it is required that Mnesia must build and
maintain an extra index table on attribute
mnesia:create_table(person,
[{ram_copies, [N1, N2]},
{index, [address]},
{attributes, record_info(fields, person)}]).
The specification of
The checkpoint is automatically deactivated when some of
the tables involved have no retainer attached to them. This
can occur when nodes go down or when a replica is deleted.
Checkpoints are also deactivated with this function.
Deletes the replica of table
This function can also be used to delete a replica of
the table named
Deletes the index on attribute with name
Calls
Deletes all records in table
The semantics of this function is context-sensitive.
For details, see
Calls
If a table is of type
The semantics of this function is context-sensitive.
For details, see
Deletes a database created with
After the database is deleted, it can still be possible
to start Mnesia as a disc-less node. This depends
on how configuration parameter
Use this function with extreme caution, as it makes existing persistent data obsolete. Think twice before using it.
Permanently deletes all replicas of table
Dirty equivalent of the function
Calls
Dirty equivalent of the function
Calls
Dirty equivalent of the function
Records in
If there are no records in the table, this function
returns the atom
Starts
Dirty equivalent of the function
Dirty equivalent of the function
Works exactly like
Calls
Dirty equivalent of the function
Traverses a table and
performs operations on all records in the table.
When the end of the table is reached, the special key
Works exactly like
Calls
Dirty equivalent of the function
Dirty equivalent of the function
Traverses a table in a
manner similar to the function
Calls
Mnesia has no special counter records. However,
records of the form
If two processes perform
If
Calls
Dirty equivalent of the function
Performs a user-initiated dump of the local log file.
This is usually not necessary, as Mnesia by default
manages this automatically. See configuration parameters
Dumps a set of
Dumps all local tables of a Mnesia system into a
text file, which can be edited (by a normal text editor)
and then be reloaded with
All Mnesia transactions, including all the schema
update functions, either return value
The following examples illustrate a function that returns an error, and the method to retrieve more detailed error information:
Calls the
Notice that calling (nesting) a
Records in
If there are no records in the table, this function
returns the atom
Iterates over the table
Works exactly like
The Mnesia algorithm for table load can lead to a situation where a table cannot be loaded. This situation occurs when a node is started and Mnesia concludes, or suspects, that another copy of the table was active after this local copy became inactive because of a system crash.
If this situation is not acceptable, this function can be used to override the strategy of the Mnesia table load algorithm. This can lead to a situation where some transaction effects are lost with an inconsistent database as result, but for some applications high availability is more important than consistent data.
Starts
In a manner similar to the function
The table
The element in position
The two index search functions described here are
automatically started when searching tables with
The semantics of this function is context-sensitive.
For details, see
Assume that there is an index on position
The semantics of this function is context-sensitive.
For details, see
Prints system information on the terminal. This function can be used even if Mnesia is not started. However, more information is displayed if Mnesia is started.
Calls
Calls
Installs a backup as fallback. The fallback is used to restore the database at the next startup. Installation of fallbacks requires Erlang to be operational on all the involved nodes, but it does not matter if Mnesia is running or not. The installation of the fallback fails if the local node is not one of the disc-resident nodes in the backup.
If
This is a dangerous feature that must be used with care. By unintentional mixing of directories, you can easily end up with an inconsistent database, if the same backup is installed on more than one directory.
When this function is executed inside a transaction-context,
it returns
Works exactly like
Loads a series of definitions and data found in the
text file (generated with
Write locks are normally acquired on all nodes where a replica of the table resides (and is active). Read locks are acquired on one node (the local node if a local replica exists). Most of the context-sensitive access functions acquire an implicit lock if they are started in a transaction-context. The granularity of a lock can either be a single record or an entire table.
The normal use is to call the function without checking
the return value, as it exits if it fails and the
transaction is restarted by the transaction manager. It
returns all the locked nodes if a write lock is acquired
and
The function
Write locks are exclusive. This means that if one transaction manages to acquire a write lock on an item, no other transaction can acquire any kind of lock on the same item.
Read locks can be shared. This means that if one transaction manages to acquire a read lock on an item, other transactions can also acquire a read lock on the same item. However, if someone has a read lock, no one can acquire a write lock at the same item. If someone has a write lock, no one can acquire either a read lock or a write lock at the same item.
Conflicting lock requests are automatically queued if there
is no risk of a deadlock. Otherwise the transaction must be
terminated and executed again. Mnesia does this
automatically as long as the upper limit of the maximum
For the sake of completeness, sticky write locks are also described here even if a sticky write lock is not supported by this function:
Sticky write locks are a mechanism that can be used to optimize write lock acquisition. If your application uses replicated tables mainly for fault tolerance (as opposed to read access optimization purpose), sticky locks can be the best option available.
When a sticky write lock is acquired, all nodes are informed which node is locked. Then, sticky lock requests from the same node are performed as a local operation without any communication with other nodes. The sticky lock lingers on the node even after the transaction ends. For details, see the User's Guide.
Currently, this function supports two kinds of
This acquires a lock of type
This acquires a lock of type
Locks are released when the outermost transaction ends.
The semantics of this function is context-sensitive.
For details, see
Calls
Takes a pattern with "don't care" variables
denoted as a
For example, the call
The function
The semantics of this function is context-sensitive.
For details, see
Moves the copy of table
The storage type is preserved. For example, a RAM table moved from one node remains a RAM on the new node. Other transactions can still read and write in the table while it is being moved.
This function cannot be used on
Traverses a table and
performs operations on all records in the table. When
the end of the table is reached, the special key
Works exactly like
Calls function
Calls function
Reads all records from table
The semantics of this function is context-sensitive.
For details, see
If the user wants to update the record, it is more
efficient to use
Calls the function
When tracing a system of Mnesia applications it is useful to be able to interleave Mnesia own events with application-related events that give information about the application context.
Whenever the application begins a
new and demanding Mnesia task, or if it enters a new
interesting phase in its execution, it can be a good idea to
use
With this function, tables can be restored online from a
backup without restarting Mnesia.
The affected tables are write-locked during the restoration. However, regardless of the lock conflicts caused by this, the applications can continue to do their work while the restoration is being performed. The restoration is performed as one single transaction.
If the database is huge, it it not always possible to restore it online. In such cases, restore the old database by installing a fallback and then restart.
Calls the function
Calls the function
Calls the function
Prints information about all table definitions on the terminal.
Prints information about one table definition on the terminal.
Matches the objects in table
Notice that for best performance,
In its simplest forms, the
For a complete description of
For example, to find the names of all male persons older
than 30 in table
MatchHead = #person{name='$1', sex=male, age='$2', _='_'},
Guard = {'>', '$2', 30},
Result = '$1',
mnesia:select(Tab,[{MatchHead, [Guard], [Result]}]),
Matches the objects in table
Notice that for best performance,
Selects more objects with the match specification initiated
by
Notice that any modifying operations, that is,
Changes the internal debug level of Mnesia.
For details, see
For each table Mnesia determines its replica nodes
(
If the application detects a
communication failure (in a potentially partitioned network)
that can have caused an inconsistent database, it can use the
function
The master node setting is always local. It can be changed regardless if Mnesia is started or not.
The database can also become inconsistent if
configuration parameter
Removes the possibility for SNMP to manipulate the table.
Transforms an SNMP index to the corresponding Mnesia key. If the SNMP table has multiple keys, the key is a tuple of the key columns.
Reads a row by its SNMP index. This index is specified as an SNMP Object Identifier, a list of integers.
A direct one-to-one mapping can be established between Mnesia tables and SNMP tables. Many telecommunication applications are controlled and monitored by the SNMP protocol. This connection between Mnesia and SNMP makes it simple and convenient to achieve this mapping.
Argument
For example, the following causes table
mnesia:snmp_open_table(person, [{key, string}])
Consider the following schema for a table of company employees. Each employee is identified by department number and name. The other table column stores the telephone number:
mnesia:create_table(employee,
[{snmp, [{key, {integer, string}}]},
{attributes, record_info(fields, employees)}]),
The corresponding SNMP table would have three columns:
An option is to have table columns that are not visible
through the SNMP protocol. These columns must be the last
columns of the table. In the previous example, the SNMP
table could have columns
In a table monitored by SNMP, all elements must be integers, strings, or lists of integers.
When a table is SNMP ordered, modifications are more expensive than usual, O(logN). Also, more memory is used.
Notice that only the lexicographical SNMP ordering is implemented in Mnesia, not the actual SNMP monitoring.
Mnesia startup is asynchronous. The function call
The startup procedure for a set of Mnesia nodes is a
fairly complicated operation. A Mnesia system consists
of a set of nodes, with Mnesia started locally on all
participating nodes. Normally, each node has a directory where
all the Mnesia files are written. This directory is
referred to as the Mnesia directory. Mnesia can
also be started on disc-less nodes. For more information
about disc-less nodes, see
The set of nodes that makes up a Mnesia system is kept
in a schema. Mnesia nodes can be added to or removed
from the schema. The initial schema is normally created on
disc with the function
Each schema has a unique cookie, which can be regarded as a unique schema identifier. The cookie must be the same on all nodes where Mnesia is supposed to run. For details, see the User's Guide.
The schema file and all other files that Mnesia
needs are kept in the Mnesia directory. The
command-line option
Stops Mnesia locally on the current node.
Ensures that a copy of all events of type
Calls the
Ensures that the local transaction log file is synced to disk.
On a single node system, data written to disk tables since the
last dump can be lost if there is a power outage.
See
Waits until data have been committed and
logged to disk (if disk is used) on every involved node before
it returns, otherwise it behaves as
This functionality can be used to avoid that one process overloads a database on another node.
Returns information about the Mnesia system, such as
transaction statistics,
New
This feature is temporary and will be removed in future releases.
If Mnesia is down on the local node, the function
returns those other
If Mnesia is started, the function returns
those nodes that Mnesia on the local node is fully
connected to. Only those nodes that Mnesia has
exchanged schema information with are included as
Returns a Query List Comprehension (QLC) query handle,
see the
There are two alternatives for
The
New
Executes the functional object
The code that executes inside the transaction
can consist of a series of table manipulation functions.
If something goes wrong inside the transaction as a result
of a user error or a certain table not being available, the
entire transaction is terminated and the function
If all is going well,
A function that adds a family to the database can be
written as follows if there is a structure
add_family({family, F, M, Children}) ->
ChildOids = lists:map(fun oid/1, Children),
Trans = fun() ->
mnesia:write(F#person{children = ChildOids},
mnesia:write(M#person{children = ChildOids},
Write = fun(Child) -> mnesia:write(Child) end,
lists:foreach(Write, Children)
end,
mnesia:transaction(Trans).
oid(Rec) -> {element(1, Rec), element(2, Rec)}.
This code adds a set of people to the database. Running
this code within one transaction ensures that either the whole
family is added to the database, or the whole transaction
terminates. For example, if the last child is badly formatted,
or the executing process terminates because of an
It is also useful to update the database within a transaction
if several processes concurrently update the same records.
For example, the function
raise(Name, Amount) ->
mnesia:transaction(fun() ->
case mnesia:wread({person, Name}) of
[P] ->
Salary = Amount + P#person.salary,
P2 = P#person{salary = Salary},
mnesia:write(P2);
_ ->
mnesia:abort("No such person")
end
end).
When this function executes within a transaction,
several processes running on different nodes can concurrently
execute the function
Since Mnesia detects deadlocks, a transaction can be
restarted any number of times. This function attempts a
restart as specified in
Applies argument
Calls
Iterates over a backup, either to transform it into a new backup, or read it. The arguments are explained briefly here. For details, see the User's Guide.
Calls the function
Deinstalls a fallback before it has been used to restore the database. This is normally a distributed operation that is either performed on all nodes with disc resident schema, or none. Uninstallation of fallbacks requires Erlang to be operational on all involved nodes, but it does not matter if Mnesia is running or not. Which nodes that are considered as disc-resident nodes is determined from the schema information in the local fallback.
Stops sending events of type
Some applications need to wait for certain tables to be
accessible to do useful work.
Calls the function
Calls the function
Writes record
The function returns
The semantics of this function is context-sensitive. For
details, see
Calls the function
Mnesia reads the following application configuration parameters:
No trace outputs. This is the default.
Activates tracing of important debug events. These
events generate
Activates all events at the verbose level plus full
trace of all debug events. These debug events generate
Activates all events at the debug level. On this level, the Mnesia event handler starts subscribing to updates on all Mnesia tables. This level is intended only for debugging small toy systems, as many large events can be generated.
This feature is temporary and will be removed in a future release
If
Mandatory disc. The schema is assumed to be located in the Mnesia directory. If the schema cannot be found, Mnesia refuses to start. This is the old behavior.
Mandatory RAM. The schema resides in RAM
only. At startup, a tiny new schema is generated. This
default schema only contains the definition of the schema
table and only resides on the local node. Since no other
nodes are found in the default schema, configuration
parameter
Parameter
Optional disc. The schema can reside on disc or in
RAM. If the schema is found on disc, Mnesia
starts as a disc-based node and the storage type of
the schema table is
First, the SASL application parameters are checked, then the command-line flags are checked, and finally, the default value is chosen.