[Ericsson AB]

mnesia

MODULE

mnesia

MODULE SUMMARY

A Distributed Telecommunications DBMS

DESCRIPTION

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:

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 Mnemosyne User's Guide.

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:

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.

EXPORTS

abort(Reason) -> transaction abort

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}

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:

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)

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)

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:

to the corresponding:

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}

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}

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

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. 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}

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}

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}

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 which Mnesia was able to connect 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.

change_table_access_mode(Tab, AccessMode) -> {aborted, R} | {atomic, ok}

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}

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}

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.

clear_table(Tab) -> {aborted, R} | {atomic, ok}

Deletes all entries in the table Tab.

create_schema(DiscNodes) -> ok | {error,Reason}

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}

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:

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}

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}

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}

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

delete({Tab, Key}) -> transaction abort | ok

Invokes mnesia:delete(Tab, Key, write)

delete(Tab, Key, LockKind) -> transaction abort | ok

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

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

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

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}

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.

Warning!

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}

Permanently deletes all replicas of table Tab.

dirty_all_keys(Tab) -> KeyList | exit({aborted, Reason}).

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

dirty_delete({Tab, Key}) -> ok | exit({aborted, Reason})

Invokes mnesia:dirty_delete(Tab, Key).

dirty_delete(Tab, Key) -> ok | exit({aborted, Reason})

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

dirty_delete_object(Record)

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

dirty_delete_object(Tab, Record)

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

dirty_first(Tab) -> Key | exit({aborted, Reason})

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)

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

dirty_index_match_object(Tab, Pattern, Pos)

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

dirty_index_read(Tab, SecondaryKey, Pos)

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

dirty_last(Tab) -> Key | exit({aborted, Reason})

This function works exactly 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}).

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

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

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

dirty_next(Tab, Key) -> Key | exit({aborted, Reason})

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})

This function works exactly 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}

Invokes mnesia:dirty_read(Tab, Key).

dirty_read(Tab, Key) -> ValueList | exit({aborted, Reason}

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

dirty_select(Tab, MatchSpec) -> ValueList | exit({aborted, Reason}

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

dirty_slot(Tab, Slot) -> RecordList | exit({aborted, Reason})

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})

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

dirty_update_counter(Tab, Key, Incr) -> NewVal | exit({aborted, Reason})

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:

If two processes perform mnesia:dirty_update_counter/3 simultaneously, both updates will take effect without the risk of loosing 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})

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

dirty_write(Tab, Record) -> ok | exit({aborted, Reason})

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

dump_log() -> dumped

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

dump_tables(TabList) -> {atomic, ok} | {aborted, Reason}

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)

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

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.

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

foldl(Function, Acc, Table) -> NewAcc | transaction abort

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

This function works exactly as 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

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

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

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 two index search functions described here are automatically invoked when searching tables with Mnemosyne list comprehensions and also when using the low level mnesia:[dirty_]match_object functions.

Note: Mnemosyne has a "search" advantage as it uses some clever heuristics 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 on a single record. Currently, the lock type read is supported.

index_read(Tab, SecondaryKey, Pos) -> transaction abort | RecordList

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

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}

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

install_fallback(Opaque), BackupMod) -> ok | {error,Reason}

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

install_fallback(Opaque, Args) -> ok | {error,Reason}

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:

load_textfile(Filename)

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) -> GoodNodes | transaction abort

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.

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:

stick_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

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

match_object(Tab, Pattern, LockKind) ->transaction abort | RecList

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. Use Mnemosyne if this is an issue.

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}

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.

read({Tab, Key}) -> transaction abort | RecordList

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

read(Tab, Key, LockKind) -> transaction abort | RecordList

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.

read_lock_table(Tab) -> ok | transaction abort

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

report_event(Event) -> ok

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}

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:

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

Invokes mnesia:delete(Tab, Key, sticky_write)

s_delete_object(Record) -> ok | transaction abort

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

s_write(Record) -> ok | transaction abort

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

schema() -> ok

Prints information about all table definitions on the tty.

schema(Tab) -> ok

Prints information about one table definition on the tty.

select(Tab, MatchSpec [, Lock]) -> transaction abort | [Object]

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:

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'

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'

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

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

set_master_nodes(MasterNodes) -> ok | {error, Reason}

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}

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}

Removes the possibility for SNMP to manipulate the table.

snmp_get_mnesia_key(Tab, RowIndex) -> {ok, Key} | undefined

Types:

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

Types:

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

Types:

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}

Types:

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}

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

Stops Mnesia locally on the current node.

application:stop(mnesia) may also be used.

subscribe(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. 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_transaction(Fun, [[, Args], Retries]) -> {aborted, Reason} | {atomic, ResultOfFun}

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})

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

table(Tab [,[Option]]) -> QueryHandle

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:

table_info(Tab, InfoKey) -> Info | exit({aborted, Reason})

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:

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

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}

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}

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}

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.

uninstall_fallback() -> ok | {error,Reason}

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

uninstall_fallback(Args) -> ok | {error,Reason}

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:

unsubscribe(EventCategory)

Stops sending events of type EventCategory to the caller.

wait_for_tables(TabList,Timeout) -> ok | {timeout, BadTabList} | {error, Reason}

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

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

write(Record) -> transaction abort | ok

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

write(Tab, Record, LockKind) -> transaction abort | ok

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

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

Configuration Parameters

Mnesia reads the following application configuration parameters:

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), mnemosyne(3), qlc(3), dets(3), ets(3), disk_log(3), application(3)

AUTHORS

Claes Wikström - support@erlang.ericsson.se
Hans Nilsson - support@erlang.ericsson.se
Håkan Mattsson - support@erlang.ericsson.se

mnesia 4.3.2
Copyright © 1991-2006 Ericsson AB