19962014 Ericsson AB. All Rights Reserved. The contents of this file are subject to the Erlang Public License, Version 1.1, (the "License"); you may not use this file except in compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at http://www.erlang.org/. Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. mnesia Claes Wikström and Håkan Mattsson
mnesia A Distributed Telecommunications DBMS

Mnesia is a distributed DataBase Management System (DBMS), appropriate for telecommunications applications and other Erlang applications which require continuous operation and exhibit soft real-time properties.

Listed below are some of the most important and attractive capabilities, Mnesia provides:

A relational/object hybrid data model which is suitable for telecommunications applications.

A specifically designed DBMS query language, QLC (as an add-on library).

Persistence. Tables may be coherently kept on disc as well as in main memory.

Replication. Tables may be replicated at several nodes.

Atomic transactions. A series of table manipulation operations can be grouped into a single atomic transaction.

Location transparency. Programs can be written without knowledge of the actual location of data.

Extremely fast real time data searches.

Schema manipulation routines. It is possible to reconfigure the DBMS at runtime without stopping the system.

This Reference Manual describes the Mnesia API. This includes functions used to define and manipulate Mnesia tables.

All functions documented in these pages can be used in any combination with queries using the list comprehension notation. The query notation is described in the QLC's man page.

Data in Mnesia is organized as a set of tables. Each table has a name which 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. Below are some of the properties that are associated with each table:

type. Each table can either have 'set', 'ordered_set' or 'bag' semantics. Note: currently 'ordered_set' is not supported for 'disc_only_copies'. If a table is of type 'set' it means that each key leads to either one or zero records.

If a new item is inserted with the same key as an existing record, the old record is overwritten. On the other hand, if a table is of type 'bag', each key can map to several records. However, all records in type bag tables are unique, only the keys may be duplicated.

record_name. All records stored in a table must have the same name. You may say that the records must be instances of the same record type.

ram_copies A table can be replicated on a number of Erlang nodes. The ram_copies property specifies a list of Erlang nodes where RAM copies are kept. These copies can be dumped to disc at regular intervals. However, updates to these copies are not written to disc on a transaction basis.

disc_copies The disc_copies property specifies a list of Erlang nodes where the table is kept in RAM as well as on disc. All updates of the table are performed on the actual table and are also logged to disc. If a table is of type disc_copies at a certain node, it means that the entire table is resident in RAM memory as well as on disc. Each transaction performed on the table is appended to a LOG file as well as written into the RAM table.

disc_only_copies Some, or all, table replicas can be kept on disc only. These replicas are considerably slower than the RAM based replicas.

index This is a list of attribute names, or integers, which specify the tuple positions on which Mnesia shall build and maintain an extra index table.

local_content When an application requires tables whose contents is local to each node, local_content tables may be used. The name of the table is known to all Mnesia nodes, but its contents is unique on each node. This means that access to such a table must be done locally. Set the local_content field to true if you want to enable the local_content behavior. The default is false.

majority This attribute can be either true or false (default is false). When true, a majority of the table replicas must be available for an update to succeed. Majority checking can be enabled on tables with mission-critical data, where it is vital to avoid inconsistencies due to network splits.

snmp Each (set based) Mnesia table can be automatically turned into an SNMP ordered table as well. This property specifies the types of the SNMP keys.

attributes. The names of the attributes for the records that are inserted in the table.

See mnesia:create_table/2 about the complete set of table properties and their details.

This document 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 attribute of the record is the primary key, or key for short.

The function descriptions are sorted in alphabetic order. Hint: start to read about mnesia:create_table/2, mnesia:lock/2 and mnesia:activity/4 before you continue on and learn about the rest.

Writing or deleting in transaction context creates a local copy of each modified record during the transaction. During iteration, i.e. mnesia:fold[lr]/4 mnesia:next/2 mnesia:prev/2 mnesia:snmp_get_next_index/2, mnesia will compensate for every written or deleted record, which may reduce the performance. If possible avoid writing or deleting records in the same transaction before iterating over the table.

abort(Reason) -> transaction abort Abort the current transaction.

Makes the transaction silently return the tuple {aborted, Reason}. The abortion of a Mnesia transaction means that an exception will be thrown to an enclosing catch. Thus, the expression catch mnesia:abort(x) does not abort the transaction.

activate_checkpoint(Args) -> {ok,Name,Nodes} | {error,Reason} Activate a checkpoint.

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 will present 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.

Args is a list of the following tuples:

{name,Name}. Name of checkpoint. Each checkpoint must have a name which is unique to the associated nodes. The name can be reused only once the checkpoint has been deactivated. By default, a name which is probably unique is generated.

{max,MaxTabs}. MaxTabs is a list of tables that should be included in the checkpoint. The default is []. For these tables, the redundancy will be maximized and checkpoint information will be retained together with all replicas. The checkpoint becomes more fault tolerant if the tables have several replicas. When a new replica is added by means of the schema manipulation function mnesia:add_table_copy/3, a retainer will also be attached automatically.

{min,MinTabs}. MinTabs is a list of tables that should be included in the checkpoint. The default is []. For these tables, the redundancy will be minimized and the checkpoint information will only be retained with one replica, preferably on the local node.

{allow_remote,Bool}. false means that all retainers must be local. The checkpoint cannot be activated if a table does not reside locally. true allows retainers to be allocated on any node. Default is set to true.

{ram_overrides_dump,Bool}. Only applicable for ram_copies. Bool allows you to choose to backup the table state as it is in RAM, or as it is on disc. true means that the latest committed records in RAM should be included in the checkpoint. These are the records that the application accesses. false means that the records dumped to DAT files should be included in the checkpoint. These are the records that will be loaded at startup. Default is false.

Returns {ok,Name,Nodes} or {error,Reason}. Name is the (possibly generated) name of the checkpoint. Nodes are the nodes that are involved in the checkpoint. Only nodes that keep a checkpoint retainer know about the checkpoint.

activity(AccessContext, Fun [, Args]) -> ResultOfFun | exit(Reason) Execute Funin AccessContext.

Invokes mnesia:activity(AccessContext, Fun, Args, AccessMod) where AccessMod is the default access callback module obtained by mnesia:system_info(access_module). Args defaults to the empty list [].

activity(AccessContext, Fun, Args, AccessMod) -> ResultOfFun | exit(Reason) Execute Funin AccessContext.

This function executes the functional object Fun with the arguments Args.

The code which executes inside the activity can consist of a series of table manipulation functions, which is performed in a AccessContext. Currently, the following access contexts are supported:

transaction

Short for {transaction, infinity}

{transaction, Retries}

Invokes mnesia:transaction(Fun, Args, Retries). Note that the result from the Fun is returned if the transaction was successful (atomic), otherwise the function exits with an abort reason.

sync_transaction

Short for {sync_transaction, infinity}

{sync_transaction, Retries}

Invokes mnesia:sync_transaction(Fun, Args, Retries). Note that the result from the Fun is returned if the transaction was successful (atomic), otherwise the function exits with an abort reason.

async_dirty

Invokes mnesia:async_dirty(Fun, Args).

sync_dirty

Invokes mnesia:sync_dirty(Fun, Args).

ets

Invokes mnesia:ets(Fun, Args).

This function (mnesia:activity/4) differs in an important aspect from the mnesia:transaction, mnesia:sync_transaction, mnesia:async_dirty, mnesia:sync_dirty and mnesia:ets functions. The AccessMod argument is the name of a callback module which implements the mnesia_access behavior.

Mnesia will forward calls to the following functions:

mnesia:lock/2 (read_lock_table/1, write_lock_table/1)

mnesia:write/3 (write/1, s_write/1)

mnesia:delete/3 (delete/1, s_delete/1)

mnesia:delete_object/3 (delete_object/1, s_delete_object/1)

mnesia:read/3 (read/1, wread/1)

mnesia:match_object/3 (match_object/1)

mnesia:all_keys/1

mnesia:first/1

mnesia:last/1

mnesia:prev/2

mnesia:next/2

mnesia:index_match_object/4 (index_match_object/2)

mnesia:index_read/3

mnesia:table_info/2

to the corresponding:

AccessMod:lock(ActivityId, Opaque, LockItem, LockKind)

AccessMod:write(ActivityId, Opaque, Tab, Rec, LockKind)

AccessMod:delete(ActivityId, Opaque, Tab, Key, LockKind)

AccessMod:delete_object(ActivityId, Opaque, Tab, RecXS, LockKind)

AccessMod:read(ActivityId, Opaque, Tab, Key, LockKind)

AccessMod:match_object(ActivityId, Opaque, Tab, Pattern, LockKind)

AccessMod:all_keys(ActivityId, Opaque, Tab, LockKind)

AccessMod:first(ActivityId, Opaque, Tab)

AccessMod:last(ActivityId, Opaque, Tab)

AccessMod:prev(ActivityId, Opaque, Tab, Key)

AccessMod:next(ActivityId, Opaque, Tab, Key)

AccessMod:index_match_object(ActivityId, Opaque, Tab, Pattern, Attr, LockKind)

AccessMod:index_read(ActivityId, Opaque, Tab, SecondaryKey, Attr, LockKind)

AccessMod:table_info(ActivityId, Opaque, Tab, InfoItem)

where ActivityId is a record which represents the identity of the enclosing Mnesia activity. The first field (obtained with element(1, ActivityId) contains an atom which may be interpreted as the type of the activity: 'ets', 'async_dirty', 'sync_dirty' or 'tid'. 'tid' means that the activity is a transaction. The structure of the rest of the identity record is internal to Mnesia.

Opaque is an opaque data structure which is internal to Mnesia.

add_table_copy(Tab, Node, Type) -> {aborted, R} | {atomic, ok} Copy a table to a remote node.

This function makes another copy of a table at the node Node. The Type argument must be either of the atoms ram_copies, disc_copies, or disc_only_copies. For example, the following call ensures that a disc replica of the person table also exists at node Node.

mnesia:add_table_copy(person, Node, disc_copies)

This function can also be used to add a replica of the table named schema.

add_table_index(Tab, AttrName) -> {aborted, R} | {atomic, ok} Create an index for a table.

Table indices can and should be used whenever the user wants to frequently use some other field than the key field to look up records. If this other field has an index associated with it, these lookups can occur in constant time and space. For example, if our application wishes to use the age field of persons to efficiently find all person with a specific age, it might be a good idea to have an index on the age field. This can be accomplished with the following call:

mnesia:add_table_index(person, age)

Indices do not come free, they occupy space which is proportional to the size of the table. They also cause insertions into the table to execute slightly slower.

all_keys(Tab) -> KeyList | transaction abort Return all keys in a table.

This function returns a list of all keys in the table named Tab. The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a read lock on the entire table.

async_dirty(Fun, [, Args]) -> ResultOfFun | exit(Reason) Call the Fun in a context which is not protected by a transaction.

Call the Fun in a context which is not protected by a transaction. The Mnesia function calls performed in the Fun are mapped to the corresponding dirty functions. This still involves logging, replication and subscriptions, but there is no locking, local transaction storage, or commit protocols involved. Checkpoint retainers and indices are updated, but they will be updated dirty. As for normal mnesia:dirty_* operations, the operations are performed semi-asynchronously. See mnesia:activity/4 and the Mnesia User's Guide for more details.

It is possible to manipulate the Mnesia tables without using transactions. This has some serious disadvantages, but is considerably faster since the transaction manager is not involved and no locks are set. A dirty operation does, however, guarantee a certain level of consistency and it is not possible for the dirty operations to 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 in order to function.

Note:It is more than 10 times more efficient to read records dirty than within a transaction.

Depending on the application, it may be a good idea to use the dirty functions for certain operations. Almost all Mnesia functions which can be called within transactions have a dirty equivalent which is much more efficient. However, it must be noted that it is possible for the database to be left in an inconsistent state if dirty operations are used to update it. Dirty operations should only be used for performance reasons when it is absolutely necessary.

Note: Calling (nesting) a mnesia:[a]sync_dirty inside a transaction context will inherit the transaction semantics.

backup(Opaque [, BackupMod]) -> ok | {error,Reason} Back up all tables in the database.

Activates a new checkpoint covering all Mnesia tables, including the schema, with maximum degree of redundancy and performs a backup using backup_checkpoint/2/3. The default value of the backup callback module BackupMod is obtained by mnesia:system_info(backup_module).

backup_checkpoint(Name, Opaque [, BackupMod]) -> ok | {error,Reason} Back up all tables in a checkpoint.

The tables are backed up to external media using the backup module BackupMod. Tables with the local contents property is being backed up as they exist on the current node. BackupMod is the default backup callback module obtained by mnesia:system_info(backup_module). See the User's Guide about the exact callback interface (the mnesia_backup behavior).

change_config(Config, Value) -> {error, Reason} | {ok, ReturnValue} Change a configuration parameter.

The Config should be an atom of the following configuration parameters:

extra_db_nodes

Value is a list of nodes which Mnesia should try to connect to. The ReturnValue will be those nodes in Value that Mnesia are connected to.

Note: This function shall only be used to connect to newly started ram nodes (N.D.R.S.N.) with an empty schema. If for example it is used after the network have been partitioned it may lead to inconsistent tables.

Note: Mnesia may be connected to other nodes than those returned in ReturnValue.

dc_dump_limit

Value is a number. See description in Configuration Parameters below. The ReturnValue is the new value. Note this configuration parameter is not persistent, it will be lost when mnesia stopped.

change_table_access_mode(Tab, AccessMode) -> {aborted, R} | {atomic, ok} Change the access mode for the table.

The AcccessMode is by default the atom read_write but it may also be set to the atom read_only. If the AccessMode is set to read_only, it means that it is not possible to perform updates to the table. At startup Mnesia always loads read_only tables locally regardless of when and if Mnesia was terminated on other nodes.

change_table_copy_type(Tab, Node, To) -> {aborted, R} | {atomic, ok} Change the storage type of a table.

For example:

mnesia:change_table_copy_type(person, node(), disc_copies)

Transforms our person table from a RAM table into a disc based table at Node.

This function can also be used to change the storage type of the table named schema. The schema table can only have ram_copies or disc_copies as the storage type. If the storage type of the schema is ram_copies, no other table can be disc resident on that node.

change_table_load_order(Tab, LoadOrder) -> {aborted, R} | {atomic, ok} Change the load order priority for the table.

The LoadOrder priority is by default 0 (zero) but may be set to any integer. The tables with the highest LoadOrder priority will be loaded first at startup.

change_table_majority(Tab, Majority) -> {aborted, R} | {atomic, ok} Change the majority check setting for the table.

Majority must be a boolean; the default is false. When true, a majority of the table's replicas must be available for an update to succeed. When used on fragmented tables, Tab must be the name base table. Directly changing the majority setting on individual fragments is not allowed.

clear_table(Tab) -> {aborted, R} | {atomic, ok} Deletes all entries in a table.

Deletes all entries in the table Tab.

create_schema(DiscNodes) -> ok | {error,Reason} Create a brand new schema on the specified nodes.

Creates a new database on disc. Various files are created in the local Mnesia directory of each node. Note that the directory must be unique for each node. Two nodes may never share the same directory. If possible, use a local disc device in order to improve performance.

mnesia:create_schema/1 fails if any of the Erlang nodes given as DiscNodes are not alive, if Mnesia is running on anyone of the nodes, or if anyone of the nodes already has a schema. Use mnesia:delete_schema/1 to get rid of old faulty schemas.

Note: Only nodes with disc should be included in DiscNodes. Disc-less nodes, that is nodes where all tables including the schema only resides in RAM, may not be included.

create_table(Name, TabDef) -> {atomic, ok} | {aborted, Reason} Create a Mnesia table called Namewith properties as described by the argument TabDef.

This function creates a Mnesia table called Name according to the argument TabDef. This list must be a list of {Item, Value} tuples, where the following values are allowed:

{access_mode, Atom}. The access mode is by default the atom read_write but it may also be set to the atom read_only. If the AccessMode is set to read_only, it means that it is not possible to perform updates to the table.

At startup Mnesia always loads read_only tables locally regardless of when and if Mnesia was terminated on other nodes. This argument returns the access mode of the table. The access mode may either be read_only or read_write.

{attributes, AtomList} a list of the attribute names for the records that are supposed to populate the table. The default value is [key, val]. The table must have at least one extra attribute in addition to the key.

When accessing single attributes in a record, it is not necessary, or even recommended, to hard code any attribute names as atoms. Use the construct record_info(fields, RecordName) instead. It can be used for records of type RecordName

{disc_copies, Nodelist}, where Nodelist is a list of the nodes where this table is supposed to have disc copies. If a table replica is of type disc_copies, all write operations on this particular replica of the table are written to disc as well as to the RAM copy of the table.

It is possible to have a replicated table of type disc_copies on one node, and another type on another node. The default value is []

{disc_only_copies, Nodelist}, where Nodelist is a list of the nodes where this table is supposed to have disc_only_copies. A disc only table replica is kept on disc only and unlike the other replica types, the contents of the replica will not reside in RAM. These replicas are considerably slower than replicas held in RAM.

{index, Intlist}, where Intlist is a list of attribute names (atoms) or record fields for which Mnesia shall build and maintain an extra index table. The qlc query compiler may or may not utilize any additional indices while processing queries on a table.

{load_order, Integer}. The load order priority is by default 0 (zero) but may be set to any integer. The tables with the highest load order priority will be loaded first at startup.

{majority, Flag}, where Flag must be a boolean. If true, any (non-dirty) update to the table will abort unless a majority of the table's replicas are available for the commit. When used on a fragmented table, all fragments will be given the same majority setting.

{ram_copies, Nodelist}, where Nodelist is a list of the nodes where this table is supposed to have RAM copies. A table replica of type ram_copies is obviously not written to disc on a per transaction basis. It is possible to dump ram_copies replicas to disc with the function mnesia:dump_tables(Tabs). The default value for this attribute is [node()].

{record_name, Name}, where Name must be an atom. All records, stored in the table, must have this name as the first element. It defaults to the same name as the name of the table.

{snmp, SnmpStruct}. See mnesia:snmp_open_table/2 for a description of SnmpStruct. If this attribute is present in the ArgList to mnesia:create_table/2, the table is immediately accessible by means of the Simple Network Management Protocol (SNMP). This means that applications which use SNMP to manipulate and control the system can be designed easily, since Mnesia provides a direct mapping between the logical tables that make up an SNMP control application and the physical data which makes up a Mnesia table.

{storage_properties, [{Backend, Properties}]. Forwards additional properties to the backend storage. Backend can currently be ets or dets and Properties is a list of options sent to the backend storage during table creation. Properties may not contain properties already used by mnesia such as type or named_table.

For example:

mnesia:create_table(table, [{ram_copies, [node()]}, {disc_only_copies, nodes()}, {storage_properties, [{ets, [compressed]}, {dets, [{auto_save, 5000}]} ]}])

{type, Type}, where Type must be either of the atoms set, ordered_set or bag. The default value is set. In a set all records have unique keys and in a bag several records may have the same key, but the record content is unique. If a non-unique record is stored the old, conflicting record(s) will simply be overwritten. Note: currently 'ordered_set' is not supported for 'disc_only_copies'.

{local_content, Bool}, where Bool must be either true or false. The default value is false.

For example, the following call creates the person table previously defined and replicates it on 2 nodes:

mnesia:create_table(person, [{ram_copies, [N1, N2]}, {attributes, record_info(fields,person)}]).

If it was required that Mnesia build and maintain an extra index table on the address attribute of all the person records that are inserted in the table, the following code would be issued:

mnesia:create_table(person, [{ram_copies, [N1, N2]}, {index, [address]}, {attributes, record_info(fields,person)}]).

The specification of index and attributes may be hard coded as {index, [2]} and {attributes, [name, age, address, salary, children]} respectively.

mnesia:create_table/2 writes records into the schema table. This function, as well as all other schema manipulation functions, are implemented with the normal transaction management system. This guarantees that schema updates are performed on all nodes in an atomic manner.

deactivate_checkpoint(Name) -> ok | {error, Reason} Deactivate a checkpoint.

The checkpoint is automatically deactivated when some of the tables involved have no retainer attached to them. This may happen when nodes go down or when a replica is deleted. Checkpoints will also be deactivated with this function. Name is the name of an active checkpoint.

del_table_copy(Tab, Node) -> {aborted, R} | {atomic, ok} Delete the replica of table Tabat node Node.

Deletes the replica of table Tab at node Node. When the last replica is deleted with this function, the table disappears entirely.

This function may also be used to delete a replica of the table named schema. Then the mnesia node will be removed. Note: Mnesia must be stopped on the node first.

del_table_index(Tab, AttrName) -> {aborted, R} | {atomic, ok} Delete an index in a table.

This function deletes the index on attribute with name AttrName in a table.

delete({Tab, Key}) -> transaction abort | ok Delete all records in table Tabwith the key Key.

Invokes mnesia:delete(Tab, Key, write)

delete(Tab, Key, LockKind) -> transaction abort | ok Delete all records in table Tabwith the key Key.

Deletes all records in table Tab with the key Key.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a lock of type LockKind in the record. Currently the lock types write and sticky_write are supported.

delete_object(Record) -> transaction abort | ok Delete a record

Invokes mnesia:delete_object(Tab, Record, write) where Tab is element(1, Record).

delete_object(Tab, Record, LockKind) -> transaction abort | ok Delete a record

If a table is of type bag, we may sometimes want to delete only some of the records with a certain key. This can be done with the delete_object/3 function. A complete record must be supplied to this function.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a lock of type LockKind on the record. Currently the lock types write and sticky_write are supported.

delete_schema(DiscNodes) -> ok | {error,Reason} Delete the schema on the given nodes

Deletes a database created with mnesia:create_schema/1. mnesia:delete_schema/1 fails if any of the Erlang nodes given as DiscNodes is not alive, or if Mnesia is running on any of the nodes.

After the database has been deleted, it may still be possible to start Mnesia as a disc-less node. This depends on how the configuration parameter schema_location is set.

This function must be used with extreme caution since it makes existing persistent data obsolete. Think twice before using it.

delete_table(Tab) -> {aborted, Reason} | {atomic, ok} Delete permanently all replicas of table Tab.

Permanently deletes all replicas of table Tab.

dirty_all_keys(Tab) -> KeyList | exit({aborted, Reason}). Dirty search for all record keys in table.

This is the dirty equivalent of the mnesia:all_keys/1 function.

dirty_delete({Tab, Key}) -> ok | exit({aborted, Reason}) Dirty delete of a record.

Invokes mnesia:dirty_delete(Tab, Key).

dirty_delete(Tab, Key) -> ok | exit({aborted, Reason}) Dirty delete of a record.

This is the dirty equivalent of the mnesia:delete/3 function.

dirty_delete_object(Record) Dirty delete of a record.

Invokes mnesia:dirty_delete_object(Tab, Record) where Tab is element(1, Record).

dirty_delete_object(Tab, Record) Dirty delete of a record.

This is the dirty equivalent of the mnesia:delete_object/3 function.

dirty_first(Tab) -> Key | exit({aborted, Reason}) Return the key for the first record in a table.

Records in set or bag tables are not ordered. However, there is an ordering of the records which is not known to the user. Accordingly, it is possible to traverse a table by means of this function in conjunction with the mnesia:dirty_next/2 function.

If there are no records at all in the table, this function returns the atom '$end_of_table'. For this reason, it is highly undesirable, but not disallowed, to use this atom as the key for any user records.

dirty_index_match_object(Pattern, Pos) Dirty pattern match using index.

Invokes mnesia:dirty_index_match_object(Tab, Pattern, Pos) where Tab is element(1, Pattern).

dirty_index_match_object(Tab, Pattern, Pos) Dirty pattern match using index.

This is the dirty equivalent of the mnesia:index_match_object/4 function.

dirty_index_read(Tab, SecondaryKey, Pos) Dirty read using index.

This is the dirty equivalent of the mnesia:index_read/3 function.

dirty_last(Tab) -> Key | exit({aborted, Reason}) Return the key for the last record in a table.

This function works exactly like mnesia:dirty_first/1 but returns the last object in Erlang term order for the ordered_set table type. For all other table types, mnesia:dirty_first/1 and mnesia:dirty_last/1 are synonyms.

dirty_match_object(Pattern) -> RecordList | exit({aborted, Reason}). Dirty pattern match pattern.

Invokes mnesia:dirty_match_object(Tab, Pattern) where Tab is element(1, Pattern).

dirty_match_object(Tab, Pattern) -> RecordList | exit({aborted, Reason}). Dirty pattern match pattern.

This is the dirty equivalent of the mnesia:match_object/3 function.

dirty_next(Tab, Key) -> Key | exit({aborted, Reason}) Return the next key in a table.

This function makes it possible to traverse a table and perform operations on all records in the table. When the end of the table is reached, the special key '$end_of_table' is returned. Otherwise, the function returns a key which can be used to read the actual record.The behavior is undefined if another Erlang process performs write operations on the table while it is being traversed with the mnesia:dirty_next/2 function.

dirty_prev(Tab, Key) -> Key | exit({aborted, Reason}) Return the previous key in a table.

This function works exactly like mnesia:dirty_next/2 but returns the previous object in Erlang term order for the ordered_set table type. For all other table types, mnesia:dirty_next/2 and mnesia:dirty_prev/2 are synonyms.

dirty_read({Tab, Key}) -> ValueList | exit({aborted, Reason} Dirty read of records.

Invokes mnesia:dirty_read(Tab, Key).

dirty_read(Tab, Key) -> ValueList | exit({aborted, Reason} Dirty read of records.

This is the dirty equivalent of the mnesia:read/3 function.

dirty_select(Tab, MatchSpec) -> ValueList | exit({aborted, Reason} Dirty match the objects in Tabagainst MatchSpec.

This is the dirty equivalent of the mnesia:select/2 function.

dirty_slot(Tab, Slot) -> RecordList | exit({aborted, Reason}) Return the list of records that are associated with Slot in a table.

This function can be used to traverse a table in a manner similar to the mnesia:dirty_next/2 function. A table has a number of slots which range from 0 (zero) to some unknown upper bound. The function mnesia:dirty_slot/2 returns the special atom '$end_of_table' when the end of the table is reached. The behavior of this function is undefined if a write operation is performed on the table while it is being traversed.

dirty_update_counter({Tab, Key}, Incr) -> NewVal | exit({aborted, Reason}) Dirty update of a counter record.

Invokes mnesia:dirty_update_counter(Tab, Key, Incr).

dirty_update_counter(Tab, Key, Incr) -> NewVal | exit({aborted, Reason}) Dirty update of a counter record.

There are no special counter records in Mnesia. However, records of the form {Tab, Key, Integer} can be used as (possibly disc resident) counters, when Tab is a set. This function updates a counter with a positive or negative number. However, counters can never become less than zero. There are two significant differences between this function and the action of first reading the record, performing the arithmetics, and then writing the record:

It is much more efficient mnesia:dirty_update_counter/3 is performed as an atomic operation despite the fact that it is not protected by a transaction.

If two processes perform mnesia:dirty_update_counter/3 simultaneously, both updates will take effect without the risk of losing one of the updates. The new value NewVal of the counter is returned.

If Key don't exits, a new record is created with the value Incr if it is larger than 0, otherwise it is set to 0.

dirty_write(Record) -> ok | exit({aborted, Reason}) Dirty write of a record.

Invokes mnesia:dirty_write(Tab, Record) where Tab is element(1, Record).

dirty_write(Tab, Record) -> ok | exit({aborted, Reason}) Dirty write of a record.

This is the dirty equivalent of mnesia:write/3.

dump_log() -> dumped Perform a user initiated dump of the local log file.

Performs a user initiated dump of the local log file. This is usually not necessary since Mnesia, by default, manages this automatically. See configuration parameters dump_log_time_threshold and dump_log_write_threshold.

dump_tables(TabList) -> {atomic, ok} | {aborted, Reason} Dump all RAM tables to disc.

This function dumps a set of ram_copies tables to disc. The next time the system is started, these tables are initiated with the data found in the files that are the result of this dump. None of the tables may have disc resident replicas.

dump_to_textfile(Filename) Dump local tables into a text file.

Dumps all local tables of a mnesia system into a text file which can then be edited (by means of a normal text editor) and then later be reloaded with mnesia:load_textfile/1. Only use this function for educational purposes. Use other functions to deal with real backups.

error_description(Error) -> String Return a string describing a particular Mnesia error.

All Mnesia transactions, including all the schema update functions, either return the value {atomic, Val} or the tuple {aborted, Reason}. The Reason can be either of the following atoms. The error_description/1 function returns a descriptive string which describes the error.

nested_transaction. Nested transactions are not allowed in this context.

badarg. Bad or invalid argument, possibly bad type.

no_transaction. Operation not allowed outside transactions.

combine_error. Table options were illegally combined.

bad_index. Index already exists or was out of bounds.

already_exists. Schema option is already set.

index_exists. Some operations cannot be performed on tabs with index.

no_exists. Tried to perform operation on non-existing, or not alive, item.

system_limit. Some system_limit was exhausted.

mnesia_down. A transaction involving records at some remote node which died while transaction was executing. Record(s) are no longer available elsewhere in the network.

not_a_db_node. A node which does not exist in the schema was mentioned.

bad_type. Bad type on some arguments.

node_not_running. Node not running.

truncated_binary_file. Truncated binary in file.

active. Some delete operations require that all active records are removed.

illegal. Operation not supported on record.

The Error may be Reason, {error, Reason}, or {aborted, Reason}. The Reason may be an atom or a tuple with Reason as an atom in the first field.

ets(Fun, [, Args]) -> ResultOfFun | exit(Reason) Call the Fun in a raw context which is not protected by a transaction.

Call the Fun in a raw context which is not protected by a transaction. The Mnesia function call is performed in the Fun are performed directly on the local ets tables on the assumption that the local storage type is ram_copies and the tables are not replicated to other nodes. Subscriptions are not triggered and checkpoints are not updated, but it is extremely fast. This function can also be applied to disc_copies tables if all operations are read only. See mnesia:activity/4 and the Mnesia User's Guide for more details.

Note: Calling (nesting) a mnesia:ets inside a transaction context will inherit the transaction semantics.

first(Tab) -> Key | transaction abort Return the key for the first record in a table.

Records in set or bag tables are not ordered. However, there is an ordering of the records which is not known to the user. Accordingly, it is possible to traverse a table by means of this function in conjunction with the mnesia:next/2 function.

If there are no records at all in the table, this function returns the atom '$end_of_table'. For this reason, it is highly undesirable, but not disallowed, to use this atom as the key for any user records.

foldl(Function, Acc, Table) -> NewAcc | transaction abort Call Function for each record in Table

Iterates over the table Table and calls Function(Record, NewAcc) for each Record in the table. The term returned from Function will be used as the second argument in the next call to the Function.

foldl returns the same term as the last call to Function returned.

foldr(Function, Acc, Table) -> NewAcc | transaction abort Call Function for each record in Table

This function works exactly like foldl/3 but iterates the table in the opposite order for the ordered_set table type. For all other table types, foldr/3 and foldl/3 are synonyms.

force_load_table(Tab) -> yes | ErrorDescription Force a table to be loaded into the system

The Mnesia algorithm for table load might 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 due to 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 could lead to a situation where some transaction effects are lost with a inconsistent database as result, but for some applications high availability is more important than consistent data.

index_match_object(Pattern, Pos) -> transaction abort | ObjList Match records and utilizes index information.

Invokes mnesia:index_match_object(Tab, Pattern, Pos, read) where Tab is element(1, Pattern).

index_match_object(Tab, Pattern, Pos, LockKind) -> transaction abort | ObjList Match records and utilizes index information.

In a manner similar to the mnesia:index_read/3 function, we can also utilize any index information when we try to match records. This function takes a pattern which obeys the same rules as the mnesia:match_object/3 function with the exception that this function requires the following conditions:

The table Tab must have an index on position Pos.

The element in position Pos in Pattern must be bound. Pos may either be an integer (#record.Field), or an attribute name.

The two index search functions described here are automatically invoked when searching tables with qlc list comprehensions and also when using the low level mnesia:[dirty_]match_object functions.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a lock of type LockKind on the entire table or on a single record. Currently, the lock type read is supported.

index_read(Tab, SecondaryKey, Pos) -> transaction abort | RecordList Read records via index table.

Assume there is an index on position Pos for a certain record type. This function can be used to read the records without knowing the actual key for the record. For example, with an index in position 1 of the person table, the call mnesia:index_read(person, 36, #person.age) returns a list of all persons with age equal to 36. Pos may also be an attribute name (atom), but if the notation mnesia:index_read(person, 36, age) is used, the field position will be searched for in runtime, for each call.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a read lock on the entire table.

info() -> ok Print some information about the system on the tty.

Prints some information about the system on the tty. This function may be used even if Mnesia is not started. However, more information will be displayed if Mnesia is started.

install_fallback(Opaque) -> ok | {error,Reason} Install a backup as fallback.

Invokes mnesia:install_fallback(Opaque, Args) where Args is [{scope, global}].

install_fallback(Opaque), BackupMod) -> ok | {error,Reason} Install a backup as fallback.

Invokes mnesia:install_fallback(Opaque, Args) where Args is [{scope, global}, {module, BackupMod}].

install_fallback(Opaque, Args) -> ok | {error,Reason} Install a backup as fallback.

This function is used to install a backup as fallback. The fallback will be used to restore the database at the next start-up. Installation of fallbacks requires Erlang to be up and running on all the involved nodes, but it does not matter if Mnesia is running or not. The installation of the fallback will fail if the local node is not one of the disc resident nodes in the backup.

Args is a list of the following tuples:

{module, BackupMod}. All accesses of the backup media is performed via a callback module named BackupMod. The Opaque argument is forwarded to the callback module which may interpret it as it wish. The default callback module is called mnesia_backup and it interprets the Opaque argument as a local filename. The default for this module is also configurable via the -mnesia mnesia_backup configuration parameter.

{scope, Scope} The Scope of a fallback may either be global for the entire database or local for one node. By default, the installation of a fallback is a global operation which either is performed all nodes with disc resident schema or none. Which nodes that are disc resident or not, is determined from the schema info in the backup.

If the Scope of the operation is local the fallback will only be installed on the local node.

{mnesia_dir, AlternateDir} This argument is only valid if the scope of the installation is local. Normally the installation of a fallback is targeted towards the Mnesia directory as configured with the -mnesia dir configuration parameter. But by explicitly supplying an AlternateDir the fallback will be installed there regardless of the Mnesia directory configuration parameter setting. After installation of a fallback on an alternate Mnesia directory that directory is fully prepared for usage as an active Mnesia directory.

This is a somewhat dangerous feature which must be used with care. By unintentional mixing of directories you may easily end up with a inconsistent database, if the same backup is installed on more than one directory.

is_transaction() -> boolean Check if code is running in a transaction.

When this function is executed inside a transaction context it returns true, otherwise false.

last(Tab) -> Key | transaction abort Return the key for the last record in a table.

This function works exactly like mnesia:first/1 but returns the last object in Erlang term order for the ordered_set table type. For all other table types, mnesia:first/1 and mnesia:last/1 are synonyms.

load_textfile(Filename) Load tables from a text file.

Loads a series of definitions and data found in the text file (generated with mnesia:dump_to_textfile/1) into Mnesia. This function also starts Mnesia and possibly creates a new schema. This function is intended for educational purposes only and using other functions to deal with real backups, is recommended.

lock(LockItem, LockKind) -> Nodes | ok | transaction abort Explicit grab lock.

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 invoked in a transaction context. The granularity of a lock may either be a single record or an entire table.

The normal usage is to call the function without checking the return value since 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 ok if it was a read lock.

This function mnesia:lock/2 is intended to support explicit locking on tables but also intended for situations when locks need to be acquired regardless of how tables are replicated. Currently, two LockKind's are supported:

write

Write locks are exclusive, which means that if one transaction manages to acquire a write lock on an item, no other transaction may acquire any kind of lock on the same item.

read

Read locks may be shared, which means that if one transaction manages to acquire a read lock on an item, other transactions may 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 some one has a write lock no one can acquire a read lock nor 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 aborted and executed again. Mnesia does this automatically as long as the upper limit of maximum retries is not reached. See mnesia:transaction/3 for the details.

For the sake of completeness sticky write locks will also be described here even if a sticky write lock is not supported by this particular function:

sticky_write

Sticky write locks are a mechanism which 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 may be the best option available.

When a sticky write lock is acquired, all nodes will be informed which node is locked. Subsequently, sticky lock requests from the same node will be performed as a local operation without any communication with other nodes. The sticky lock lingers on the node even after the transaction has ended. See the Mnesia User's Guide for more information.

Currently, two kinds of LockItem's are supported by this function:

{table, Tab}

This acquires a lock of type LockKind on the entire table Tab.

{global, GlobalKey, Nodes}

This acquires a lock of type LockKind on the global resource GlobalKey. The lock is acquired on all active nodes in the Nodes list.

Locks are released when the outermost transaction ends.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires locks otherwise it just ignores the request.

match_object(Pattern) ->transaction abort | RecList Match Patternfor records.

Invokes mnesia:match_object(Tab, Pattern, read) where Tab is element(1, Pattern).

match_object(Tab, Pattern, LockKind) ->transaction abort | RecList Match Patternfor records.

This function takes a pattern with 'don't care' variables denoted as a '_' parameter. This function returns a list of records which matched the pattern. Since the second element of a record in a table is considered to be the key for the record, the performance of this function depends on whether this key is bound or not.

For example, the call mnesia:match_object(person, {person, '_', 36, '_', '_'}, read) returns a list of all person records with an age field of thirty-six (36).

The function mnesia:match_object/3 automatically uses indices if these exist. However, no heuristics are performed in order to select the best index.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a lock of type LockKind on the entire table or a single record. Currently, the lock type read is supported.

move_table_copy(Tab, From, To) -> {aborted, Reason} | {atomic, ok} Move the copy of table Tabfrom nodeFromto node To.

Moves the copy of table Tab from node From to node To.

The storage type is preserved. For example, a RAM table moved from one node remains a RAM on the new node. It is still possible for other transactions to read and write in the table while it is being moved.

This function cannot be used on local_content tables.

next(Tab, Key) -> Key | transaction abort Return the next key in a table.

This function makes it possible to traverse a table and perform operations on all records in the table. When the end of the table is reached, the special key '$end_of_table' is returned. Otherwise, the function returns a key which can be used to read the actual record.

prev(Tab, Key) -> Key | transaction abort Return the previous key in a table.

This function works exactly like mnesia:next/2 but returns the previous object in Erlang term order for the ordered_set table type. For all other table types, mnesia:next/2 and mnesia:prev/2 are synonyms.

read({Tab, Key}) -> transaction abort | RecordList Read records(s) with a given key.

Invokes mnesia:read(Tab, Key, read).

read(Tab, Key) -> transaction abort | RecordList Read records(s) with a given key.

Invokes mnesia:read(Tab, Key, read).

read(Tab, Key, LockKind) -> transaction abort | RecordList Read records(s) with a given key.

This function reads all records from table Tab with key Key. This function has the same semantics regardless of the location of Tab. If the table is of type bag, the mnesia:read(Tab, Key) can return an arbitrarily long list. If the table is of type set, the list is either of length 1, or [].

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a lock of type LockKind. Currently, the lock types read, write and sticky_write are supported.

If the user wants to update the record it is more efficient to use write/sticky_write as the LockKind. If majority checking is active on the table, it will be checked as soon as a write lock is attempted. This can be used to quickly abort if the majority condition isn't met.

read_lock_table(Tab) -> ok | transaction abort Set a read lock on an entire table.

Invokes mnesia:lock({table, Tab}, read).

report_event(Event) -> ok Report a user event to Mnesia's event handler.

When tracing a system of Mnesia applications it is useful to be able to interleave Mnesia's 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 is entering a new interesting phase in its execution, it may be a good idea to use mnesia:report_event/1. The Event may be any term and generates a {mnesia_user, Event} event for any processes that subscribe to Mnesia system events.

restore(Opaque, Args) -> {atomic, RestoredTabs} |{aborted, Reason} Online restore of backup.

With this function, tables may be restored online from a backup without restarting Mnesia. Opaque is forwarded to the backup module. Args is a list of the following tuples:

{module,BackupMod} The backup module BackupMod will be used to access the backup media. If omitted, the default backup module will be used.

{skip_tables, TabList} Where TabList is a list of tables which should not be read from the backup. {clear_tables, TabList} Where TabList is a list of tables which should be cleared, before the records from the backup are inserted, ie. all records in the tables are deleted before the tables are restored. Schema information about the tables is not cleared or read from backup. {keep_tables, TabList} Where TabList is a list of tables which should be not be cleared, before the records from the backup are inserted, i.e. the records in the backup will be added to the records in the table. Schema information about the tables is not cleared or read from backup. {recreate_tables, TabList} Where TabList is a list of tables which should be re-created, before the records from the backup are inserted. The tables are first deleted and then created with the schema information from the backup. All the nodes in the backup needs to be up and running. {default_op, Operation} Where Operation is one of the following operations skip_tables, clear_tables, keep_tables or recreate_tables. The default operation specifies which operation should be used on tables from the backup which are not specified in any of the lists above. If omitted, the operation clear_tables will be used.

The affected tables are write locked during the restoration, but 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 may not be possible to restore it online. In such cases, the old database must be restored by installing a fallback and then restart.

s_delete({Tab, Key}) -> ok | transaction abort Set sticky lock and delete records.

Invokes mnesia:delete(Tab, Key, sticky_write)

s_delete_object(Record) -> ok | transaction abort Set sticky lock and delete record.

Invokes mnesia:delete_object(Tab, Record, sticky_write) where Tab is element(1, Record).

s_write(Record) -> ok | transaction abort Write Recordand sets stick lock.

Invokes mnesia:write(Tab, Record, sticky_write) where Tab is element(1, Record).

schema() -> ok Print information about all table definitions on the tty.

Prints information about all table definitions on the tty.

schema(Tab) -> ok Print information about one table definition on the tty.

Prints information about one table definition on the tty.

select(Tab, MatchSpec [, Lock]) -> transaction abort | [Object] Match the objects in Tabagainst MatchSpec.

Matches the objects in the table Tab using a match_spec as described in the ERTS Users Guide. Optionally a lock read or write can be given as the third argument, default is read. The return value depends on the MatchSpec.

Note: for best performance select should be used before any modifying operations are done on that table in the same transaction, i.e. don't use write or delete before a select.

In its simplest forms the match_spec's look like this:

MatchSpec = [MatchFunction] MatchFunction = {MatchHead, [Guard], [Result]} MatchHead = tuple() | record() Guard = {"Guardtest name", ...} Result = "Term construct"

See the ERTS Users Guide and ets documentation for a complete description of the select.

For example to find the names of all male persons with an age over 30 in table Tab do:

MatchHead = #person{name='$1', sex=male, age='$2', _='_'}, Guard = {'>', '$2', 30}, Result = '$1', mnesia:select(Tab,[{MatchHead, [Guard], [Result]}]),
select(Tab, MatchSpec, NObjects, Lock) -> transaction abort | {[Object],Cont} | '$end_of_table' Match the objects in Tabagainst MatchSpec.

Matches the objects in the table Tab using a match_spec as described in ERTS users guide, and returns a chunk of terms and a continuation, the wanted number of returned terms is specified by the NObjects argument. The lock argument can be read or write. The continuation should be used as argument to mnesia:select/1, if more or all answers are needed.

Note: for best performance select should be used before any modifying operations are done on that table in the same transaction, i.e. don't use mnesia:write or mnesia:delete before a mnesia:select. For efficiency the NObjects is a recommendation only and the result may contain anything from an empty list to all available results.

select(Cont) -> transaction abort | {[Object],Cont} | '$end_of_table' Continues selecting objects.

Selects more objects with the match specification initiated by mnesia:select/4.

Note: Any modifying operations, i.e. mnesia:write or mnesia:delete, that are done between the mnesia:select/4 and mnesia:select/1 calls will not be visible in the result.

set_debug_level(Level) -> OldLevel Change the internal debug level of Mnesia

Changes the internal debug level of Mnesia. See the chapter about configuration parameters for details.

set_master_nodes(MasterNodes) -> ok | {error, Reason} Set the master nodes for all tables

For each table Mnesia will determine its replica nodes (TabNodes) and invoke mnesia:set_master_nodes(Tab, TabMasterNodes) where TabMasterNodes is the intersection of MasterNodes and TabNodes. See mnesia:set_master_nodes/2 about the semantics.

set_master_nodes(Tab, MasterNodes) -> ok | {error, Reason} Set the master nodes for a table

If the application detects that there has been a communication failure (in a potentially partitioned network) which may have caused an inconsistent database, it may use the function mnesia:set_master_nodes(Tab, MasterNodes) to define from which nodes each table will be loaded. At startup Mnesia's normal table load algorithm will be bypassed and the table will be loaded from one of the master nodes defined for the table, regardless of when and if Mnesia was terminated on other nodes. The MasterNodes may only contain nodes where the table has a replica and if the MasterNodes list is empty, the master node recovery mechanism for the particular table will be reset and the normal load mechanism will be used at next restart.

The master node setting is always local and it may be changed regardless of whether Mnesia is started or not.

The database may also become inconsistent if the max_wait_for_decision configuration parameter is used or if mnesia:force_load_table/1 is used.

snmp_close_table(Tab) -> {aborted, R} | {atomic, ok} Remove the possibility for SNMP to manipulate the table.

Removes the possibility for SNMP to manipulate the table.

snmp_get_mnesia_key(Tab, RowIndex) -> {ok, Key} | undefined Get the corresponding Mnesia key from an SNMP index. Tab ::= atom() RowIndex ::= [integer()] Key ::= key() | {key(), key(), ...} key() ::= integer() | string() | [integer()]

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.

snmp_get_next_index(Tab, RowIndex) -> {ok, NextIndex} | endOfTable Get the index of the next lexicographical row. Tab ::= atom() RowIndex ::= [integer()] NextIndex ::= [integer()]

The RowIndex may specify a non-existing row. Specifically, it might be the empty list. Returns the index of the next lexicographical row. If RowIndex is the empty list, this function will return the index of the first row in the table.

snmp_get_row(Tab, RowIndex) -> {ok, Row} | undefined Retrieve a row indexed by an SNMP index. Tab ::= atom() RowIndex ::= [integer()] Row ::= record(Tab)

Makes it possible to read a row by its SNMP index. This index is specified as an SNMP OBJECT IDENTIFIER, a list of integers.

snmp_open_table(Tab, SnmpStruct) -> {aborted, R} | {atomic, ok} Organize a Mnesia table as an SNMP table. Tab ::= atom() SnmpStruct ::= [{key, type()}] type() ::= type_spec() | {type_spec(), type_spec(), ...} type_spec() ::= fix_string | string | integer

It is possible to establish a direct one to one mapping 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.

The SnmpStruct argument is a list of SNMP information. Currently, the only information needed is information about the key types in the table. It is not possible to handle multiple keys in Mnesia, but many SNMP tables have multiple keys. Therefore, the following convention is used: if a table has multiple keys, these must always be stored as a tuple of the keys. Information about the key types is specified as a tuple of atoms describing the types. The only significant type is fix_string. This means that a string has fixed size. For example:

mnesia:snmp_open_table(person, [{key, string}])

causes the person table to be ordered as an SNMP table.

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; department, name and telno.

It is possible 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 department and name only. The application could then use the telno column internally, but it would not be visible to the SNMP managers.

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). And more memory is used.

Note:Only the lexicographical SNMP ordering is implemented in Mnesia, not the actual SNMP monitoring.

start() -> ok | {error, Reason} Start a local Mnesia system.

The start-up 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 will be referred to as the Mnesia directory. Mnesia may also be started on disc-less nodes. See mnesia:create_schema/1 and the Mnesia User's Guide for more information about disc-less nodes.

The set of nodes which makes up a Mnesia system is kept in a schema and it is possible to add and remove Mnesia nodes from the schema. The initial schema is normally created on disc with the function mnesia:create_schema/1. On disc-less nodes, a tiny default schema is generated each time Mnesia is started. During the start-up procedure, Mnesia will exchange schema information between the nodes in order to verify that the table definitions are compatible.

Each schema has a unique cookie which may be regarded as a unique schema identifier. The cookie must be the same on all nodes where Mnesia is supposed to run. See the Mnesia User's Guide for more information about these details.

The schema file, as well as all other files which Mnesia needs, are kept in the Mnesia directory. The command line option -mnesia dir Dir can be used to specify the location of this directory to the Mnesia system. If no such command line option is found, the name of the directory defaults to Mnesia.Node.

application:start(mnesia) may also be used.

stop() -> stopped Stop Mnesia locally.

Stops Mnesia locally on the current node.

application:stop(mnesia) may also be used.

subscribe(EventCategory) Subscribe to events of type EventCategory.

Ensures that a copy of all events of type EventCategory are sent to the caller. The event types available are described in the Mnesia User's Guide.

sync_dirty(Fun, [, Args]) -> ResultOfFun | exit(Reason) Call the Fun in a context which is not protected by a transaction.

Call the Fun in a context which is not protected by a transaction. The Mnesia function calls performed in the Fun are mapped to the corresponding dirty functions. It is performed in almost the same context as mnesia:async_dirty/1,2. The difference is that the operations are performed synchronously. The caller waits for the updates to be performed on all active replicas before the Fun returns. See mnesia:activity/4 and the Mnesia User's Guide for more details.

sync_log() -> ok | {error, Reason} Perform a file sync of the local log file.

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 in case of a power outage. See dump_log/0.

sync_transaction(Fun, [[, Args], Retries]) -> {aborted, Reason} | {atomic, ResultOfFun} Synchronously execute a transaction.

This function 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 mnesia:transaction/[1,2,3].

This functionality can be used to avoid that one process may overload a database on another node.

system_info(InfoKey) -> Info | exit({aborted, Reason}) Return information about the Mnesia system

Returns information about the Mnesia system, such as transaction statistics, db_nodes, and configuration parameters. Valid keys are:

all. This argument returns a list of all local system information. Each element is a {InfoKey, InfoVal} tuples.Note: New InfoKey's may be added and old undocumented InfoKey's may be removed without notice.

access_module. This argument returns the name of the module which is configured to be the activity access callback module.

auto_repair. This argument returns true or false to indicate if Mnesia is configured to invoke the auto repair facility on corrupted disc files.

backup_module. This argument returns the name of the module which is configured to be the backup callback module.

checkpoints. This argument returns a list of the names of the checkpoints currently active on this node.

event_module. This argument returns the name of the module which is the event handler callback module.

db_nodes. This argument returns the nodes which make up the persistent database. Disc less nodes will only be included in the list of nodes if they explicitly has been added to the schema, e.g. with mnesia:add_table_copy/3. The function can be invoked even if Mnesia is not yet running.

debug. This argument returns the current debug level of Mnesia.

directory. This argument returns the name of the Mnesia directory. It can be invoked even if Mnesia is not yet running.

dump_log_load_regulation. This argument returns a boolean which tells whether Mnesia is configured to load regulate the dumper process or not. This feature is temporary and will disappear in future releases.

dump_log_time_threshold. This argument returns the time threshold for transaction log dumps in milliseconds.

dump_log_update_in_place. This argument returns a boolean which tells whether Mnesia is configured to perform the updates in the dets files directly or if the updates should be performed in a copy of the dets files.

dump_log_write_threshold. This argument returns the write threshold for transaction log dumps as the number of writes to the transaction log.

extra_db_nodes. This argument returns a list of extra db_nodes to be contacted at start-up.

fallback_activated. This argument returns true if a fallback is activated, otherwise false.

held_locks. This argument returns a list of all locks held by the local Mnesia lock manager.

is_running. This argument returns yes or no to indicate if Mnesia is running. It may also return starting or stopping. Can be invoked even if Mnesia is not yet running.

local_tables. This argument returns a list of all tables which are configured to reside locally.

lock_queue. This argument returns a list of all transactions that are queued for execution by the local lock manager.

log_version. This argument returns the version number of the Mnesia transaction log format.

master_node_tables. This argument returns a list of all tables with at least one master node.

protocol_version. This argument returns the version number of the Mnesia inter-process communication protocol.

running_db_nodes. This argument returns a list of nodes where Mnesia currently is running. This function can be invoked even if Mnesia is not yet running, but it will then have slightly different semantics. If Mnesia is down on the local node, the function will return those other db_nodes and extra_db_nodes that for the moment are up and running. If Mnesia is started, the function will return 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 running_db_nodes. After the merge of schemas, the local Mnesia system is fully operable and applications may perform access of remote replicas. Before the schema merge Mnesia will only operate locally. Sometimes there may be more nodes included in the running_db_nodes list than all db_nodes and extra_db_nodes together.

schema_location. This argument returns the initial schema location.

subscribers. This argument returns a list of local processes currently subscribing to system events.

tables. This argument returns a list of all locally known tables.

transactions. This argument returns a list of all currently active local transactions.

transaction_failures. This argument returns a number which indicates how many transactions have failed since Mnesia was started.

transaction_commits. This argument returns a number which indicates how many transactions have terminated successfully since Mnesia was started.

transaction_restarts. This argument returns a number which indicates how many transactions have been restarted since Mnesia was started.

transaction_log_writes. This argument returns a number which indicates the number of write operation that have been performed to the transaction log since start-up.

use_dir. This argument returns a boolean which indicates whether the Mnesia directory is used or not. Can be invoked even if Mnesia is not yet running.

version. This argument returns the current version number of Mnesia.

table(Tab [,[Option]]) -> QueryHandle Return a QLC query handle.

Returns a QLC (Query List Comprehension) query handle, see qlc(3).The module qlc implements a query language, it can use mnesia tables as sources of data. Calling mnesia:table/1,2 is the means to make the mnesia table Tab usable to QLC.

The list of Options may contain mnesia options or QLC options, the following options are recognized by Mnesia: {traverse, SelectMethod},{lock, Lock},{n_objects,Number}, any other option is forwarded to QLC. The lock option may be read or write, default is read. The option n_objects specifies (roughly) the number of objects returned from mnesia to QLC. Queries to remote tables may need a larger chunks to reduce network overhead, default 100 objects at a time are returned. The option traverse determines the method to traverse the whole table (if needed), the default method is select:

select. The table is traversed by calling mnesia:select/4 and mnesia:select/1. The match specification (the second argument of select/3) is assembled by QLC: simple filters are translated into equivalent match specifications while more complicated filters have to be applied to all objects returned by select/3 given a match specification that matches all objects.

{select, MatchSpec}. As for select the table is traversed by calling mnesia:select/3 and mnesia:select/1. The difference is that the match specification is explicitly given. This is how to state match specifications that cannot easily be expressed within the syntax provided by QLC.

table_info(Tab, InfoKey) -> Info | exit({aborted, Reason}) Return local information about table.

The table_info/2 function takes two arguments. The first is the name of a Mnesia table, the second is one of the following keys:

all. This argument returns a list of all local table information. Each element is a {InfoKey, ItemVal} tuples. Note: New InfoItem's may be added and old undocumented InfoItem's may be removed without notice.

access_mode. This argument returns the access mode of the table. The access mode may either be read_only or read_write.

arity. This argument returns the arity of records in the table as specified in the schema.

attributes. This argument returns the table attribute names which are specified in the schema.

checkpoints. This argument returns the names of the currently active checkpoints which involves this table on this node.

cookie. This argument returns a table cookie which is a unique system generated identifier for the table. The cookie is used internally to ensure that two different table definitions using the same table name cannot accidentally be intermixed. The cookie is generated when the table is initially created.

disc_copies. This argument returns the nodes where a disc_copy of the table resides according to the schema.

disc_only_copies . This argument returns the nodes where a disc_only_copy of the table resides according to the schema.

index. This argument returns the list of index position integers for the table.

load_node. This argument returns the name of the node that Mnesia loaded the table from. The structure of the returned value is unspecified but may be useful for debugging purposes.

load_order. This argument returns the load order priority of the table. It is an integer and defaults to 0 (zero).

load_reason. This argument returns the reason of why Mnesia decided to load the table. The structure of the returned value is unspecified but may be useful for debugging purposes.

local_content. This argument returns true or false to indicate whether the table is configured to have locally unique content on each node.

master_nodes. This argument returns the master nodes of a table.

memory. This argument returns the number of words allocated to the table on this node.

ram_copies. This argument returns the nodes where a ram_copy of the table resides according to the schema.

record_name. This argument returns the record name, common for all records in the table

size. This argument returns the number of records inserted in the table.

snmp. This argument returns the SNMP struct. []meaning that the table currently has no SNMP properties.

storage_type.This argument returns the local storage type of the table. It can be disc_copies, ram_copies, disc_only_copies, or the atom unknown. unknown is returned for all tables which only reside remotely.

subscribers. This argument returns a list of local processes currently subscribing to local table events which involve this table on this node.

type. This argument returns the table type, which is either bag, set or ordered_set..

user_properties. This argument returns the user associated table properties of the table. It is a list of the stored property records.

version. This argument returns the current version of the table definition. The table version is incremented when the table definition is changed. The table definition may be incremented directly when the table definition has been changed in a schema transaction, or when a committed table definition is merged with table definitions from other nodes during start-up.

where_to_read.This argument returns the node where the table can be read. If the value nowhere is returned, the table is not loaded, or it resides at a remote node which is not running.

where_to_write. This argument returns a list of the nodes that currently hold an active replica of the table.

wild_pattern. This argument returns a structure which can be given to the various match functions for a certain table. A record tuple is where all record fields have the value '_'.

transaction(Fun [[, Args], Retries]) -> {aborted, Reason} | {atomic, ResultOfFun} Execute a transaction.

This function executes the functional object Fun with arguments Args as a transaction.

The code which 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 aborted and the function transaction/1 returns the tuple {aborted, Reason}.

If all is well, {atomic, ResultOfFun} is returned where ResultOfFun is the value of the last expression in Fun.

A function which adds a family to the database can be written as follows if we have a structure {family, Father, Mother, ChildrenList}:

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 will ensure that either the whole family is added to the database, or the whole transaction aborts. For example, if the last child is badly formatted, or the executing process terminates due to an 'EXIT' signal while executing the family code, the transaction aborts. Accordingly, the situation where half a family is added can never occur.

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), which adds Amount to the salary field of a person, should be implemented as follows:

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 raise/2 function without interfering with each other.

Since Mnesia detects deadlocks, a transaction can be restarted any number of times. This function will attempt a restart as specified in Retries. Retries must be an integer greater than 0 or the atom infinity. Default is infinity.

transform_table(Tab, Fun, NewAttributeList, NewRecordName) -> {aborted, R} | {atomic, ok} Change format on all records in table. Tab

This function applies the argument Fun to all records in the table. Fun is a function which takes a record of the old type and returns a transformed record of the new type. The Fun argument can also be the atom ignore, it indicates that only the meta data about the table will be updated. Usage of ignore is not recommended but included as a possibility for the user do to his own transform. NewAttributeList and NewRecordName specifies the attributes and the new record type of converted table. Table name will always remain unchanged, if the record_name is changed only the mnesia functions which uses table identifiers will work, e.g. mnesia:write/3 will work but mnesia:write/1 will not.

transform_table(Tab, Fun, NewAttributeList) -> {aborted, R} | {atomic, ok} Change format on all records in table. Tab

Invokes mnesia:transform_table(Tab, Fun, NewAttributeList, RecName) where RecName is mnesia:table_info(Tab, record_name).

traverse_backup(Source, [SourceMod,] Target, [TargetMod,] Fun, Acc) -> {ok, LastAcc} | {error, Reason} Traversal of a backup.

With this function it is possible to iterate over a backup, either for the purpose of transforming it into a new backup, or just reading it. The arguments are explained briefly below. See the Mnesia User's Guide for additional details.

SourceMod and TargetMod are the names of the modules which actually access the backup media. Source and Target are opaque data used exclusively by the modules SourceMod and TargetMod for the purpose of initializing the backup media. Acc is an initial accumulator value. Fun(BackupItems, Acc) is applied to each item in the backup. The Fun must return a tuple {BackupItems,NewAcc}, where BackupItems is a list of valid backup items, and NewAcc is a new accumulator value. The returned backup items are written in the target backup. LastAcc is the last accumulator value. This is the last NewAcc value that was returned by Fun.
uninstall_fallback() -> ok | {error,Reason} Uninstall a fallback.

Invokes mnesia:uninstall_fallback([{scope, global}]).

uninstall_fallback(Args) -> ok | {error,Reason} Uninstall a fallback.

This function is used to de-install 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 up and running 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 info in the local fallback.

Args is a list of the following tuples:

{module, BackupMod}. See mnesia:install_fallback/2 about the semantics.

{scope, Scope} See mnesia:install_fallback/2 about the semantics.

{mnesia_dir, AlternateDir} See mnesia:install_fallback/2 about the semantics.

unsubscribe(EventCategory) Subscribe to events of type EventCategory.

Stops sending events of type EventCategory to the caller.

wait_for_tables(TabList,Timeout) -> ok | {timeout, BadTabList} | {error, Reason} Wait for tables to be accessible.

Some applications need to wait for certain tables to be accessible in order to do useful work. mnesia:wait_for_tables/2 hangs until all tables in the TabList are accessible, or until timeout is reached.

wread({Tab, Key}) -> transaction abort | RecordList Read records with given key.

Invoke mnesia:read(Tab, Key, write).

write(Record) -> transaction abort | ok Writes a record into the database.

Invoke mnesia:write(Tab, Record, write) where Tab is element(1, Record).

write(Tab, Record, LockKind) -> transaction abort | ok Write a record into the database.

Writes the record Record to the table Tab.

The function returns ok, or aborts if an error occurs. For example, the transaction aborts if no person table exists.

The semantics of this function is context sensitive. See mnesia:activity/4 for more information. In transaction context it acquires a lock of type LockKind. The following lock types are supported: write and sticky_write.

write_lock_table(Tab) -> ok | transaction abort Set write lock on an entire table.

Invokes mnesia:lock({table, Tab}, write).

Configuration Parameters

Mnesia reads the following application configuration parameters:

-mnesia access_module Module. The name of the Mnesia activity access callback module. The default is mnesia.

-mnesia auto_repair true | false. This flag controls whether Mnesia will try to automatically repair files that have not been properly closed. The default is true.

-mnesia backup_module Module. The name of the Mnesia backup callback module. The default is mnesia_backup.

-mnesia debug Level Controls the debug level of Mnesia. Possible values are:

none

No trace outputs at all. This is the default setting.

verbose

Activates tracing of important debug events. These debug events generate {mnesia_info, Format, Args} system events. Processes may subscribe to these events with mnesia:subscribe/1. The events are always sent to Mnesia's event handler.

debug

Activates all events at the verbose level plus full trace of all debug events. These debug events generate {mnesia_info, Format, Args} system events. Processes may subscribe to these events with mnesia:subscribe/1. The events are always sent to the Mnesia event handler. On this debug level, the Mnesia event handler starts subscribing to updates in the schema table.

trace

Activates all events at the level debug. On this debug level, the Mnesia event handler starts subscribing to updates on all Mnesia tables. This level is only intended for debugging small toy systems since many large events may be generated.

false

An alias for none.

true

An alias for debug.

-mnesia core_dir Directory. The name of the directory where Mnesia core files is stored or false. Setting it implies that also ram only nodes, will generate a core file if a crash occurs.

-mnesia dc_dump_limit Number. Controls how often disc_copies tables are dumped from memory. Tables are dumped when filesize(Log) > (filesize(Tab)/Dc_dump_limit). Lower values reduces cpu overhead but increases disk space and startup times. The default is 4.

-mnesia dir Directory. The name of the directory where all Mnesia data is stored. The name of the directory must be unique for the current node. Two nodes may, under no circumstances, share the same Mnesia directory. The results are totally unpredictable.

-mnesia dump_log_load_regulation true | false. Controls if the log dumps should be performed as fast as possible or if the dumper should do its own load regulation. This feature is temporary and will disappear in a future release. The default is false.

-mnesia dump_log_update_in_place true | false. Controls if log dumps are performed on a copy of the original data file, or if the log dump is performed on the original data file. The default is true

-mnesia dump_log_write_threshold Max, where Max is an integer which specifies the maximum number of writes allowed to the transaction log before a new dump of the log is performed. It defaults to 100 log writes.

-mnesia dump_log_time_threshold Max, where Max is an integer which specifies the dump log interval in milliseconds. It defaults to 3 minutes. If a dump has not been performed within dump_log_time_threshold milliseconds, then a new dump is performed regardless of how many writes have been performed.

-mnesia event_module Module. The name of the Mnesia event handler callback module. The default is mnesia_event.

-mnesia extra_db_nodes Nodes specifies a list of nodes, in addition to the ones found in the schema, with which Mnesia should also establish contact. The default value is the empty list [].

-mnesia fallback_error_function {UserModule, UserFunc} specifies a user supplied callback function which will be called if a fallback is installed and mnesia goes down on another node. Mnesia will call the function with one argument the name of the dying node, e.g. UserModule:UserFunc(DyingNode). Mnesia should be restarted or else the database could be inconsistent. The default behaviour is to terminate mnesia.

-mnesia max_wait_for_decision Timeout. Specifies how long Mnesia will wait for other nodes to share their knowledge regarding the outcome of an unclear transaction. By default the Timeout is set to the atom infinity, which implies that if Mnesia upon startup encounters a "heavyweight transaction" whose outcome is unclear, the local Mnesia will wait until Mnesia is started on some (in worst cases all) of the other nodes that were involved in the interrupted transaction. This is a very rare situation, but when/if it happens, Mnesia does not guess if the transaction on the other nodes was committed or aborted. Mnesia will wait until it knows the outcome and then act accordingly.

If Timeout is set to an integer value in milliseconds, Mnesia will force "heavyweight transactions" to be finished, even if the outcome of the transaction for the moment is unclear. After Timeout milliseconds, Mnesia will commit/abort the transaction and continue with the startup. This may lead to a situation where the transaction is committed on some nodes and aborted on other nodes. If the transaction was a schema transaction, the inconsistency may be fatal.

-mnesia no_table_loaders NUMBER specifies the number of parallel table loaders during start. More loaders can be good if the network latency is high or if many tables contains few records. The default value is 2.

-mnesia send_compressed Level specifies the level of compression to be used when copying a table from the local node to another one. The default level is 0.

Level must be an integer in the interval [0, 9], with 0 representing no compression and 9 representing maximum compression. Before setting it to a non-zero value, make sure the remote nodes understand this configuration.

-mnesia schema_location Loc controls where Mnesia will look for its schema. The parameter Loc may be one of the following atoms:

disc

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.

ram

Mandatory RAM. The schema resides in RAM only. At start-up, a tiny new schema is generated. This default schema just contains the definition of the schema table and only resides on the local node. Since no other nodes are found in the default schema, the configuration parameter extra_db_nodes must be used in order to let the node share its table definitions with other nodes. (The extra_db_nodes parameter may also be used on disc based nodes.)

opt_disc

Optional disc. The schema may reside either 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 disc_copies. If no schema is found on disc, Mnesia starts as a disc-less node and the storage type of the schema table is ram_copies. The default value for the application parameter is opt_disc.

First the SASL application parameters are checked, then the command line flags are checked, and finally, the default value is chosen.

See Also

mnesia_registry(3), mnesia_session(3), qlc(3), dets(3), ets(3), disk_log(3), application(3)