mnesia(3erl)

๐Ÿ“ฆ
version 25.3.2.8 ยท 4 versions
, in ubuntu noble

๐Ÿ’… NAME ๐Ÿ’…

okay bestie, welcome to the mnesia(3erl) page โ€” Erlang Module Definition, but make it cute. This is the manual for mnesia โ€” a distributed telecommunications DBMS. Periodt. ๐Ÿ’–

๐ŸŒธ DESCRIPTION ๐ŸŒธ

Hereโ€™s the glow-up list of Mnesiaโ€™s most important and attractive capabilities, bestie:

  • A relational/object hybrid data model thatโ€™s literally suitable for telecommunications applications.
  • A DBMS query language, Query List Comprehension (QLC) as an add-on library.
  • Persistence, periodt: tables can be coherently kept on disc and in the main memory.
  • Replication, no cap: tables can be replicated at several nodes.
  • Atomic transactions: a series of table manipulation operations can be grouped into a single atomic transaction.
  • Location transparency: programs can be written without knowledge of the actual data location.
  • Extremely fast real-time data searches โ€” yes, actually.
  • Schema manipulation routines: the DBMS can be reconfigured at runtime without stopping the system.

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:

  • type โ€” bestie, each table can have set, ordered_set, or bag semantics. Just know that currently ordered_set is not supported for disc_only_copies.

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.

  • record_name โ€” all records stored in a table must have the same name. The records must be instances of the same record type.
  • ram_copies โ€” a table can be replicated on a number of Erlang nodes. Property ram_copies specifies a list of Erlang nodes where RAM copies are kept. These copies can be dumped to disc at regular intervals. However, updates to these copies are not written to disc on a transaction basis.
  • disc_copies โ€” this property specifies a list of Erlang nodes where the table is kept in RAM and on disc. All updates of the table are performed in the actual table and are also logged to disc. If a table is of type disc_copies at a certain node, the entire table is resident in RAM memory and on disc. Each transaction performed on the table is appended to a LOG file and written into the RAM table.
  • disc_only_copies โ€” some, or all, table replicas can be kept on disc only. These replicas are considerably slower than the RAM-based replicas.
  • index โ€” this is a list of attribute names, or integers, which specify the tuple positions on which Mnesia is to build and maintain an extra index table.
  • local_content โ€” when an application requires tables whose contents are local to each node, local_content tables can be used. The table name is known to all Mnesia nodes, but its content is unique on each node. This means that access to such a table must be done locally. Set field local_content to true to enable the local_content behavior. Default is false.
  • majority โ€” this attribute is true or false; default is false. When true, a majority of the table replicas must be available for an update to succeed. Majority checking can be enabled on tables with mission-critical data, where it is vital to avoid inconsistencies because of network splits.
  • snmp โ€” each (set-based) Mnesia table can be automatically turned into a Simple Network Management Protocol (SNMP) ordered table as well. This property specifies the types of the SNMP keys.
  • attributes โ€” the names of the attributes for the records that are inserted in the table.

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.

bestie, if possible, avoid writing or deleting records in the same transaction before iterating over the table. Your future self will thank you. ๐Ÿ’€

๐Ÿฆ‹ DATA TYPES ๐Ÿฆ‹

vibe check: here are the type aliases, exactly as they appear โ€” no cap:

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

๐Ÿ‘‘ EXPORTS ๐Ÿ‘‘

abort/1

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/1

activate_checkpoint(Args :: [Arg]) ->
                        {ok, Name, [node()]} |
                        {error, Reason :: term()}

Types:

Arg =
    {name, Name} |
    {max, [table()]} |
    {min, [table()]} |
    {allow_remote, boolean()} |
    {ram_overrides_dump, boolean()}

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:

  • {name,Name} โ€” Name is the checkpoint name. Each checkpoint must have a name that is unique to the associated nodes. The name can be reused only once the checkpoint has been deactivated. By default, a name that is probably unique is generated.
  • {max,MaxTabs} โ€” MaxTabs is a list of tables that are to be included in the checkpoint. Default is []. For these tables, the redundancy is maximized and checkpoint information is retained together with all replicas. The checkpoint becomes more fault tolerant if the tables have several replicas. When a new replica is added by the schema manipulation function mnesia:add_table_copy/3, a retainer is also attached automatically.
  • {min,MinTabs} โ€” MinTabs is a list of tables that are to be included in the checkpoint. Default is []. For these tables, the redundancy is minimized and the checkpoint information is only retained with one replica, preferably on the local node.
  • {allow_remote,Bool} โ€” false means that all retainers must be local. The checkpoint cannot be activated if a table does not reside locally. true allows retainers to be allocated on any node. Default is true.
  • {ram_overrides_dump,Bool} โ€” only applicable for ram_copies. Bool allows you to choose to back up the table state as it is in RAM, or as it is on disc. true means that the latest committed records in RAM are to be included in the checkpoint. These are the records that the application accesses. false means that the records dumped to DAT files are to be included in the checkpoint. These records are loaded at startup. Default is false.

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/2

activity(Kind, Fun) -> t_result(Res) | Res

Types:

Kind = activity()
Fun = fun(() -> Res)

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/4

activity(Kind, Fun, Args :: [Arg :: term()], Mod) ->
             t_result(Res) | Res

Types:

Kind = activity()
Fun = fun((...) -> Res)
Mod = atom()

Executes the functional object Fun with argument Args.

Okay so, the code that executes inside the activity can be a whole little series of table manipulation functions, and those run inside an AccessContext. Right now, these access contexts are supported:

  • transaction โ€” short for {transaction, infinity}.
  • {transaction, Retries} โ€” calls mnesia:transaction(Fun, Args, Retries). The result from Fun is returned if the transaction succeeds (atomic); otherwise the function exits with an abort reason.
  • sync_transaction โ€” short for {sync_transaction, infinity}.
  • {sync_transaction, Retries} โ€” calls mnesia:sync_transaction(Fun, Args, Retries). The result from Fun is returned if the transaction succeeds (atomic); otherwise the function exits with an abort reason.
  • async_dirty โ€” calls mnesia:async_dirty(Fun, Args).
  • sync_dirty โ€” calls mnesia:sync_dirty(Fun, Args).
  • ets โ€” calls mnesia:ets(Fun, Args).

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

Mnesia forwards calls to these functions:

  • mnesia:lock/2 (read_lock_table/1, write_lock_table/1)
  • mnesia:write/3 (write/1, s_write/1)
  • mnesia:delete/3 (delete/1, s_delete/1)
  • mnesia:delete_object/3 (delete_object/1, s_delete_object/1)
  • mnesia:read/3 (read/1, wread/1)
  • mnesia:match_object/3 (match_object/1)
  • mnesia:all_keys/1
  • mnesia:first/1
  • mnesia:last/1
  • mnesia:prev/2
  • mnesia:next/2
  • mnesia:index_match_object/4 (index_match_object/2)
  • mnesia:index_read/3
  • mnesia:table_info/2

to the corresponding callback calls:

  • AccessMod:lock(ActivityId, Opaque, LockItem, LockKind)
  • AccessMod:write(ActivityId, Opaque, Tab, Rec, LockKind)
  • AccessMod:delete(ActivityId, Opaque, Tab, Key, LockKind)
  • AccessMod:delete_object(ActivityId, Opaque, Tab, RecXS, LockKind)
  • AccessMod:read(ActivityId, Opaque, Tab, Key, LockKind)
  • AccessMod:match_object(ActivityId, Opaque, Tab, Pattern, LockKind)
  • AccessMod:all_keys(ActivityId, Opaque, Tab, LockKind)
  • AccessMod:first(ActivityId, Opaque, Tab)
  • AccessMod:last(ActivityId, Opaque, Tab)
  • AccessMod:prev(ActivityId, Opaque, Tab, Key)
  • AccessMod:next(ActivityId, Opaque, Tab, Key)
  • AccessMod:index_match_object(ActivityId, Opaque, Tab, Pattern, Attr, LockKind)
  • AccessMod:index_read(ActivityId, Opaque, Tab, SecondaryKey, Attr, LockKind)
  • AccessMod:table_info(ActivityId, Opaque, Tab, InfoItem)

ActivityId is a record that represents the identity of the enclosing Mnesia activity. The first field, obtained with element(1, ActivityId), contains an atom that can be interpreted as the activity type: ets, async_dirty, sync_dirty, or tid. tid means 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. iykyk ๐Ÿ’…


add_table_copy(Tab, N, ST) -> t_result(ok)

Types:

  • Tab = table()
  • N = node()
  • ST = storage_type()

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, this call makes sure 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. slay a little schema copy โœจ

add_table_index(Tab, I) -> t_result(ok)

Types:

  • Tab = table()
  • I = index_attr()

Table indexes can be used whenever the user wants to use some other field than the key field, frequently, 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 wants to use field age to efficiently find 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. iconic but not free, bestie ๐Ÿ’ธ

all_keys(Tab :: table()) -> [Key :: term()]

Returns a list of all keys in the table named Tab. The semantics of this function are context-sensitive. For more information, see mnesia:activity/4. In transaction-context, it acquires a read lock on the entire table. whole-table lock moment ๐Ÿ”’

async_dirty(Fun) -> Res | no_return()

async_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()

Types:

  • Fun = fun((...) -> Res)

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 it 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. ten times, no cap ๐Ÿ˜ญ๐Ÿ”ฅ

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:

  • Name = Dest = term()
  • Mod = module()

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 = config_key()
  • Value = config_value()

Config is to be an atom of the following configuration parameters:

  • extra_db_nodes โ€” Value is a list of nodes that Mnesia is to try to connect to. ReturnValue is those nodes in Value that Mnesia is connected to.
โš ๏ธ 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.

  • dc_dump_limit โ€” Value is a number. See the description in Section Configuration Parameters. ReturnValue is the new value. Notice that this configuration parameter is not persistent. It is lost when Mnesia has stopped. gone-gone, not saved ๐Ÿซ 

change_table_access_mode(Tab :: table(), Mode) -> t_result(ok)

Types:

  • Mode = read_only | read_write

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. read-only era ๐Ÿ”’๐Ÿ’œ

change_table_copy_type ๐ŸŽ€

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:

  • Order = integer() >= 0

Okay so 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)

M has to be a boolean, bestie โ€” default is false. When itโ€™s 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. Periodt. ๐Ÿซถ

clear_table(Tab :: table()) -> t_result(ok)

Deletes all entries in the table Tab. Like, every single one. ๐Ÿงน

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 reside 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:

  • {access_mode, Atom} โ€” the access mode 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 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.
  • {attributes, AtomList} โ€” a list of the attribute names for the records that are supposed to populate the table. Default is [key, val]. The table must at least have one extra attribute in addition to the key. When accessing single attributes in a record, it is not necessary, or even recommended, to hard code any attribute names as atoms. Use construct record_info(fields, RecordName) instead. It can be used for records of type RecordName.
  • {disc_copies, Nodelist} โ€” where Nodelist is a list of the nodes where this table is supposed to have disc copies. If a table replica is of type disc_copies, all write operations on this particular replica of the table are written to disc and to the RAM copy of the table. It is possible to have a replicated table of type disc_copies on one node and another type on another node. Default is [].
  • {disc_only_copies, Nodelist} โ€” where Nodelist is a list of the nodes where this table is supposed to have disc_only_copies. A disc only table replica is kept on disc only and, unlike the other replica types, the contents of the replica do not reside in RAM. These replicas are considerably slower than replicas held in RAM. ๐Ÿข
  • {index, Intlist} โ€” where Intlist is a list of attribute names (atoms) or record fields for which Mnesia is to build and maintain an extra index table. The qlc query compiler may be able to optimize queries if there are indexes available.
  • {load_order, Integer} โ€” the load order priority is by default 0 (zero) but can be set to any integer. The tables with the highest load order priority are loaded first at startup.
  • {majority, Flag} โ€” where Flag must be a boolean. If true, any (non-dirty) update to the table is aborted unless a majority of the table replicas are available for the commit. When used on a fragmented table, all fragments are given the same majority setting.
  • {ram_copies, Nodelist} โ€” where Nodelist is a list of the nodes where this table is supposed to have RAM copies. A table replica of type ram_copies is not written to disc on a per transaction basis. ram_copies replicas can be dumped to disc with the function mnesia:dump_tables(Tabs). Default value for this attribute is [node()].
  • {record_name, Name} โ€” where Name must be an atom. All records stored in the table must have this name as the first element. It defaults to the same name as the table name.
  • {snmp, SnmpStruct} โ€” for a description of SnmpStruct, see mnesia:snmp_open_table/2. If this attribute is present in ArgList to mnesia:create_table/2, the table is immediately accessible by SNMP. Therefore applications that use SNMP to manipulate and control the system can be designed easily, since Mnesia provides a direct mapping between the logical tables that make up an SNMP control application and the physical data that makes up a Mnesia table.
  • {storage_properties, [{Backend, Properties}]} โ€” forwards more properties to the back end storage. Backend can currently be ets or dets. Properties is a list of options sent to the back end storage during table creation. Properties cannot contain properties already used by Mnesia, such as type or named_table.

For example:

mnesia:create_table(table, [{ram_copies, [node()]}, {disc_only_copies, nodes()},
                       {storage_properties,
                        [{ets, [compressed]}, {dets, [{auto_save, 5000}]} ]}])
  • {type, Type} โ€” where Type must be either of the atoms set, ordered_set, or bag. Default is set. In a set, all records have unique keys. In a bag, several records can have the same key, but the record content is unique. If a non-unique record is stored, the old conflicting records are overwritten. Notice that currently ordered_set is not supported for disc_only_copies.
  • {local_content, Bool} โ€” where Bool is true or false. Default is false.

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:

Tab = table()
I = index_attr()

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.

โš ๏ธ Warning: Use this function with extreme caution, as it makes existing persistent data obsolete. Think twice before using it. ๐Ÿ˜ญ

delete_table(Tab :: table()) -> t_result(ok)

Permanently deletes all replicas of table Tab. ๐Ÿ’…

dirty_all_keys โœจ

dirty_all_keys(Tab :: table()) -> [Key :: term()]

Itโ€™s the dirty equivalent of mnesia:all_keys/1 โ€” same facts, less ceremony. ๐Ÿ’…


dirty_delete ๐Ÿ“

dirty_delete(Oid :: {Tab :: table(), Key :: term()}) -> ok

Calls mnesia:dirty_delete(Tab, Key).

dirty_delete ๐Ÿ“

dirty_delete(Tab :: table(), Key :: term()) -> ok

Dirty equivalent of the function mnesia:delete/3.


dirty_delete_object ๐ŸŽ€

dirty_delete_object(Record :: tuple()) -> ok

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

dirty_delete_object ๐ŸŽ€

dirty_delete_object(Tab :: table(), Record :: tuple()) -> ok

Dirty equivalent of the function mnesia:delete_object/3.


dirty_first ๐ŸŒธ

dirty_first(Tab :: table()) -> Key :: term()

Records in set or bag tables are not ordered. But there is an ordering of the records that is unknown to the user. So a table can be traversed by this function together 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 ๐Ÿฆ‹

dirty_index_match_object(Pattern, Attr) -> [Record]

Types:

  • Pattern = tuple()
  • Attr = index_attr()
  • Record = tuple()

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

dirty_index_match_object ๐Ÿฆ‹

dirty_index_match_object(Tab, Pattern, Attr) -> [Record]

Types:

  • Tab = table()
  • Pattern = tuple()
  • Attr = index_attr()
  • Record = tuple()

Dirty equivalent of the function mnesia:index_match_object/4.


dirty_index_read ๐Ÿ’œ

dirty_index_read(Tab, Key, Attr) -> [Record]

Types:

  • Tab = table()
  • Key = term()
  • Attr = index_attr()
  • Record = tuple()

Dirty equivalent of the function mnesia:index_read/3.


dirty_last ๐ŸŒˆ

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 ๐Ÿงš

dirty_match_object(Pattern :: tuple()) -> [Record :: tuple()]

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

dirty_match_object ๐Ÿงš

dirty_match_object(Tab, Pattern) -> [Record]

Types:

  • Tab = table()
  • Pattern = Record = tuple()

Dirty equivalent of the function mnesia:match_object/3.


dirty_next ๐Ÿ”ฅ

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 mnesia:dirty_next/2. ๐Ÿ’€

dirty_prev โญ

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 ๐Ÿซถ

dirty_read(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]

Calls mnesia:dirty_read(Tab, Key).

dirty_read ๐Ÿซถ

dirty_read(Tab :: table(), Key :: term()) -> [tuple()]

Dirty equivalent of the function mnesia:read/3.


dirty_select ๐ŸŽ€

dirty_select(Tab, Spec) -> [Match]

Types:

  • Tab = table()
  • Spec = ets:match_spec()
  • Match = term()

Dirty equivalent of the function mnesia:select/2.


dirty_update_counter ๐Ÿ’–

dirty_update_counter(Counter :: {Tab :: table(), Key :: term()},
                     Incr :: integer()) ->
                        NewVal :: integer()

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

dirty_update_counter ๐Ÿ’–

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 arithmetic, and then writing the record:

  • It is much more efficient.
  • mnesia:dirty_update_counter/3 is performed as an atomic operation although it is not protected by a transaction.

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 ๐Ÿฆ‹

dirty_write(Record :: tuple()) -> ok

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

dirty_write ๐Ÿฆ‹

dirty_write(Tab :: table(), Record :: tuple()) -> ok

Dirty equivalent of the function mnesia:write/3.


dump_log ๐ŸŒธ

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 ๐ŸŽ€

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 ๐Ÿ“

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

  • nested_transaction. Nested transactions are not allowed in this context.
  • badarg. Bad or invalid argument, possibly bad type.
  • no_transaction. Operation not allowed outside transactions.
  • combine_error. Table options illegally combined.
  • bad_index. Index already exists, or was out of bounds.
  • already_exists. Schema option to be activated is already on.
  • index_exists. Some operations cannot be performed on tables with an index.
  • no_exists. Tried to perform operation on non-existing (not-alive) item.
  • system_limit. A system limit was exhausted.
  • mnesia_down. A transaction involves records on a remote node, which became unavailable before the transaction was completed. Records are no longer available elsewhere in the network.
  • not_a_db_node. A node was mentioned that does not exist in the schema.
  • bad_type. Bad type specified in argument.
  • node_not_running. Node is not running.
  • truncated_binary_file. Truncated binary in file.
  • active. Some delete operations require that all active records are removed.
  • illegal. Operation not supported on this record.

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:

  • The function mnesia:create_table(bar, [{attributes, 3.14}]) returns the tuple {aborted,Reason}, where Reason is the tuple {bad_type,bar,3.14000}.
  • The function mnesia:error_description(Reason) returns the term {"Bad type on some provided arguments",bar,3.14000}, which is an error description suitable for display.

ets โšก

ets(Fun) -> Res | no_return()
ets(Fun, Args :: [Arg :: term()]) -> Res | no_return()

Types:

  • Fun = fun((...) -> Res)

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 ๐ŸŒŸ

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 ๐Ÿซถ

foldl(Fun, Acc0, Tab :: table()) -> Acc

Types:

  • Fun = fun((Record :: tuple(), Acc0) -> Acc)

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 ๐ŸŽ€

foldr(Fun, Acc0, Tab :: table()) -> Acc

Types:

  • Fun = fun((Record :: tuple(), Acc0) -> Acc)

foldr/3 โ€” the reverse-order twin ๐Ÿชž

Ok so it's literally foldl/3 but it walks the table backwards โ€” and like, only for ordered_set. For every other table type? foldr/3 and foldl/3 are just synonyms, no cap. โœจ

force_load_table(Tab :: table()) -> yes | {error, Reason :: term()} ๐Ÿ’ฅ

Bestie, listen. The Mnesia table-load algorithm can lowkey get itself into a situation where a table just cannot be loaded. It happens when a node starts up and Mnesia concludes โ€” or suspects โ€” that another copy of the table was active after this local copy went inactive because of a system crash. Messy. ๐Ÿ˜ญ

If that situation is not acceptable to you, this function lets you override the strategy of the Mnesia table-load algorithm. Yes queen, override it. But be warned: this can lead to a situation where some transaction effects are lost, with an inconsistent database as a result. For some applications though, high availability matters more than consistent data โ€” and honestly? Valid. ๐Ÿซถ

index_match_object(Pattern, Attr) -> [Record] ๐Ÿ”

Types:

Pattern = tuple()
Attr = index_attr()
Record = tuple()

This one kicks off mnesia:index_match_object(Tab, Pattern, Pos, read), where Tab is element(1, Pattern). Slay. โœจ

index_match_object(Tab, Pattern, Attr, LockKind) -> [Record] ๐Ÿ”๐Ÿ”

Types:

Tab = table()
Pattern = tuple()
Attr = index_attr()
LockKind = lock_kind()
Record = tuple()

So, in a manner similar to mnesia:index_read/3, literally any index information can be used when you're trying to match records. This function takes a pattern that obeys the same rules as mnesia:match_object/3 โ€” except it requires these conditions:

  • The table Tab must have an index on position Pos.
  • The element in position Pos in Pattern must be bound. Pos is an integer (#record.Field) or an attribute name.

The two index search functions described here get started automatically when you're searching tables with qlc list comprehensions, and also when using the low-level mnesia:[dirty_]match_object functions. iykyk ๐Ÿ’…

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:

Tab = table()
Key = term()
Attr = index_attr()
Record = tuple()

Picture this: there's an index on position Pos for a certain record type. This function lets you read the records without knowing the actual key for the record. Iconic behaviour honestly.

Example time ๐Ÿ“ โ€” 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 (an atom), but if you use the notation mnesia:index_read(person, 36, age), the field position is searched for in runtime, for each call. So like, every single call. Just so you know. ๐Ÿ™ˆ

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. You can use this function even if Mnesia is not started โ€” but more information is displayed if Mnesia is started. More data, more fun, obviously. โœจ

install_fallback(Src :: term()) -> result() ๐ŸŽ€

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

install_fallback(Src :: term(), Mod :: module() | [Opt]) -> result() ๐ŸŽ€โœจ

Types:

Opt = Module | Scope | Dir
Module = {module, Mod :: module()}
Scope = {scope, global | local}
Dir = {mnesia_dir, Dir :: string()}

Installs a backup as fallback. The fallback is used to restore the database at the next startup. Installing fallbacks requires Erlang to be operational on all the involved nodes, but it truly does not matter whether 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. Rude, but fair. ๐Ÿ’€

Args is a list of the following tuples:

  • {module, BackupMod}. All accesses of the backup media are performed through a callback module named BackupMod. Argument Opaque is forwarded to the callback module, which can interpret it as it wishes. The default callback module is called mnesia_backup, and it interprets argument Opaque as a local filename. The default for this module is also configurable through configuration parameter -mnesia mnesia_backup.
  • {scope, Scope}. The Scope of a fallback is either global for the entire database or local for one node. By default, the installation of a fallback is a global operation, which either is performed on all nodes with a disc-resident schema or none. Which nodes that are disc-resident is determined from the schema information in the backup.

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

  • {mnesia_dir, AlternateDir}. This argument is only valid if the scope of the installation is local. Normally the installation of a fallback is targeted to the Mnesia directory, as configured with configuration parameter -mnesia dir. But by explicitly supplying an AlternateDir, the fallback is installed there regardless of the Mnesia directory configuration parameter setting. After installation of a fallback on an alternative Mnesia directory, that directory is fully prepared for use as an active Mnesia directory.
โš ๏ธ This is a dangerous feature that must be used with care, bestie. 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. Like, don't. ๐Ÿ˜ญ

is_transaction() -> boolean() ๐Ÿ•ต๏ธโ€โ™€๏ธ

When this function is executed inside a transaction-context, it returns true. Otherwise false. That's it, that's the whole vibe check. โœ…

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. ๐ŸŽ‰

It's intended for educational purposes only. For real backups, please use other functions โ€” this one is not the moment. ๐Ÿ™ˆ

lock(LockItem, LockKind) -> list() | tuple() | no_return() ๐Ÿ”’

Types:

LockItem =
    {record, table(), Key :: term()} |
    {table, table()} |
    {global, Key :: term(), MnesiaNodes :: [node()]}
LockKind = lock_kind() | load

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're 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. So like, no return-value anxiety needed. ๐Ÿซถ

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:

  • write: Write locks are exclusive. This means that if one transaction manages to acquire a write lock on an item, no other transaction can acquire any kind of lock on the same item. Periodt. ๐Ÿ”ฅ
  • read: Read locks can be shared. This means that if one transaction manages to acquire a read lock on an item, other transactions can also acquire a read lock on the same item. However, if someone has a read lock, no one can acquire a write lock at the same item. And if someone has a write lock, no one can acquire either a read lock or a write lock at the same item. Sharing is caring, but only up to a point. ๐ŸŒธ

Conflicting lock requests are automatically queued if there's 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:

  • sticky_write: Sticky write locks are a mechanism that can be used to optimize write lock acquisition. If your application uses replicated tables mainly for fault tolerance (as opposed to read access optimization purpose), sticky locks can be the best option available. ๐Ÿ‘‘

When a sticky write lock is acquired, all nodes are informed which node is locked. Then sticky lock requests from the same node are performed as a local operation, with zero 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:

  • {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. That's the tea. โ˜•

okay so real talk, this function is like super context-sensitive โ€” read mnesia:activity/4 for the deets. In a transaction context it grabs locks, otherwise it's like "whatever, ignoring the request" ๐Ÿ’…

match_object(Pattern :: tuple()) -> [Record :: tuple()] โœจ

Just calls mnesia:match_object(Tab, Pattern, read), where Tab is element(1, Pattern). Easy peasy.

match_object(Tab, Pattern, LockKind) -> [Record] ๐ŸŽ€

Types:

  • Tab = table()
  • Pattern = tuple()
  • LockKind = lock_kind()
  • Record = tuple()

Takes a pattern where '_' means "don't care". Returns a list of records that matched. Since the second element of a record is the key, performance depends on whether that key is bound or not. (So if you bind it, it's fast; if not, it's scanning, bestie.)

For example, mnesia:match_object(person, {person, '_', 36, '_', '_'}, read) returns all person records with an age field of 36.

The function mnesia:match_object/3 automatically uses indexes if they exist. But no heuristics are performed to select the best index โ€” it's not doing that extra credit work.

Semantics context-sensitive โ€” 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 โ€” like a RAM table moved from one node stays RAM on the new node. Other transactions can still read and write while it's being moved. (So no downtime, slay.) But this function cannot be used on local_content tables โ€” that's a hard no.

next(Tab :: table(), Key :: term()) -> NextKey :: term() โญ

Traverses a table and performs operations on all records. When you hit the end, you get the special key '$end_of_table'. Otherwise it returns a key you can use 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 ordered_set table type. For all other table types, mnesia:next/2 and mnesia:prev/2 are synonyms โ€” same vibe.

read(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()] / read(Tab :: table(), Key :: term()) -> [tuple()] ๐Ÿ’–

Calls mnesia:read(Tab, Key, read). That's it.

read(Tab :: table(), Key :: term(), LockKind :: lock_kind()) -> [tuple()] ๐Ÿ”ฅ

Reads all records from table Tab with key Key. Same semantics regardless of where Tab lives. If the table is a bag, mnesia:read(Tab, Key) can return an arbitrarily long list. If it's a set, the list is either length 1 or [].

Context-sensitive again โ€” see mnesia:activity/4. In transaction-context, it acquires a lock of type LockKind. Currently supported: read, write, and sticky_write.

If you want to update the record, it's more efficient to use write/sticky_write as the LockKind. And if majority checking is active, it's checked as soon as a write lock is attempted โ€” so you can bail quickly if majority isn't met.

read_lock_table(Tab :: table()) -> ok ๐Ÿ”’

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

report_event(Event :: term()) -> ok ๐Ÿ“ฃ

When tracing a system of Mnesia apps, it's useful to interleave Mnesia's own events with app-related events that give info about the application context.

Whenever the app begins a new and demanding Mnesia task, or enters a new interesting phase, 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. So you can drop your own markers in the trace, cute.

restore(Src :: term(), Args :: [Arg]) -> t_result([table()]) ๐Ÿงš

Types:

  • Op = skip_tables | clear_tables | keep_tables | restore_tables
  • Arg = {module, module()} | {Op, [table()]} | {default_op, Op}

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:

  • {module,BackupMod} โ€” The backup module BackupMod is used to access the backup media. If omitted, the default backup module is used.
  • {skip_tables, TabList} โ€” where TabList is a list of tables that is not to be read from the backup.
  • {clear_tables, TabList} โ€” where TabList is a list of tables that is to be cleared before the records from the backup are inserted. That is, all records in the tables are deleted before the tables are restored. Schema information about the tables is not cleared or read from the backup.
  • {keep_tables, TabList} โ€” where TabList is a list of tables that is not to be cleared before the records from the backup are inserted. That is, the records in the backup are added to the records in the table. Schema information about the tables is not cleared or read from the backup.
  • {recreate_tables, TabList} โ€” where TabList is a list of tables that is to be recreated before the records from the backup are inserted. The tables are first deleted and then created with the schema information from the backup. All the nodes in the backup need to be operational.
  • {default_op, Operation} โ€” where Operation is either of the operations skip_tables, clear_tables, keep_tables, or recreate_tables. The default operation specifies which operation that is to be used on tables from the backup that is not specified in any of the mentioned lists. If omitted, operation clear_tables is used.

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 mnesia:delete(Tab, Key, sticky_write).

s_delete_object(Rec :: tuple()) -> ok ๐Ÿšฎ

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

s_write(Record :: tuple()) -> ok โœ๏ธ

Calls 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:

  • Tab = table()
  • Spec = ets:match_spec()
  • Match = term()
  • LockKind = lock_kind()

Matches the objects in table Tab using a match_spec as described in 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:

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

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:

  • Tab = table()
  • Spec = ets:match_spec()
  • Match = term()
  • N = integer() >= 0
  • LockKind = lock_kind()
  • Cont = select_continuation()

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:

  • Match = term()
  • Cont = select_continuation()

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() ๐Ÿ‘‘

...okay so for each table, Mnesia figures out its replica nodes (TabNodes) and starts mnesia:set_master_nodes(Tab, TabMasterNodes), where TabMasterNodes is the intersection of MasterNodes and TabNodes. for the full semantics breakdown, go peek at mnesia:set_master_nodes/2. ๐Ÿซถ

set_master_nodes(Tab :: table(), Ns :: [node()]) -> result()

so say your app clocks a communication failure (classic potentially partitioned network core ๐Ÿ’€) and there's a chance the database went inconsistent โ€” this is the function you reach for. mnesia:set_master_nodes(Tab, MasterNodes) defines which nodes each table gets loaded from. at startup the normal Mnesia table load algorithm gets bypassed entirely and the table loads from one of the master nodes you defined for that table, no matter when (or whether) Mnesia terminated on the other nodes. main character energy only.

heads up though, MasterNodes can only contain nodes where the table has a replica. and if the MasterNodes list is empty, the master node recovery mechanism for that particular table resets, and the normal load mechanism comes back at the next restart. โœจ

the master node setting is always local. you can change it whether Mnesia is started or not, no gatekeeping.

๐Ÿšจ also real talk: the database can also go inconsistent if the configuration parameter max_wait_for_decision is used, or if mnesia:force_load_table/1 is used. not a vibe, just facts.

snmp_close_table(Tab :: table()) -> ok

removes the possibility for SNMP to manipulate the table. that's it, that's the whole thing. bye bestie ๐Ÿ‘‹

snmp_get_mnesia_key(Tab :: table(), RowIndex :: [integer()]) -> {ok, Key :: term()} | undefined

types, bestie:

Tab ::= atom()
RowIndex ::= [integer()]
Key ::= key() | {key(), key(), ...}
key() ::= integer() | string() | [integer()]

transforms an SNMP index into the matching Mnesia key. if the SNMP table has multiple keys, the key comes back as a tuple of the key columns. multi-key slay ๐Ÿ”‘

snmp_get_next_index(Tab :: table(), RowIndex :: [integer()]) -> {ok, [integer()]} | endOfTable

types:

Tab ::= atom()
RowIndex ::= [integer()]
NextIndex ::= [integer()]

RowIndex is allowed to point at a row that doesn't even exist โ€” specifically, it can be the empty list, no questions asked. returns the index of the next lexicographical row. and if RowIndex is the empty list, you get the index of the very first row in the table. first-row behavior, iconic ๐ŸŒธ

snmp_get_row(Tab :: table(), RowIndex :: [integer()]) -> {ok, Row :: tuple()} | undefined

types:

Tab ::= atom()
RowIndex ::= [integer()]
Row ::= record(Tab)

reads a row by its SNMP index. that index is specified as an SNMP Object Identifier โ€” literally a list of integers. ๐Ÿงš

snmp_open_table(Tab :: table(), Snmp :: snmp_struct()) -> ok

types:

Tab ::= atom()
SnmpStruct ::= [{key, type()}]
type() ::= type_spec() | {type_spec(), type_spec(), ...}
type_spec() ::= fix_string | string | integer

okay this one's kind of a big deal: you can set up a direct one-to-one mapping between Mnesia tables and SNMP tables. a lot of telecommunication applications are controlled and monitored by the SNMP protocol, and this Mnesiaโ†”SNMP connection makes achieving that mapping simple and convenient. lowkey the whole point ๐Ÿ’…

the SnmpStruct argument is a list of SNMP information. currently the only information needed is info about the key types in the table. multiple keys cannot be handled in Mnesia, but many SNMP tables do have multiple keys โ€” so here's the convention: if a table has multiple keys, those keys must always be stored as a tuple of the keys. info about the key types is specified as a tuple of atoms describing the types. the only significant type is fix_string, which means a string has a fixed size. periodt.

for example, this next line causes table person to be ordered as an SNMP table:

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

now consider this schema for a table of company employees โ€” each employee is identified by department number and name, and 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. ๐ŸŽ€

there's also an option to have table columns that are not visible through the SNMP protocol. those columns have to be the last columns of the table. in the previous example, the SNMP table could have the department and name columns only โ€” the application could then use the telno column internally, but it would not be visible to the SNMP managers. sneaky but legal ๐Ÿ™ˆ

๐Ÿ’€ in a table monitored by SNMP, all elements must be integers, strings, or lists of integers. no exceptions.

when a table is SNMP ordered, modifications are more expensive than usual โ€” O(logN). also, more memory is used. the price of fame honestly.

also notice: only the lexicographical SNMP ordering is implemented in Mnesia, not the actual SNMP monitoring. read that twice bestie, it matters ๐Ÿซถ

start() -> result()

Mnesia startup is asynchronous. the call mnesia:start() returns the atom ok and then starts initializing the different tables. depending on the size of the database this can take some time, and as the application programmer you must wait for the tables your application needs before they can be used. you do that with mnesia:wait_for_tables/2. no skipping ahead ๐Ÿงš

the startup procedure for a set of Mnesia nodes is a fairly complicated operation, ngl. 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 info about those, 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. trust but verify ๐Ÿ’–

each schema has a unique cookie, which you can regard as a unique schema identifier. that 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 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. options on options.

stop() -> stopped | {error, term()}

stops Mnesia locally on the current node. local only, bestie.

application:stop(mnesia) can also be used. ๐ŸŽ€

subscribe(What) -> {ok, node()} | {error, Reason :: term()}

types:

What = system | activity | {table, table(), simple | detailed}

ensures that a copy of all events of type EventCategory gets sent to the caller. the available event types are described in the User's Guide. subscription era ๐Ÿ’Œ

sync_dirty(Fun) -> Res | no_return()

sync_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()

types:

Fun = fun((...) -> Res)

calls the Fun in a context that is not protected by a transaction. the Mnesia function calls performed inside Fun are mapped to the corresponding dirty functions. it's 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 Fun returns. for details, see mnesia:activity/4 and the User's Guide. sync > async, sorry not sorry ๐Ÿ”ฅ

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's a power outage โ€” see dump_log/0. plug in a UPS, love u ๐Ÿ’œ

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:

Fun = fun((...) -> Res)
Retries = integer() >= 0 | infinity

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 one process overloading a database on another node. be considerate, share the server ๐Ÿซถ

system_info(Iterm :: term()) -> Info :: term()

returns information about the Mnesia system, like transaction statistics, db_nodes, and configuration parameters. the valid keys are as follows:

  • all. returns a list of all local system information. each element is a {InfoKey, InfoVal} tuple.
๐Ÿ™ˆ heads up: new InfoKeys can be added and old undocumented InfoKeys can be removed without notice. no cap, don't build your whole life on them.
  • access_module. returns the name of the module that is configured to be the activity access callback module.
  • auto_repair. returns true or false to indicate whether Mnesia is configured to start the auto-repair facility on corrupted disc files.
  • backup_module. returns the name of the module that is configured to be the backup callback module.
  • checkpoints. returns a list of the names of the checkpoints currently active on this node.
  • event_module. returns the name of the module that is the event handler callback module.
  • db_nodes โ€” gives you the nodes that make up the persistent database. Disc-less nodes only show up in that list if they've explicitly been added to the schema (like, with mnesia:add_table_copy/3, you know?). Cute detail: you can call this one even if Mnesia isn't running yet. โœจ
  • debug โ€” the current debug level of Mnesia. that's it, that's the info ๐Ÿ’…
  • directory โ€” the name of the Mnesia directory. Also callable while Mnesia is not yet running, slay.
  • dump_log_load_regulation โ€” a boolean telling you if Mnesia is configured to regulate the dumper process load.
Heads up bestie: this feature is temporary and will be removed in future releases. โš ๏ธ
  • dump_log_time_threshold โ€” the time threshold for transaction log dumps, in milliseconds.
  • dump_log_update_in_place โ€” a boolean telling you whether Mnesia is set up to do the updates directly in the Dets files, or whether the updates get done in a copy of the Dets files instead.
  • dump_log_write_threshold โ€” the write threshold for transaction log dumps, given as the number of writes to the transaction log.
  • extra_db_nodes โ€” a list of extra db_nodes to be contacted at startup.
  • fallback_activated โ€” true if a fallback is activated, otherwise false.
  • held_locks โ€” a list of all the locks held by the local Mnesia lock manager. all of 'em. ๐Ÿ”’
  • is_running โ€” returns yes or no to say whether Mnesia is running. It can also return starting or stopping. And yes, you can call it even if Mnesia isn't running yet.
  • local_tables โ€” a list of every table configured to reside locally.
  • lock_queue โ€” a list of all the transactions queued up for execution by the local lock manager.
  • log_version โ€” the version number of the Mnesia transaction log format.
  • master_node_tables โ€” a list of all tables that have at least one master node.
  • protocol_version โ€” the version number of the Mnesia inter-process communication protocol.
  • running_db_nodes โ€” a list of nodes where Mnesia is currently running. You can call this even if Mnesia isn't running yet, but then it's got slightly different semantics, so pay attention ๐Ÿ‘€

If Mnesia is down on the local node, the function returns those other db_nodes and extra_db_nodes that happen to be operational at that moment.

If Mnesia is started, it returns those nodes that Mnesia on the local node is fully connected to. Only the nodes that Mnesia has exchanged schema information with get included as running_db_nodes. After the merge of schemas, the local Mnesia system is fully operable and apps can go access remote replicas. Before the schema merge, Mnesia only operates locally. And sometimes there are more nodes in the running_db_nodes list than all db_nodes and extra_db_nodes put together. weird? yeah. iconic? also yeah. ๐Ÿฆ‹

  • schema_location โ€” the initial schema location.
  • subscribers โ€” a list of local processes currently subscribing to system events.
  • tables โ€” a list of all locally known tables.
  • transactions โ€” a list of all currently active local transactions.
  • transaction_failures โ€” a number showing how many transactions have failed since Mnesia was started.
  • transaction_commits โ€” a number showing how many transactions have terminated successfully since Mnesia was started. ๐Ÿ’–
  • transaction_restarts โ€” a number showing how many transactions have been restarted since Mnesia was started.
  • transaction_log_writes โ€” a number showing how many write operations have been performed to the transaction log since startup.
  • use_dir โ€” a boolean showing whether the Mnesia directory is used or not. Can be started even if Mnesia is not yet running.
  • version โ€” the current version number of Mnesia. ๐ŸŽ€

โœจ table/1,2 โœจ

table(Tab :: table()) -> qlc:query_handle()

table(Tab :: table(), Options) -> qlc:query_handle()

Types:

Options = Option | [Option]
Option = MnesiaOpt | QlcOption
MnesiaOpt =
    {traverse, SelectOp} |
    {lock, lock_kind()} |
    {n_objects, integer() >= 0}
SelectOp = select | {select, ets:match_spec()}
QlcOption = {key_equality, '==' | '=:='}

Returns a Query List Comprehension (QLC) query handle โ€” peep the qlc(3erl) manual page over in STDLIB if you wanna go deeper. The qlc module implements a query language that can use Mnesia tables as data sources. Calling mnesia:table/1,2 is literally the way you make the mnesia table Tab usable to QLC. ๐Ÿงš

Option can hold Mnesia options or QLC options. Mnesia recognizes these ones (anything else gets forwarded to QLC, no questions asked):

  • {lock, Lock} โ€” where Lock can be read or write. Default is read.
  • {n_objects,Number} โ€” where n_objects specifies (roughly!) the number of objects returned from Mnesia to QLC. Queries to remote tables can need a bigger chunk to cut down on network overhead. By default, 100 objects at a time are returned.
  • {traverse, SelectMethod} โ€” where traverse determines the method used to traverse the whole table (if that's needed). Default method is select.

There are two alternatives for select:

  • select โ€” the table gets traversed by calling mnesia:select/4 and mnesia:select/1. The match specification (the second argument of select/3) is assembled by QLC: simple filters get translated into equivalent match specifications. More complicated filters need to be applied to all objects returned by select/3, given a match specification that matches all objects.
  • {select, MatchSpec} โ€” same deal as select, the table gets traversed by calling mnesia:select/3 and mnesia:select/1. The difference is that the match specification is explicitly given. This is how you state match specifications that can't easily be expressed within the syntax QLC provides. ๐Ÿ’…

๐ŸŒธ table_info/2 ๐ŸŒธ

table_info(Tab :: table(), Item :: term()) -> Info :: term()

table_info/2 takes two arguments. First one's the name of a Mnesia table. Second one's one of these keys:

  • all โ€” a list of all local table information. Each element is a {InfoKey, ItemVal} tuple.
Bestie, real talk: new InfoItems can be added and old undocumented InfoItems can be removed without notice. So don't get too attached. ๐Ÿ˜ญ
  • access_mode โ€” the access mode of the table. It can be read_only or read_write.
  • arity โ€” the arity of records in the table, as specified in the schema.
  • attributes โ€” the table attribute names specified in the schema.
  • checkpoints โ€” the names of the currently active checkpoints that involve this table on this node.
  • cookie โ€” a table cookie, which is a unique system-generated identifier for the table. The cookie is used internally to make sure two different table definitions using the same table name can't accidentally get intermixed. The cookie is generated when the table is created initially. ๐Ÿ“
  • disc_copies โ€” the nodes where a disc_copy of the table resides, according to the schema.
  • disc_only_copies โ€” the nodes where a disc_only_copy of the table resides, according to the schema.
  • index โ€” the list of index position integers for the table.
  • load_node โ€” the name of the node that Mnesia loaded the table from. The structure of the returned value is unspecified, but it can be useful for debugging purposes.
  • load_order โ€” the load order priority of the table. It's an integer and defaults to 0 (zero).
  • load_reason โ€” the reason Mnesia decided to load the table. The structure of the returned value is unspecified, but it can be useful for debugging purposes.
  • local_content โ€” true or false to show whether the table is configured to have locally unique content on each node.
  • master_nodes โ€” the master nodes of a table.
  • memory โ€” for ram_copies and disc_copies tables, the number of words allocated in memory to the table on this node. For disc_only_copies tables, the number of bytes stored on disc is returned.
  • ram_copies โ€” the nodes where a ram_copy of the table resides, according to the schema.
  • record_name โ€” the record name, common for all records in the table.
  • size โ€” the number of records inserted in the table.
  • snmp โ€” the SNMP struct. [] means the table currently has no SNMP properties.
  • storage_type โ€” the local storage type of the table. It can be disc_copies, ram_copies, disc_only_copies, or the atom unknown. unknown is returned for all tables that only reside remotely.
  • subscribers โ€” a list of local processes currently subscribing to local table events that involve this table on this node.
  • type โ€” the table type, which is bag, set, or ordered_set.
  • user_properties โ€” the user-associated table properties of the table. It's a list of the stored property records. ๐Ÿ’œ

okay so the table-meta tour is still rolling, and these last keys are giving serious backstage-pass energy ๐ŸŽŸ๏ธโœจ

  • version โ€” returns the current version of the table definition. The table version is incremented when the table definition is changed. It can be incremented directly when it has been changed in a schema transaction, or when a committed table definition is merged with table definitions from other nodes during startup. ๐Ÿ‘‘
  • where_to_read โ€” returns the node where the table can be read. If the value nowhere is returned, either the table is not loaded or it resides at a remote node that is not running. ๐Ÿซฅ
  • where_to_write โ€” returns a list of the nodes that currently hold an active replica of the table. ๐Ÿ’…
  • wild_pattern โ€” returns a structure that can be given to the various match functions for a certain table. It's a record tuple where all record fields have value '_'. ๐ŸŽ€

transaction is the main-character โ€œdo a whole bunch of table stuff as one atomic unitโ€ API, and it comes in four flavors:

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:

Fun = fun((...) -> Res)
Retries = integer() >= 0 | infinity

It 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 and therefore the Fun shall not have any side effects such as waiting for specific messages. This function attempts a restart as many times as specified in Retries.

โš ๏ธ Retries must be an integer greater than 0 or the atom infinity, default is infinity. Mnesia uses exit exceptions to signal that a transaction needs to be restarted, thus a Fun must not catch exit exceptions with reason {aborted, term()}. ๐Ÿ’€

transform_table(Tab :: table(), Fun, NewA :: [Attr], RecName) ->
                   t_result(ok)

Types:

RecName = Attr = atom()
Fun =
    fun((Record :: tuple()) -> Transformed :: tuple()) |
ignore

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 it's included as a possibility for the user to do their 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:

Attr = atom()
Fun =
    fun((Record :: tuple()) -> Transformed :: tuple()) |
ignore

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:

Fun = fun((Items, Acc) -> {Items, Acc})

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. ๐ŸŒธ

  • SourceMod and TargetMod are the names of the modules that actually access the backup media.
  • Source and Target are opaque data used exclusively by modules SourceMod and TargetMod to initialize the backup media.
  • Acc is an initial accumulator value.
  • Fun(BackupItems, Acc) is applied to each item in the backup. The Fun must return a tuple {BackupItems,NewAcc}, where BackupItems is a list of valid backup items, and NewAcc is a new accumulator value. The returned backup items are written in the target backup.
  • LastAcc is the last accumulator value. This is the last NewAcc value that was returned by Fun. ๐Ÿ’–

uninstall_fallback() -> result()

Calls the function mnesia:uninstall_fallback([{scope, global}]). โœจ

uninstall_fallback(Args) -> result()

Types:

Args = [{mnesia_dir, Dir :: string()}]

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:

  • {module, BackupMod}. For semantics, see mnesia:install_fallback/2.
  • {scope, Scope}. For semantics, see mnesia:install_fallback/2.
  • {mnesia_dir, AlternateDir}. For semantics, see mnesia:install_fallback/2.

unsubscribe(What) -> {ok, node()} | {error, Reason :: term()}

Types:

What = system | activity | {table, table(), simple | detailed}

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). ๐Ÿ‘‘

๐Ÿ’– CONFIGURATION PARAMETERS ๐Ÿ’–

Okay so Mnesia reads the following application configuration parameters, bestie โ€” it's giving settings menu for your whole database era. ๐ŸŽ€

  • -mnesia access_module Module โ€” tells Mnesia which activity access callback module to use. Default is mnesia. Slay.
  • -mnesia auto_repair true | false โ€” this flag controls whether Mnesia automatically tries to repair files that have not been properly closed. Default is true.
  • -mnesia backup_module Module โ€” the name of the Mnesia backup callback module. Default is mnesia_backup.
  • -mnesia debug Level โ€” controls the debug level of Mnesia. The possible Level values are giving:
    • none: no trace outputs. This is the default.
    • verbose: activates tracing of important debug events. These events generate {mnesia_info, Format, Args} system events. Processes can subscribe to these events with mnesia:subscribe/1. The events are always sent to the Mnesia event handler.
    • debug: activates all events at the verbose level plus full trace of all debug events. These debug events generate {mnesia_info, Format, Args} system events. Processes can subscribe to these events with mnesia:subscribe/1. The events are always sent to the Mnesia event handler. On this debug level, the Mnesia event handler starts subscribing to updates in the schema table.
    • trace: activates all events at the debug level. On this level, the Mnesia event handler starts subscribing to updates on all Mnesia tables. This level is intended only for debugging small toy systems, as many large events can be generated. ๐Ÿ’€
    • false: an alias for none.
    • true: an alias for debug.
  • -mnesia core_dir Directory โ€” the name of the directory where Mnesia core files get stored, or false. Setting it implies that also RAM-only nodes generate a core file if a crash occurs. ๐Ÿซถ
  • -mnesia dc_dump_limit Number โ€” controls how often disc_copies tables are dumped from memory. Tables are dumped when filesize(Log) > (filesize(Tab)/Dc_dump_limit). Lower values reduce CPU overhead but increase disk space and startup times. Default is 4.
  • -mnesia dir Directory โ€” the name of the directory where all Mnesia data is stored. The directory name must be unique for the current node. Two nodes must never share the same Mnesia directory โ€” the results are unpredictable. No cap, do not do this. ๐Ÿšจ
  • -mnesia dump_disc_copies_at_startup true | false โ€” if set to false, this disables the dumping of disc_copies tables during startup while tables are being loaded. The default is true.
  • -mnesia dump_log_load_regulation true | false โ€” controls if log dumps are to be performed as fast as possible, or if the dumper is to do its own load regulation. Default is false.
Heads up: this feature is temporary and will be removed in a future release.
  • -mnesia dump_log_update_in_place true | false โ€” controls if log dumps are performed on a copy of the original data file, or if the log dump is performed on the original data file. Default is true.
  • -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 1000 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. โฐ
  • -mnesia event_module Module โ€” the name of the Mnesia event handler callback module. Default is mnesia_event.
  • -mnesia extra_db_nodes Nodes โ€” specifies a list of nodes, in addition to the ones found in the schema, with which Mnesia is also to establish contact. Default is [] (empty list).
  • -mnesia fallback_error_function {UserModule, UserFunc} โ€” specifies a user-supplied callback function, which is called if a fallback is installed and Mnesia goes down on another node. Mnesia calls the function with one argument, the name of the dying node, for example, UserModule:UserFunc(DyingNode). Mnesia must be restarted, otherwise the database can be inconsistent. The default behavior is to terminate Mnesia. ๐Ÿ˜ญ
  • -mnesia max_wait_for_decision Timeout โ€” specifies how long Mnesia waits for other nodes to share their knowledge about the outcome of an unclear transaction. By default, Timeout is set to the atom infinity. This implies that if Mnesia upon startup detects a "heavyweight transaction" whose outcome is unclear, the local Mnesia waits until Mnesia is started on some (in the worst case all) of the other nodes that were involved in the interrupted transaction. This is a rare situation, but if it occurs, Mnesia does not guess if the transaction on the other nodes was committed or terminated. Mnesia waits until it knows the outcome and then acts accordingly. 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. Fatal. Like, actually fatal. ๐Ÿ’€
  • -mnesia no_table_loaders NUMBER โ€” specifies the number of parallel table loaders during start. More loaders can be good if the network latency is high or if many tables contain few records. Default is 2.
  • -mnesia send_compressed Level โ€” specifies the level of compression to be used when copying a table from the local node to another one. Default is 0. 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. ๐Ÿฆ‹
  • -mnesia max_transfer_size Number โ€” specifies the estimated size in bytes of a single packet of data to be used when copying a table from the local node to another one. Default is 64000.
  • -mnesia schema_location Loc โ€” controls where Mnesia looks for its schema. Parameter Loc can be one of the following atoms:
    • disc: mandatory disc. The schema is assumed to be located in the Mnesia directory. If the schema cannot be found, Mnesia refuses to start. This is the old behavior.
    • ram: mandatory RAM. The schema resides in RAM only. At startup, a tiny new schema is generated. This default schema only contains the definition of the schema table and only resides on the local node. Since no other nodes are found in the default schema, configuration parameter extra_db_nodes must be used to let the node share its table definitions with other nodes. Parameter extra_db_nodes can also be used on disc based nodes.
    • opt_disc: optional disc. The schema can reside on disc or in RAM. If the schema is found on disc, Mnesia starts as a disc-based node and the storage type of the schema table is disc_copies. If no schema is found on disc, Mnesia starts as a disc-less node and the storage type of the schema table is ram_copies. Default value for the application parameter is opt_disc.

The check order is: SASL application parameters first, then command-line flags, and finally the default value gets chosen. Periodt. ๐Ÿ’…


๐ŸŒˆ SEE ALSO ๐ŸŒˆ


That's the config section, bestie โ€” go forth and tune your Mnesia era. ๐Ÿ’…โœจ Source/version: Ericsson AB, mnesia 4.21.4.2. Page: mnesia(3erl). Date: not shown in this footer, so I'm not inventing one โ€” no cap ๐Ÿ˜ญ๐Ÿซถ

๐Ÿ“ฆ where this page comes from