1mnesia(3) Erlang Module Definition mnesia(3)
2
3
4
6 mnesia - A distributed telecommunications DBMS
7
9 The following are some of the most important and attractive capabili‐
10 ties provided by Mnesia:
11
12 * A relational/object hybrid data model that is suitable for telecom‐
13 munications applications.
14
15 * A DBMS query language, Query List Comprehension (QLC) as an add-on
16 library.
17
18 * Persistence. Tables can be coherently kept on disc and in the main
19 memory.
20
21 * Replication. Tables can be replicated at several nodes.
22
23 * Atomic transactions. A series of table manipulation operations can
24 be grouped into a single atomic transaction.
25
26 * Location transparency. Programs can be written without knowledge of
27 the actual data location.
28
29 * Extremely fast real-time data searches.
30
31 * Schema manipulation routines. The DBMS can be reconfigured at run‐
32 time without stopping the system.
33
34 This Reference Manual describes the Mnesia API. This includes functions
35 that define and manipulate Mnesia tables.
36
37 All functions in this Reference Manual can be used in any combination
38 with queries using the list comprehension notation. For information
39 about the query notation, see the qlc manual page in STDLIB.
40
41 Data in Mnesia is organized as a set of tables. Each table has a name
42 that must be an atom. Each table is made up of Erlang records. The user
43 is responsible for the record definitions. Each table also has a set of
44 properties. The following are some of the properties that are associ‐
45 ated with each table:
46
47 * type. Each table can have set, ordered_set, or bag semantics. No‐
48 tice that currently ordered_set is not supported for
49 disc_only_copies.
50
51 If a table is of type set, each key leads to either one or zero
52 records.
53
54 If a new item is inserted with the same key as an existing record,
55 the old record is overwritten. However, if a table is of type bag,
56 each key can map to several records. All records in type bag tables
57 are unique, only the keys can be duplicated.
58
59 * record_name. All records stored in a table must have the same name.
60 The records must be instances of the same record type.
61
62 * ram_copies. A table can be replicated on a number of Erlang nodes.
63 Property ram_copies specifies a list of Erlang nodes where RAM
64 copies are kept. These copies can be dumped to disc at regular in‐
65 tervals. However, updates to these copies are not written to disc
66 on a transaction basis.
67
68 * disc_copies. This property specifies a list of Erlang nodes where
69 the table is kept in RAM and on disc. All updates of the table are
70 performed in the actual table and are also logged to disc. If a ta‐
71 ble is of type disc_copies at a certain node, the entire table is
72 resident in RAM memory and on disc. Each transaction performed on
73 the table is appended to a LOG file and written into the RAM table.
74
75 * disc_only_copies. Some, or all, table replicas can be kept on disc
76 only. These replicas are considerably slower than the RAM-based
77 replicas.
78
79 * index. This is a list of attribute names, or integers, which spec‐
80 ify the tuple positions on which Mnesia is to build and maintain an
81 extra index table.
82
83 * local_content. When an application requires tables whose contents
84 are local to each node, local_content tables can be used. The table
85 name is known to all Mnesia nodes, but its content is unique on
86 each node. This means that access to such a table must be done lo‐
87 cally. Set field local_content to true to enable the local_content
88 behavior. Default is false.
89
90 * majority. This attribute is true or false; default is false. When
91 true, a majority of the table replicas must be available for an up‐
92 date to succeed. Majority checking can be enabled on tables with
93 mission-critical data, where it is vital to avoid inconsistencies
94 because of network splits.
95
96 * snmp. Each (set-based) Mnesia table can be automatically turned
97 into a Simple Network Management Protocol (SNMP) ordered table as
98 well. This property specifies the types of the SNMP keys.
99
100 * attributes. The names of the attributes for the records that are
101 inserted in the table.
102
103 For information about the complete set of table properties and their
104 details, see mnesia:create_table/2.
105
106 This Reference Manual uses a table of persons to illustrate various ex‐
107 amples. The following record definition is assumed:
108
109 -record(person, {name,
110 age = 0,
111 address = unknown,
112 salary = 0,
113 children = []}),
114
115 The first record attribute is the primary key, or key for short.
116
117 The function descriptions are sorted in alphabetical order. It is rec‐
118 ommended to start to read about mnesia:create_table/2, mnesia:lock/2,
119 and mnesia:activity/4 before you continue and learn about the rest.
120
121 Writing or deleting in transaction-context creates a local copy of each
122 modified record during the transaction. During iteration, that is, mne‐
123 sia:fold[lr]/4, mnesia:next/2, mnesia:prev/2, and mne‐
124 sia:snmp_get_next_index/2, Mnesia compensates for every written or
125 deleted record, which can reduce the performance.
126
127 If possible, avoid writing or deleting records in the same transaction
128 before iterating over the table.
129
131 table() = atom()
132
133 activity() =
134 ets | async_dirty | sync_dirty | transaction |
135 sync_transaction |
136 {transaction, Retries :: integer() >= 0} |
137 {sync_transaction, Retries :: integer() >= 0}
138
139 create_option() =
140 {access_mode, read_write | read_only} |
141 {attributes, [atom()]} |
142 {disc_copies, [node()]} |
143 {disc_only_copies, [node()]} |
144 {index, [index_attr()]} |
145 {load_order, integer() >= 0} |
146 {majority, boolean()} |
147 {ram_copies, [node()]} |
148 {record_name, atom()} |
149 {snmp, SnmpStruct :: term()} |
150 {storage_properties,
151 [{Backend :: module(), [BackendProp :: term()]}]} |
152 {type, set | ordered_set | bag} |
153 {local_content, boolean()} |
154 {user_properties, proplists:proplist()}
155
156 storage_type() = ram_copies | disc_copies | disc_only_copies
157
158 t_result(Res) = {atomic, Res} | {aborted, Reason :: term()}
159
160 result() = ok | {error, Reason :: term()}
161
162 index_attr() = atom() | integer() >= 0 | {atom()}
163
164 write_locks() = write | sticky_write
165
166 read_locks() = read
167
168 lock_kind() = write_locks() | read_locks()
169
170 select_continuation() = term()
171
172 snmp_struct() = [{atom(), snmp_type() | tuple_of(snmp_type())}]
173
174 snmp_type() = fix_string | string | integer
175
176 tuple_of(_T) = tuple()
177
178 config_key() = extra_db_nodes | dc_dump_limit
179
180 config_value() = [node()] | number()
181
182 config_result() = {ok, config_value()} | {error, term()}
183
184 debug_level() = none | verbose | debug | trace
185
187 abort(Reason :: term()) -> no_return()
188
189 Makes the transaction silently return the tuple {aborted, Rea‐
190 son}. Termination of a Mnesia transaction means that an excep‐
191 tion is thrown to an enclosing catch. Thus, the expression catch
192 mnesia:abort(x) does not terminate the transaction.
193
194 activate_checkpoint(Args :: [Arg]) ->
195 {ok, Name, [node()]} |
196 {error, Reason :: term()}
197
198 Types:
199
200 Arg =
201 {name, Name} |
202 {max, [table()]} |
203 {min, [table()]} |
204 {allow_remote, boolean()} |
205 {ram_overrides_dump, boolean()}
206
207 A checkpoint is a consistent view of the system. A checkpoint
208 can be activated on a set of tables. This checkpoint can then be
209 traversed and presents a view of the system as it existed at the
210 time when the checkpoint was activated, even if the tables are
211 being or have been manipulated.
212
213 Args is a list of the following tuples:
214
215 * {name,Name}. Name is the checkpoint name. Each checkpoint
216 must have a name that is unique to the associated nodes. The
217 name can be reused only once the checkpoint has been deacti‐
218 vated. By default, a name that is probably unique is gener‐
219 ated.
220
221 * {max,MaxTabs}. MaxTabs is a list of tables that are to be
222 included in the checkpoint. Default is []. For these tables,
223 the redundancy is maximized and checkpoint information is
224 retained together with all replicas. The checkpoint becomes
225 more fault tolerant if the tables have several replicas.
226 When a new replica is added by the schema manipulation func‐
227 tion mnesia:add_table_copy/3, a retainer is also attached
228 automatically.
229
230 * {min,MinTabs}. MinTabs is a list of tables that are to be
231 included in the checkpoint. Default is []. For these tables,
232 the redundancy is minimized and the checkpoint information
233 is only retained with one replica, preferably on the local
234 node.
235
236 * {allow_remote,Bool}. false means that all retainers must be
237 local. The checkpoint cannot be activated if a table does
238 not reside locally. true allows retainers to be allocated on
239 any node. Default is true.
240
241 * {ram_overrides_dump,Bool}. Only applicable for ram_copies.
242 Bool allows you to choose to back up the table state as it
243 is in RAM, or as it is on disc. true means that the latest
244 committed records in RAM are to be included in the check‐
245 point. These are the records that the application accesses.
246 false means that the records dumped to DAT files are to be
247 included in the checkpoint. These records are loaded at
248 startup. Default is false.
249
250 Returns {ok,Name,Nodes} or {error,Reason}. Name is the (possibly
251 generated) checkpoint name. Nodes are the nodes that are in‐
252 volved in the checkpoint. Only nodes that keep a checkpoint re‐
253 tainer know about the checkpoint.
254
255 activity(Kind, Fun) -> t_result(Res) | Res
256
257 Types:
258
259 Kind = activity()
260 Fun = fun(() -> Res)
261
262 Calls mnesia:activity(AccessContext, Fun, Args, AccessMod),
263 where AccessMod is the default access callback module obtained
264 by mnesia:system_info(access_module). Args defaults to [] (empty
265 list).
266
267 activity(Kind, Fun, Args :: [Arg :: term()], Mod) ->
268 t_result(Res) | Res
269
270 Types:
271
272 Kind = activity()
273 Fun = fun((...) -> Res)
274 Mod = atom()
275
276 Executes the functional object Fun with argument Args.
277
278 The code that executes inside the activity can consist of a se‐
279 ries of table manipulation functions, which are performed in an
280 AccessContext. Currently, the following access contexts are sup‐
281 ported:
282
283 transaction:
284 Short for {transaction, infinity}
285
286 {transaction, Retries}:
287 Calls mnesia:transaction(Fun, Args, Retries). Notice that
288 the result from Fun is returned if the transaction is suc‐
289 cessful (atomic), otherwise the function exits with an abort
290 reason.
291
292 sync_transaction:
293 Short for {sync_transaction, infinity}
294
295 {sync_transaction, Retries}:
296 Calls mnesia:sync_transaction(Fun, Args, Retries). Notice
297 that the result from Fun is returned if the transaction is
298 successful (atomic), otherwise the function exits with an
299 abort reason.
300
301 async_dirty:
302 Calls mnesia:async_dirty(Fun, Args).
303
304 sync_dirty:
305 Calls mnesia:sync_dirty(Fun, Args).
306
307 ets:
308 Calls mnesia:ets(Fun, Args).
309
310 This function (mnesia:activity/4) differs in an important way
311 from the functions mnesia:transaction, mnesia:sync_transaction,
312 mnesia:async_dirty, mnesia:sync_dirty, and mnesia:ets. Argument
313 AccessMod is the name of a callback module, which implements the
314 mnesia_access behavior.
315
316 Mnesia forwards calls to the following functions:
317
318 * mnesia:lock/2 (read_lock_table/1, write_lock_table/1)
319
320 * mnesia:write/3 (write/1, s_write/1)
321
322 * mnesia:delete/3 (delete/1, s_delete/1)
323
324 * mnesia:delete_object/3 (delete_object/1, s_delete_object/1)
325
326 * mnesia:read/3 (read/1, wread/1)
327
328 * mnesia:match_object/3 (match_object/1)
329
330 * mnesia:all_keys/1
331
332 * mnesia:first/1
333
334 * mnesia:last/1
335
336 * mnesia:prev/2
337
338 * mnesia:next/2
339
340 * mnesia:index_match_object/4 (index_match_object/2)
341
342 * mnesia:index_read/3
343
344 * mnesia:table_info/2
345
346 to the corresponding:
347
348 * AccessMod:lock(ActivityId, Opaque, LockItem, LockKind)
349
350 * AccessMod:write(ActivityId, Opaque, Tab, Rec, LockKind)
351
352 * AccessMod:delete(ActivityId, Opaque, Tab, Key, LockKind)
353
354 * AccessMod:delete_object(ActivityId, Opaque, Tab, RecXS,
355 LockKind)
356
357 * AccessMod:read(ActivityId, Opaque, Tab, Key, LockKind)
358
359 * AccessMod:match_object(ActivityId, Opaque, Tab, Pattern,
360 LockKind)
361
362 * AccessMod:all_keys(ActivityId, Opaque, Tab, LockKind)
363
364 * AccessMod:first(ActivityId, Opaque, Tab)
365
366 * AccessMod:last(ActivityId, Opaque, Tab)
367
368 * AccessMod:prev(ActivityId, Opaque, Tab, Key)
369
370 * AccessMod:next(ActivityId, Opaque, Tab, Key)
371
372 * AccessMod:index_match_object(ActivityId, Opaque, Tab, Pat‐
373 tern, Attr, LockKind)
374
375 * AccessMod:index_read(ActivityId, Opaque, Tab, SecondaryKey,
376 Attr, LockKind)
377
378 * AccessMod:table_info(ActivityId, Opaque, Tab, InfoItem)
379
380 ActivityId is a record that represents the identity of the en‐
381 closing Mnesia activity. The first field (obtained with ele‐
382 ment(1, ActivityId)) contains an atom, which can be interpreted
383 as the activity type: ets, async_dirty, sync_dirty, or tid. tid
384 means that the activity is a transaction. The structure of the
385 rest of the identity record is internal to Mnesia.
386
387 Opaque is an opaque data structure that is internal to Mnesia.
388
389 add_table_copy(Tab, N, ST) -> t_result(ok)
390
391 Types:
392
393 Tab = table()
394 N = node()
395 ST = storage_type()
396
397 Makes another copy of a table at the node Node. Argument Type
398 must be either of the atoms ram_copies, disc_copies, or
399 disc_only_copies. For example, the following call ensures that a
400 disc replica of the person table also exists at node Node:
401
402 mnesia:add_table_copy(person, Node, disc_copies)
403
404 This function can also be used to add a replica of the table
405 named schema.
406
407 add_table_index(Tab, I) -> t_result(ok)
408
409 Types:
410
411 Tab = table()
412 I = index_attr()
413
414 Table indexes can be used whenever the user wants to use fre‐
415 quently some other field than the key field to look up records.
416 If this other field has an associated index, these lookups can
417 occur in constant time and space. For example, if your applica‐
418 tion wishes to use field age to find efficiently all persons
419 with a specific age, it can be a good idea to have an index on
420 field age. This can be done with the following call:
421
422 mnesia:add_table_index(person, age)
423
424 Indexes do not come for free. They occupy space that is propor‐
425 tional to the table size, and they cause insertions into the ta‐
426 ble to execute slightly slower.
427
428 all_keys(Tab :: table()) -> [Key :: term()]
429
430 Returns a list of all keys in the table named Tab. The semantics
431 of this function is context-sensitive. For more information, see
432 mnesia:activity/4. In transaction-context, it acquires a read
433 lock on the entire table.
434
435 async_dirty(Fun) -> Res | no_return()
436
437 async_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()
438
439 Types:
440
441 Fun = fun((...) -> Res)
442
443 Calls the Fun in a context that is not protected by a transac‐
444 tion. The Mnesia function calls performed in the Fun are mapped
445 to the corresponding dirty functions. This still involves log‐
446 ging, replication, and subscriptions, but there is no locking,
447 local transaction storage, or commit protocols involved. Check‐
448 point retainers and indexes are updated, but they are updated
449 dirty. As for normal mnesia:dirty_* operations, the operations
450 are performed semi-asynchronously. For details, see mnesia:ac‐
451 tivity/4 and the User's Guide.
452
453 The Mnesia tables can be manipulated without using transactions.
454 This has some serious disadvantages, but is considerably faster,
455 as the transaction manager is not involved and no locks are set.
456 A dirty operation does, however, guarantee a certain level of
457 consistency, and the dirty operations cannot return garbled
458 records. All dirty operations provide location transparency to
459 the programmer, and a program does not have to be aware of the
460 whereabouts of a certain table to function.
461
462 Notice that it is more than ten times more efficient to read
463 records dirty than within a transaction.
464
465 Depending on the application, it can be a good idea to use the
466 dirty functions for certain operations. Almost all Mnesia func‐
467 tions that can be called within transactions have a dirty equiv‐
468 alent, which is much more efficient.
469
470 However, notice that there is a risk that the database can be
471 left in an inconsistent state if dirty operations are used to
472 update it. Dirty operations are only to be used for performance
473 reasons when it is absolutely necessary.
474
475 Notice that calling (nesting) mnesia:[a]sync_dirty inside a
476 transaction-context inherits the transaction semantics.
477
478 backup(Dest :: term()) -> result()
479
480 backup(Dest :: term(), Mod :: module()) -> result()
481
482 Activates a new checkpoint covering all Mnesia tables, including
483 the schema, with maximum degree of redundancy, and performs a
484 backup using backup_checkpoint/2/3. The default value of the
485 backup callback module BackupMod is obtained by mnesia:sys‐
486 tem_info(backup_module).
487
488 backup_checkpoint(Name, Dest) -> result()
489
490 backup_checkpoint(Name, Dest, Mod) -> result()
491
492 Types:
493
494 Name = Dest = term()
495 Mod = module()
496
497 The tables are backed up to external media using backup module
498 BackupMod. Tables with the local contents property are backed up
499 as they exist on the current node. BackupMod is the default
500 backup callback module obtained by mnesia:sys‐
501 tem_info(backup_module). For information about the exact call‐
502 back interface (the mnesia_backup behavior), see the User's
503 Guide.
504
505 change_config(Config, Value) -> config_result()
506
507 Types:
508
509 Config = config_key()
510 Value = config_value()
511
512 Config is to be an atom of the following configuration parame‐
513 ters:
514
515 extra_db_nodes:
516 Value is a list of nodes that Mnesia is to try to connect
517 to. ReturnValue is those nodes in Value that Mnesia is con‐
518 nected to.
519
520 Notice that this function must only be used to connect to
521 newly started RAM nodes (N.D.R.S.N.) with an empty schema.
522 If, for example, this function is used after the network has
523 been partitioned, it can lead to inconsistent tables.
524
525 Notice that Mnesia can be connected to other nodes than
526 those returned in ReturnValue.
527
528 dc_dump_limit:
529 Value is a number. See the description in Section Configura‐
530 tion Parameters. ReturnValue is the new value. Notice that
531 this configuration parameter is not persistent. It is lost
532 when Mnesia has stopped.
533
534 change_table_access_mode(Tab :: table(), Mode) -> t_result(ok)
535
536 Types:
537
538 Mode = read_only | read_write
539
540 AcccessMode is by default the atom read_write but it can also be
541 set to the atom read_only. If AccessMode is set to read_only,
542 updates to the table cannot be performed. At startup, Mnesia al‐
543 ways loads read_only tables locally regardless of when and if
544 Mnesia is terminated on other nodes.
545
546 change_table_copy_type(Tab :: table(),
547 Node :: node(),
548 To :: storage_type()) ->
549 t_result(ok)
550
551 For example:
552
553 mnesia:change_table_copy_type(person, node(), disc_copies)
554
555 Transforms the person table from a RAM table into a disc-based
556 table at Node.
557
558 This function can also be used to change the storage type of the
559 table named schema. The schema table can only have ram_copies or
560 disc_copies as the storage type. If the storage type of the
561 schema is ram_copies, no other table can be disc-resident on
562 that node.
563
564 change_table_load_order(Tab :: table(), Order) -> t_result(ok)
565
566 Types:
567
568 Order = integer() >= 0
569
570 The LoadOrder priority is by default 0 (zero) but can be set to
571 any integer. The tables with the highest LoadOrder priority are
572 loaded first at startup.
573
574 change_table_majority(Tab :: table(), M :: boolean()) ->
575 t_result(ok)
576
577 Majority must be a boolean. Default is false. When true, a ma‐
578 jority of the table replicas must be available for an update to
579 succeed. When used on fragmented tables, Tab must be the base
580 table name. Directly changing the majority setting on individual
581 fragments is not allowed.
582
583 clear_table(Tab :: table()) -> t_result(ok)
584
585 Deletes all entries in the table Tab.
586
587 create_schema(Ns :: [node()]) -> result()
588
589 Creates a new database on disc. Various files are created in the
590 local Mnesia directory of each node. Notice that the directory
591 must be unique for each node. Two nodes must never share the
592 same directory. If possible, use a local disc device to improve
593 performance.
594
595 mnesia:create_schema/1 fails if any of the Erlang nodes given as
596 DiscNodes are not alive, if Mnesia is running on any of the
597 nodes, or if any of the nodes already have a schema. Use mne‐
598 sia:delete_schema/1 to get rid of old faulty schemas.
599
600 Notice that only nodes with disc are to be included in DiscN‐
601 odes. Disc-less nodes, that is, nodes where all tables including
602 the schema only resides in RAM, must not be included.
603
604 create_table(Name :: table(), Arg :: [create_option()]) ->
605 t_result(ok)
606
607 Creates a Mnesia table called Name according to argument TabDef.
608 This list must be a list of {Item, Value} tuples, where the fol‐
609 lowing values are allowed:
610
611 * {access_mode, Atom}. The access mode is by default the atom
612 read_write but it can also be set to the atom read_only. If
613 AccessMode is set to read_only, updates to the table cannot
614 be performed.
615
616 At startup, Mnesia always loads read_only table locally re‐
617 gardless of when and if Mnesia is terminated on other nodes.
618 This argument returns the access mode of the table. The ac‐
619 cess mode can be read_only or read_write.
620
621 * {attributes, AtomList} is a list of the attribute names for
622 the records that are supposed to populate the table. Default
623 is [key, val]. The table must at least have one extra attri‐
624 bute in addition to the key.
625
626 When accessing single attributes in a record, it is not nec‐
627 essary, or even recommended, to hard code any attribute
628 names as atoms. Use construct record_info(fields, Record‐
629 Name) instead. It can be used for records of type Record‐
630 Name.
631
632 * {disc_copies, Nodelist}, where Nodelist is a list of the
633 nodes where this table is supposed to have disc copies. If a
634 table replica is of type disc_copies, all write operations
635 on this particular replica of the table are written to disc
636 and to the RAM copy of the table.
637
638 It is possible to have a replicated table of type
639 disc_copies on one node and another type on another node.
640 Default is [].
641
642 * {disc_only_copies, Nodelist}, where Nodelist is a list of
643 the nodes where this table is supposed to have
644 disc_only_copies. A disc only table replica is kept on disc
645 only and unlike the other replica types, the contents of the
646 replica do not reside in RAM. These replicas are consider‐
647 ably slower than replicas held in RAM.
648
649 * {index, Intlist}, where Intlist is a list of attribute names
650 (atoms) or record fields for which Mnesia is to build and
651 maintain an extra index table. The qlc query compiler may be
652 able to optimize queries if there are indexes available.
653
654 * {load_order, Integer}. The load order priority is by default
655 0 (zero) but can be set to any integer. The tables with the
656 highest load order priority are loaded first at startup.
657
658 * {majority, Flag}, where Flag must be a boolean. If true, any
659 (non-dirty) update to the table is aborted, unless a major‐
660 ity of the table replicas are available for the commit. When
661 used on a fragmented table, all fragments are given the same
662 majority setting.
663
664 * {ram_copies, Nodelist}, where Nodelist is a list of the
665 nodes where this table is supposed to have RAM copies. A ta‐
666 ble replica of type ram_copies is not written to disc on a
667 per transaction basis. ram_copies replicas can be dumped to
668 disc with the function mnesia:dump_tables(Tabs). Default
669 value for this attribute is [node()].
670
671 * {record_name, Name}, where Name must be an atom. All records
672 stored in the table must have this name as the first ele‐
673 ment. It defaults to the same name as the table name.
674
675 * {snmp, SnmpStruct}. For a description of SnmpStruct, see
676 mnesia:snmp_open_table/2. If this attribute is present in
677 ArgList to mnesia:create_table/2, the table is immediately
678 accessible by SNMP. Therefore applications that use SNMP to
679 manipulate and control the system can be designed easily,
680 since Mnesia provides a direct mapping between the logical
681 tables that make up an SNMP control application and the
682 physical data that makes up a Mnesia table.
683
684 * {storage_properties, [{Backend, Properties}] forwards more
685 properties to the back end storage. Backend can currently be
686 ets or dets. Properties is a list of options sent to the
687 back end storage during table creation. Properties cannot
688 contain properties already used by Mnesia, such as type or
689 named_table.
690
691 For example:
692
693 mnesia:create_table(table, [{ram_copies, [node()]}, {disc_only_copies, nodes()},
694 {storage_properties,
695 [{ets, [compressed]}, {dets, [{auto_save, 5000}]} ]}])
696
697 * {type, Type}, where Type must be either of the atoms set,
698 ordered_set, or bag. Default is set. In a set, all records
699 have unique keys. In a bag, several records can have the
700 same key, but the record content is unique. If a non-unique
701 record is stored, the old conflicting records are overwrit‐
702 ten.
703
704 Notice that currently ordered_set is not supported for
705 disc_only_copies.
706
707 * {local_content, Bool}, where Bool is true or false. Default
708 is false.
709
710 For example, the following call creates the person table (de‐
711 fined earlier) and replicates it on two nodes:
712
713 mnesia:create_table(person,
714 [{ram_copies, [N1, N2]},
715 {attributes, record_info(fields, person)}]).
716
717 If it is required that Mnesia must build and maintain an extra
718 index table on attribute address of all the person records that
719 are inserted in the table, the following code would be issued:
720
721 mnesia:create_table(person,
722 [{ram_copies, [N1, N2]},
723 {index, [address]},
724 {attributes, record_info(fields, person)}]).
725
726
727 The specification of index and attributes can be hard-coded as
728 {index, [2]} and {attributes, [name, age, address, salary, chil‐
729 dren]}, respectively.
730
731 mnesia:create_table/2 writes records into the table schema. This
732 function, and all other schema manipulation functions, are im‐
733 plemented with the normal transaction management system. This
734 guarantees that schema updates are performed on all nodes in an
735 atomic manner.
736
737 deactivate_checkpoint(Name :: term()) -> result()
738
739 The checkpoint is automatically deactivated when some of the ta‐
740 bles involved have no retainer attached to them. This can occur
741 when nodes go down or when a replica is deleted. Checkpoints are
742 also deactivated with this function. Name is the name of an ac‐
743 tive checkpoint.
744
745 del_table_copy(Tab :: table(), N :: node()) -> t_result(ok)
746
747 Deletes the replica of table Tab at node Node. When the last
748 replica is deleted with this function, the table disappears en‐
749 tirely.
750
751 This function can also be used to delete a replica of the table
752 named schema. The Mnesia node is then removed. Notice that Mne‐
753 sia must be stopped on the node first.
754
755 del_table_index(Tab, I) -> t_result(ok)
756
757 Types:
758
759 Tab = table()
760 I = index_attr()
761
762 Deletes the index on attribute with name AttrName in a table.
763
764 delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
765
766 Calls mnesia:delete(Tab, Key, write).
767
768 delete(Tab :: table(), Key :: term(), LockKind :: write_locks()) ->
769 ok
770
771 Deletes all records in table Tab with the key Key.
772
773 The semantics of this function is context-sensitive. For de‐
774 tails, see mnesia:activity/4. In transaction-context, it ac‐
775 quires a lock of type LockKind in the record. Currently, the
776 lock types write and sticky_write are supported.
777
778 delete_object(Rec :: tuple()) -> ok
779
780 Calls mnesia:delete_object(Tab, Record, write), where Tab is el‐
781 ement(1, Record).
782
783 delete_object(Tab :: table(),
784 Rec :: tuple(),
785 LockKind :: write_locks()) ->
786 ok
787
788 If a table is of type bag, it can sometimes be needed to delete
789 only some of the records with a certain key. This can be done
790 with the function delete_object/3. A complete record must be
791 supplied to this function.
792
793 The semantics of this function is context-sensitive. For de‐
794 tails, see mnesia:activity/4. In transaction-context, it ac‐
795 quires a lock of type LockKind on the record. Currently, the
796 lock types write and sticky_write are supported.
797
798 delete_schema(Ns :: [node()]) -> result()
799
800 Deletes a database created with mnesia:create_schema/1. mne‐
801 sia:delete_schema/1 fails if any of the Erlang nodes given as
802 DiscNodes are not alive, or if Mnesia is running on any of the
803 nodes.
804
805 After the database is deleted, it can still be possible to start
806 Mnesia as a disc-less node. This depends on how configuration
807 parameter schema_location is set.
808
809 Warning:
810 Use this function with extreme caution, as it makes existing
811 persistent data obsolete. Think twice before using it.
812
813
814 delete_table(Tab :: table()) -> t_result(ok)
815
816 Permanently deletes all replicas of table Tab.
817
818 dirty_all_keys(Tab :: table()) -> [Key :: term()]
819
820 Dirty equivalent of the function mnesia:all_keys/1.
821
822 dirty_delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
823
824 Calls mnesia:dirty_delete(Tab, Key).
825
826 dirty_delete(Tab :: table(), Key :: term()) -> ok
827
828 Dirty equivalent of the function mnesia:delete/3.
829
830 dirty_delete_object(Record :: tuple()) -> ok
831
832 Calls mnesia:dirty_delete_object(Tab, Record), where Tab is ele‐
833 ment(1, Record).
834
835 dirty_delete_object(Tab :: table(), Record :: tuple()) -> ok
836
837 Dirty equivalent of the function mnesia:delete_object/3.
838
839 dirty_first(Tab :: table()) -> Key :: term()
840
841 Records in set or bag tables are not ordered. However, there is
842 an ordering of the records that is unknown to the user. There‐
843 fore, a table can be traversed by this function with the func‐
844 tion mnesia:dirty_next/2.
845
846 If there are no records in the table, this function returns the
847 atom '$end_of_table'. It is therefore highly undesirable, but
848 not disallowed, to use this atom as the key for any user
849 records.
850
851 dirty_index_match_object(Pattern, Attr) -> [Record]
852
853 Types:
854
855 Pattern = tuple()
856 Attr = index_attr()
857 Record = tuple()
858
859 Starts mnesia:dirty_index_match_object(Tab, Pattern, Pos), where
860 Tab is element(1, Pattern).
861
862 dirty_index_match_object(Tab, Pattern, Attr) -> [Record]
863
864 Types:
865
866 Tab = table()
867 Pattern = tuple()
868 Attr = index_attr()
869 Record = tuple()
870
871 Dirty equivalent of the function mnesia:index_match_object/4.
872
873 dirty_index_read(Tab, Key, Attr) -> [Record]
874
875 Types:
876
877 Tab = table()
878 Key = term()
879 Attr = index_attr()
880 Record = tuple()
881
882 Dirty equivalent of the function mnesia:index_read/3.
883
884 dirty_last(Tab :: table()) -> Key :: term()
885
886 Works exactly like mnesia:dirty_first/1 but returns the last ob‐
887 ject in Erlang term order for the ordered_set table type. For
888 all other table types, mnesia:dirty_first/1 and mne‐
889 sia:dirty_last/1 are synonyms.
890
891 dirty_match_object(Pattern :: tuple()) -> [Record :: tuple()]
892
893 Calls mnesia:dirty_match_object(Tab, Pattern), where Tab is ele‐
894 ment(1, Pattern).
895
896 dirty_match_object(Tab, Pattern) -> [Record]
897
898 Types:
899
900 Tab = table()
901 Pattern = Record = tuple()
902
903 Dirty equivalent of the function mnesia:match_object/3.
904
905 dirty_next(Tab :: table(), Key :: term()) -> NextKey :: term()
906
907 Traverses a table and performs operations on all records in the
908 table. When the end of the table is reached, the special key
909 '$end_of_table' is returned. Otherwise, the function returns a
910 key that can be used to read the actual record. The behavior is
911 undefined if another Erlang process performs write operations on
912 the table while it is being traversed with the function mne‐
913 sia:dirty_next/2.
914
915 dirty_prev(Tab :: table(), Key :: term()) -> PrevKey :: term()
916
917 Works exactly like mnesia:dirty_next/2 but returns the previous
918 object in Erlang term order for the ordered_set table type. For
919 all other table types, mnesia:dirty_next/2 and mne‐
920 sia:dirty_prev/2 are synonyms.
921
922 dirty_read(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
923
924 Calls mnesia:dirty_read(Tab, Key).
925
926 dirty_read(Tab :: table(), Key :: term()) -> [tuple()]
927
928 Dirty equivalent of the function mnesia:read/3.
929
930 dirty_select(Tab, Spec) -> [Match]
931
932 Types:
933
934 Tab = table()
935 Spec = ets:match_spec()
936 Match = term()
937
938 Dirty equivalent of the function mnesia:select/2.
939
940 dirty_update_counter(Counter :: {Tab :: table(), Key :: term()},
941 Incr :: integer()) ->
942 NewVal :: integer()
943
944 Calls mnesia:dirty_update_counter(Tab, Key, Incr).
945
946 dirty_update_counter(Tab :: table(),
947 Key :: term(),
948 Incr :: integer()) ->
949 NewVal :: integer()
950
951 Mnesia has no special counter records. However, records of the
952 form {Tab, Key, Integer} can be used as (possibly disc-resident)
953 counters when Tab is a set. This function updates a counter with
954 a positive or negative number. However, counters can never be‐
955 come less than zero. There are two significant differences be‐
956 tween this function and the action of first reading the record,
957 performing the arithmetic, and then writing the record:
958
959 * It is much more efficient.
960
961 * mnesia:dirty_update_counter/3 is performed as an atomic op‐
962 eration although it is not protected by a transaction.
963
964 If two processes perform mnesia:dirty_update_counter/3 simulta‐
965 neously, both updates take effect without the risk of losing one
966 of the updates. The new value NewVal of the counter is returned.
967
968 If Key does not exist, a new record is created with value Incr
969 if it is larger than 0, otherwise it is set to 0.
970
971 dirty_write(Record :: tuple()) -> ok
972
973 Calls mnesia:dirty_write(Tab, Record), where Tab is element(1,
974 Record).
975
976 dirty_write(Tab :: table(), Record :: tuple()) -> ok
977
978 Dirty equivalent of the function mnesia:write/3.
979
980 dump_log() -> dumped
981
982 Performs a user-initiated dump of the local log file. This is
983 usually not necessary, as Mnesia by default manages this auto‐
984 matically. See configuration parameters dump_log_time_threshold
985 and dump_log_write_threshold.
986
987 dump_tables(Tabs :: [Tab :: table()]) -> t_result(ok)
988
989 Dumps a set of ram_copies tables to disc. The next time the sys‐
990 tem is started, these tables are initiated with the data found
991 in the files that are the result of this dump. None of the ta‐
992 bles can have disc-resident replicas.
993
994 dump_to_textfile(File :: file:filename()) -> result() | error
995
996 Dumps all local tables of a Mnesia system into a text file,
997 which can be edited (by a normal text editor) and then be
998 reloaded with mnesia:load_textfile/1. Only use this function for
999 educational purposes. Use other functions to deal with real
1000 backups.
1001
1002 error_description(Error :: term()) -> string()
1003
1004 All Mnesia transactions, including all the schema update func‐
1005 tions, either return value {atomic, Val} or the tuple {aborted,
1006 Reason}. Reason can be either of the atoms in the following
1007 list. The function error_description/1 returns a descriptive
1008 string that describes the error.
1009
1010 * nested_transaction. Nested transactions are not allowed in
1011 this context.
1012
1013 * badarg. Bad or invalid argument, possibly bad type.
1014
1015 * no_transaction. Operation not allowed outside transactions.
1016
1017 * combine_error. Table options illegally combined.
1018
1019 * bad_index. Index already exists, or was out of bounds.
1020
1021 * already_exists. Schema option to be activated is already on.
1022
1023 * index_exists. Some operations cannot be performed on tables
1024 with an index.
1025
1026 * no_exists. Tried to perform operation on non-existing (not-
1027 alive) item.
1028
1029 * system_limit. A system limit was exhausted.
1030
1031 * mnesia_down. A transaction involves records on a remote
1032 node, which became unavailable before the transaction was
1033 completed. Records are no longer available elsewhere in the
1034 network.
1035
1036 * not_a_db_node. A node was mentioned that does not exist in
1037 the schema.
1038
1039 * bad_type. Bad type specified in argument.
1040
1041 * node_not_running. Node is not running.
1042
1043 * truncated_binary_file. Truncated binary in file.
1044
1045 * active. Some delete operations require that all active
1046 records are removed.
1047
1048 * illegal. Operation not supported on this record.
1049
1050 Error can be Reason, {error, Reason}, or {aborted, Reason}. Rea‐
1051 son can be an atom or a tuple with Reason as an atom in the
1052 first field.
1053
1054 The following examples illustrate a function that returns an er‐
1055 ror, and the method to retrieve more detailed error information:
1056
1057 * The function mnesia:create_table(bar, [{attributes, 3.14}])
1058 returns the tuple {aborted,Reason}, where Reason is the tu‐
1059 ple {bad_type,bar,3.14000}.
1060
1061 * The function mnesia:error_description(Reason) returns the
1062 term {"Bad type on some provided arguments",bar,3.14000},
1063 which is an error description suitable for display.
1064
1065 ets(Fun) -> Res | no_return()
1066
1067 ets(Fun, Args :: [Arg :: term()]) -> Res | no_return()
1068
1069 Types:
1070
1071 Fun = fun((...) -> Res)
1072
1073 Calls the Fun in a raw context that is not protected by a trans‐
1074 action. The Mnesia function call is performed in the Fun and
1075 performed directly on the local ETS tables on the assumption
1076 that the local storage type is ram_copies and the tables are not
1077 replicated to other nodes. Subscriptions are not triggered and
1078 checkpoints are not updated, but it is extremely fast. This
1079 function can also be applied to disc_copies tables if all opera‐
1080 tions are read only. For details, see mnesia:activity/4 and the
1081 User's Guide.
1082
1083 Notice that calling (nesting) a mnesia:ets inside a transaction-
1084 context inherits the transaction semantics.
1085
1086 first(Tab :: table()) -> Key :: term()
1087
1088 Records in set or bag tables are not ordered. However, there is
1089 an ordering of the records that is unknown to the user. A table
1090 can therefore be traversed by this function with the function
1091 mnesia:next/2.
1092
1093 If there are no records in the table, this function returns the
1094 atom '$end_of_table'. It is therefore highly undesirable, but
1095 not disallowed, to use this atom as the key for any user
1096 records.
1097
1098 foldl(Fun, Acc0, Tab :: table()) -> Acc
1099
1100 Types:
1101
1102 Fun = fun((Record :: tuple(), Acc0) -> Acc)
1103
1104 Iterates over the table Table and calls Function(Record, NewAcc)
1105 for each Record in the table. The term returned from Function is
1106 used as the second argument in the next call to Function.
1107
1108 foldl returns the same term as the last call to Function re‐
1109 turned.
1110
1111 foldr(Fun, Acc0, Tab :: table()) -> Acc
1112
1113 Types:
1114
1115 Fun = fun((Record :: tuple(), Acc0) -> Acc)
1116
1117 Works exactly like foldl/3 but iterates the table in the oppo‐
1118 site order for the ordered_set table type. For all other table
1119 types, foldr/3 and foldl/3 are synonyms.
1120
1121 force_load_table(Tab :: table()) ->
1122 yes | {error, Reason :: term()}
1123
1124 The Mnesia algorithm for table load can lead to a situation
1125 where a table cannot be loaded. This situation occurs when a
1126 node is started and Mnesia concludes, or suspects, that another
1127 copy of the table was active after this local copy became inac‐
1128 tive because of a system crash.
1129
1130 If this situation is not acceptable, this function can be used
1131 to override the strategy of the Mnesia table load algorithm.
1132 This can lead to a situation where some transaction effects are
1133 lost with an inconsistent database as result, but for some ap‐
1134 plications high availability is more important than consistent
1135 data.
1136
1137 index_match_object(Pattern, Attr) -> [Record]
1138
1139 Types:
1140
1141 Pattern = tuple()
1142 Attr = index_attr()
1143 Record = tuple()
1144
1145 Starts mnesia:index_match_object(Tab, Pattern, Pos, read), where
1146 Tab is element(1, Pattern).
1147
1148 index_match_object(Tab, Pattern, Attr, LockKind) -> [Record]
1149
1150 Types:
1151
1152 Tab = table()
1153 Pattern = tuple()
1154 Attr = index_attr()
1155 LockKind = lock_kind()
1156 Record = tuple()
1157
1158 In a manner similar to the function mnesia:index_read/3, any in‐
1159 dex information can be used when trying to match records. This
1160 function takes a pattern that obeys the same rules as the func‐
1161 tion mnesia:match_object/3, except that this function requires
1162 the following conditions:
1163
1164 * The table Tab must have an index on position Pos.
1165
1166 * The element in position Pos in Pattern must be bound. Pos is
1167 an integer (#record.Field) or an attribute name.
1168
1169 The two index search functions described here are automatically
1170 started when searching tables with qlc list comprehensions and
1171 also when using the low-level mnesia:[dirty_]match_object func‐
1172 tions.
1173
1174 The semantics of this function is context-sensitive. For de‐
1175 tails, see mnesia:activity/4. In transaction-context, it ac‐
1176 quires a lock of type LockKind on the entire table or on a sin‐
1177 gle record. Currently, the lock type read is supported.
1178
1179 index_read(Tab, Key, Attr) -> [Record]
1180
1181 Types:
1182
1183 Tab = table()
1184 Key = term()
1185 Attr = index_attr()
1186 Record = tuple()
1187
1188 Assume that there is an index on position Pos for a certain
1189 record type. This function can be used to read the records with‐
1190 out knowing the actual key for the record. For example, with an
1191 index in position 1 of table person, the call mnesia:in‐
1192 dex_read(person, 36, #person.age) returns a list of all persons
1193 with age 36. Pos can also be an attribute name (atom), but if
1194 the notation mnesia:index_read(person, 36, age) is used, the
1195 field position is searched for in runtime, for each call.
1196
1197 The semantics of this function is context-sensitive. For de‐
1198 tails, see mnesia:activity/4. In transaction-context, it ac‐
1199 quires a read lock on the entire table.
1200
1201 info() -> ok
1202
1203 Prints system information on the terminal. This function can be
1204 used even if Mnesia is not started. However, more information is
1205 displayed if Mnesia is started.
1206
1207 install_fallback(Src :: term()) -> result()
1208
1209 Calls mnesia:install_fallback(Opaque, Args), where Args is
1210 [{scope, global}].
1211
1212 install_fallback(Src :: term(), Mod :: module() | [Opt]) ->
1213 result()
1214
1215 Types:
1216
1217 Opt = Module | Scope | Dir
1218 Module = {module, Mod :: module()}
1219 Scope = {scope, global | local}
1220 Dir = {mnesia_dir, Dir :: string()}
1221
1222 Installs a backup as fallback. The fallback is used to restore
1223 the database at the next startup. Installation of fallbacks re‐
1224 quires Erlang to be operational on all the involved nodes, but
1225 it does not matter if Mnesia is running or not. The installation
1226 of the fallback fails if the local node is not one of the disc-
1227 resident nodes in the backup.
1228
1229 Args is a list of the following tuples:
1230
1231 * {module, BackupMod}. All accesses of the backup media are
1232 performed through a callback module named BackupMod. Argu‐
1233 ment Opaque is forwarded to the callback module, which can
1234 interpret it as it wishes. The default callback module is
1235 called mnesia_backup and it interprets argument Opaque as a
1236 local filename. The default for this module is also config‐
1237 urable through configuration parameter -mnesia mne‐
1238 sia_backup.
1239
1240 * {scope, Scope}. The Scope of a fallback is either global for
1241 the entire database or local for one node. By default, the
1242 installation of a fallback is a global operation, which ei‐
1243 ther is performed on all nodes with a disc-resident schema
1244 or none. Which nodes that are disc-resident is determined
1245 from the schema information in the backup.
1246
1247 If Scope of the operation is local, the fallback is only in‐
1248 stalled on the local node.
1249
1250 * {mnesia_dir, AlternateDir}. This argument is only valid if
1251 the scope of the installation is local. Normally the instal‐
1252 lation of a fallback is targeted to the Mnesia directory, as
1253 configured with configuration parameter -mnesia dir. But by
1254 explicitly supplying an AlternateDir, the fallback is in‐
1255 stalled there regardless of the Mnesia directory configura‐
1256 tion parameter setting. After installation of a fallback on
1257 an alternative Mnesia directory, that directory is fully
1258 prepared for use as an active Mnesia directory.
1259
1260 This is a dangerous feature that must be used with care. By
1261 unintentional mixing of directories, you can easily end up
1262 with an inconsistent database, if the same backup is in‐
1263 stalled on more than one directory.
1264
1265 is_transaction() -> boolean()
1266
1267 When this function is executed inside a transaction-context, it
1268 returns true, otherwise false.
1269
1270 last(Tab :: table()) -> Key :: term()
1271
1272 Works exactly like mnesia:first/1, but returns the last object
1273 in Erlang term order for the ordered_set table type. For all
1274 other table types, mnesia:first/1 and mnesia:last/1 are syn‐
1275 onyms.
1276
1277 load_textfile(File :: file:filename()) ->
1278 t_result(ok) | {error, term()}
1279
1280 Loads a series of definitions and data found in the text file
1281 (generated with mnesia:dump_to_textfile/1) into Mnesia. This
1282 function also starts Mnesia and possibly creates a new schema.
1283 This function is intended for educational purposes only. It is
1284 recommended to use other functions to deal with real backups.
1285
1286 lock(LockItem, LockKind) -> list() | tuple() | no_return()
1287
1288 Types:
1289
1290 LockItem =
1291 {record, table(), Key :: term()} |
1292 {table, table()} |
1293 {global, Key :: term(), MnesiaNodes :: [node()]}
1294 LockKind = lock_kind() | load
1295
1296 Write locks are normally acquired on all nodes where a replica
1297 of the table resides (and is active). Read locks are acquired on
1298 one node (the local node if a local replica exists). Most of the
1299 context-sensitive access functions acquire an implicit lock if
1300 they are started in a transaction-context. The granularity of a
1301 lock can either be a single record or an entire table.
1302
1303 The normal use is to call the function without checking the re‐
1304 turn value, as it exits if it fails and the transaction is
1305 restarted by the transaction manager. It returns all the locked
1306 nodes if a write lock is acquired and ok if it was a read lock.
1307
1308 The function mnesia:lock/2 is intended to support explicit lock‐
1309 ing on tables, but is also intended for situations when locks
1310 need to be acquired regardless of how tables are replicated.
1311 Currently, two kinds of LockKind are supported:
1312
1313 write:
1314 Write locks are exclusive. This means that if one transac‐
1315 tion manages to acquire a write lock on an item, no other
1316 transaction can acquire any kind of lock on the same item.
1317
1318 read:
1319 Read locks can be shared. This means that if one transaction
1320 manages to acquire a read lock on an item, other transac‐
1321 tions can also acquire a read lock on the same item. How‐
1322 ever, if someone has a read lock, no one can acquire a write
1323 lock at the same item. If someone has a write lock, no one
1324 can acquire either a read lock or a write lock at the same
1325 item.
1326
1327 Conflicting lock requests are automatically queued if there is
1328 no risk of a deadlock. Otherwise the transaction must be termi‐
1329 nated and executed again. Mnesia does this automatically as long
1330 as the upper limit of the maximum retries is not reached. For
1331 details, see mnesia:transaction/3.
1332
1333 For the sake of completeness, sticky write locks are also de‐
1334 scribed here even if a sticky write lock is not supported by
1335 this function:
1336
1337 sticky_write:
1338 Sticky write locks are a mechanism that can be used to opti‐
1339 mize write lock acquisition. If your application uses repli‐
1340 cated tables mainly for fault tolerance (as opposed to read
1341 access optimization purpose), sticky locks can be the best
1342 option available.
1343
1344 When a sticky write lock is acquired, all nodes are informed
1345 which node is locked. Then, sticky lock requests from the
1346 same node are performed as a local operation without any
1347 communication with other nodes. The sticky lock lingers on
1348 the node even after the transaction ends. For details, see
1349 the User's Guide.
1350
1351 Currently, this function supports two kinds of LockItem:
1352
1353 {table, Tab}:
1354 This acquires a lock of type LockKind on the entire table
1355 Tab.
1356
1357 {global, GlobalKey, Nodes}:
1358 This acquires a lock of type LockKind on the global resource
1359 GlobalKey. The lock is acquired on all active nodes in the
1360 Nodes list.
1361
1362 Locks are released when the outermost transaction ends.
1363
1364 The semantics of this function is context-sensitive. For de‐
1365 tails, see mnesia:activity/4. In transaction-context, it ac‐
1366 quires locks, otherwise it ignores the request.
1367
1368 match_object(Pattern :: tuple()) -> [Record :: tuple()]
1369
1370 Calls mnesia:match_object(Tab, Pattern, read), where Tab is ele‐
1371 ment(1, Pattern).
1372
1373 match_object(Tab, Pattern, LockKind) -> [Record]
1374
1375 Types:
1376
1377 Tab = table()
1378 Pattern = tuple()
1379 LockKind = lock_kind()
1380 Record = tuple()
1381
1382 Takes a pattern with "don't care" variables denoted as a '_' pa‐
1383 rameter. This function returns a list of records that matched
1384 the pattern. Since the second element of a record in a table is
1385 considered to be the key for the record, the performance of this
1386 function depends on whether this key is bound or not.
1387
1388 For example, the call mnesia:match_object(person, {person, '_',
1389 36, '_', '_'}, read) returns a list of all person records with
1390 an age field of 36.
1391
1392 The function mnesia:match_object/3 automatically uses indexes if
1393 these exist. However, no heuristics are performed to select the
1394 best index.
1395
1396 The semantics of this function is context-sensitive. For de‐
1397 tails, see mnesia:activity/4. In transaction-context, it ac‐
1398 quires a lock of type LockKind on the entire table or a single
1399 record. Currently, the lock type read is supported.
1400
1401 move_table_copy(Tab :: table(), From :: node(), To :: node()) ->
1402 t_result(ok)
1403
1404 Moves the copy of table Tab from node From to node To.
1405
1406 The storage type is preserved. For example, a RAM table moved
1407 from one node remains a RAM on the new node. Other transactions
1408 can still read and write in the table while it is being moved.
1409
1410 This function cannot be used on local_content tables.
1411
1412 next(Tab :: table(), Key :: term()) -> NextKey :: term()
1413
1414 Traverses a table and performs operations on all records in the
1415 table. When the end of the table is reached, the special key
1416 '$end_of_table' is returned. Otherwise the function returns a
1417 key that can be used to read the actual record.
1418
1419 prev(Tab :: table(), Key :: term()) -> PrevKey :: term()
1420
1421 Works exactly like mnesia:next/2, but returns the previous ob‐
1422 ject in Erlang term order for the ordered_set table type. For
1423 all other table types, mnesia:next/2 and mnesia:prev/2 are syn‐
1424 onyms.
1425
1426 read(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
1427
1428 read(Tab :: table(), Key :: term()) -> [tuple()]
1429
1430 Calls function mnesia:read(Tab, Key, read).
1431
1432 read(Tab :: table(), Key :: term(), LockKind :: lock_kind()) ->
1433 [tuple()]
1434
1435 Reads all records from table Tab with key Key. This function has
1436 the same semantics regardless of the location of Tab. If the ta‐
1437 ble is of type bag, the function mnesia:read(Tab, Key) can re‐
1438 turn an arbitrarily long list. If the table is of type set, the
1439 list is either of length 1, or [].
1440
1441 The semantics of this function is context-sensitive. For de‐
1442 tails, see mnesia:activity/4. In transaction-context, it ac‐
1443 quires a lock of type LockKind. Currently, the lock types read,
1444 write, and sticky_write are supported.
1445
1446 If the user wants to update the record, it is more efficient to
1447 use write/sticky_write as the LockKind. If majority checking is
1448 active on the table, it is checked as soon as a write lock is
1449 attempted. This can be used to end quickly if the majority con‐
1450 dition is not met.
1451
1452 read_lock_table(Tab :: table()) -> ok
1453
1454 Calls the function mnesia:lock({table, Tab}, read).
1455
1456 report_event(Event :: term()) -> ok
1457
1458 When tracing a system of Mnesia applications it is useful to be
1459 able to interleave Mnesia own events with application-related
1460 events that give information about the application context.
1461
1462 Whenever the application begins a new and demanding Mnesia task,
1463 or if it enters a new interesting phase in its execution, it can
1464 be a good idea to use mnesia:report_event/1. Event can be any
1465 term and generates a {mnesia_user, Event} event for any pro‐
1466 cesses that subscribe to Mnesia system events.
1467
1468 restore(Src :: term(), Args :: [Arg]) -> t_result([table()])
1469
1470 Types:
1471
1472 Op = skip_tables | clear_tables | keep_tables | restore_ta‐
1473 bles
1474 Arg = {module, module()} | {Op, [table()]} | {default_op, Op}
1475
1476 With this function, tables can be restored online from a backup
1477 without restarting Mnesia. Opaque is forwarded to the backup
1478 module. Args is a list of the following tuples:
1479
1480 * {module,BackupMod}. The backup module BackupMod is used to
1481 access the backup media. If omitted, the default backup mod‐
1482 ule is used.
1483
1484 * {skip_tables, TabList}, where TabList is a list of tables
1485 that is not to be read from the backup.
1486
1487 * {clear_tables, TabList}, where TabList is a list of tables
1488 that is to be cleared before the records from the backup are
1489 inserted. That is, all records in the tables are deleted be‐
1490 fore the tables are restored. Schema information about the
1491 tables is not cleared or read from the backup.
1492
1493 * {keep_tables, TabList}, where TabList is a list of tables
1494 that is not to be cleared before the records from the backup
1495 are inserted. That is, the records in the backup are added
1496 to the records in the table. Schema information about the
1497 tables is not cleared or read from the backup.
1498
1499 * {recreate_tables, TabList}, where TabList is a list of ta‐
1500 bles that is to be recreated before the records from the
1501 backup are inserted. The tables are first deleted and then
1502 created with the schema information from the backup. All the
1503 nodes in the backup need to be operational.
1504
1505 * {default_op, Operation}, where Operation is either of the
1506 operations skip_tables, clear_tables, keep_tables, or recre‐
1507 ate_tables. The default operation specifies which operation
1508 that is to be used on tables from the backup that is not
1509 specified in any of the mentioned lists. If omitted, opera‐
1510 tion clear_tables is used.
1511
1512 The affected tables are write-locked during the restoration.
1513 However, regardless of the lock conflicts caused by this, the
1514 applications can continue to do their work while the restoration
1515 is being performed. The restoration is performed as one single
1516 transaction.
1517
1518 If the database is huge, it it not always possible to restore it
1519 online. In such cases, restore the old database by installing a
1520 fallback and then restart.
1521
1522 s_delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
1523
1524 Calls the function mnesia:delete(Tab, Key, sticky_write)
1525
1526 s_delete_object(Rec :: tuple()) -> ok
1527
1528 Calls the function mnesia:delete_object(Tab, Record,
1529 sticky_write), where Tab is element(1, Record).
1530
1531 s_write(Record :: tuple()) -> ok
1532
1533 Calls the function mnesia:write(Tab, Record, sticky_write),
1534 where Tab is element(1, Record).
1535
1536 schema() -> ok
1537
1538 Prints information about all table definitions on the terminal.
1539
1540 schema(Tab :: table()) -> ok
1541
1542 Prints information about one table definition on the terminal.
1543
1544 select(Tab, Spec) -> [Match]
1545
1546 select(Tab, Spec, LockKind) -> [Match]
1547
1548 Types:
1549
1550 Tab = table()
1551 Spec = ets:match_spec()
1552 Match = term()
1553 LockKind = lock_kind()
1554
1555 Matches the objects in table Tab using a match_spec as described
1556 in the ets:select/3. Optionally a lock read or write can be
1557 given as the third argument. Default is read. The return value
1558 depends on MatchSpec.
1559
1560 Notice that for best performance, select is to be used before
1561 any modifying operations are done on that table in the same
1562 transaction. That is, do not use write or delete before a se‐
1563 lect.
1564
1565 In its simplest forms, the match_spec look as follows:
1566
1567 * MatchSpec = [MatchFunction]
1568
1569 * MatchFunction = {MatchHead, [Guard], [Result]}
1570
1571 * MatchHead = tuple() | record()
1572
1573 * Guard = {"Guardtest name", ...}
1574
1575 * Result = "Term construct"
1576
1577 For a complete description of select, see the ERTS User's Guide
1578 and the ets manual page in STDLIB.
1579
1580 For example, to find the names of all male persons older than 30
1581 in table Tab:
1582
1583 MatchHead = #person{name='$1', sex=male, age='$2', _='_'},
1584 Guard = {'>', '$2', 30},
1585 Result = '$1',
1586 mnesia:select(Tab,[{MatchHead, [Guard], [Result]}]),
1587
1588 select(Tab, Spec, N, LockKind) ->
1589 {[Match], Cont} | '$end_of_table'
1590
1591 Types:
1592
1593 Tab = table()
1594 Spec = ets:match_spec()
1595 Match = term()
1596 N = integer() >= 0
1597 LockKind = lock_kind()
1598 Cont = select_continuation()
1599
1600 Matches the objects in table Tab using a match_spec as described
1601 in the ERTS User's Guide, and returns a chunk of terms and a
1602 continuation. The wanted number of returned terms is specified
1603 by argument NObjects. The lock argument can be read or write.
1604 The continuation is to be used as argument to mnesia:select/1,
1605 if more or all answers are needed.
1606
1607 Notice that for best performance, select is to be used before
1608 any modifying operations are done on that table in the same
1609 transaction. That is, do not use mnesia:write or mnesia:delete
1610 before a mnesia:select. For efficiency, NObjects is a recommen‐
1611 dation only and the result can contain anything from an empty
1612 list to all available results.
1613
1614 select(Cont) -> {[Match], Cont} | '$end_of_table'
1615
1616 Types:
1617
1618 Match = term()
1619 Cont = select_continuation()
1620
1621 Selects more objects with the match specification initiated by
1622 mnesia:select/4.
1623
1624 Notice that any modifying operations, that is, mnesia:write or
1625 mnesia:delete, that are done between the mnesia:select/4 and
1626 mnesia:select/1 calls are not visible in the result.
1627
1628 set_debug_level(Level :: debug_level()) ->
1629 OldLevel :: debug_level()
1630
1631 Changes the internal debug level of Mnesia. For details, see
1632 Section Configuration Parameters.
1633
1634 set_master_nodes(Ns :: [node()]) -> result()
1635
1636 For each table Mnesia determines its replica nodes (TabNodes)
1637 and starts mnesia:set_master_nodes(Tab, TabMasterNodes). where
1638 TabMasterNodes is the intersection of MasterNodes and TabNodes.
1639 For semantics, see mnesia:set_master_nodes/2.
1640
1641 set_master_nodes(Tab :: table(), Ns :: [node()]) -> result()
1642
1643 If the application detects a communication failure (in a poten‐
1644 tially partitioned network) that can have caused an inconsistent
1645 database, it can use the function mnesia:set_master_nodes(Tab,
1646 MasterNodes) to define from which nodes each table is to be
1647 loaded. At startup, the Mnesia normal table load algorithm is
1648 bypassed and the table is loaded from one of the master nodes
1649 defined for the table, regardless of when and if Mnesia termi‐
1650 nated on other nodes. MasterNodes can only contain nodes where
1651 the table has a replica. If the MasterNodes list is empty, the
1652 master node recovery mechanism for the particular table is re‐
1653 set, and the normal load mechanism is used at the next restart.
1654
1655 The master node setting is always local. It can be changed re‐
1656 gardless if Mnesia is started or not.
1657
1658 The database can also become inconsistent if configuration pa‐
1659 rameter max_wait_for_decision is used or if mne‐
1660 sia:force_load_table/1 is used.
1661
1662 snmp_close_table(Tab :: table()) -> ok
1663
1664 Removes the possibility for SNMP to manipulate the table.
1665
1666 snmp_get_mnesia_key(Tab :: table(), RowIndex :: [integer()]) ->
1667 {ok, Key :: term()} | undefined
1668
1669 Types:
1670
1671 Tab ::= atom()
1672 RowIndex ::= [integer()]
1673 Key ::= key() | {key(), key(), ...}
1674 key() ::= integer() | string() | [integer()]
1675
1676 Transforms an SNMP index to the corresponding Mnesia key. If the
1677 SNMP table has multiple keys, the key is a tuple of the key col‐
1678 umns.
1679
1680 snmp_get_next_index(Tab :: table(), RowIndex :: [integer()]) ->
1681 {ok, [integer()]} | endOfTable
1682
1683 Types:
1684
1685 Tab ::= atom()
1686 RowIndex ::= [integer()]
1687 NextIndex ::= [integer()]
1688
1689 RowIndex can specify a non-existing row. Specifically, it can be
1690 the empty list. Returns the index of the next lexicographical
1691 row. If RowIndex is the empty list, this function returns the
1692 index of the first row in the table.
1693
1694 snmp_get_row(Tab :: table(), RowIndex :: [integer()]) ->
1695 {ok, Row :: tuple()} | undefined
1696
1697 Types:
1698
1699 Tab ::= atom()
1700 RowIndex ::= [integer()]
1701 Row ::= record(Tab)
1702
1703 Reads a row by its SNMP index. This index is specified as an
1704 SNMP Object Identifier, a list of integers.
1705
1706 snmp_open_table(Tab :: table(), Snmp :: snmp_struct()) -> ok
1707
1708 Types:
1709
1710 Tab ::= atom()
1711 SnmpStruct ::= [{key, type()}]
1712 type() ::= type_spec() | {type_spec(), type_spec(), ...}
1713 type_spec() ::= fix_string | string | integer
1714
1715 A direct one-to-one mapping can be established between Mnesia
1716 tables and SNMP tables. Many telecommunication applications are
1717 controlled and monitored by the SNMP protocol. This connection
1718 between Mnesia and SNMP makes it simple and convenient to
1719 achieve this mapping.
1720
1721 Argument SnmpStruct is a list of SNMP information. Currently,
1722 the only information needed is information about the key types
1723 in the table. Multiple keys cannot be handled in Mnesia, but
1724 many SNMP tables have multiple keys. Therefore, the following
1725 convention is used: if a table has multiple keys, these must al‐
1726 ways be stored as a tuple of the keys. Information about the key
1727 types is specified as a tuple of atoms describing the types. The
1728 only significant type is fix_string. This means that a string
1729 has a fixed size.
1730
1731 For example, the following causes table person to be ordered as
1732 an SNMP table:
1733
1734 mnesia:snmp_open_table(person, [{key, string}])
1735
1736 Consider the following schema for a table of company employees.
1737 Each employee is identified by department number and name. The
1738 other table column stores the telephone number:
1739
1740 mnesia:create_table(employee,
1741 [{snmp, [{key, {integer, string}}]},
1742 {attributes, record_info(fields, employees)}]),
1743
1744 The corresponding SNMP table would have three columns: depart‐
1745 ment, name, and telno.
1746
1747 An option is to have table columns that are not visible through
1748 the SNMP protocol. These columns must be the last columns of the
1749 table. In the previous example, the SNMP table could have col‐
1750 umns department and name only. The application could then use
1751 column telno internally, but it would not be visible to the SNMP
1752 managers.
1753
1754 In a table monitored by SNMP, all elements must be integers,
1755 strings, or lists of integers.
1756
1757 When a table is SNMP ordered, modifications are more expensive
1758 than usual, O(logN). Also, more memory is used.
1759
1760 Notice that only the lexicographical SNMP ordering is imple‐
1761 mented in Mnesia, not the actual SNMP monitoring.
1762
1763 start() -> result()
1764
1765 Mnesia startup is asynchronous. The function call mnesia:start()
1766 returns the atom ok and then starts to initialize the different
1767 tables. Depending on the size of the database, this can take
1768 some time, and the application programmer must wait for the ta‐
1769 bles that the application needs before they can be used. This is
1770 achieved by using the function mnesia:wait_for_tables/2.
1771
1772 The startup procedure for a set of Mnesia nodes is a fairly com‐
1773 plicated operation. A Mnesia system consists of a set of nodes,
1774 with Mnesia started locally on all participating nodes. Nor‐
1775 mally, each node has a directory where all the Mnesia files are
1776 written. This directory is referred to as the Mnesia directory.
1777 Mnesia can also be started on disc-less nodes. For more informa‐
1778 tion about disc-less nodes, see mnesia:create_schema/1 and the
1779 User's Guide.
1780
1781 The set of nodes that makes up a Mnesia system is kept in a
1782 schema. Mnesia nodes can be added to or removed from the schema.
1783 The initial schema is normally created on disc with the function
1784 mnesia:create_schema/1. On disc-less nodes, a tiny default
1785 schema is generated each time Mnesia is started. During the
1786 startup procedure, Mnesia exchanges schema information between
1787 the nodes to verify that the table definitions are compatible.
1788
1789 Each schema has a unique cookie, which can be regarded as a
1790 unique schema identifier. The cookie must be the same on all
1791 nodes where Mnesia is supposed to run. For details, see the
1792 User's Guide.
1793
1794 The schema file and all other files that Mnesia needs are kept
1795 in the Mnesia directory. The command-line option -mnesia dir Dir
1796 can be used to specify the location of this directory to the
1797 Mnesia system. If no such command-line option is found, the name
1798 of the directory defaults to Mnesia.Node.
1799
1800 application:start(mnesia) can also be used.
1801
1802 stop() -> stopped | {error, term()}
1803
1804 Stops Mnesia locally on the current node.
1805
1806 application:stop(mnesia) can also be used.
1807
1808 subscribe(What) -> {ok, node()} | {error, Reason :: term()}
1809
1810 Types:
1811
1812 What = system | activity | {table, table(), simple | de‐
1813 tailed}
1814
1815 Ensures that a copy of all events of type EventCategory is sent
1816 to the caller. The available event types are described in the
1817 User's Guide.
1818
1819 sync_dirty(Fun) -> Res | no_return()
1820
1821 sync_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()
1822
1823 Types:
1824
1825 Fun = fun((...) -> Res)
1826
1827 Calls the Fun in a context that is not protected by a transac‐
1828 tion. The Mnesia function calls performed in the Fun are mapped
1829 to the corresponding dirty functions. It is performed in almost
1830 the same context as mnesia:async_dirty/1,2. The difference is
1831 that the operations are performed synchronously. The caller
1832 waits for the updates to be performed on all active replicas be‐
1833 fore the Fun returns. For details, see mnesia:activity/4 and the
1834 User's Guide.
1835
1836 sync_log() -> result()
1837
1838 Ensures that the local transaction log file is synced to disk.
1839 On a single node system, data written to disk tables since the
1840 last dump can be lost if there is a power outage. See
1841 dump_log/0.
1842
1843 sync_transaction(Fun) -> t_result(Res)
1844
1845 sync_transaction(Fun, Retries) -> t_result(Res)
1846
1847 sync_transaction(Fun, Args :: [Arg :: term()]) -> t_result(Res)
1848
1849 sync_transaction(Fun, Args :: [Arg :: term()], Retries) ->
1850 t_result(Res)
1851
1852 Types:
1853
1854 Fun = fun((...) -> Res)
1855 Retries = integer() >= 0 | infinity
1856
1857 Waits until data have been committed and logged to disk (if disk
1858 is used) on every involved node before it returns, otherwise it
1859 behaves as mnesia:transaction/[1,2,3].
1860
1861 This functionality can be used to avoid that one process over‐
1862 loads a database on another node.
1863
1864 system_info(Iterm :: term()) -> Info :: term()
1865
1866 Returns information about the Mnesia system, such as transaction
1867 statistics, db_nodes, and configuration parameters. The valid
1868 keys are as follows:
1869
1870 * all. Returns a list of all local system information. Each
1871 element is a {InfoKey, InfoVal} tuple.
1872
1873 New InfoKeys can be added and old undocumented InfoKeys can
1874 be removed without notice.
1875
1876 * access_module. Returns the name of module that is configured
1877 to be the activity access callback module.
1878
1879 * auto_repair. Returns true or false to indicate if Mnesia is
1880 configured to start the auto-repair facility on corrupted
1881 disc files.
1882
1883 * backup_module. Returns the name of the module that is con‐
1884 figured to be the backup callback module.
1885
1886 * checkpoints. Returns a list of the names of the checkpoints
1887 currently active on this node.
1888
1889 * event_module. Returns the name of the module that is the
1890 event handler callback module.
1891
1892 * db_nodes. Returns the nodes that make up the persistent
1893 database. Disc-less nodes are only included in the list of
1894 nodes if they explicitly have been added to the schema, for
1895 example, with mnesia:add_table_copy/3. The function can be
1896 started even if Mnesia is not yet running.
1897
1898 * debug. Returns the current debug level of Mnesia.
1899
1900 * directory. Returns the name of the Mnesia directory. It can
1901 be called even if Mnesia is not yet running.
1902
1903 * dump_log_load_regulation. Returns a boolean that tells if
1904 Mnesia is configured to regulate the dumper process load.
1905
1906 This feature is temporary and will be removed in future re‐
1907 leases.
1908
1909 * dump_log_time_threshold. Returns the time threshold for
1910 transaction log dumps in milliseconds.
1911
1912 * dump_log_update_in_place. Returns a boolean that tells if
1913 Mnesia is configured to perform the updates in the Dets
1914 files directly, or if the updates are to be performed in a
1915 copy of the Dets files.
1916
1917 * dump_log_write_threshold. Returns the write threshold for
1918 transaction log dumps as the number of writes to the trans‐
1919 action log.
1920
1921 * extra_db_nodes. Returns a list of extra db_nodes to be con‐
1922 tacted at startup.
1923
1924 * fallback_activated. Returns true if a fallback is activated,
1925 otherwise false.
1926
1927 * held_locks. Returns a list of all locks held by the local
1928 Mnesia lock manager.
1929
1930 * is_running. Returns yes or no to indicate if Mnesia is run‐
1931 ning. It can also return starting or stopping. Can be called
1932 even if Mnesia is not yet running.
1933
1934 * local_tables. Returns a list of all tables that are config‐
1935 ured to reside locally.
1936
1937 * lock_queue. Returns a list of all transactions that are
1938 queued for execution by the local lock manager.
1939
1940 * log_version. Returns the version number of the Mnesia trans‐
1941 action log format.
1942
1943 * master_node_tables. Returns a list of all tables with at
1944 least one master node.
1945
1946 * protocol_version. Returns the version number of the Mnesia
1947 inter-process communication protocol.
1948
1949 * running_db_nodes. Returns a list of nodes where Mnesia cur‐
1950 rently is running. This function can be called even if Mne‐
1951 sia is not yet running, but it then has slightly different
1952 semantics.
1953
1954 If Mnesia is down on the local node, the function returns
1955 those other db_nodes and extra_db_nodes that for the moment
1956 are operational.
1957
1958 If Mnesia is started, the function returns those nodes that
1959 Mnesia on the local node is fully connected to. Only those
1960 nodes that Mnesia has exchanged schema information with are
1961 included as running_db_nodes. After the merge of schemas,
1962 the local Mnesia system is fully operable and applications
1963 can perform access of remote replicas. Before the schema
1964 merge, Mnesia only operates locally. Sometimes there are
1965 more nodes included in the running_db_nodes list than all
1966 db_nodes and extra_db_nodes together.
1967
1968 * schema_location. Returns the initial schema location.
1969
1970 * subscribers. Returns a list of local processes currently
1971 subscribing to system events.
1972
1973 * tables. Returns a list of all locally known tables.
1974
1975 * transactions. Returns a list of all currently active local
1976 transactions.
1977
1978 * transaction_failures. Returns a number that indicates how
1979 many transactions have failed since Mnesia was started.
1980
1981 * transaction_commits. Returns a number that indicates how
1982 many transactions have terminated successfully since Mnesia
1983 was started.
1984
1985 * transaction_restarts. Returns a number that indicates how
1986 many transactions have been restarted since Mnesia was
1987 started.
1988
1989 * transaction_log_writes. Returns a number that indicates how
1990 many write operations that have been performed to the trans‐
1991 action log since startup.
1992
1993 * use_dir. Returns a boolean that indicates if the Mnesia di‐
1994 rectory is used or not. Can be started even if Mnesia is not
1995 yet running.
1996
1997 * version. Returns the current version number of Mnesia.
1998
1999 table(Tab :: table()) -> qlc:query_handle()
2000
2001 table(Tab :: table(), Options) -> qlc:query_handle()
2002
2003 Types:
2004
2005 Options = Option | [Option]
2006 Option = MnesiaOpt | QlcOption
2007 MnesiaOpt =
2008 {traverse, SelectOp} |
2009 {lock, lock_kind()} |
2010 {n_objects, integer() >= 0}
2011 SelectOp = select | {select, ets:match_spec()}
2012 QlcOption = {key_equality, '==' | '=:='}
2013
2014 Returns a Query List Comprehension (QLC) query handle, see the
2015 qlc(3) manual page in STDLIB. The module qlc implements a query
2016 language that can use Mnesia tables as sources of data. Calling
2017 mnesia:table/1,2 is the means to make the mnesia table Tab us‐
2018 able to QLC.
2019
2020 Option can contain Mnesia options or QLC options. Mnesia recog‐
2021 nizes the following options (any other option is forwarded to
2022 QLC).
2023
2024 * {lock, Lock}, where lock can be read or write. Default is
2025 read.
2026
2027 * {n_objects,Number}, where n_objects specifies (roughly) the
2028 number of objects returned from Mnesia to QLC. Queries to
2029 remote tables can need a larger chunk to reduce network
2030 overhead. By default, 100 objects at a time are returned.
2031
2032 * {traverse, SelectMethod}, where traverse determines the
2033 method to traverse the whole table (if needed). The default
2034 method is select.
2035
2036 There are two alternatives for select:
2037
2038 * select. The table is traversed by calling mnesia:select/4
2039 and mnesia:select/1. The match specification (the second ar‐
2040 gument of select/3) is assembled by QLC: simple filters are
2041 translated into equivalent match specifications. More com‐
2042 plicated filters need to be applied to all objects returned
2043 by select/3 given a match specification that matches all ob‐
2044 jects.
2045
2046 * {select, MatchSpec}. As for select, the table is traversed
2047 by calling mnesia:select/3 and mnesia:select/1. The differ‐
2048 ence is that the match specification is explicitly given.
2049 This is how to state match specifications that cannot easily
2050 be expressed within the syntax provided by QLC.
2051
2052 table_info(Tab :: table(), Item :: term()) -> Info :: term()
2053
2054 The table_info/2 function takes two arguments. The first is the
2055 name of a Mnesia table. The second is one of the following keys:
2056
2057 * all. Returns a list of all local table information. Each el‐
2058 ement is a {InfoKey, ItemVal} tuple.
2059
2060 New InfoItems can be added and old undocumented InfoItems
2061 can be removed without notice.
2062
2063 * access_mode. Returns the access mode of the table. The ac‐
2064 cess mode can be read_only or read_write.
2065
2066 * arity. Returns the arity of records in the table as speci‐
2067 fied in the schema.
2068
2069 * attributes. Returns the table attribute names that are spec‐
2070 ified in the schema.
2071
2072 * checkpoints. Returns the names of the currently active
2073 checkpoints, which involve this table on this node.
2074
2075 * cookie. Returns a table cookie, which is a unique system-
2076 generated identifier for the table. The cookie is used in‐
2077 ternally to ensure that two different table definitions us‐
2078 ing the same table name cannot accidentally be intermixed.
2079 The cookie is generated when the table is created initially.
2080
2081 * disc_copies. Returns the nodes where a disc_copy of the ta‐
2082 ble resides according to the schema.
2083
2084 * disc_only_copies. Returns the nodes where a disc_only_copy
2085 of the table resides according to the schema.
2086
2087 * index. Returns the list of index position integers for the
2088 table.
2089
2090 * load_node. Returns the name of the node that Mnesia loaded
2091 the table from. The structure of the returned value is un‐
2092 specified, but can be useful for debugging purposes.
2093
2094 * load_order. Returns the load order priority of the table. It
2095 is an integer and defaults to 0 (zero).
2096
2097 * load_reason. Returns the reason of why Mnesia decided to
2098 load the table. The structure of the returned value is un‐
2099 specified, but can be useful for debugging purposes.
2100
2101 * local_content. Returns true or false to indicate if the ta‐
2102 ble is configured to have locally unique content on each
2103 node.
2104
2105 * master_nodes. Returns the master nodes of a table.
2106
2107 * memory. Returns for ram_copies and disc_copies tables the
2108 number of words allocated in memory to the table on this
2109 node. For disc_only_copies tables the number of bytes stored
2110 on disc is returned.
2111
2112 * ram_copies. Returns the nodes where a ram_copy of the table
2113 resides according to the schema.
2114
2115 * record_name. Returns the record name, common for all records
2116 in the table.
2117
2118 * size. Returns the number of records inserted in the table.
2119
2120 * snmp. Returns the SNMP struct. [] means that the table cur‐
2121 rently has no SNMP properties.
2122
2123 * storage_type. Returns the local storage type of the table.
2124 It can be disc_copies, ram_copies, disc_only_copies, or the
2125 atom unknown. unknown is returned for all tables that only
2126 reside remotely.
2127
2128 * subscribers. Returns a list of local processes currently
2129 subscribing to local table events that involve this table on
2130 this node.
2131
2132 * type. Returns the table type, which is bag, set, or or‐
2133 dered_set.
2134
2135 * user_properties. Returns the user-associated table proper‐
2136 ties of the table. It is a list of the stored property
2137 records.
2138
2139 * version. Returns the current version of the table defini‐
2140 tion. The table version is incremented when the table defi‐
2141 nition is changed. The table definition can be incremented
2142 directly when it has been changed in a schema transaction,
2143 or when a committed table definition is merged with table
2144 definitions from other nodes during startup.
2145
2146 * where_to_read. Returns the node where the table can be read.
2147 If value nowhere is returned, either the table is not loaded
2148 or it resides at a remote node that is not running.
2149
2150 * where_to_write. Returns a list of the nodes that currently
2151 hold an active replica of the table.
2152
2153 * wild_pattern. Returns a structure that can be given to the
2154 various match functions for a certain table. A record tuple
2155 is where all record fields have value '_'.
2156
2157 transaction(Fun) -> t_result(Res)
2158
2159 transaction(Fun, Retries) -> t_result(Res)
2160
2161 transaction(Fun, Args :: [Arg :: term()]) -> t_result(Res)
2162
2163 transaction(Fun, Args :: [Arg :: term()], Retries) ->
2164 t_result(Res)
2165
2166 Types:
2167
2168 Fun = fun((...) -> Res)
2169 Retries = integer() >= 0 | infinity
2170
2171 Executes the functional object Fun with arguments Args as a
2172 transaction.
2173
2174 The code that executes inside the transaction can consist of a
2175 series of table manipulation functions. If something goes wrong
2176 inside the transaction as a result of a user error or a certain
2177 table not being available, the entire transaction is terminated
2178 and the function transaction/1 returns the tuple {aborted, Rea‐
2179 son}.
2180
2181 If all is going well, {atomic, ResultOfFun} is returned, where
2182 ResultOfFun is the value of the last expression in Fun.
2183
2184 A function that adds a family to the database can be written as
2185 follows if there is a structure {family, Father, Mother, Chil‐
2186 drenList}:
2187
2188 add_family({family, F, M, Children}) ->
2189 ChildOids = lists:map(fun oid/1, Children),
2190 Trans = fun() ->
2191 mnesia:write(F#person{children = ChildOids}),
2192 mnesia:write(M#person{children = ChildOids}),
2193 Write = fun(Child) -> mnesia:write(Child) end,
2194 lists:foreach(Write, Children)
2195 end,
2196 mnesia:transaction(Trans).
2197
2198 oid(Rec) -> {element(1, Rec), element(2, Rec)}.
2199
2200 This code adds a set of people to the database. Running this
2201 code within one transaction ensures that either the whole family
2202 is added to the database, or the whole transaction terminates.
2203 For example, if the last child is badly formatted, or the exe‐
2204 cuting process terminates because of an 'EXIT' signal while exe‐
2205 cuting the family code, the transaction terminates. Thus, the
2206 situation where half a family is added can never occur.
2207
2208 It is also useful to update the database within a transaction if
2209 several processes concurrently update the same records. For ex‐
2210 ample, the function raise(Name, Amount), which adds Amount to
2211 the salary field of a person, is to be implemented as follows:
2212
2213 raise(Name, Amount) ->
2214 mnesia:transaction(fun() ->
2215 case mnesia:wread({person, Name}) of
2216 [P] ->
2217 Salary = Amount + P#person.salary,
2218 P2 = P#person{salary = Salary},
2219 mnesia:write(P2);
2220 _ ->
2221 mnesia:abort("No such person")
2222 end
2223 end).
2224
2225 When this function executes within a transaction, several pro‐
2226 cesses running on different nodes can concurrently execute the
2227 function raise/2 without interfering with each other.
2228
2229 Since Mnesia detects deadlocks, a transaction can be restarted
2230 any number of times and therefore the Fun shall not have any
2231 side effects such as waiting for specific messages. This func‐
2232 tion attempts a restart as many times as specified in Retries.
2233 Retries must be an integer greater than 0 or the atom infinity,
2234 default is infinity. Mnesia uses exit exceptions to signal that
2235 a transaction needs to be restarted, thus a Fun must not catch
2236 exit exceptions with reason {aborted, term()}.
2237
2238 transform_table(Tab :: table(), Fun, NewA :: [Attr], RecName) ->
2239 t_result(ok)
2240
2241 Types:
2242
2243 RecName = Attr = atom()
2244 Fun =
2245 fun((Record :: tuple()) -> Transformed :: tuple()) | ig‐
2246 nore
2247
2248 Applies argument Fun to all records in the table. Fun is a func‐
2249 tion that takes a record of the old type and returns a trans‐
2250 formed record of the new type. Argument Fun can also be the atom
2251 ignore, which indicates that only the metadata about the table
2252 is updated. Use of ignore is not recommended, but included as a
2253 possibility for the user do to an own transformation.
2254
2255 NewAttributeList and NewRecordName specify the attributes and
2256 the new record type of the converted table. Table name always
2257 remains unchanged. If record_name is changed, only the Mnesia
2258 functions that use table identifiers work, for example, mne‐
2259 sia:write/3 works, but not mnesia:write/1.
2260
2261 transform_table(Tab :: table(), Fun, NewA :: [Attr]) ->
2262 t_result(ok)
2263
2264 Types:
2265
2266 Attr = atom()
2267 Fun =
2268 fun((Record :: tuple()) -> Transformed :: tuple()) | ig‐
2269 nore
2270
2271 Calls mnesia:transform_table(Tab, Fun, NewAttributeList, Rec‐
2272 Name), where RecName is mnesia:table_info(Tab, record_name).
2273
2274 traverse_backup(Src :: term(), Dest :: term(), Fun, Acc) ->
2275 {ok, Acc} | {error, Reason :: term()}
2276
2277 traverse_backup(Src :: term(),
2278 SrcMod :: module(),
2279 Dest :: term(),
2280 DestMod :: module(),
2281 Fun, Acc) ->
2282 {ok, Acc} | {error, Reason :: term()}
2283
2284 Types:
2285
2286 Fun = fun((Items, Acc) -> {Items, Acc})
2287
2288 Iterates over a backup, either to transform it into a new
2289 backup, or read it. The arguments are explained briefly here.
2290 For details, see the User's Guide.
2291
2292 * SourceMod and TargetMod are the names of the modules that
2293 actually access the backup media.
2294
2295 * Source and Target are opaque data used exclusively by mod‐
2296 ules SourceMod and TargetMod to initialize the backup media.
2297
2298 * Acc is an initial accumulator value.
2299
2300 * Fun(BackupItems, Acc) is applied to each item in the backup.
2301 The Fun must return a tuple {BackupItems,NewAcc}, where
2302 BackupItems is a list of valid backup items, and NewAcc is a
2303 new accumulator value. The returned backup items are written
2304 in the target backup.
2305
2306 * LastAcc is the last accumulator value. This is the last
2307 NewAcc value that was returned by Fun.
2308
2309 uninstall_fallback() -> result()
2310
2311 Calls the function mnesia:uninstall_fallback([{scope, global}]).
2312
2313 uninstall_fallback(Args) -> result()
2314
2315 Types:
2316
2317 Args = [{mnesia_dir, Dir :: string()}]
2318
2319 Deinstalls a fallback before it has been used to restore the
2320 database. This is normally a distributed operation that is ei‐
2321 ther performed on all nodes with disc resident schema, or none.
2322 Uninstallation of fallbacks requires Erlang to be operational on
2323 all involved nodes, but it does not matter if Mnesia is running
2324 or not. Which nodes that are considered as disc-resident nodes
2325 is determined from the schema information in the local fallback.
2326
2327 Args is a list of the following tuples:
2328
2329 * {module, BackupMod}. For semantics, see mnesia:install_fall‐
2330 back/2.
2331
2332 * {scope, Scope}. For semantics, see mnesia:install_fall‐
2333 back/2.
2334
2335 * {mnesia_dir, AlternateDir}. For semantics, see mnesia:in‐
2336 stall_fallback/2.
2337
2338 unsubscribe(What) -> {ok, node()} | {error, Reason :: term()}
2339
2340 Types:
2341
2342 What = system | activity | {table, table(), simple | de‐
2343 tailed}
2344
2345 Stops sending events of type EventCategory to the caller.
2346
2347 Node is the local node.
2348
2349 wait_for_tables(Tabs :: [Tab :: table()], TMO :: timeout()) ->
2350 result() | {timeout, [table()]}
2351
2352 Some applications need to wait for certain tables to be accessi‐
2353 ble to do useful work. mnesia:wait_for_tables/2 either hangs un‐
2354 til all tables in TabList are accessible, or until timeout is
2355 reached.
2356
2357 wread(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
2358
2359 Calls the function mnesia:read(Tab, Key, write).
2360
2361 write(Record :: tuple()) -> ok
2362
2363 Calls the function mnesia:write(Tab, Record, write), where Tab
2364 is element(1, Record).
2365
2366 write(Tab :: table(),
2367 Record :: tuple(),
2368 LockKind :: write_locks()) ->
2369 ok
2370
2371 Writes record Record to table Tab.
2372
2373 The function returns ok, or terminates if an error occurs. For
2374 example, the transaction terminates if no person table exists.
2375
2376 The semantics of this function is context-sensitive. For de‐
2377 tails, see mnesia:activity/4. In transaction-context, it ac‐
2378 quires a lock of type LockKind. The lock types write and
2379 sticky_write are supported.
2380
2381 write_lock_table(Tab :: table()) -> ok
2382
2383 Calls the function mnesia:lock({table, Tab}, write).
2384
2386 Mnesia reads the following application configuration parameters:
2387
2388 * -mnesia access_module Module. The name of the Mnesia activity ac‐
2389 cess callback module. Default is mnesia.
2390
2391 * -mnesia auto_repair true | false. This flag controls if Mnesia au‐
2392 tomatically tries to repair files that have not been properly
2393 closed. Default is true.
2394
2395 * -mnesia backup_module Module. The name of the Mnesia backup call‐
2396 back module. Default is mnesia_backup.
2397
2398 * -mnesia debug Level. Controls the debug level of Mnesia. The possi‐
2399 ble values are as follows:
2400
2401 none:
2402 No trace outputs. This is the default.
2403
2404 verbose:
2405 Activates tracing of important debug events. These events gener‐
2406 ate {mnesia_info, Format, Args} system events. Processes can sub‐
2407 scribe to these events with mnesia:subscribe/1. The events are
2408 always sent to the Mnesia event handler.
2409
2410 debug:
2411 Activates all events at the verbose level plus full trace of all
2412 debug events. These debug events generate {mnesia_info, Format,
2413 Args} system events. Processes can subscribe to these events with
2414 mnesia:subscribe/1. The events are always sent to the Mnesia
2415 event handler. On this debug level, the Mnesia event handler
2416 starts subscribing to updates in the schema table.
2417
2418 trace:
2419 Activates all events at the debug level. On this level, the Mne‐
2420 sia event handler starts subscribing to updates on all Mnesia ta‐
2421 bles. This level is intended only for debugging small toy sys‐
2422 tems, as many large events can be generated.
2423
2424 false:
2425 An alias for none.
2426
2427 true:
2428 An alias for debug.
2429
2430 * -mnesia core_dir Directory. The name of the directory where Mnesia
2431 core files is stored, or false. Setting it implies that also RAM-
2432 only nodes generate a core file if a crash occurs.
2433
2434 * -mnesia dc_dump_limit Number. Controls how often disc_copies tables
2435 are dumped from memory. Tables are dumped when filesize(Log) >
2436 (filesize(Tab)/Dc_dump_limit). Lower values reduce CPU overhead but
2437 increase disk space and startup times. Default is 4.
2438
2439 * -mnesia dir Directory. The name of the directory where all Mnesia
2440 data is stored. The directory name must be unique for the current
2441 node. Two nodes must never share the the same Mnesia directory. The
2442 results are unpredictable.
2443
2444 * -mnesia dump_disc_copies_at_startup true | false. If set to false,
2445 this disables the dumping of disc_copies tables during startup
2446 while tables are being loaded. The default is true.
2447
2448 * -mnesia dump_log_load_regulation true | false. Controls if log
2449 dumps are to be performed as fast as possible, or if the dumper is
2450 to do its own load regulation. Default is false.
2451
2452 This feature is temporary and will be removed in a future release
2453
2454 * -mnesia dump_log_update_in_place true | false. Controls if log
2455 dumps are performed on a copy of the original data file, or if the
2456 log dump is performed on the original data file. Default is true
2457
2458 *
2459
2460
2461 -mnesia dump_log_write_threshold Max. Max is an integer that speci‐
2462 fies the maximum number of writes allowed to the transaction log
2463 before a new dump of the log is performed. Default is 1000 log
2464 writes.
2465
2466 *
2467
2468
2469 -mnesia dump_log_time_threshold Max. Max is an integer that speci‐
2470 fies the dump log interval in milliseconds. Default is 3 minutes.
2471 If a dump has not been performed within dump_log_time_threshold
2472 milliseconds, a new dump is performed regardless of the number of
2473 writes performed.
2474
2475 * -mnesia event_module Module. The name of the Mnesia event handler
2476 callback module. Default is mnesia_event.
2477
2478 * -mnesia extra_db_nodes Nodes specifies a list of nodes, in addition
2479 to the ones found in the schema, with which Mnesia is also to es‐
2480 tablish contact. Default is [] (empty list).
2481
2482 * -mnesia fallback_error_function {UserModule, UserFunc}. Specifies a
2483 user-supplied callback function, which is called if a fallback is
2484 installed and Mnesia goes down on another node. Mnesia calls the
2485 function with one argument, the name of the dying node, for exam‐
2486 ple, UserModule:UserFunc(DyingNode). Mnesia must be restarted, oth‐
2487 erwise the database can be inconsistent. The default behavior is to
2488 terminate Mnesia.
2489
2490 * -mnesia max_wait_for_decision Timeout. Specifies how long Mnesia
2491 waits for other nodes to share their knowledge about the outcome of
2492 an unclear transaction. By default, Timeout is set to the atom in‐
2493 finity. This implies that if Mnesia upon startup detects a "heavy‐
2494 weight transaction" whose outcome is unclear, the local Mnesia
2495 waits until Mnesia is started on some (in the worst case all) of
2496 the other nodes that were involved in the interrupted transaction.
2497 This is a rare situation, but if it occurs, Mnesia does not guess
2498 if the transaction on the other nodes was committed or terminated.
2499 Mnesia waits until it knows the outcome and then acts accordingly.
2500
2501 If Timeout is set to an integer value in milliseconds, Mnesia
2502 forces "heavyweight transactions" to be finished, even if the out‐
2503 come of the transaction for the moment is unclear. After Timeout
2504 milliseconds, Mnesia commits or terminates the transaction and con‐
2505 tinues with the startup. This can lead to a situation where the
2506 transaction is committed on some nodes and terminated on other
2507 nodes. If the transaction is a schema transaction, the inconsis‐
2508 tency can be fatal.
2509
2510 * -mnesia no_table_loaders NUMBER. Specifies the number of parallel
2511 table loaders during start. More loaders can be good if the network
2512 latency is high or if many tables contain few records. Default is
2513 2.
2514
2515 * -mnesia send_compressed Level. Specifies the level of compression
2516 to be used when copying a table from the local node to another one.
2517 Default is 0.
2518
2519 Level must be an integer in the interval [0, 9], where 0 means no
2520 compression and 9 means maximum compression. Before setting it to a
2521 non-zero value, ensure that the remote nodes understand this con‐
2522 figuration.
2523
2524 * -mnesia max_transfer_size Number. Specifies the estimated size in
2525 bytes of a single packet of data to be used when copying a table
2526 from the local node to another one. Default is 64000.
2527
2528 * -mnesia schema_location Loc. Controls where Mnesia looks for its
2529 schema. Parameter Loc can be one of the following atoms:
2530
2531 disc:
2532 Mandatory disc. The schema is assumed to be located in the Mnesia
2533 directory. If the schema cannot be found, Mnesia refuses to
2534 start. This is the old behavior.
2535
2536 ram:
2537 Mandatory RAM. The schema resides in RAM only. At startup, a tiny
2538 new schema is generated. This default schema only contains the
2539 definition of the schema table and only resides on the local
2540 node. Since no other nodes are found in the default schema, con‐
2541 figuration parameter extra_db_nodes must be used to let the node
2542 share its table definitions with other nodes.
2543
2544 Parameter extra_db_nodes can also be used on disc based nodes.
2545
2546 opt_disc:
2547 Optional disc. The schema can reside on disc or in RAM. If the
2548 schema is found on disc, Mnesia starts as a disc-based node and
2549 the storage type of the schema table is disc_copies. If no schema
2550 is found on disc, Mnesia starts as a disc-less node and the stor‐
2551 age type of the schema table is ram_copies. Default value for the
2552 application parameter is opt_disc.
2553
2554 First, the SASL application parameters are checked, then the command-
2555 line flags are checked, and finally, the default value is chosen.
2556
2558 application(3), dets(3), disk_log(3), ets(3), mnesia_registry(3),
2559 qlc(3)
2560
2561
2562
2563Ericsson AB mnesia 4.22.1 mnesia(3)