mnesia(3erl) | Erlang Module Definition | mnesia(3erl) |
mnesia - A distributed telecommunications DBMS
The following are some of the most important and attractive capabilities provided by Mnesia:
This Reference Manual describes the Mnesia API. This includes functions that define and manipulate Mnesia tables.
All functions in this Reference Manual can be used in any combination with queries using the list comprehension notation. For information about the query notation, see the qlc manual page in STDLIB.
Data in Mnesia is organized as a set of tables. Each table has a name that must be an atom. Each table is made up of Erlang records. The user is responsible for the record definitions. Each table also has a set of properties. The following are some of the properties that are associated with each table:
If a table is of type set, 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. However, if a table is of type bag, each key can map to several records. All records in type bag tables are unique, only the keys can be duplicated.
For information about the complete set of table properties and their details, see mnesia:create_table/2.
This Reference Manual uses a table of persons to illustrate various examples. The following record definition is assumed:
-record(person, {name,
age = 0,
address = unknown,
salary = 0,
children = []}),
The first record attribute is the primary key, or key for short.
The function descriptions are sorted in alphabetical order. It is recommended to start to read about mnesia:create_table/2, mnesia:lock/2, and mnesia:activity/4 before you continue and learn about the rest.
Writing or deleting in transaction-context creates a local copy of each modified record during the transaction. During iteration, that is, mnesia:fold[lr]/4, mnesia:next/2, mnesia:prev/2, and mnesia:snmp_get_next_index/2, Mnesia compensates for every written or deleted record, which can reduce the performance.
If possible, avoid writing or deleting records in the same transaction before iterating over the table.
table() = atom()
activity() =
ets | async_dirty | sync_dirty | transaction |
sync_transaction |
{transaction, Retries :: integer() >= 0} |
{sync_transaction, Retries :: integer() >= 0}
create_option() =
{access_mode, read_write | read_only} |
{attributes, [atom()]} |
{disc_copies, [node()]} |
{disc_only_copies, [node]} |
{index, [index_attr()]} |
{load_order, integer() >= 0} |
{majority, boolean()} |
{ram_copies, [node()]} |
{record_name, atom()} |
{snmp, SnmpStruct :: term()} |
{storage_properties,
[{Backend :: module(), [BackendProp :: term()]}]} |
{type, set | ordered_set | bag} |
{local_content, boolean()} |
{user_properties, proplists:proplist()}
storage_type() = ram_copies | disc_copies | disc_only_copies
t_result(Res) = {atomic, Res} | {aborted, Reason :: term()}
result() = ok | {error, Reason :: term()}
index_attr() = atom() | integer() >= 0 | {atom()}
write_locks() = write | sticky_write
read_locks() = read
lock_kind() = write_locks() | read_locks()
select_continuation() = term()
snmp_struct() = [{atom(), snmp_type() | tuple_of(snmp_type())}]
snmp_type() = fix_string | string | integer
tuple_of(_T) = tuple()
config_key() = extra_db_nodes | dc_dump_limit
config_value() = [node()] | number()
config_result() = {ok, config_value()} | {error, term()}
debug_level() = none | verbose | debug | trace
abort(Reason :: term()) -> no_return()
Makes the transaction silently return the tuple {aborted, Reason}. Termination of a Mnesia transaction means that an exception is thrown to an enclosing catch. Thus, the expression catch mnesia:abort(x) does not terminate the transaction.
activate_checkpoint(Args :: [Arg]) ->
{ok, Name, [node()]} |
{error, Reason :: term()}
Types:
A checkpoint is a consistent view of the system. A checkpoint can be activated on a set of tables. This checkpoint can then be traversed and presents a view of the system as it existed at the time when the checkpoint was activated, even if the tables are being or have been manipulated.
Args is a list of the following tuples:
Returns {ok,Name,Nodes} or {error,Reason}. Name is the (possibly generated) checkpoint name. Nodes are the nodes that are involved in the checkpoint. Only nodes that keep a checkpoint retainer know about the checkpoint.
activity(Kind, Fun) -> t_result(Res) | Res
Types:
Calls mnesia:activity(AccessContext, Fun, Args, AccessMod), where AccessMod is the default access callback module obtained by mnesia:system_info(access_module). Args defaults to [] (empty list).
activity(Kind, Fun, Args :: [Arg :: term()], Mod) ->
t_result(Res) | Res
Types:
Executes the functional object Fun with argument Args.
The code that executes inside the activity can consist of a series of table manipulation functions, which are performed in an AccessContext. Currently, the following access contexts are supported:
This function (mnesia:activity/4) differs in an important way from the functions mnesia:transaction, mnesia:sync_transaction, mnesia:async_dirty, mnesia:sync_dirty, and mnesia:ets. Argument AccessMod is the name of a callback module, which implements the mnesia_access behavior.
Mnesia forwards calls to the following functions:
to the corresponding:
ActivityId is a record that represents the identity of the enclosing Mnesia activity. The first field (obtained with element(1, ActivityId)) contains an atom, which can be interpreted as the activity type: 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 that is internal to Mnesia.
add_table_copy(Tab, N, ST) -> t_result(ok)
Types:
Makes another copy of a table at the node Node. Argument Type 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, I) -> t_result(ok)
Types:
Table indexes can be used whenever the user wants to use frequently some other field than the key field to look up records. If this other field has an associated index, these lookups can occur in constant time and space. For example, if your application wishes to use field age to find efficiently all persons with a specific age, it can be a good idea to have an index on field age. This can be done with the following call:
mnesia:add_table_index(person, age)
Indexes do not come for free. They occupy space that is proportional to the table size, and they cause insertions into the table to execute slightly slower.
all_keys(Tab :: table()) -> [Key :: term()]
Returns a list of all keys in the table named Tab. The semantics of this function is context-sensitive. For more information, see mnesia:activity/4. In transaction-context, it acquires a read lock on the entire table.
async_dirty(Fun) -> Res | no_return()
async_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()
Types:
Calls the Fun in a context that 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 indexes are updated, but they are updated dirty. As for normal mnesia:dirty_* operations, the operations are performed semi-asynchronously. For details, see mnesia:activity/4 and the User's Guide.
The Mnesia tables can be manipulated without using transactions. This has some serious disadvantages, but is considerably faster, as the transaction manager is not involved and no locks are set. A dirty operation does, however, guarantee a certain level of consistency, and the dirty operations cannot return garbled records. All dirty operations provide location transparency to the programmer, and a program does not have to be aware of the whereabouts of a certain table to function.
Notice that it is more than ten times more efficient to read records dirty than within a transaction.
Depending on the application, it can be a good idea to use the dirty functions for certain operations. Almost all Mnesia functions that can be called within transactions have a dirty equivalent, which is much more efficient.
However, notice that there is a risk that the database can be left in an inconsistent state if dirty operations are used to update it. Dirty operations are only to be used for performance reasons when it is absolutely necessary.
Notice that calling (nesting) mnesia:[a]sync_dirty inside a transaction-context inherits the transaction semantics.
backup(Dest :: term()) -> result()
backup(Dest :: term(), Mod :: module()) -> result()
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, Dest) -> result()
backup_checkpoint(Name, Dest, Mod) -> result()
Types:
The tables are backed up to external media using backup module BackupMod. Tables with the local contents property are backed up as they exist on the current node. BackupMod is the default backup callback module obtained by mnesia:system_info(backup_module). For information about the exact callback interface (the mnesia_backup behavior), see the User's Guide.
change_config(Config, Value) -> config_result()
Types:
Config is to be an atom of the following configuration parameters:
Notice that this function must only be used to connect to newly started RAM nodes (N.D.R.S.N.) with an empty schema. If, for example, this function is used after the network has been partitioned, it can lead to inconsistent tables.
Notice that Mnesia can be connected to other nodes than those returned in ReturnValue.
change_table_access_mode(Tab :: table(), Mode) -> t_result(ok)
Types:
AcccessMode is by default the atom read_write but it can also be set to the atom read_only. If AccessMode is set to read_only, updates to the table cannot be performed. At startup, Mnesia always loads read_only tables locally regardless of when and if Mnesia is terminated on other nodes.
change_table_copy_type(Tab :: table(),
Node :: node(),
To :: storage_type()) ->
t_result(ok)
For example:
mnesia:change_table_copy_type(person, node(), disc_copies)
Transforms the 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 :: table(), Order) -> t_result(ok)
Types:
The LoadOrder priority is by default 0 (zero) but can be set to any integer. The tables with the highest LoadOrder priority are loaded first at startup.
change_table_majority(Tab :: table(), M :: boolean()) ->
t_result(ok)
Majority must be a boolean. Default is false. When true, a majority of the table replicas must be available for an update to succeed. When used on fragmented tables, Tab must be the base table name. Directly changing the majority setting on individual fragments is not allowed.
clear_table(Tab :: table()) -> t_result(ok)
Deletes all entries in the table Tab.
create_schema(Ns :: [node()]) -> result()
Creates a new database on disc. Various files are created in the local Mnesia directory of each node. Notice that the directory must be unique for each node. Two nodes must never share the same directory. If possible, use a local disc device to improve performance.
mnesia:create_schema/1 fails if any of the Erlang nodes given as DiscNodes are not alive, if Mnesia is running on any of the nodes, or if any of the nodes already have a schema. Use mnesia:delete_schema/1 to get rid of old faulty schemas.
Notice that only nodes with disc are to be included in DiscNodes. Disc-less nodes, that is, nodes where all tables including the schema only resides in RAM, must not be included.
create_table(Name :: table(), Arg :: [create_option()]) ->
t_result(ok)
Creates a Mnesia table called Name according to argument TabDef. This list must be a list of {Item, Value} tuples, where the following values are allowed:
At startup, Mnesia always loads read_only table locally regardless of when and if Mnesia is terminated on other nodes. This argument returns the access mode of the table. The access mode can be read_only or read_write.
When accessing single attributes in a record, it is not necessary, or even recommended, to hard code any attribute names as atoms. Use construct record_info(fields, RecordName) instead. It can be used for records of type RecordName.
It is possible to have a replicated table of type disc_copies on one node and another type on another node. Default is [].
For example:
mnesia:create_table(table, [{ram_copies, [node()]}, {disc_only_copies, nodes()},
{storage_properties,
[{ets, [compressed]}, {dets, [{auto_save, 5000}]} ]}])
Notice that currently ordered_set is not supported for disc_only_copies.
For example, the following call creates the person table (defined earlier) and replicates it on two nodes:
mnesia:create_table(person,
[{ram_copies, [N1, N2]},
{attributes, record_info(fields, person)}]).
If it is required that Mnesia must build and maintain an extra index table on attribute address 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 can be hard-coded as {index, [2]} and {attributes, [name, age, address, salary, children]}, respectively.
mnesia:create_table/2 writes records into the table schema. This function, and 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 :: term()) -> result()
The checkpoint is automatically deactivated when some of the tables involved have no retainer attached to them. This can occur when nodes go down or when a replica is deleted. Checkpoints are also deactivated with this function. Name is the name of an active checkpoint.
del_table_copy(Tab :: table(), N :: node()) -> t_result(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 can also be used to delete a replica of the table named schema. The Mnesia node is then removed. Notice that Mnesia must be stopped on the node first.
del_table_index(Tab, I) -> t_result(ok)
Types:
Deletes the index on attribute with name AttrName in a table.
delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
Calls mnesia:delete(Tab, Key, write).
delete(Tab :: table(), Key :: term(), LockKind :: write_locks()) ->
ok
Deletes all records in table Tab with the key Key.
The semantics of this function is context-sensitive. For details, see mnesia:activity/4. 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(Rec :: tuple()) -> ok
Calls mnesia:delete_object(Tab, Record, write), where Tab is element(1, Record).
delete_object(Tab :: table(),
Rec :: tuple(),
LockKind :: write_locks()) ->
ok
If a table is of type bag, it can sometimes be needed to delete only some of the records with a certain key. This can be done with the function delete_object/3. A complete record must be supplied to this function.
The semantics of this function is context-sensitive. For details, see mnesia:activity/4. 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(Ns :: [node()]) -> result()
Deletes a database created with mnesia:create_schema/1. mnesia:delete_schema/1 fails if any of the Erlang nodes given as DiscNodes are not alive, or if Mnesia is running on any of the nodes.
After the database is deleted, it can still be possible to start Mnesia as a disc-less node. This depends on how configuration parameter schema_location is set.
delete_table(Tab :: table()) -> t_result(ok)
Permanently deletes all replicas of table Tab.
dirty_all_keys(Tab :: table()) -> [Key :: term()]
Dirty equivalent of the function mnesia:all_keys/1.
dirty_delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
Calls mnesia:dirty_delete(Tab, Key).
dirty_delete(Tab :: table(), Key :: term()) -> ok
Dirty equivalent of the function mnesia:delete/3.
dirty_delete_object(Record :: tuple()) -> ok
Calls mnesia:dirty_delete_object(Tab, Record), where Tab is element(1, Record).
dirty_delete_object(Tab :: table(), Record :: tuple()) -> ok
Dirty equivalent of the function mnesia:delete_object/3.
dirty_first(Tab :: table()) -> Key :: term()
Records in set or bag tables are not ordered. However, there is an ordering of the records that is unknown to the user. Therefore, a table can be traversed by this function with the function mnesia:dirty_next/2.
If there are no records in the table, this function returns the atom '$end_of_table'. It is therefore highly undesirable, but not disallowed, to use this atom as the key for any user records.
dirty_index_match_object(Pattern, Attr) -> [Record]
Types:
Starts mnesia:dirty_index_match_object(Tab, Pattern, Pos), where Tab is element(1, Pattern).
dirty_index_match_object(Tab, Pattern, Attr) -> [Record]
Types:
Dirty equivalent of the function mnesia:index_match_object/4.
dirty_index_read(Tab, Key, Attr) -> [Record]
Types:
Dirty equivalent of the function mnesia:index_read/3.
dirty_last(Tab :: table()) -> Key :: term()
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 :: tuple()) -> [Record :: tuple()]
Calls mnesia:dirty_match_object(Tab, Pattern), where Tab is element(1, Pattern).
dirty_match_object(Tab, Pattern) -> [Record]
Types:
Dirty equivalent of the function mnesia:match_object/3.
dirty_next(Tab :: table(), Key :: term()) -> NextKey :: term()
Traverses a table and performs 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 that 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 function mnesia:dirty_next/2.
dirty_prev(Tab :: table(), Key :: term()) -> PrevKey :: term()
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(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
Calls mnesia:dirty_read(Tab, Key).
dirty_read(Tab :: table(), Key :: term()) -> [tuple()]
Dirty equivalent of the function mnesia:read/3.
dirty_select(Tab, Spec) -> [Match]
Types:
Dirty equivalent of the function mnesia:select/2.
dirty_update_counter(Counter :: {Tab :: table(), Key :: term()},
Incr :: integer()) ->
NewVal :: integer()
Calls mnesia:dirty_update_counter(Tab, Key, Incr).
dirty_update_counter(Tab :: table(),
Key :: term(),
Incr :: integer()) ->
NewVal :: integer()
Mnesia has no special counter records. 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 take effect without the risk of losing one of the updates. The new value NewVal of the counter is returned.
If Key does not exist, a new record is created with value Incr if it is larger than 0, otherwise it is set to 0.
dirty_write(Record :: tuple()) -> ok
Calls mnesia:dirty_write(Tab, Record), where Tab is element(1, Record).
dirty_write(Tab :: table(), Record :: tuple()) -> ok
Dirty equivalent of the function mnesia:write/3.
dump_log() -> dumped
Performs a user-initiated dump of the local log file. This is usually not necessary, as Mnesia by default manages this automatically. See configuration parameters dump_log_time_threshold and dump_log_write_threshold.
dump_tables(Tabs :: [Tab :: table()]) -> t_result(ok)
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 can have disc-resident replicas.
dump_to_textfile(File :: file:filename()) -> result() | error
Dumps all local tables of a Mnesia system into a text file, which can be edited (by a normal text editor) and then be reloaded with mnesia:load_textfile/1. Only use this function for educational purposes. Use other functions to deal with real backups.
error_description(Error :: term()) -> string()
All Mnesia transactions, including all the schema update functions, either return value {atomic, Val} or the tuple {aborted, Reason}. Reason can be either of the atoms in the following list. The function error_description/1 returns a descriptive string that describes the error.
Error can be Reason, {error, Reason}, or {aborted, Reason}. Reason can be an atom or a tuple with Reason as an atom in the first field.
The following examples illustrate a function that returns an error, and the method to retrieve more detailed error information:
ets(Fun) -> Res | no_return()
ets(Fun, Args :: [Arg :: term()]) -> Res | no_return()
Types:
Calls the Fun in a raw context that is not protected by a transaction. The Mnesia function call is performed in the Fun and 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. For details, see mnesia:activity/4 and the User's Guide.
Notice that calling (nesting) a mnesia:ets inside a transaction-context inherits the transaction semantics.
first(Tab :: table()) -> Key :: term()
Records in set or bag tables are not ordered. However, there is an ordering of the records that is unknown to the user. A table can therefore be traversed by this function with the function mnesia:next/2.
If there are no records in the table, this function returns the atom '$end_of_table'. It is therefore highly undesirable, but not disallowed, to use this atom as the key for any user records.
foldl(Fun, Acc0, Tab :: table()) -> Acc
Types:
Iterates over the table Table and calls Function(Record, NewAcc) for each Record in the table. The term returned from Function is used as the second argument in the next call to Function.
foldl returns the same term as the last call to Function returned.
foldr(Fun, Acc0, Tab :: table()) -> Acc
Types:
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 :: table()) ->
yes | {error, Reason :: term()}
The Mnesia algorithm for table load can lead to a situation where a table cannot be loaded. This situation occurs when a node is started and Mnesia concludes, or suspects, that another copy of the table was active after this local copy became inactive because of a system crash.
If this situation is not acceptable, this function can be used to override the strategy of the Mnesia table load algorithm. This can lead to a situation where some transaction effects are lost with an inconsistent database as result, but for some applications high availability is more important than consistent data.
index_match_object(Pattern, Attr) -> [Record]
Types:
Starts mnesia:index_match_object(Tab, Pattern, Pos, read), where Tab is element(1, Pattern).
index_match_object(Tab, Pattern, Attr, LockKind) -> [Record]
Types:
In a manner similar to the function mnesia:index_read/3, any index information can be used when trying to match records. This function takes a pattern that obeys the same rules as the function mnesia:match_object/3, except that this function requires the following conditions:
The two index search functions described here are automatically started 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. For details, see mnesia:activity/4. 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, Key, Attr) -> [Record]
Types:
Assume that 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 table person, the call mnesia:index_read(person, 36, #person.age) returns a list of all persons with age 36. Pos can also be an attribute name (atom), but if the notation mnesia:index_read(person, 36, age) is used, the field position is searched for in runtime, for each call.
The semantics of this function is context-sensitive. For details, see mnesia:activity/4. In transaction-context, it acquires a read lock on the entire table.
info() -> ok
Prints system information on the terminal. This function can be used even if Mnesia is not started. However, more information is displayed if Mnesia is started.
install_fallback(Src :: term()) -> result()
Calls mnesia:install_fallback(Opaque, Args), where Args is [{scope, global}].
install_fallback(Src :: term()) -> result()
Calls mnesia:install_fallback(Opaque, Args), where Args is [{scope, global}, {module, BackupMod}].
install_fallback(Src :: term(), Mod :: module() | [Opt]) ->
result()
Types:
Installs a backup as fallback. The fallback is used to restore the database at the next startup. Installation of fallbacks requires Erlang to be operational on all the involved nodes, but it does not matter if Mnesia is running or not. The installation of the fallback fails if the local node is not one of the disc-resident nodes in the backup.
Args is a list of the following tuples:
If Scope of the operation is local, the fallback is only installed on the local node.
This is a dangerous feature that must be used with care. By unintentional mixing of directories, you can easily end up with an inconsistent database, if the same backup is installed on more than one directory.
is_transaction() -> boolean()
When this function is executed inside a transaction-context, it returns true, otherwise false.
last(Tab :: table()) -> Key :: term()
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(File :: file:filename()) ->
t_result(ok) | {error, term()}
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. It is recommended to use other functions to deal with real backups.
lock(LockItem, LockKind) -> list() | tuple() | no_return()
Types:
Write locks are normally acquired on all nodes where a replica of the table resides (and is active). Read locks are acquired on one node (the local node if a local replica exists). Most of the context-sensitive access functions acquire an implicit lock if they are started in a transaction-context. The granularity of a lock can either be a single record or an entire table.
The normal use is to call the function without checking the return value, as it exits if it fails and the transaction is restarted by the transaction manager. It returns all the locked nodes if a write lock is acquired and ok if it was a read lock.
The function mnesia:lock/2 is intended to support explicit locking on tables, but is also intended for situations when locks need to be acquired regardless of how tables are replicated. Currently, two kinds of LockKind are supported:
Conflicting lock requests are automatically queued if there is no risk of a deadlock. Otherwise the transaction must be terminated and executed again. Mnesia does this automatically as long as the upper limit of the maximum retries is not reached. For details, see mnesia:transaction/3.
For the sake of completeness, sticky write locks are also described here even if a sticky write lock is not supported by this function:
When a sticky write lock is acquired, all nodes are informed which node is locked. Then, sticky lock requests from the same node are performed as a local operation without any communication with other nodes. The sticky lock lingers on the node even after the transaction ends. For details, see the User's Guide.
Currently, this function supports two kinds of LockItem:
Locks are released when the outermost transaction ends.
The semantics of this function is context-sensitive. For details, see mnesia:activity/4. In transaction-context, it acquires locks, otherwise it ignores the request.
match_object(Pattern :: tuple()) -> [Record :: tuple()]
Calls mnesia:match_object(Tab, Pattern, read), where Tab is element(1, Pattern).
match_object(Tab, Pattern, LockKind) -> [Record]
Types:
Takes a pattern with "don't care" variables denoted as a '_' parameter. This function returns a list of records that 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 36.
The function mnesia:match_object/3 automatically uses indexes if these exist. However, no heuristics are performed to select the best index.
The semantics of this function is context-sensitive. For details, see mnesia:activity/4. 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 :: table(), From :: node(), To :: node()) ->
t_result(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. Other transactions can still read and write in the table while it is being moved.
This function cannot be used on local_content tables.
next(Tab :: table(), Key :: term()) -> NextKey :: term()
Traverses a table and performs 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 that can be used to read the actual record.
prev(Tab :: table(), Key :: term()) -> PrevKey :: term()
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(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
read(Tab :: table(), Key :: term()) -> [tuple()]
Calls function mnesia:read(Tab, Key, read).
read(Tab :: table(), Key :: term(), LockKind :: lock_kind()) ->
[tuple()]
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 function 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. For details, see mnesia:activity/4. 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 is checked as soon as a write lock is attempted. This can be used to end quickly if the majority condition is not met.
read_lock_table(Tab :: table()) -> ok
Calls the function mnesia:lock({table, Tab}, read).
report_event(Event :: term()) -> ok
When tracing a system of Mnesia applications it is useful to be able to interleave Mnesia own events with application-related events that give information about the application context.
Whenever the application begins a new and demanding Mnesia task, or if it enters a new interesting phase in its execution, it can be a good idea to use mnesia:report_event/1. Event can be any term and generates a {mnesia_user, Event} event for any processes that subscribe to Mnesia system events.
restore(Src :: term(), Args :: [Arg]) -> t_result([table()])
Types:
With this function, tables can 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. However, regardless of the lock conflicts caused by this, the applications can continue to do their work while the restoration is being performed. The restoration is performed as one single transaction.
If the database is huge, it it not always possible to restore it online. In such cases, restore the old database by installing a fallback and then restart.
s_delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
Calls the function mnesia:delete(Tab, Key, sticky_write)
s_delete_object(Rec :: tuple()) -> ok
Calls the function mnesia:delete_object(Tab, Record, sticky_write), where Tab is element(1, Record).
s_write(Record :: tuple()) -> ok
Calls the function mnesia:write(Tab, Record, sticky_write), where Tab is element(1, Record).
schema() -> ok
Prints information about all table definitions on the terminal.
schema(Tab :: table()) -> ok
Prints information about one table definition on the terminal.
select(Tab, Spec) -> [Match]
select(Tab, Spec, LockKind) -> [Match]
Types:
Matches the objects in table Tab using a match_spec as described in the ets:select/3. Optionally a lock read or write can be given as the third argument. Default is read. The return value depends on MatchSpec.
Notice that for best performance, select is to be used before any modifying operations are done on that table in the same transaction. That is, do not use write or delete before a select.
In its simplest forms, the match_spec look as follows:
For a complete description of select, see the ERTS User's Guide and the ets manual page in STDLIB.
For example, to find the names of all male persons older than 30 in table Tab:
MatchHead = #person{name='$1', sex=male, age='$2', _='_'}, Guard = {'>', '$2', 30}, Result = '$1', mnesia:select(Tab,[{MatchHead, [Guard], [Result]}]),
select(Tab, Spec, N, LockKind) ->
{[Match], Cont} | '$end_of_table'
Types:
Matches the objects in table Tab using a match_spec as described in the ERTS User's Guide, and returns a chunk of terms and a continuation. The wanted number of returned terms is specified by argument NObjects. The lock argument can be read or write. The continuation is to be used as argument to mnesia:select/1, if more or all answers are needed.
Notice that for best performance, select is to be used before any modifying operations are done on that table in the same transaction. That is, do not use mnesia:write or mnesia:delete before a mnesia:select. For efficiency, NObjects is a recommendation only and the result can contain anything from an empty list to all available results.
select(Cont) -> {[Match], Cont} | '$end_of_table'
Types:
Selects more objects with the match specification initiated by mnesia:select/4.
Notice that any modifying operations, that is, mnesia:write or mnesia:delete, that are done between the mnesia:select/4 and mnesia:select/1 calls are not visible in the result.
set_debug_level(Level :: debug_level()) ->
OldLevel :: debug_level()
Changes the internal debug level of Mnesia. For details, see Section Configuration Parameters.
set_master_nodes(Ns :: [node()]) -> result()
For each table Mnesia determines its replica nodes (TabNodes) and starts mnesia:set_master_nodes(Tab, TabMasterNodes). where TabMasterNodes is the intersection of MasterNodes and TabNodes. For semantics, see mnesia:set_master_nodes/2.
set_master_nodes(Tab :: table(), Ns :: [node()]) -> result()
If the application detects a communication failure (in a potentially partitioned network) that can have caused an inconsistent database, it can use the function mnesia:set_master_nodes(Tab, MasterNodes) to define from which nodes each table is to be loaded. At startup, the Mnesia normal table load algorithm is bypassed and the table is loaded from one of the master nodes defined for the table, regardless of when and if Mnesia terminated on other nodes. MasterNodes can only contain nodes where the table has a replica. If the MasterNodes list is empty, the master node recovery mechanism for the particular table is reset, and the normal load mechanism is used at the next restart.
The master node setting is always local. It can be changed regardless if Mnesia is started or not.
The database can also become inconsistent if configuration parameter max_wait_for_decision is used or if mnesia:force_load_table/1 is used.
snmp_close_table(Tab :: table()) -> ok
Removes the possibility for SNMP to manipulate the table.
snmp_get_mnesia_key(Tab :: table(), RowIndex :: [integer()]) ->
{ok, Key :: term()} | undefined
Types:
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 :: table(), RowIndex :: [integer()]) ->
{ok, [integer()]} | endOfTable
Types:
RowIndex can specify a non-existing row. Specifically, it can be the empty list. Returns the index of the next lexicographical row. If RowIndex is the empty list, this function returns the index of the first row in the table.
snmp_get_row(Tab :: table(), RowIndex :: [integer()]) ->
{ok, Row :: tuple()} | undefined
Types:
Reads a row by its SNMP index. This index is specified as an SNMP Object Identifier, a list of integers.
snmp_open_table(Tab :: table(), Snmp :: snmp_struct()) -> ok
Types:
A direct one-to-one mapping can be established between Mnesia tables and SNMP tables. Many telecommunication applications are controlled and monitored by the SNMP protocol. This connection between Mnesia and SNMP makes it simple and convenient to achieve this mapping.
Argument SnmpStruct is a list of SNMP information. Currently, the only information needed is information about the key types in the table. Multiple keys cannot be handled 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 a fixed size.
For example, the following causes table person to be ordered as an SNMP table:
mnesia:snmp_open_table(person, [{key, string}])
Consider the following schema for a table of company employees. Each employee is identified by department number and name. The other table column stores the telephone number:
mnesia:create_table(employee,
[{snmp, [{key, {integer, string}}]},
{attributes, record_info(fields, employees)}]),
The corresponding SNMP table would have three columns: department, name, and telno.
An option is to have table columns that are not visible through the SNMP protocol. These columns must be the last columns of the table. In the previous example, the SNMP table could have columns department and name only. The application could then use column telno 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). Also, more memory is used.
Notice that only the lexicographical SNMP ordering is implemented in Mnesia, not the actual SNMP monitoring.
start() -> result()
Mnesia startup is asynchronous. The function call mnesia:start() returns the atom ok and then starts to initialize the different tables. Depending on the size of the database, this can take some time, and the application programmer must wait for the tables that the application needs before they can be used. This is achieved by using the function mnesia:wait_for_tables/2.
The startup procedure for a set of Mnesia nodes is a fairly complicated operation. A Mnesia system consists of a set of nodes, with Mnesia started locally on all participating nodes. Normally, each node has a directory where all the Mnesia files are written. This directory is referred to as the Mnesia directory. Mnesia can also be started on disc-less nodes. For more information about disc-less nodes, see mnesia:create_schema/1 and the User's Guide.
The set of nodes that makes up a Mnesia system is kept in a schema. Mnesia nodes can be added to or removed from the schema. The initial schema is normally created on disc with the function mnesia:create_schema/1. On disc-less nodes, a tiny default schema is generated each time Mnesia is started. During the startup procedure, Mnesia exchanges schema information between the nodes to verify that the table definitions are compatible.
Each schema has a unique cookie, which can be regarded as a unique schema identifier. The cookie must be the same on all nodes where Mnesia is supposed to run. For details, see the User's Guide.
The schema file and all other files that Mnesia needs are kept in the Mnesia directory. The command-line option -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) can also be used.
stop() -> stopped | {error, term()}
Stops Mnesia locally on the current node.
application:stop(mnesia) can also be used.
subscribe(What) -> {ok, node()} | {error, Reason :: term()}
Types:
Ensures that a copy of all events of type EventCategory is sent to the caller. The available event types are described in the User's Guide.
sync_dirty(Fun) -> Res | no_return()
sync_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()
Types:
Calls the Fun in a context that 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. For details, see mnesia:activity/4 and the User's Guide.
sync_log() -> result()
Ensures that the local transaction log file is synced to disk. On a single node system, data written to disk tables since the last dump can be lost if there is a power outage. See dump_log/0.
sync_transaction(Fun) -> t_result(Res)
sync_transaction(Fun, Retries) -> t_result(Res)
sync_transaction(Fun, Args :: [Arg :: term()]) -> t_result(Res)
sync_transaction(Fun, Args :: [Arg :: term()], Retries) ->
t_result(Res)
Types:
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 overloads a database on another node.
system_info(Iterm :: term()) -> Info :: term()
Returns information about the Mnesia system, such as transaction statistics, db_nodes, and configuration parameters. The valid keys are as follows:
New InfoKeys can be added and old undocumented InfoKeys can be removed without notice.
This feature is temporary and will be removed in future releases.
If Mnesia is down on the local node, the function returns those other db_nodes and extra_db_nodes that for the moment are operational.
If Mnesia is started, the function returns those nodes that Mnesia on the local node is fully connected to. Only those nodes that Mnesia has exchanged schema information with are included as running_db_nodes. After the merge of schemas, the local Mnesia system is fully operable and applications can perform access of remote replicas. Before the schema merge, Mnesia only operates locally. Sometimes there are more nodes included in the running_db_nodes list than all db_nodes and extra_db_nodes together.
table(Tab :: table()) -> qlc:query_handle()
table(Tab :: table(), Options) -> qlc:query_handle()
Types:
Returns a Query List Comprehension (QLC) query handle, see the qlc(3erl) manual page in STDLIB. The module qlc implements a query language that 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.
Option can contain Mnesia options or QLC options. Mnesia recognizes the following options (any other option is forwarded to QLC).
There are two alternatives for select:
table_info(Tab :: table(), Item :: term()) -> Info :: term()
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:
New InfoItems can be added and old undocumented InfoItems can be removed without notice.
transaction(Fun) -> t_result(Res)
transaction(Fun, Retries) -> t_result(Res)
transaction(Fun, Args :: [Arg :: term()]) -> t_result(Res)
transaction(Fun, Args :: [Arg :: term()], Retries) ->
t_result(Res)
Types:
Executes the functional object Fun with arguments Args as a transaction.
The code that executes inside the transaction can consist of a series of table manipulation functions. If something goes wrong inside the transaction as a result of a user error or a certain table not being available, the entire transaction is terminated and the function transaction/1 returns the tuple {aborted, Reason}.
If all is going well, {atomic, ResultOfFun} is returned, where ResultOfFun is the value of the last expression in Fun.
A function that adds a family to the database can be written as follows if there is 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 ensures that either the whole family is added to the database, or the whole transaction terminates. For example, if the last child is badly formatted, or the executing process terminates because of an 'EXIT' signal while executing the family code, the transaction terminates. Thus, 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, is to 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 function raise/2 without interfering with each other.
Since Mnesia detects deadlocks, a transaction can be restarted any number of times. This function attempts a restart as specified in Retries. Retries must be an integer greater than 0 or the atom infinity. Default is infinity.
transform_table(Tab :: table(), Fun, NewA :: [Attr], RecName) ->
t_result(ok)
Types:
Applies argument Fun to all records in the table. Fun is a function that takes a record of the old type and returns a transformed record of the new type. Argument Fun can also be the atom ignore, which indicates that only the metadata about the table is updated. Use of ignore is not recommended, but included as a possibility for the user do to an own transformation.
NewAttributeList and NewRecordName specify the attributes and the new record type of the converted table. Table name always remains unchanged. If record_name is changed, only the Mnesia functions that use table identifiers work, for example, mnesia:write/3 works, but not mnesia:write/1.
transform_table(Tab :: table(), Fun, NewA :: [Attr]) ->
t_result(ok)
Types:
Calls mnesia:transform_table(Tab, Fun, NewAttributeList, RecName), where RecName is mnesia:table_info(Tab, record_name).
traverse_backup(Src :: term(), Dest :: term(), Fun, Acc) ->
{ok, Acc} | {error, Reason :: term()}
traverse_backup(Src :: term(),
SrcMod :: module(),
Dest :: term(),
DestMod :: module(),
Fun, Acc) ->
{ok, Acc} | {error, Reason :: term()}
Types:
Iterates over a backup, either to transform it into a new backup, or read it. The arguments are explained briefly here. For details, see the User's Guide.
uninstall_fallback() -> result()
Calls the function mnesia:uninstall_fallback([{scope, global}]).
uninstall_fallback(Args) -> result()
Types:
Deinstalls a fallback before it has been used to restore the database. This is normally a distributed operation that is either performed on all nodes with disc resident schema, or none. Uninstallation of fallbacks requires Erlang to be operational on all involved nodes, but it does not matter if Mnesia is running or not. Which nodes that are considered as disc-resident nodes is determined from the schema information in the local fallback.
Args is a list of the following tuples:
unsubscribe(What) -> {ok, node()} | {error, Reason :: term()}
Types:
Stops sending events of type EventCategory to the caller.
Node is the local node.
wait_for_tables(Tabs :: [Tab :: table()], TMO :: timeout()) ->
result() | {timeout, [table()]}
Some applications need to wait for certain tables to be accessible to do useful work. mnesia:wait_for_tables/2 either hangs until all tables in TabList are accessible, or until timeout is reached.
wread(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
Calls the function mnesia:read(Tab, Key, write).
write(Record :: tuple()) -> ok
Calls the function mnesia:write(Tab, Record, write), where Tab is element(1, Record).
write(Tab :: table(),
Record :: tuple(),
LockKind :: write_locks()) ->
ok
Writes record Record to table Tab.
The function returns ok, or terminates if an error occurs. For example, the transaction terminates if no person table exists.
The semantics of this function is context-sensitive. For details, see mnesia:activity/4. In transaction-context, it acquires a lock of type LockKind. The lock types write and sticky_write are supported.
write_lock_table(Tab :: table()) -> ok
Calls the function mnesia:lock({table, Tab}, write).
Mnesia reads the following application configuration parameters:
This feature is temporary and will be removed in a future release
-mnesia dump_log_write_threshold Max. Max is an integer that specifies the maximum number of writes allowed to the transaction log before a new dump of the log is performed. Default is 100 log writes.
-mnesia dump_log_time_threshold Max. Max is an integer that specifies the dump log interval in milliseconds. Default is 3 minutes. If a dump has not been performed within dump_log_time_threshold milliseconds, a new dump is performed regardless of the number of writes performed.
If Timeout is set to an integer value in milliseconds, Mnesia forces "heavyweight transactions" to be finished, even if the outcome of the transaction for the moment is unclear. After Timeout milliseconds, Mnesia commits or terminates the transaction and continues with the startup. This can lead to a situation where the transaction is committed on some nodes and terminated on other nodes. If the transaction is a schema transaction, the inconsistency can be fatal.
Level must be an integer in the interval [0, 9], where 0 means no compression and 9 means maximum compression. Before setting it to a non-zero value, ensure that the remote nodes understand this configuration.
Parameter extra_db_nodes can also be used on disc based nodes.
First, the SASL application parameters are checked, then the command-line flags are checked, and finally, the default value is chosen.
application(3erl), dets(3erl), disk_log(3erl), ets(3erl), mnesia_registry(3erl), qlc(3erl)
mnesia 4.18.1 | Ericsson AB |