mnesia(3)

πŸ“¦
version 29.0.6 Β· 3 versions
, in ubuntu stonking

πŸ’– NAME πŸ’–

mnesia β€” A distributed key-value DBMS. Also, bestie, this is the Erlang Module Definition for it. πŸ—„οΈβœ¨


🌸 DESCRIPTION 🌸

okay so listen, Mnesia comes with some absolutely iconic capabilities that you're gonna be obsessed with. Here's the lineup:

  • relational/object hybrid data model that is suitable for telecommunications applications. πŸ’…
  • DBMS query language, Query List Comprehension (QLC) as an add-on library. πŸ”₯
  • Persistence. Tables can be coherently kept on disc and in the main memory. πŸ’Ύ
  • Replication. 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. ⚑
  • Schema manipulation routines. The DBMS can be reconfigured at runtime without stopping the system. πŸ”§

This Reference Manual describes the Mnesia API. That 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 info about the query notation, check 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. Here are some of the properties associated with each table:

  • type. Each table can have set, ordered_set, or bag semantics. Notice 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 info 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:foldl/4, mnesia:foldr/4, mnesia:next/2, mnesia:prev/2, and mnesia:snmp_get_next_index/2, Mnesia compensates for every written or deleted record, which can reduce the performance. 😬

If possible, avoid writing or deleting records in the same transaction before iterating over the table. πŸ™…β€β™€οΈ


βš™οΈ Configuration Parameters βš™οΈ

Mnesia reads these application configuration parameters, bestie:

  • -mnesia access_module Module β€” The name of the Mnesia activity access callback module. Default is mnesia. πŸ’–
  • -mnesia auto_repair true | false β€” This flag controls if 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 values are as follows:
    • 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 is 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. 🚨
  • -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.

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 the "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. Which can absolutely lead to a situation where the transaction is committed on some nodes and terminated on other nodes, bestie. And if that transaction is a schema transaction? The inconsistency can be fatal. πŸ’€

  • -mnesia no_table_loaders NUMBER β€” how many parallel table loaders you get during start. More loaders can be good if the network latency is high, or if you've got a ton of tables with only a few records in them. Default is 2.
  • -mnesia send_compressed Level β€” the level of compression 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. And before you set it to anything non-zero, please please please make sure the remote nodes understand this configuration. πŸ™ˆ

  • -mnesia max_transfer_size Number β€” 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 goes looking for its schema. Loc can be one of these 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.

First, the SASL application parameters are checked, then the command-line flags are checked, and finally, the default value is chosen. that's the order of operations and we respect it πŸ’…


πŸ” See Also

application, dets, disk_log, ets, qlc 🌸


🧬 DATA TYPES

okay so here's the whole type situation, and yes I'm listing every single one because you deserve the full picture and also I refuse to skip πŸ’–

  • activity() β€” every way you're allowed to run stuff:
activity() ::
          ets | async_dirty | sync_dirty | transaction |
          sync_transaction |
          {transaction, Retries :: non_neg_integer()} |
          {sync_transaction, Retries :: non_neg_integer()}.
  • change_frag_prop() β€” the lil list of ways a fragmented table's properties can change:
change_frag_prop() ::
          deactivate |
          {activate, [frag_prop()]} |
          {add_frag, [node()] | [{node(), non_neg_integer()}]} |
          del_frag |
          {add_node, node()} |
          {del_node, node()}.
  • config_key() β€” the two things that count as a config key:
config_key() :: extra_db_nodes | dc_dump_limit.
  • config_result() β€” what comes back from a config call:
config_result() :: {ok, config_value()} | {error, term()}.
  • config_value() β€” either a list of nodes or a number, that's the whole vibe:
config_value() :: [node()] | number().
  • create_option() β€” the big one, everything you can hand over when you make a table ✨:
create_option() ::
          {access_mode, read_write | read_only} |
          {attributes, [atom()]} |
          {disc_copies, [node()]} |
          {disc_only_copies, [node()]} |
          {index, [index_attr()]} |
          {load_order, non_neg_integer()} |
          {majority, boolean()} |
          {ram_copies, [node()]} |
          {record_name, atom()} |
          {snmp, SnmpStruct :: term()} |
          {storage_properties,
           [{Backend :: module(), [BackendProp :: _]}]} |
          {type, set | ordered_set | bag} |
          {local_content, boolean()} |
          {user_properties, proplists:proplist()} |
          {frag_properties, [frag_prop()]}.
  • debug_level() β€” four whole levels of debugging loudness:
debug_level() :: none | verbose | debug | trace.
  • frag_prop() β€” the properties a fragmented table can carry around:
frag_prop() ::
          {n_fragments, pos_integer()} |
          {node_pool, [node()]} |
          {n_ram_copies, non_neg_integer()} |
          {n_disc_copies, non_neg_integer()} |
          {n_disc_only_copies, non_neg_integer()} |
          {foreign_key, undefined | {table(), atom()}} |
          {hash_module, atom()} |
          {hash_state, term()}.
  • index_attr() β€” the ways you can point at an attribute you want indexed:
index_attr() :: atom() | non_neg_integer() | {atom()}.
  • lock_kind() β€” the two flavours of lock:
lock_kind() :: write_locks() | read_locks().
  • read_locks() β€” there is exactly one read lock and it is read. iconic:
read_locks() :: read.
  • result() β€” the classic ok or {error, Reason} situation:
result() :: ok | {error, Reason :: term()}.
  • select_continuation() β€” type-wise it's literally just term():
select_continuation() :: term().
  • snmp_struct() πŸ“:
snmp_struct() :: [{atom(), snmp_type() | tuple_of(snmp_type())}].
  • snmp_type():
snmp_type() :: fix_string | string | integer.
  • storage_type() β€” the three storage types, no more, no less:
storage_type() :: ram_copies | disc_copies | disc_only_copies.
  • t_result(Res) β€” transaction result energy, Res is whatever you plugged in:
t_result(Res) :: {atomic, Res} | {aborted, Reason :: term()}.
  • table() β€” a table is just an atom and I think that's beautiful:
table() :: atom().
  • tuple_of(_T) β€” a tuple of _T. it's giving tuple():
tuple_of(_T) :: tuple().
  • write_locks() β€” two write locks, write and sticky_write:
write_locks() :: write | sticky_write.

πŸ› οΈ FUNCTIONS

πŸ’₯ abort(Reason :: term()) -> no_return().

abort(Reason :: term()) -> no_return().

Terminate the current transaction.

It makes the transaction silently return the tuple {aborted, Reason}. Here's the thing though: termination of a Mnesia transaction means an exception gets thrown to an enclosing catch. So the expression catch mnesia:abort(x) does not terminate the transaction. yeah. i know. 🌸

πŸŽ€ activate_checkpoint([Arg])

activate_checkpoint([Arg]) ->
                             {ok, Name, [node()]} |
                             {error, Reason :: term()}
                             when
                                 Arg ::
                                     {name, Name} |
                                     {max, [table()]} |
                                     {min, [table()]} |
                                     {allow_remote, boolean()} |
                                     {ram_overrides_dump, boolean()}.

Activate a checkpoint. ✨

A checkpoint is a consistent view of the system. A checkpoint can be activated on a set of tables. This checkpoint can then be traversed and 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. it's a little frozen moment in time, love that for us

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(AccessContext, Fun)

activity(AccessContext, Fun) -> t_result(Res) | Res
                     when
                         AccessContext :: activity(),
                         Fun :: fun(() -> Res).

Execute Fun in AccessContext.

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(AccessContext, Fun, Args, AccessMod)

activity(AccessContext, Fun, Args, AccessMod) ->
                     t_result(Res) | Res
                     when
                         AccessContext :: activity(),
                         Args :: [Arg :: _],
                         Fun :: fun((...) -> Res),
                         AccessMod :: atom().

Execute Fun in AccessContext.

Executes the functional object Fun with argument Args.

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

  • transaction β€” short for {transaction, infinity}
  • {transaction, Retries} β€” calls mnesia:transaction(Fun, Args, Retries). Notice that the result from Fun is returned if the transaction is successful (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). Notice that the result from Fun is returned if the transaction is successful (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).
Not me needing to point this out but this one is important: this function (mnesia:activity/4) differs in an important way from the functions mnesia:transaction/3, mnesia:sync_transaction/3, mnesia:async_dirty/2, mnesia:sync_dirty/2, and mnesia:ets/2. Argument AccessMod is the name of a callback module, which implements the mnesia_access behavior. πŸ’…

πŸ” The level of indirection, bestie

Mnesia forwards calls to the following functions:

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

…straight over to the corresponding:

  • AccessMod:lock(ActivityId, Opaque, LockItem, LockKind)
  • AccessMod:write(ActivityId, Opaque, Tab, Rec, LockKind)
  • AccessMod:delete(ActivityId, Opaque, Tab, Key, LockKind)
  • AccessMod:delete_object(ActivityId, Opaque, Tab, RecXS, LockKind)
  • AccessMod:read(ActivityId, Opaque, Tab, Key, LockKind)
  • AccessMod:match_object(ActivityId, Opaque, Tab, Pattern, LockKind)
  • AccessMod:all_keys(ActivityId, Opaque, Tab, LockKind)
  • AccessMod:first(ActivityId, Opaque, Tab)
  • AccessMod:last(ActivityId, Opaque, Tab)
  • AccessMod:prev(ActivityId, Opaque, Tab, Key)
  • AccessMod:next(ActivityId, Opaque, Tab, Key)
  • AccessMod:index_match_object(ActivityId, Opaque, Tab, Pattern, Attr, LockKind)
  • AccessMod:index_read(ActivityId, Opaque, Tab, SecondaryKey, Attr, LockKind)
  • AccessMod:table_info(ActivityId, Opaque, Tab, InfoItem)
  • AccessMod:foldl(ActivityId, Opaque, Fun, Acc, Tab, LockKind)
  • AccessMod:foldr(ActivityId, Opaque, Fun, Acc, Tab, LockKind)
  • AccessMod:select(ActivityId, Opaque, Tab, Spec, LockKind)
  • AccessMod:select(ActivityId, Opaque, Tab, Spec, NObjects, LockKind)
  • AccessMod:select_cont(ActivityId, Opaque, Cont)
  • AccessMod:select_reverse(ActivityId, Opaque, Tab, Spec, LockKind)
  • AccessMod:select_reverse(ActivityId, Opaque, Tab, Spec, NObjects, LockKind)
  • AccessMod:clear_table(ActivityId, Opaque, Tab, Obj)

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

Opaque is an opaque data structure that is internal to Mnesia. (iykyk? no bestie, literally nobody outside Mnesia knows. leave it alone πŸ’…)


🫢 add_table_copy(Tab, Node, Type) -> t_result(ok)

add_table_copy(Tab, Node, Type) -> t_result(ok)
    when
        Tab :: table(),
        Node :: node(),
        Type :: storage_type().

Copy a table to a remote node. πŸ’–

This one 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. So like, for example, the following call ensures that a disc replica of the person table also exists at node Node:

mnesia:add_table_copy(person, Node, disc_copies)

This function can also be used to add a replica of the table named schema. ✨ (yes the schema table is a table too, she's just built different πŸ‘‘)


πŸŽ€ add_table_index(Tab, I) -> t_result(ok)

add_table_index(Tab, I) -> t_result(ok)
    when Tab :: table(), I :: index_attr().

Add table index. πŸ”

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

mnesia:add_table_index(person, age)

Indexes do not come for free, bestie. 😭 They occupy space that is proportional to the table size, and they cause insertions into the table to execute slightly slower. It's giving "you gotta spend money to make money" but for memory.


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

Return all keys in a table.

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


🌈 async_dirty(Fun, [Arg :: _]) -> Res | no_return()

async_dirty(Fun, [Arg :: _]) -> Res | no_return()
    when Fun :: fun((...) -> Res).

Call 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, no local transaction storage, and no commit protocols involved. Checkpoint retainers and indexes are updated, but they are updated dirty. As for normal mnesia:dirty_* operations, the operations are performed semi-asynchronously. For details, see mnesia:activity/4 and the User's Guide.

The Mnesia tables can be manipulated without using transactions. This has some serious disadvantages, but is considerably faster, as the transaction manager is not involved and no locks are set. A dirty operation does, however, guarantee a certain level of consistency, and the dirty operations cannot return garbled records. All dirty operations provide location transparency to the programmer, and a program does not have to be aware of the whereabouts of a certain table to function. πŸ¦‹

Notice that it is more than ten times more efficient to read records dirty than within a transaction. πŸ”₯

Depending on the application, it can be a good idea to use the dirty functions for certain operations. Almost all Mnesia functions that can be called within transactions have a dirty equivalent, which is much more efficient.

However, notice that there is a risk that the database can be left in an inconsistent state if dirty operations are used to update it. Dirty operations are only to be used for performance reasons when it is absolutely necessary. 😭 no cap, do not use these as your default, bestie.

Notice that calling (nesting) mnesia:[a]sync_dirty inside a transaction-context inherits the transaction semantics. 🫢


πŸ’Ύ backup(Dest :: term(), BackupMod :: module()) -> result().

Back up all tables in the database. πŸŽ€

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


πŸ’Ύ backup_checkpoint(Name, Dest, BackupMod) -> result()

backup_checkpoint(Name, Dest, BackupMod) -> result()
    when
        Name :: term(),
        Dest :: term(),
        BackupMod :: module().

Back up all tables in a checkpoint. 🫢

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

change_config(Config, Value) -> ReturnValue
    when
        Config :: config_key(),
        Value :: config_value(),
        ReturnValue :: config_result().

Change a configuration setting. πŸ”§

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. πŸ’€

πŸ”“ change_table_access_mode(Tab :: table(), AccessMode) -> t_result(ok)

change_table_access_mode(Tab :: table(), AccessMode) ->
                                 t_result(ok)
                                 when
                                     AccessMode ::
                                         read_only | read_write.

Change table access mode. πŸ’…

AccessMode is by default the atom read_write but it can also be set to the atom read_only. If AccessMode is set to read_only, updates to the table cannot be performed. At startup, Mnesia always loads read_only tables locally regardless of when and if Mnesia is terminated on other nodes. 🌈


πŸ”„ change_table_copy_type(Tab :: table(), Node :: node(), To :: storage_type()) -> t_result(ok).

change_table_copy_type(Tab :: table(),
                            Node :: node(),
                            To :: storage_type()) ->
                               t_result(ok).

Change the storage type of a table. ✨

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

change_table_frag(Tab :: table(), FragProp :: change_frag_prop()) ->
                                  t_result(ok).

Okay bestie, this function is literally here to reconfigure table fragment properties, no cap. Argument FragProp should have one of these values:

  • {activate, FragProps} β€” activates the fragmentation properties of an existing table. FragProps is either to contain {node_pool, Nodes} or be empty. That's it, that's the vibe.
  • deactivate β€” deactivates the fragmentation properties of a table. The number of fragments must be 1. No other table can refer to this table in its foreign key. It's giving "you're on your own, babe."
  • {add_frag, NodesOrDist} β€” adds a fragment to a fragmented table. All records in one of the old fragments are rehashed and about half of them are moved to the new (last) fragment. All other fragmented tables, which refer to this table in their foreign key, automatically get a new fragment. Also, their records are dynamically rehashed in the same manner as for the main table.

Argument NodesOrDist can either be a list of nodes or the result from the function mnesia:table_info(Tab, frag_dist). Argument NodesOrDist is assumed to be a sorted list with the best nodes to host new replicas first in the list. The new fragment gets the same number of replicas as the first fragment (see n_ram_copies, n_disc_copies, and n_disc_only_copies in Fragmentation Properties). The NodesOrDist list must at least contain one element for each replica that needs to be allocated.

  • del_frag β€” deletes a fragment from a fragmented table. All records in the last fragment are moved to one of the other fragments. All other fragmented tables, which refer to this table in their foreign key, automatically lose their last fragment. Also, their records are dynamically rehashed in the same manner as for the main table.
  • {add_node, Node} β€” adds a node to node_pool. The new node pool affects the list returned from the function mnesia:table_info(Tab, frag_dist).
  • {del_node, Node} β€” deletes a node from node_pool. The new node pool affects the list returned from the function mnesia:table_info(Tab, frag_dist).

That's the whole thing. πŸ’…


✨ change_table_load_order/2

change_table_load_order(Tab :: table(), Order) -> t_result(ok)
                                        when Order :: non_neg_integer().

Change table load order. 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. So if you want your faves to show up first, set that integer high, bestie. πŸ”₯


✨ change_table_majority/2

change_table_majority(Tab :: table(), Majority :: boolean()) ->
                                      t_result(ok).

Change table majority. Majority must be a boolean. Default is false. When true, a majority of the table replicas must be available for an update to succeed. When used on fragmented tables, Tab must be the base table name. Directly changing the majority setting on individual fragments is not allowed. So don't even try it, okay? 🚫


✨ clear_table/1

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

Delete all entries in the table Tab. That's it. It's giving "clear the group chat" energy. πŸ’€


✨ create_schema/1

create_schema(DiscNodes :: [node()]) -> result().

Create a new schema on the specified nodes.

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

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

Notice that only nodes with disc are to be included in DiscNodes. Disc-less nodes, that is, nodes where all tables including the schema only resides in RAM, must not be included.


✨ create_table/2

create_table(Name :: table(), Opts :: [create_option()]) ->
                             t_result(ok).

Create a table.

Creates a Mnesia table called Name according to argument Opts. 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} β€” is 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.
  • {user_properties, PropList} β€” where PropList is a list of user-defined properties associated with the table. The property is a tuple where the first element is the property key. These properties can be read and modified using mnesia:read_table_property/2, mnesia:write_table_property/2, and mnesia:delete_table_property/2. Default is [].
  • {frag_properties, FragProps} β€” where FragProps is a list of fragmentation properties for the table. See Fragmentation Properties for details on fragmentation options.

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. like, you can just hardcode the vibe in there if you want πŸ’…

mnesia:create_table/2 writes records into the table schema. This function, and all the other schema manipulation functions, are implemented with the normal transaction management system. Which means β€” and this is the iconic part β€” schema updates are performed on all nodes in an atomic manner. no half-updated mess, bestie. it's all or nothing. periodt ✨


πŸ’– FUNCTIONS (the saga continues) πŸ’–

πŸŽ€ deactivate_checkpoint(Name :: _) -> result().

Deactivate a checkpoint. bye babe 🫢

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(), Node :: node()) -> t_result(ok).

Delete the replica of table.

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

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 β€” no cap, you can't do this while it's running.

πŸŽ€ del_table_index(Tab, I) -> t_result(ok) when Tab :: table(), I :: index_attr().

Delete table index.

Deletes the index on attribute with name AttrName in a table.

πŸŽ€ delete(Tab :: table(), Key :: _, LockKind :: write_locks()) -> ok.

Delete 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. iykyk πŸ’…

πŸŽ€ delete_object(Tab :: table(), Rec :: tuple(), LockKind :: write_locks()) -> ok.

Delete a record.

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 β€” like, the whole thing, not just a lil piece πŸ™ˆ

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(DiscNodes :: [node()]) -> result().

Delete the schema on the given nodes.

Deletes a database created with mnesia:create_schema/1. mnesia:delete_schema/1 fails if any of the Erlang nodes given as DiscNodes 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. like fr fr think THREE times. this is not a drill πŸ’€

πŸŽ€ delete_table(Tab :: table()) -> t_result(ok).

Permanently delete all replicas of table Tab. permanent. forever. no takebacks πŸ‘‘

πŸŽ€ delete_table_property(Tab :: table(), PropKey :: term()) -> t_result(ok).

Delete a user-defined table property.

Deletes a user-defined property from a table if such property exists. The property is identified by its key. User-defined properties can be read with mnesia:read_table_property/2 and written with mnesia:write_table_property/2.

πŸŽ€ dirty_all_keys(Tab :: table()) -> [Key :: term()].

Dirty equivalent to mnesia:all_keys/1. 🧚 living on the edge, no transaction, no safety net

πŸŽ€ dirty_delete(Tab :: table(), Key :: _) -> ok.

Dirty equivalent to mnesia:delete/3.

πŸŽ€ dirty_delete_object(Tab :: table(), Record :: tuple()) -> ok.

Dirty equivalent to mnesia:delete_object/3.

πŸŽ€ dirty_first(Tab :: table()) -> Key :: term().

Return the key for the first record in a table.

Records in set or bag tables are not ordered. However, there is an ordering of the records that is unknown to the user. Therefore, a table can be traversed by this function with the function mnesia:dirty_next/2.

If there are no records in the table, this function returns the atom '$end_of_table'. It is therefore highly undesirable, but not disallowed, to use this atom as the key for any user records. 😬 like pls don't do that, it's giving chaos

πŸŽ€ dirty_index_match_object(Tab, Pattern, Attr) -> [Record] when Tab :: table(), Pattern :: tuple(), Attr :: index_attr(), Record :: tuple().

Dirty equivalent to mnesia:index_match_object/4.

πŸŽ€ dirty_index_read(Tab, Key, Attr) -> [Record] when Tab :: table(), Key :: term(), Attr :: index_attr(), Record :: tuple().

Dirty equivalent to mnesia:index_read/3.

πŸŽ€ dirty_last(Tab :: table()) -> Key :: term().

Return the key for the last record in a table.

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. same energy, different name πŸ¦‹

πŸŽ€ dirty_match_object(Tab, Pattern) -> [Record] when Tab :: table(), Pattern :: tuple(), Record :: tuple().

Dirty equivalent to mnesia:match_object/3.

πŸŽ€ dirty_next(Tab :: table(), Key :: _) -> NextKey :: term().

Return the next key in a table.

Traverses a table and performs operations on all records in the table. When the end of the table is reached, the special key '$end_of_table' is returned. Otherwise, the function returns a key that can be used to read the actual record. The behavior is undefined if another Erlang process performs write operations on the table while it is being traversed with the function mnesia:dirty_next/2. so like... don't do that. that's the vibe check failing πŸ’€

πŸŽ€ dirty_prev(Tab :: table(), Key :: _) -> PrevKey :: term().

Return the previous key in a table.

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

πŸŽ€ dirty_read(Tab :: table(), Key :: _) -> [tuple()].

Dirty equivalent to mnesia:read/3.

πŸŽ€ dirty_select(Tab, MatchSpec) -> [Match] when Tab :: table(), MatchSpec :: ets:match_spec(), Match :: term().

Dirty equivalent to mnesia:select/2.

πŸŽ€ dirty_select_reverse(Tab, MatchSpec) -> [Match] when Tab :: table(), MatchSpec :: ets:match_spec(), Match :: term().

Dirty equivalent to mnesia:select_reverse/2.

πŸŽ€ dirty_update_counter(Tab :: table(), Key :: _, Incr :: integer()) -> NewVal :: integer().

Dirty update of a counter record.

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. πŸ“ no negativity allowed in this house

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(Tab :: table(), Record :: tuple()) -> ok.

Dirty equivalent to mnesia:write/3.

πŸŽ€ dump_log() -> dumped.

Perform 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. let the system cook, bestie 😌

πŸŽ€ dump_tables([Tab :: table()]) -> t_result(ok).

Dump ram_copies tables to disc.

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

πŸŽ€ dump_to_textfile(File :: file:filename()) -> result() | error.

Dump local tables into a text file.

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. ✨ like it's cute for learning, not for your actual production data, okay??

πŸŽ€ error_description(Error) -> string() when Error :: {error, Reason} | {aborted, Reason} | Reason, Reason :: term().

Return a string describing a particular Mnesia error.

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. 😀 pick a lane
  • badarg. Bad or invalid argument, possibly bad type.
  • no_transaction. Operation not allowed outside transactions.
  • combine_error β€” bestie the table options got illegally combined πŸ’€
  • bad_index β€” that index already exists, or it was straight-up out of bounds 🚫
  • already_exists β€” the schema option you're trying to activate is already on, like it's been on ✨
  • index_exists β€” some operations literally cannot be performed on tables that have an index, periodt
  • no_exists β€” you tried to do an operation on a non-existing (not-alive) item πŸ™ˆ
  • system_limit β€” a system limit was exhausted, we ran outta room 🫠
  • mnesia_down β€” a transaction involves records on a remote node that became unavailable before the transaction finished. Those records are no longer available anywhere else in the network 😭
  • not_a_db_node β€” a node was mentioned that doesn't exist in the schema, awkward πŸ’…
  • bad_type β€” bad type specified in argument, the vibes were off
  • node_not_running β€” the node is not running, it's giving dormant πŸ¦‹
  • truncated_binary_file β€” truncated binary in file, chopped fr fr
  • active β€” some delete operations require that all active records are removed first
  • illegal β€” operation not supported on this record, not allowed, no cap

Error can be Reason, {error, Reason}, {aborted, Reason}, or 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(Fun, [Arg :: _]) -> Res | no_return()

when Fun :: fun((...) -> Res).

Okay so this one calls Fun in a raw context that is not protected by a transaction. No transactional safety net, we're being feral πŸ™ˆ

The Mnesia function call happens inside Fun and it's performed directly on the local ETS tables, on the assumption that the local storage type is ram_copies and the tables aren't replicated to other nodes. Subscriptions don't get triggered and checkpoints don't get 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.

Not me nesting a mnesia:ets inside a transaction-context β€” heads up bestie, that inherits the transaction semantics. Just so you know πŸ’…

🌸 first(Tab :: table()) -> Key :: term()

Return the key for the first record in a table πŸ”‘

Records in set or bag tables are not ordered. However, there is an ordering of the records, it's just unknown to you. So a table can be traversed by this function together with mnesia:next/2.

If there are no records in the table, this function returns the atom '$end_of_table'. So it's highly undesirable β€” but not disallowed β€” to use this atom as the key for any user records. Like, don't do it, but nobody's stopping you 😭


πŸ¦‹ foldl(Fun, Acc0, Table :: table(), LockKind :: lock_kind()) -> Acc

when Fun :: fun((Record :: tuple(), Acc0) -> Acc).

Call Fun for each record in Table β€” the classic fold moment.

It iterates over the table Table and calls Fun(Record, Acc) for each Record in the table. The term returned from Fun is used as the second argument in the next call to Fun.

foldl returns the same term as the last call to Fun returned. And that's the whole vibe.


🧚 foldr(Fun, Acc0, Table :: table(), LockKind :: lock_kind()) -> Acc

when Fun :: fun((Record :: tuple(), Acc0) -> Acc).

Call Fun for each record in Table β€” yes it's the sibling of foldl, we love a duo πŸ’œ

Works exactly like foldl/3 but iterates the table in the opposite order for the ordered_set table type. For all other table types, foldr/3 and foldl/3 are synonyms. Like, straight-up the same thing fr fr.


πŸŽ€ force_load_table(Tab :: table()) -> yes | {error, Reason :: term()}

Force a table to be loaded into the system. We're being pushy and it's fine πŸ’…

The Mnesia algorithm for table load can lead to a situation where a table cannot be loaded. This happens when a node is started and Mnesia concludes, or suspects, that another copy of the table was active after this local copy became inactive because of a system crash. Messy.

If this situation is not acceptable to you, this function can be used to override the strategy of the Mnesia table load algorithm. But bestie, listen β€” this can lead to a situation where some transaction effects are lost, with an inconsistent database as result. For some applications, though, high availability is more important than consistent data, and that's just the tradeoff πŸ‘‘

So dramatic but so necessary. Choose your struggle wisely.

⭐ index_match_object(Pattern, Attr) -> [Record]

when
    Pattern :: tuple(),
    Attr :: index_attr(),
    Record :: tuple().

Match records and use index information πŸ”

It starts mnesia:index_match_object(Tab, Pattern, Attr, read), where Tab is element(1, Pattern). Sneaky little shortcut, love that for you.


🌈 index_match_object(Tab, Pattern, Attr, LockKind) -> [Record]

when
    Tab :: table(),
    Pattern :: tuple(),
    Attr :: index_attr(),
    LockKind :: lock_kind(),
    Record :: tuple().

Match records and use index information β€” the full version now, no shortcut πŸ’…

In a manner similar to the function mnesia:index_read/3, any index information can be used when trying to match records. This function takes a pattern that obeys the same rules as the function mnesia:match_object/3, except that this function requires the following conditions:

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

The two index search functions described here are automatically started when searching tables with qlc list comprehensions, and also when using the low-level mnesia:[dirty_]match_object functions. Iconic automation honestly ✨

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]

when
    Tab :: table(),
    Key :: term(),
    Attr :: index_attr(),
    Record :: tuple().

Read records through the index table πŸ“–

Assume there's an index on position Attr for a certain record type. This function can be used to read the records without knowing the actual key for the record. Like, imagine. For example, with an index in position 1 of table person, the call mnesia:index_read(person, 36, #person.age) returns a list of all persons with age 36. Attr can also be an attribute name (atom), but if the notation mnesia:index_read(person, 36, age) is used, the field position is searched for in runtime, for each call. So, you know, slightly more work per call πŸ‘€

The semantics of this function is context-sensitive. For details, see mnesia:activity/4. In transaction-context, it acquires a read lock on the entire table.


🌺 info() -> ok

Print system information on the terminal πŸ–¨οΈ

Prints system information on the terminal. This function can be used even if Mnesia is not started. However, more information is displayed if Mnesia is started. So boot it up first for the full tea πŸ’…


πŸ”₯ install_fallback(Source :: term(), BackupMod | Args) -> result()

when
    Args :: [Arg],
    Arg :: Module | Scope | Dir,
    Module :: {module, BackupMod},
    Scope :: {scope, global | local},
    Dir :: {mnesia_dir, Dir :: string()},
    BackupMod :: module().

Install a backup as fallback. This is a big one bestie, lock in πŸ”

The fallback is used to restore the database at the next startup. Installation of fallbacks requires Erlang to be operational on all the involved nodes, but it doesn't matter if Mnesia is running or not. The installation of the fallback fails if the local node is not one of the disc-resident nodes in the backup.

Args is a list of the following tuples:

  • {module, BackupMod}. All accesses of the backup media are performed through a callback module named BackupMod. Argument Source 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 Source 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. 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 please be careful, I'm begging πŸ™

πŸ’œ is_transaction() -> boolean()

Return true if inside a transaction context. Simple, clean, iconic, no notes πŸ’…

Okay bestie, one more thing from the last part: when this function is executed inside a transaction-context, it returns true, otherwise false. πŸ’…


last/1 πŸŒ™

last(Tab :: table()) -> Key :: term().

Returns the key for the last record in a table. 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 just synonyms. No cap. πŸ¦‹


load_textfile/1 πŸ“„βœ¨

load_textfile(File :: file:filename()) ->
                       t_result(ok) | {error, term()}.

Loads tables from a text file. Like, it loads a whole series of definitions and data found in the text file (one that was generated with mnesia:dump_to_textfile/1) into Mnesia. This function also starts Mnesia and possibly creates a new schema. πŸ‘‘

⚠️ Heads up bestie β€” this function is intended for educational purposes only. It is recommended to use other functions to deal with real backups. fr fr, do not be trusting your production data to this one. πŸ™ˆ

lock/2 πŸ”’πŸ’…

lock(LockItem, LockKind) -> list() | tuple() | no_return()
              when
                  LockItem ::
                      {record, table(), Key :: term()} |
                      {table, table()} |
                      {global, Key :: term(), MnesiaNodes :: [node()]},
                  LockKind :: lock_kind() | load.

Explicitly grab a lock. Okay so here's the whole situation, bestie β˜•:

Write locks are normally acquired on all nodes where a replica of the table resides (and is active). Read locks are acquired on one node (the local node if a local replica exists). Most of the context-sensitive access functions acquire an implicit lock if they are started in a transaction-context. The granularity of a lock can either be a single record or an entire table.

The normal use is to call the function without checking the return value, as it exits if it fails and the transaction is restarted by the transaction manager. It returns all the locked nodes if a write lock is acquired, and ok if it was a read lock. πŸ‘‘

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

  • 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. It's giving only-child energy, honestly. πŸ’€
  • 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. If someone has a write lock, no one can acquire either a read lock or a write lock at the same item. πŸ”₯

Conflicting lock requests are automatically queued if there is no risk of a deadlock. Otherwise the transaction must be terminated and executed again. Mnesia does this automatically as long as the upper limit of the maximum 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 without any communication with other nodes. The sticky lock lingers on the node even after the transaction ends. For details, see the User's Guide. 🫢

Currently, this function supports two kinds of LockItem:

  • {table, Tab} β€” This acquires a lock of type LockKind on the entire table Tab.
  • {global, GlobalKey, Nodes} β€” This acquires a lock of type LockKind on the global resource GlobalKey. The lock is acquired on all active nodes in the Nodes list.

Locks are released when the outermost transaction ends. ✨

The semantics of this function is context-sensitive. For details, see mnesia:activity/4. In transaction-context, it acquires locks; otherwise it ignores the request. πŸ™ˆ


match_object/3 🎯

match_object(Tab, Pattern, LockKind) -> [Record]
                      when
                          Tab :: table(),
                          Pattern :: tuple(),
                          LockKind :: lock_kind(),
                          Record :: tuple().

Match Pattern for records. Takes a pattern with "don't care" variables denoted as a '_' parameter. This function returns a list of records that matched the pattern. Since the second element of a record in a table is considered to be the key for the record, the performance of this function depends on whether this key is bound or not. πŸ‘€

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

The function mnesia:match_object/3 automatically uses indexes if these exist. However, no heuristics are performed to select the best index. πŸ™ˆ

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


move_table_copy/3 🚚

move_table_copy(Tab :: table(), From :: node(), To :: node()) ->
                         t_result(ok).

Moves the copy of table Tab from node From to node To. πŸ¦‹

The storage type is preserved. For example, a RAM table moved from one node remains a RAM on the new node. Other transactions can still read and write in the table while it is being moved. πŸ‘‘

🚫 This function cannot be used on local_content tables. Periodt.

next/2 ➑️

next(Tab :: table(), Key :: term()) -> NextKey :: term().

Return the next key in a table. Traverses a table and performs operations on all records in the table. When the end of the table is reached, the special key '$end_of_table' is returned. Otherwise the function returns a key that can be used to read the actual record. πŸ’…


prev/2 ⬅️

prev(Tab :: table(), Key :: term()) -> PrevKey :: term().

Return the previous key in a table. Works exactly like mnesia:next/2, but returns the previous object in Erlang term order for the ordered_set table type. For all other table types, mnesia:next/2 and mnesia:prev/2 are synonyms. πŸŽ€


read/3 πŸ“–

read(Tab :: table(), Key :: _, LockKind :: lock_kind()) ->
              [tuple()].

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

The semantics of this function is context-sensitive. For details, see mnesia:activity/4. In transaction-context, it acquires a lock of type LockKind. Currently, the lock types read, write, and sticky_write are supported. ✨

If the user wants to update the record, it is more efficient to use write/sticky_write as the LockKind. If majority checking is active on the table, it is checked as soon as a write lock is attempted. This can be used to end quickly if the majority condition is not met. πŸ’…


read_table_property/2 🏷️

read_table_property(Tab :: table(), PropKey :: term()) ->
                             Res :: tuple().

Reads a user-defined property associated with a table. User-defined properties are set when creating a table with the user_properties option in mnesia:create_table/2, or can be added later with mnesia:write_table_property/2. 🌸

Returns the property tuple if it exists, otherwise raises an exception. 😭 So like, be emotionally prepared for that one.


report_event/1 πŸ“£

report_event(Event :: _) -> ok.

Report a user event to the Mnesia event handler. When tracing a system of Mnesia applications it is useful to be able to interleave Mnesia's own events with application-related events that give information about the application context. πŸ‘‘

Whenever the application begins a new and demanding Mnesia task, or if it enters a new interesting phase in its execution, it can be a good idea to use mnesia:report_event/1. Event can be any term and generates a {mnesia_user, Event} event for any processes that subscribe to Mnesia system events. ✨


restore/2 ♻️

restore(Source :: _, [Arg]) -> t_result([table()])
                 when
                     Op ::
                         skip_tables | clear_tables | keep_tables |
                         restore_tables,
                     Arg ::
                         {module, module()} |
                         {Op, [table()]} |
                         {default_op, Op}.

Restore a backup, bestie. With this function, tables can be restored online from a backup without restarting Mnesia. Source 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} β€” TabList is a list of tables that get recreated before the records from the backup even get inserted. Like, they're deleted first, and then remade using the schema info that came with the backup. 🌸 Heads up tho: all the nodes in the backup need to be operational for this one, no exceptions.
  • {default_op, Operation} β€” Operation is one of skip_tables, clear_tables, keep_tables, or recreate_tables. This is the fallback vibe: it says which operation gets used on any table from the backup that you didn't name in any of those lists. Leave it out and clear_tables is what you get. That's the default, periodt. πŸ’…

The affected tables are write-locked while the restoration is happening. But bestie, listen β€” regardless of whatever lock conflicts that causes, applications can keep doing their thing while the restoration runs. Lowkey iconic. The restoration itself is performed as one single transaction. 🫢

⚠️ If the database is huge, it's not always possible to restore it online. In those cases, restore the old database by installing a fallback and then restart. No cap, sometimes offline is just the move.

πŸ¦‹ s_delete/1

s_delete(TabKey :: {Tab :: table(), Key :: _}) -> ok.

Literally just calls mnesia:delete(Tab, Key, sticky_write). A lil shortcut, nothing more. πŸ’–


πŸŽ€ schema/0

schema() -> ok.

Prints info about all table definitions on the terminal. All of them. Every single one. ✨

πŸŽ€ schema/1

schema(Tab :: table()) -> ok.

Prints info about one table definition on the terminal. Just the one you asked for, bestie.


🌈 select/1

select(Cont) -> {[Match], Cont} | '$end_of_table'
                when Match :: term(), Cont :: select_continuation().

Continue selecting objects. 🌸

Selects more objects with the match specification that mnesia:select/4 kicked off.

πŸ“Œ Notice: any modifying operations β€” that's mnesia:write or mnesia:delete β€” that happen between the mnesia:select/4 and mnesia:select/1 calls are not visible in the result. So don't be surprised, k?

🌈 select/3

select(Tab, MatchSpec, LockKind) -> [Match]
                when
                    Tab :: table(),
                    MatchSpec :: ets:match_spec(),
                    Match :: term(),
                    LockKind :: lock_kind().

Select the objects in Tab against MatchSpec. πŸ’…

Matches the objects in table Tab using a match_spec as described in ets:select/3. Optionally you can hand it a lock β€” read or write β€” as the third argument. Default is read. The return value depends on MatchSpec.

πŸ”₯ For best performance, select is to be used before any modifying operations are done on that table in the same transaction. That means: do not use write or delete before a select. It's giving "order matters", fr fr.

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

select(Tab, MatchSpec, NObjects, LockKind) ->
                {[Match], Cont} | '$end_of_table'
                when
                    Tab :: table(),
                    MatchSpec :: ets:match_spec(),
                    Match :: term(),
                    NObjects :: non_neg_integer(),
                    LockKind :: lock_kind(),
                    Cont :: select_continuation().

Select the objects in Tab against MatchSpec. ✨

Matches the objects in table Tab using a match_spec as described in the ERTS User's Guide, and returns a chunk of terms plus a continuation. How many terms you want back is specified by the NObjects argument. The lock argument can be read or write. If you need more answers β€” or all of them β€” the continuation is what you feed to mnesia:select/1.

πŸ”₯ For best performance, select is to be used before any modifying operations are done on that table in the same transaction. That means: do not use mnesia:write or mnesia:delete before a mnesia:select. And for efficiency reasons, NObjects is a recommendation only β€” the result can contain anything from an empty list to all available results. She's flexible like that. πŸ’€

πŸ¦‹ select_reverse/1

select_reverse(Cont) -> {[Match], Cont} | '$end_of_table'
                        when
                            Match :: term(),
                            Cont :: select_continuation().

Continue selecting objects. πŸ’œ

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

πŸ“Œ Notice: any modifying operations, that is, mnesia:write or mnesia:delete, that are done between the mnesia:select_reverse/4 and mnesia:select_reverse/1 calls are not visible in the result.

πŸ¦‹ select_reverse/3

select_reverse(Tab, MatchSpec, LockKind) -> [Match]
                        when
                            Tab :: table(),
                            MatchSpec :: ets:match_spec(),
                            Match :: term(),
                            LockKind :: lock_kind().

Works like select/3, but for table type ordered_set, the traversal starts at the last object in Erlang term order and moves to the first. For all other table types, the return value is identical to that of select/3. πŸ‘‘

See select/3 for more information.


🧚 select_reverse/4

select_reverse(Tab, MatchSpec, NObjects, LockKind) ->
                        {[Match], Cont} | '$end_of_table'
                        when
                            Tab :: table(),
                            MatchSpec :: ets:match_spec(),
                            Match :: term(),
                            NObjects :: non_neg_integer(),
                            LockKind :: lock_kind(),
                            Cont :: select_continuation().

Select the objects in Tab against MatchSpec, but in reverse order. πŸ”„

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 the NObjects argument. The lock argument can be read or write. The continuation is to be used as argument to mnesia:select_reverse/1, if more or all answers are needed.

πŸ”₯ For best performance, select_reverse is to be used before any modifying operations are done on that table in the same transaction. That means: do not use mnesia:write or mnesia:delete before a mnesia:select_reverse. And for efficiency, NObjects is a recommendation only β€” the result can contain anything from an empty list to all available results. Same energy as before, just backwards. 🫢

πŸ’… set_debug_level/1

set_debug_level(Level :: debug_level()) ->
                            OldLevel :: debug_level().

Change the internal debug level of Mnesia. Returns the old level, so you can put it back if the vibes get weird.

For details, see the Section Configuration Parameters in the mnesia manual page. ✨


πŸ‘‘ set_master_nodes/1

set_master_nodes(MasterNodes :: [node()]) -> result().

Set the master nodes for all tables.

For each table Mnesia determines its replica nodes (TabNodes) and starts mnesia:set_master_nodes(Tab, TabMasterNodes), where TabMasterNodes is the intersection of MasterNodes and TabNodes. For semantics, see mnesia:set_master_nodes/2. πŸ’–


πŸ‘‘ set_master_nodes/2

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

Set the master nodes for a table.

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

The master node setting is always local. It can be changed regardless of whether Mnesia is started or not.

⚠️ The database can also become inconsistent if configuration parameter max_wait_for_decision is used or if mnesia:force_load_table/1 is used. Not a drill. 😭

πŸ“ snmp_close_table/1

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

Remove the possibility for SNMP to manipulate the table. Bye bestie, she's offline now. πŸ™ˆ


πŸ“ snmp_get_mnesia_key/2

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

Get the corresponding Mnesia key from an SNMP index. πŸ”‘

Transforms an SNMP index to the corresponding Mnesia key. If the SNMP table has multiple keys, the key is a tuple of the key columns.


πŸ“ snmp_get_next_index/2

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

Get the index of the next lexicographical row. 🧚

RowIndex can specify a non-existing row. Specifically, it can be the empty list. Returns the index of the next lexicographical row. If RowIndex is the empty list, this function returns the index of the first row in the table.


πŸ“ snmp_get_row/2

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

Retrieve a row indexed by an SNMP index.

Reads a row by its SNMP index. This index is specified as an SNMP Object Identifier β€” that's a list of integers. πŸ’œ


πŸ“ snmp_open_table/2

snmp_open_table(Tab :: table(), SnmpStruct :: snmp_struct()) -> ok.

Organize a Mnesia table as an SNMP table. ✨

A direct one-to-one mapping can be established between Mnesia tables and SNMP tables. Many telecommunication applications are controlled and monitored by the SNMP protocol. This connection between Mnesia and SNMP makes it simple and convenient to achieve this mapping. It's giving "match made in heaven", no cap. 🫢

So SnmpStruct is a list of SNMP info β€” and rn the only thing it actually needs to know about is the key types in the table. Now here's the tea: Mnesia can't do multiple keys, but a LOT of SNMP tables have multiple keys. So the convention is: if your table has multiple keys, bestie, you store them as a tuple of the keys. Periodt. πŸ’…

You describe the key types as a tuple of atoms telling Mnesia what each type is. The only type that actually matters here is fix_string β€” that one means the string has a fixed size. ✨

So like, this right here makes the table person get ordered as an SNMP table:

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

Now picture this schema for a table of company employees πŸ‘‘ β€” every employee is IDed by their department number and their name, and the other column just holds the phone number:

mnesia:create_table(employee,
    [{snmp, [{key, {integer, string}}]},
     {attributes, record_info(fields, employees)}]),

The matching SNMP table would have three columns: department, name, and telno. Slay. 🌸

Okay but here's a fun option β€” you can have table columns that are not visible through the SNMP protocol at all πŸ™ˆ. Those columns have to be the last columns of the table. So in that employee example, the SNMP table could have just department and name. Then your application can use telno internally, and the SNMP managers will literally never see it. Sneaky. Iconic.

In a table that's monitored by SNMP, all elements must be integers, strings, or lists of integers. No vibes-based data types, sorry. 😭

Heads up: when a table is SNMP ordered, modifications are more expensive than usual β€” O(logN). And it eats more memory too. Just so you know what you're signing up for. πŸ’€

And one more thing, bestie: only the lexicographical SNMP ordering is actually implemented in Mnesia. Not the actual SNMP monitoring. So don't come for me thinking it does the whole thing. 🀷


🌟 start() -> result().

Starts a local Mnesia system. Let's gooo. πŸ”₯

Mnesia startup is asynchronous β€” the call mnesia:start() returns the atom ok and then starts initializing all the different tables. Depending on how big your database is, this can take a minute (or a lot of minutes 😭), and the application programmer must wait for the tables the application needs before touching them. How? With mnesia:wait_for_tables/2. That's your girl. 🫢

The startup procedure for a set of Mnesia nodes is a fairly complicated operation, ngl. A Mnesia system is a set of nodes, with Mnesia started locally on all the participating nodes. Normally every node has a directory where all the Mnesia files get written β€” that's the Mnesia directory. Mnesia can also be started on disc-less nodes β€” for more on that whole situation, 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. Nodes can be added to or removed from the schema. The initial schema is normally created on disc with mnesia:create_schema/1. On disc-less nodes, a tiny default schema is generated every single time Mnesia is started. During startup, Mnesia exchanges schema info between the nodes to check that the table definitions are compatible. Vibe check, basically. ✨

Every schema has a unique cookie, which you can think of as a unique schema identifier. That cookie has to be the same on all nodes where Mnesia is supposed to run. Details are in the User's Guide. πŸ“

The schema file and every other file Mnesia needs live in the Mnesia directory. The command-line option -mnesia dir Dir specifies where that directory is. If Mnesia can't find that option, the directory name defaults to Mnesia.Node. 🌈

application:start(mnesia) works too, btw. πŸ’œ


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

Stops Mnesia locally on the current node. Bye bestie. πŸ‘‹

application:stop(mnesia) also works. πŸŽ€


🌟 subscribe(EventCategory) -> {ok, node()} | {error, Reason :: term()} when EventCategory :: system | activity | {table, table(), simple | detailed}.

Subscribes you to events of type EventCategory.

It makes sure a copy of all events of type EventCategory gets sent to the caller. The available event types are described in the User's Guide. πŸ“¬


🌟 sync_dirty(Fun, [Arg :: _]) -> Res | no_return() when Fun :: fun((...) -> Res).

Calls Fun in a context that is not protected by a transaction. Living dangerously, respectfully. πŸ’…

The Mnesia function calls you make inside Fun get mapped to the corresponding dirty functions. It runs in almost the same context as mnesia:async_dirty/1,2 β€” the difference being that the operations are performed synchronously. The caller waits for the updates to be performed on all active replicas before Fun returns. For the full rundown, see mnesia:activity/4 and the User's Guide. ✨


🌟 sync_log() -> result().

Performs a file sync of the local log file. πŸ’Ύ

It makes sure 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. ⚑

Fr fr, if the lights go out and you haven't synced, that data is GONE. 😭

🌟 sync_transaction(Fun, [Arg :: _], Retries) -> t_result(Res) when Fun :: fun((...) -> Res), Retries :: non_neg_integer() | infinity.

Synchronously executes a transaction. πŸ¦‹

It waits until data has been committed and logged to disk (if disk is being used) on every involved node before it returns β€” otherwise it behaves exactly like mnesia:transaction/[1,2,3].

This is the move when you want to avoid one process overloading a database on another node. πŸ’–


🌟 system_info(Item :: term()) -> ItemVal :: term().

Returns info about the Mnesia system. πŸ‘‘

Like transaction statistics, db_nodes, and configuration parameters. Everything you'd want to snoop on.

The valid keys are as follows:

  • all β€” returns a list of all local system information. Each element is a {InfoItem, ItemVal} tuple.
New InfoItems can be added and old undocumented ones can be removed without notice. So don't get too attached. πŸ™ˆ
  • access_module β€” returns the name of the module configured to be the activity access callback module.
  • auto_repair β€” returns true or false, telling you if Mnesia is configured to start the auto-repair facility on corrupted disc files.
  • backup_module β€” returns the name of the module 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 β€” returns the nodes that make up the persistent database. Disc-less nodes are only included in the list if they've explicitly been added to the schema, for example with mnesia:add_table_copy/3. This function can be started even if Mnesia isn't running yet. ✨
  • debug β€” returns the current debug level of Mnesia.
  • directory β€” returns the name of the Mnesia directory. Can be called even if Mnesia isn't running yet.
  • dump_log_load_regulation β€” returns a boolean telling you if Mnesia is configured to regulate the dumper process load.
This feature is temporary and will be removed in future releases. Rip. πŸ’€
  • dump_log_time_threshold β€” returns the time threshold for transaction log dumps, in milliseconds.
  • dump_log_update_in_place β€” returns a boolean telling you whether Mnesia is configured to perform updates in the Dets files directly, or whether updates go into a copy of the Dets files.
  • dump_log_write_threshold β€” returns the write threshold for transaction log dumps, as the number of writes to the transaction log.
  • extra_db_nodes β€” returns a list of extra db_nodes to contact at startup.
  • fallback_activated β€” returns true if a fallback is activated, otherwise false.
  • held_locks β€” returns a list of all locks held by the local Mnesia lock manager. πŸ”’
  • is_running β€” returns yes or no telling you if Mnesia is running. It can also return starting or stopping. Can be called even if Mnesia isn't running yet.
  • local_tables β€” returns a list of all tables configured to reside locally.
  • lock_queue β€” returns a list of all transactions queued for execution by the local lock manager.
  • log_version β€” returns the version number of the Mnesia transaction log format.
  • master_node_tables β€” returns a list of all tables with at least one master node.
  • protocol_version β€” returns the version number of the Mnesia inter-process communication protocol.
  • running_db_nodes β€” returns a list of nodes where Mnesia currently is running. This function can be called even if Mnesia isn't running yet, but then it has slightly different semantics πŸ‘€.
    • If Mnesia is down on the local node, it returns those other db_nodes and extra_db_nodes that for the moment are operational.
    • If Mnesia is started, it returns those nodes that Mnesia on the local node is fully connected to. Only nodes that Mnesia has exchanged schema information with are included as running_db_nodes. After the merge of schemas, the local Mnesia system is fully operable and applications can access remote replicas. Before the schema merge, Mnesia only operates locally. Sometimes there are more nodes in the running_db_nodes list than all db_nodes and extra_db_nodes together. Wild, I know. 😭
  • schema_location β€” returns the initial schema location.

Still working our way through the info-item menu, bestie β€” here's the rest of the alphabet πŸ’…

  • subscribers β€” hands you a list of the local processes that are currently subscribed to system events.
  • tables β€” a list of every table that's known locally.
  • transactions β€” a list of all the local transactions that are active right this second.
  • transaction_failures β€” a number: how many transactions have flopped since Mnesia got started.
  • transaction_commits β€” a number: how many transactions wrapped up successfully since Mnesia got started.
  • transaction_restarts β€” a number: how many transactions have been restarted since Mnesia got started.
  • transaction_log_writes β€” a number: how many write operations have hit the transaction log since startup.
  • use_dir β€” a boolean, true or false, for whether the Mnesia directory is being used or not. You can call this one even if Mnesia isn't running yet, no cap.
  • version β€” the current version number of Mnesia. That's it, that's the whole thing. ✨

🌸 FUNCTIONS, cont. β€” the query + info girlies 🌸

table(Tab :: table(), Options) -> qlc:query_handle()
               when
                   Options :: Option | [Option],
                   Option :: MnesiaOpt | QlcOption,
                   MnesiaOpt ::
                       {traverse, SelectOp} |
                       {lock, lock_kind()} |
                       {n_objects, non_neg_integer()},
                   SelectOp :: select | {select, ets:match_spec()},
                   QlcOption :: {key_equality, '==' | '=:='}.

Return a QLC query handle. πŸ¦‹

Okay so this hands you back a Query List Comprehension (QLC) query handle β€” go peek at the qlc manual page over in STDLIB if you want the lore. The qlc module implements a query language that can straight up use Mnesia tables as sources of data, which is iconic tbh. Calling mnesia:table/1,2 is the way to make the mnesia table Tab usable by QLC. Periodt.

Option can hold Mnesia options or QLC options. Mnesia recognizes the ones below, and any other option just gets forwarded straight 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, it says roughly) the number of objects returned from Mnesia to QLC. Queries to remote tables can need a larger chunk to cut down on network overhead, so if you're doing remote stuff, size up. By default, 100 objects at a time are returned.
  • {traverse, SelectMethod} β€” where traverse decides the method used to walk the whole table (if that's needed). The default method is select.

There are two alternatives for select:

  • select β€” the table is traversed by calling mnesia:select/4 and mnesia:select/1. The match specification (that's the second argument of select/3) gets assembled by QLC: simple filters are 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 as select, the table is traversed by calling mnesia:select/3 and mnesia:select/1. The difference? The match specification is explicitly given by you. This is how you state match specifications that cannot easily be expressed within the syntax QLC provides.

table_info(Tab :: table(), InfoItem :: term()) ->
                    ItemVal :: term().

Return local information about table. πŸ”

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

  • all β€” returns a list of all local table information. Each element is a {InfoItem, ItemVal} tuple.
New InfoItems can be added and old undocumented InfoItems can be removed without notice. So don't get too attached to undocumented ones, bestie 😭
  • access_mode β€” returns the access mode of the table. It can be read_only or read_write.
  • arity β€” returns the arity of records in the table, as specified in the schema.
  • attributes β€” returns the table attribute names that are specified in the schema.
  • checkpoints β€” returns the names of the currently active checkpoints that involve this table on this node.
  • cookie β€” returns a table cookie, which is a unique system-generated identifier for the table. The cookie is used internally so that 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 β€” returns the nodes where a disc_copy of the table resides according to the schema.
  • disc_only_copies β€” returns the nodes where a disc_only_copy of the table resides according to the schema.
  • index β€” returns the list of index position integers for the table.
  • load_node β€” returns 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 β€” returns the load order priority of the table. It's an integer and defaults to 0 (zero).
  • load_reason β€” returns the reason why Mnesia decided to load the table. The structure of the returned value is unspecified, but it can be useful for debugging purposes.
  • local_content β€” returns true or false to indicate whether the table is configured to have locally unique content on each node.
  • master_nodes β€” returns the master nodes of a table.
  • memory β€” for ram_copies and disc_copies tables it returns the number of words allocated in memory to the table on this node. For disc_only_copies tables it returns the number of bytes stored on disc instead.
  • ram_copies β€” returns the nodes where a ram_copy of the table resides according to the schema.
  • record_name β€” returns the record name, which is common for all records in the table.
  • size β€” returns the number of records inserted in the table.
  • snmp β€” returns the SNMP struct. [] means the table currently has no SNMP properties.
  • storage_type β€” returns the local storage type of the table. It can be disc_copies, ram_copies, disc_only_copies, or the atom unknown. unknown comes back for all tables that only reside remotely.
  • subscribers β€” returns a list of local processes currently subscribing to local table events that involve this table on this node.
  • type β€” returns the table type, which is bag, set, or ordered_set.
  • user_properties β€” returns the user-associated table properties of the table. It's a list of the stored property records.
  • version β€” returns the current version of the table definition. The table version gets incremented when the table definition changes. The table definition can be incremented directly when it's 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 comes back, either the table isn't loaded, or it lives at a remote node that isn't 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 handed to the various match functions for a certain table. It's a record tuple where all record fields have the value '_'.

transaction(Fun, Args, Retries) -> t_result(Res)
                     when
                         Fun :: fun((...) -> Res),
                         Args :: [Arg :: _],
                         Retries :: non_neg_integer() | infinity.

Execute Fun with arguments Args as a transaction. πŸ‘‘

The code that executes inside the transaction can be a whole series of table manipulation functions. If something goes wrong inside the transaction β€” whether it's 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 though, {atomic, Res} is returned, where Res is the value of the last expression in Fun. ✨

A function that adds a family to the database can be written like this, if you've got a structure {family, Father, Mother, ChildrenList}:

add_family({family, Father, Mother, ChildrenList}) ->
    ChildOids = lists:map(fun oid/1, ChildrenList),
    Trans = fun() ->
        mnesia:write(Father#person{children = ChildOids}),
        mnesia:write(Mother#person{children = ChildOids}),
        Write = fun(Child) -> mnesia:write(Child) end,
        lists:foreach(Write, ChildrenList)
    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 inside one transaction means either the whole family gets added to the database, or the whole transaction terminates. Like, for example, if the last child is badly formatted, or the executing process terminates because of an 'EXIT' signal while it's running the family code, the transaction terminates. So the situation where half a family gets added can literally never happen. Slay.

It's also useful to update the database inside a transaction when 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).

ok bestie, so when this function runs inside a transaction, like, multiple processes on different nodes can all vibe and execute raise/2 at the same time without messing with each other. πŸ’…βœ¨

Mnesia is a deadlock detective, so a transaction can get restarted as many times as needed, which means your Fun absolutely cannot have side effects like waiting for specific messages. This function tries to restart as many times as Retries says. Retries has to be an integer > 0 or the atom infinity, default is infinity. Mnesia throws exit exceptions to signal "yo, restart needed", so your Fun must NOT catch exit exceptions with reason {aborted, term()}. periodt.


✨ transform_table ✨

       transform_table(Tab :: table(),
                             Fun, NewAttributeList, NewRecordName) ->
                                t_result(ok)
                                when
                                    NewRecordName :: atom(),
                                    NewAttributeList :: [atom()],
                                    Fun ::
                                        fun((Record :: tuple()) ->
                                                Transformed :: tuple()) |
                                        ignore.

Change format on all records in table. πŸ¦‹

So it applies the argument Fun to every single record in the table. Fun is a function that takes a record of the old type and returns a transformed record of the new type. You can also pass the atom ignore as Fun, which means only the metadata about the table gets updated. Using ignore is not recommended, but it's there as a possibility for you to do your own transformation.

NewAttributeList and NewRecordName specify the attributes and the new record type of the converted table. The table name always stays the same, no cap. 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. πŸ’€


🌈 traverse_backup 🌈

       traverse_backup(Source :: term(),
                             SourceMod :: module(),
                             Target :: term(),
                             TargetMod :: module(),
                             Fun, Acc) ->
                                {ok, LastAcc} | {error, Reason :: term()}
                                when
                                    Fun ::
                                        fun((BackupItems, Acc) ->
                                                {BackupItems, NewAcc}),
                                    LastAcc :: NewAcc.

Traverse a backup. πŸŽ€

It iterates over a backup, either to transform it into a new backup, or just to read it. Here's the tea on the arguments (for details, check 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 πŸ’–

       uninstall_fallback(Args) -> result()
                                   when Args :: [{mnesia_dir, Dir ::
       string()}].

Uninstall a fallback. 🌸

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 doesn't 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 πŸ¦‹

       unsubscribe(EventCategory) ->
                            {ok, node()} | {error, Reason :: term()}
                            when
                                EventCategory ::
                                    system | activity |
                                    {table, table(), simple | detailed}.

Stop sending events of type EventCategory to the caller. ✨

Node is the local node.


πŸŽ€ wait_for_tables πŸŽ€

       wait_for_tables([Tab :: table()], TMO :: timeout()) ->
                                result() | {timeout, [table()]}.

Wait for tables to be accessible. πŸ’…

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


🌟 write/1 🌟

       write(Record :: tuple()) -> ok.

Write a record into the database. πŸ”₯

Calls the function mnesia:write(Tab, Record, write), where Tab is element(1, Record).


πŸ’œ write/3 πŸ’œ

       write(Tab :: table(),
                   Record :: tuple(),
                   LockKind :: write_locks()) ->
                      ok.

Write Record to table Tab. 🫢

The function returns ok, or terminates if an error occurs. For example, the transaction terminates if no Tab 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_table_property ⭐

       write_table_property(Tab :: table(), Prop :: tuple()) ->
                                     t_result(ok).

Write a user-defined table property. 🌈

Writes or updates a user-defined property for a table. The property is a tuple where the first element is the property key. User-defined properties can be read with mnesia:read_table_property/2 and deleted with mnesia:delete_table_property/2.


and that's a wrap, bestie! πŸ’– this page was brought to you by Ericsson AB, mnesia version 4.26.2, and the mnesia(3) manual. the date? it's giving timeless, but you know it's from the manual. stay slaying with your Mnesia skills! πŸ‘‘

πŸ“¦ where this page comes from