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 the same 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 arithmetics, 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()) -> result()
1213
1214 Calls mnesia:install_fallback(Opaque, Args), where Args is
1215 [{scope, global}, {module, BackupMod}].
1216
1217 install_fallback(Src :: term(), Mod :: module() | [Opt]) ->
1218 result()
1219
1220 Types:
1221
1222 Opt = Module | Scope | Dir
1223 Module = {module, Mod :: module()}
1224 Scope = {scope, global | local}
1225 Dir = {mnesia_dir, Dir :: string()}
1226
1227 Installs a backup as fallback. The fallback is used to restore
1228 the database at the next startup. Installation of fallbacks re‐
1229 quires Erlang to be operational on all the involved nodes, but
1230 it does not matter if Mnesia is running or not. The installation
1231 of the fallback fails if the local node is not one of the disc-
1232 resident nodes in the backup.
1233
1234 Args is a list of the following tuples:
1235
1236 * {module, BackupMod}. All accesses of the backup media are
1237 performed through a callback module named BackupMod. Argu‐
1238 ment Opaque is forwarded to the callback module, which can
1239 interpret it as it wishes. The default callback module is
1240 called mnesia_backup and it interprets argument Opaque as a
1241 local filename. The default for this module is also config‐
1242 urable through configuration parameter -mnesia mne‐
1243 sia_backup.
1244
1245 * {scope, Scope}. The Scope of a fallback is either global for
1246 the entire database or local for one node. By default, the
1247 installation of a fallback is a global operation, which ei‐
1248 ther is performed on all nodes with a disc-resident schema
1249 or none. Which nodes that are disc-resident is determined
1250 from the schema information in the backup.
1251
1252 If Scope of the operation is local, the fallback is only in‐
1253 stalled on the local node.
1254
1255 * {mnesia_dir, AlternateDir}. This argument is only valid if
1256 the scope of the installation is local. Normally the instal‐
1257 lation of a fallback is targeted to the Mnesia directory, as
1258 configured with configuration parameter -mnesia dir. But by
1259 explicitly supplying an AlternateDir, the fallback is in‐
1260 stalled there regardless of the Mnesia directory configura‐
1261 tion parameter setting. After installation of a fallback on
1262 an alternative Mnesia directory, that directory is fully
1263 prepared for use as an active Mnesia directory.
1264
1265 This is a dangerous feature that must be used with care. By
1266 unintentional mixing of directories, you can easily end up
1267 with an inconsistent database, if the same backup is in‐
1268 stalled on more than one directory.
1269
1270 is_transaction() -> boolean()
1271
1272 When this function is executed inside a transaction-context, it
1273 returns true, otherwise false.
1274
1275 last(Tab :: table()) -> Key :: term()
1276
1277 Works exactly like mnesia:first/1, but returns the last object
1278 in Erlang term order for the ordered_set table type. For all
1279 other table types, mnesia:first/1 and mnesia:last/1 are syn‐
1280 onyms.
1281
1282 load_textfile(File :: file:filename()) ->
1283 t_result(ok) | {error, term()}
1284
1285 Loads a series of definitions and data found in the text file
1286 (generated with mnesia:dump_to_textfile/1) into Mnesia. This
1287 function also starts Mnesia and possibly creates a new schema.
1288 This function is intended for educational purposes only. It is
1289 recommended to use other functions to deal with real backups.
1290
1291 lock(LockItem, LockKind) -> list() | tuple() | no_return()
1292
1293 Types:
1294
1295 LockItem =
1296 {record, table(), Key :: term()} |
1297 {table, table()} |
1298 {global, Key :: term(), MnesiaNodes :: [node()]}
1299 LockKind = lock_kind() | load
1300
1301 Write locks are normally acquired on all nodes where a replica
1302 of the table resides (and is active). Read locks are acquired on
1303 one node (the local node if a local replica exists). Most of the
1304 context-sensitive access functions acquire an implicit lock if
1305 they are started in a transaction-context. The granularity of a
1306 lock can either be a single record or an entire table.
1307
1308 The normal use is to call the function without checking the re‐
1309 turn value, as it exits if it fails and the transaction is
1310 restarted by the transaction manager. It returns all the locked
1311 nodes if a write lock is acquired and ok if it was a read lock.
1312
1313 The function mnesia:lock/2 is intended to support explicit lock‐
1314 ing on tables, but is also intended for situations when locks
1315 need to be acquired regardless of how tables are replicated.
1316 Currently, two kinds of LockKind are supported:
1317
1318 write:
1319 Write locks are exclusive. This means that if one transac‐
1320 tion manages to acquire a write lock on an item, no other
1321 transaction can acquire any kind of lock on the same item.
1322
1323 read:
1324 Read locks can be shared. This means that if one transaction
1325 manages to acquire a read lock on an item, other transac‐
1326 tions can also acquire a read lock on the same item. How‐
1327 ever, if someone has a read lock, no one can acquire a write
1328 lock at the same item. If someone has a write lock, no one
1329 can acquire either a read lock or a write lock at the same
1330 item.
1331
1332 Conflicting lock requests are automatically queued if there is
1333 no risk of a deadlock. Otherwise the transaction must be termi‐
1334 nated and executed again. Mnesia does this automatically as long
1335 as the upper limit of the maximum retries is not reached. For
1336 details, see mnesia:transaction/3.
1337
1338 For the sake of completeness, sticky write locks are also de‐
1339 scribed here even if a sticky write lock is not supported by
1340 this function:
1341
1342 sticky_write:
1343 Sticky write locks are a mechanism that can be used to opti‐
1344 mize write lock acquisition. If your application uses repli‐
1345 cated tables mainly for fault tolerance (as opposed to read
1346 access optimization purpose), sticky locks can be the best
1347 option available.
1348
1349 When a sticky write lock is acquired, all nodes are informed
1350 which node is locked. Then, sticky lock requests from the
1351 same node are performed as a local operation without any
1352 communication with other nodes. The sticky lock lingers on
1353 the node even after the transaction ends. For details, see
1354 the User's Guide.
1355
1356 Currently, this function supports two kinds of LockItem:
1357
1358 {table, Tab}:
1359 This acquires a lock of type LockKind on the entire table
1360 Tab.
1361
1362 {global, GlobalKey, Nodes}:
1363 This acquires a lock of type LockKind on the global resource
1364 GlobalKey. The lock is acquired on all active nodes in the
1365 Nodes list.
1366
1367 Locks are released when the outermost transaction ends.
1368
1369 The semantics of this function is context-sensitive. For de‐
1370 tails, see mnesia:activity/4. In transaction-context, it ac‐
1371 quires locks, otherwise it ignores the request.
1372
1373 match_object(Pattern :: tuple()) -> [Record :: tuple()]
1374
1375 Calls mnesia:match_object(Tab, Pattern, read), where Tab is ele‐
1376 ment(1, Pattern).
1377
1378 match_object(Tab, Pattern, LockKind) -> [Record]
1379
1380 Types:
1381
1382 Tab = table()
1383 Pattern = tuple()
1384 LockKind = lock_kind()
1385 Record = tuple()
1386
1387 Takes a pattern with "don't care" variables denoted as a '_' pa‐
1388 rameter. This function returns a list of records that matched
1389 the pattern. Since the second element of a record in a table is
1390 considered to be the key for the record, the performance of this
1391 function depends on whether this key is bound or not.
1392
1393 For example, the call mnesia:match_object(person, {person, '_',
1394 36, '_', '_'}, read) returns a list of all person records with
1395 an age field of 36.
1396
1397 The function mnesia:match_object/3 automatically uses indexes if
1398 these exist. However, no heuristics are performed to select the
1399 best index.
1400
1401 The semantics of this function is context-sensitive. For de‐
1402 tails, see mnesia:activity/4. In transaction-context, it ac‐
1403 quires a lock of type LockKind on the entire table or a single
1404 record. Currently, the lock type read is supported.
1405
1406 move_table_copy(Tab :: table(), From :: node(), To :: node()) ->
1407 t_result(ok)
1408
1409 Moves the copy of table Tab from node From to node To.
1410
1411 The storage type is preserved. For example, a RAM table moved
1412 from one node remains a RAM on the new node. Other transactions
1413 can still read and write in the table while it is being moved.
1414
1415 This function cannot be used on local_content tables.
1416
1417 next(Tab :: table(), Key :: term()) -> NextKey :: term()
1418
1419 Traverses a table and performs operations on all records in the
1420 table. When the end of the table is reached, the special key
1421 '$end_of_table' is returned. Otherwise the function returns a
1422 key that can be used to read the actual record.
1423
1424 prev(Tab :: table(), Key :: term()) -> PrevKey :: term()
1425
1426 Works exactly like mnesia:next/2, but returns the previous ob‐
1427 ject in Erlang term order for the ordered_set table type. For
1428 all other table types, mnesia:next/2 and mnesia:prev/2 are syn‐
1429 onyms.
1430
1431 read(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
1432
1433 read(Tab :: table(), Key :: term()) -> [tuple()]
1434
1435 Calls function mnesia:read(Tab, Key, read).
1436
1437 read(Tab :: table(), Key :: term(), LockKind :: lock_kind()) ->
1438 [tuple()]
1439
1440 Reads all records from table Tab with key Key. This function has
1441 the same semantics regardless of the location of Tab. If the ta‐
1442 ble is of type bag, the function mnesia:read(Tab, Key) can re‐
1443 turn an arbitrarily long list. If the table is of type set, the
1444 list is either of length 1, or [].
1445
1446 The semantics of this function is context-sensitive. For de‐
1447 tails, see mnesia:activity/4. In transaction-context, it ac‐
1448 quires a lock of type LockKind. Currently, the lock types read,
1449 write, and sticky_write are supported.
1450
1451 If the user wants to update the record, it is more efficient to
1452 use write/sticky_write as the LockKind. If majority checking is
1453 active on the table, it is checked as soon as a write lock is
1454 attempted. This can be used to end quickly if the majority con‐
1455 dition is not met.
1456
1457 read_lock_table(Tab :: table()) -> ok
1458
1459 Calls the function mnesia:lock({table, Tab}, read).
1460
1461 report_event(Event :: term()) -> ok
1462
1463 When tracing a system of Mnesia applications it is useful to be
1464 able to interleave Mnesia own events with application-related
1465 events that give information about the application context.
1466
1467 Whenever the application begins a new and demanding Mnesia task,
1468 or if it enters a new interesting phase in its execution, it can
1469 be a good idea to use mnesia:report_event/1. Event can be any
1470 term and generates a {mnesia_user, Event} event for any pro‐
1471 cesses that subscribe to Mnesia system events.
1472
1473 restore(Src :: term(), Args :: [Arg]) -> t_result([table()])
1474
1475 Types:
1476
1477 Op = skip_tables | clear_tables | keep_tables | restore_ta‐
1478 bles
1479 Arg = {module, module()} | {Op, [table()]} | {default_op, Op}
1480
1481 With this function, tables can be restored online from a backup
1482 without restarting Mnesia. Opaque is forwarded to the backup
1483 module. Args is a list of the following tuples:
1484
1485 * {module,BackupMod}. The backup module BackupMod is used to
1486 access the backup media. If omitted, the default backup mod‐
1487 ule is used.
1488
1489 * {skip_tables, TabList}, where TabList is a list of tables
1490 that is not to be read from the backup.
1491
1492 * {clear_tables, TabList}, where TabList is a list of tables
1493 that is to be cleared before the records from the backup are
1494 inserted. That is, all records in the tables are deleted be‐
1495 fore the tables are restored. Schema information about the
1496 tables is not cleared or read from the backup.
1497
1498 * {keep_tables, TabList}, where TabList is a list of tables
1499 that is not to be cleared before the records from the backup
1500 are inserted. That is, the records in the backup are added
1501 to the records in the table. Schema information about the
1502 tables is not cleared or read from the backup.
1503
1504 * {recreate_tables, TabList}, where TabList is a list of ta‐
1505 bles that is to be recreated before the records from the
1506 backup are inserted. The tables are first deleted and then
1507 created with the schema information from the backup. All the
1508 nodes in the backup need to be operational.
1509
1510 * {default_op, Operation}, where Operation is either of the
1511 operations skip_tables, clear_tables, keep_tables, or recre‐
1512 ate_tables. The default operation specifies which operation
1513 that is to be used on tables from the backup that is not
1514 specified in any of the mentioned lists. If omitted, opera‐
1515 tion clear_tables is used.
1516
1517 The affected tables are write-locked during the restoration.
1518 However, regardless of the lock conflicts caused by this, the
1519 applications can continue to do their work while the restoration
1520 is being performed. The restoration is performed as one single
1521 transaction.
1522
1523 If the database is huge, it it not always possible to restore it
1524 online. In such cases, restore the old database by installing a
1525 fallback and then restart.
1526
1527 s_delete(Oid :: {Tab :: table(), Key :: term()}) -> ok
1528
1529 Calls the function mnesia:delete(Tab, Key, sticky_write)
1530
1531 s_delete_object(Rec :: tuple()) -> ok
1532
1533 Calls the function mnesia:delete_object(Tab, Record,
1534 sticky_write), where Tab is element(1, Record).
1535
1536 s_write(Record :: tuple()) -> ok
1537
1538 Calls the function mnesia:write(Tab, Record, sticky_write),
1539 where Tab is element(1, Record).
1540
1541 schema() -> ok
1542
1543 Prints information about all table definitions on the terminal.
1544
1545 schema(Tab :: table()) -> ok
1546
1547 Prints information about one table definition on the terminal.
1548
1549 select(Tab, Spec) -> [Match]
1550
1551 select(Tab, Spec, LockKind) -> [Match]
1552
1553 Types:
1554
1555 Tab = table()
1556 Spec = ets:match_spec()
1557 Match = term()
1558 LockKind = lock_kind()
1559
1560 Matches the objects in table Tab using a match_spec as described
1561 in the ets:select/3. Optionally a lock read or write can be
1562 given as the third argument. Default is read. The return value
1563 depends on MatchSpec.
1564
1565 Notice that for best performance, select is to be used before
1566 any modifying operations are done on that table in the same
1567 transaction. That is, do not use write or delete before a se‐
1568 lect.
1569
1570 In its simplest forms, the match_spec look as follows:
1571
1572 * MatchSpec = [MatchFunction]
1573
1574 * MatchFunction = {MatchHead, [Guard], [Result]}
1575
1576 * MatchHead = tuple() | record()
1577
1578 * Guard = {"Guardtest name", ...}
1579
1580 * Result = "Term construct"
1581
1582 For a complete description of select, see the ERTS User's Guide
1583 and the ets manual page in STDLIB.
1584
1585 For example, to find the names of all male persons older than 30
1586 in table Tab:
1587
1588 MatchHead = #person{name='$1', sex=male, age='$2', _='_'},
1589 Guard = {'>', '$2', 30},
1590 Result = '$1',
1591 mnesia:select(Tab,[{MatchHead, [Guard], [Result]}]),
1592
1593 select(Tab, Spec, N, LockKind) ->
1594 {[Match], Cont} | '$end_of_table'
1595
1596 Types:
1597
1598 Tab = table()
1599 Spec = ets:match_spec()
1600 Match = term()
1601 N = integer() >= 0
1602 LockKind = lock_kind()
1603 Cont = select_continuation()
1604
1605 Matches the objects in table Tab using a match_spec as described
1606 in the ERTS User's Guide, and returns a chunk of terms and a
1607 continuation. The wanted number of returned terms is specified
1608 by argument NObjects. The lock argument can be read or write.
1609 The continuation is to be used as argument to mnesia:select/1,
1610 if more or all answers are needed.
1611
1612 Notice that for best performance, select is to be used before
1613 any modifying operations are done on that table in the same
1614 transaction. That is, do not use mnesia:write or mnesia:delete
1615 before a mnesia:select. For efficiency, NObjects is a recommen‐
1616 dation only and the result can contain anything from an empty
1617 list to all available results.
1618
1619 select(Cont) -> {[Match], Cont} | '$end_of_table'
1620
1621 Types:
1622
1623 Match = term()
1624 Cont = select_continuation()
1625
1626 Selects more objects with the match specification initiated by
1627 mnesia:select/4.
1628
1629 Notice that any modifying operations, that is, mnesia:write or
1630 mnesia:delete, that are done between the mnesia:select/4 and
1631 mnesia:select/1 calls are not visible in the result.
1632
1633 set_debug_level(Level :: debug_level()) ->
1634 OldLevel :: debug_level()
1635
1636 Changes the internal debug level of Mnesia. For details, see
1637 Section Configuration Parameters.
1638
1639 set_master_nodes(Ns :: [node()]) -> result()
1640
1641 For each table Mnesia determines its replica nodes (TabNodes)
1642 and starts mnesia:set_master_nodes(Tab, TabMasterNodes). where
1643 TabMasterNodes is the intersection of MasterNodes and TabNodes.
1644 For semantics, see mnesia:set_master_nodes/2.
1645
1646 set_master_nodes(Tab :: table(), Ns :: [node()]) -> result()
1647
1648 If the application detects a communication failure (in a poten‐
1649 tially partitioned network) that can have caused an inconsistent
1650 database, it can use the function mnesia:set_master_nodes(Tab,
1651 MasterNodes) to define from which nodes each table is to be
1652 loaded. At startup, the Mnesia normal table load algorithm is
1653 bypassed and the table is loaded from one of the master nodes
1654 defined for the table, regardless of when and if Mnesia termi‐
1655 nated on other nodes. MasterNodes can only contain nodes where
1656 the table has a replica. If the MasterNodes list is empty, the
1657 master node recovery mechanism for the particular table is re‐
1658 set, and the normal load mechanism is used at the next restart.
1659
1660 The master node setting is always local. It can be changed re‐
1661 gardless if Mnesia is started or not.
1662
1663 The database can also become inconsistent if configuration pa‐
1664 rameter max_wait_for_decision is used or if mne‐
1665 sia:force_load_table/1 is used.
1666
1667 snmp_close_table(Tab :: table()) -> ok
1668
1669 Removes the possibility for SNMP to manipulate the table.
1670
1671 snmp_get_mnesia_key(Tab :: table(), RowIndex :: [integer()]) ->
1672 {ok, Key :: term()} | undefined
1673
1674 Types:
1675
1676 Tab ::= atom()
1677 RowIndex ::= [integer()]
1678 Key ::= key() | {key(), key(), ...}
1679 key() ::= integer() | string() | [integer()]
1680
1681 Transforms an SNMP index to the corresponding Mnesia key. If the
1682 SNMP table has multiple keys, the key is a tuple of the key col‐
1683 umns.
1684
1685 snmp_get_next_index(Tab :: table(), RowIndex :: [integer()]) ->
1686 {ok, [integer()]} | endOfTable
1687
1688 Types:
1689
1690 Tab ::= atom()
1691 RowIndex ::= [integer()]
1692 NextIndex ::= [integer()]
1693
1694 RowIndex can specify a non-existing row. Specifically, it can be
1695 the empty list. Returns the index of the next lexicographical
1696 row. If RowIndex is the empty list, this function returns the
1697 index of the first row in the table.
1698
1699 snmp_get_row(Tab :: table(), RowIndex :: [integer()]) ->
1700 {ok, Row :: tuple()} | undefined
1701
1702 Types:
1703
1704 Tab ::= atom()
1705 RowIndex ::= [integer()]
1706 Row ::= record(Tab)
1707
1708 Reads a row by its SNMP index. This index is specified as an
1709 SNMP Object Identifier, a list of integers.
1710
1711 snmp_open_table(Tab :: table(), Snmp :: snmp_struct()) -> ok
1712
1713 Types:
1714
1715 Tab ::= atom()
1716 SnmpStruct ::= [{key, type()}]
1717 type() ::= type_spec() | {type_spec(), type_spec(), ...}
1718 type_spec() ::= fix_string | string | integer
1719
1720 A direct one-to-one mapping can be established between Mnesia
1721 tables and SNMP tables. Many telecommunication applications are
1722 controlled and monitored by the SNMP protocol. This connection
1723 between Mnesia and SNMP makes it simple and convenient to
1724 achieve this mapping.
1725
1726 Argument SnmpStruct is a list of SNMP information. Currently,
1727 the only information needed is information about the key types
1728 in the table. Multiple keys cannot be handled in Mnesia, but
1729 many SNMP tables have multiple keys. Therefore, the following
1730 convention is used: if a table has multiple keys, these must al‐
1731 ways be stored as a tuple of the keys. Information about the key
1732 types is specified as a tuple of atoms describing the types. The
1733 only significant type is fix_string. This means that a string
1734 has a fixed size.
1735
1736 For example, the following causes table person to be ordered as
1737 an SNMP table:
1738
1739 mnesia:snmp_open_table(person, [{key, string}])
1740
1741 Consider the following schema for a table of company employees.
1742 Each employee is identified by department number and name. The
1743 other table column stores the telephone number:
1744
1745 mnesia:create_table(employee,
1746 [{snmp, [{key, {integer, string}}]},
1747 {attributes, record_info(fields, employees)}]),
1748
1749 The corresponding SNMP table would have three columns: depart‐
1750 ment, name, and telno.
1751
1752 An option is to have table columns that are not visible through
1753 the SNMP protocol. These columns must be the last columns of the
1754 table. In the previous example, the SNMP table could have col‐
1755 umns department and name only. The application could then use
1756 column telno internally, but it would not be visible to the SNMP
1757 managers.
1758
1759 In a table monitored by SNMP, all elements must be integers,
1760 strings, or lists of integers.
1761
1762 When a table is SNMP ordered, modifications are more expensive
1763 than usual, O(logN). Also, more memory is used.
1764
1765 Notice that only the lexicographical SNMP ordering is imple‐
1766 mented in Mnesia, not the actual SNMP monitoring.
1767
1768 start() -> result()
1769
1770 Mnesia startup is asynchronous. The function call mnesia:start()
1771 returns the atom ok and then starts to initialize the different
1772 tables. Depending on the size of the database, this can take
1773 some time, and the application programmer must wait for the ta‐
1774 bles that the application needs before they can be used. This is
1775 achieved by using the function mnesia:wait_for_tables/2.
1776
1777 The startup procedure for a set of Mnesia nodes is a fairly com‐
1778 plicated operation. A Mnesia system consists of a set of nodes,
1779 with Mnesia started locally on all participating nodes. Nor‐
1780 mally, each node has a directory where all the Mnesia files are
1781 written. This directory is referred to as the Mnesia directory.
1782 Mnesia can also be started on disc-less nodes. For more informa‐
1783 tion about disc-less nodes, see mnesia:create_schema/1 and the
1784 User's Guide.
1785
1786 The set of nodes that makes up a Mnesia system is kept in a
1787 schema. Mnesia nodes can be added to or removed from the schema.
1788 The initial schema is normally created on disc with the function
1789 mnesia:create_schema/1. On disc-less nodes, a tiny default
1790 schema is generated each time Mnesia is started. During the
1791 startup procedure, Mnesia exchanges schema information between
1792 the nodes to verify that the table definitions are compatible.
1793
1794 Each schema has a unique cookie, which can be regarded as a
1795 unique schema identifier. The cookie must be the same on all
1796 nodes where Mnesia is supposed to run. For details, see the
1797 User's Guide.
1798
1799 The schema file and all other files that Mnesia needs are kept
1800 in the Mnesia directory. The command-line option -mnesia dir Dir
1801 can be used to specify the location of this directory to the
1802 Mnesia system. If no such command-line option is found, the name
1803 of the directory defaults to Mnesia.Node.
1804
1805 application:start(mnesia) can also be used.
1806
1807 stop() -> stopped | {error, term()}
1808
1809 Stops Mnesia locally on the current node.
1810
1811 application:stop(mnesia) can also be used.
1812
1813 subscribe(What) -> {ok, node()} | {error, Reason :: term()}
1814
1815 Types:
1816
1817 What = system | activity | {table, table(), simple | de‐
1818 tailed}
1819
1820 Ensures that a copy of all events of type EventCategory is sent
1821 to the caller. The available event types are described in the
1822 User's Guide.
1823
1824 sync_dirty(Fun) -> Res | no_return()
1825
1826 sync_dirty(Fun, Args :: [Arg :: term()]) -> Res | no_return()
1827
1828 Types:
1829
1830 Fun = fun((...) -> Res)
1831
1832 Calls the Fun in a context that is not protected by a transac‐
1833 tion. The Mnesia function calls performed in the Fun are mapped
1834 to the corresponding dirty functions. It is performed in almost
1835 the same context as mnesia:async_dirty/1,2. The difference is
1836 that the operations are performed synchronously. The caller
1837 waits for the updates to be performed on all active replicas be‐
1838 fore the Fun returns. For details, see mnesia:activity/4 and the
1839 User's Guide.
1840
1841 sync_log() -> result()
1842
1843 Ensures that the local transaction log file is synced to disk.
1844 On a single node system, data written to disk tables since the
1845 last dump can be lost if there is a power outage. See
1846 dump_log/0.
1847
1848 sync_transaction(Fun) -> t_result(Res)
1849
1850 sync_transaction(Fun, Retries) -> t_result(Res)
1851
1852 sync_transaction(Fun, Args :: [Arg :: term()]) -> t_result(Res)
1853
1854 sync_transaction(Fun, Args :: [Arg :: term()], Retries) ->
1855 t_result(Res)
1856
1857 Types:
1858
1859 Fun = fun((...) -> Res)
1860 Retries = integer() >= 0 | infinity
1861
1862 Waits until data have been committed and logged to disk (if disk
1863 is used) on every involved node before it returns, otherwise it
1864 behaves as mnesia:transaction/[1,2,3].
1865
1866 This functionality can be used to avoid that one process over‐
1867 loads a database on another node.
1868
1869 system_info(Iterm :: term()) -> Info :: term()
1870
1871 Returns information about the Mnesia system, such as transaction
1872 statistics, db_nodes, and configuration parameters. The valid
1873 keys are as follows:
1874
1875 * all. Returns a list of all local system information. Each
1876 element is a {InfoKey, InfoVal} tuple.
1877
1878 New InfoKeys can be added and old undocumented InfoKeys can
1879 be removed without notice.
1880
1881 * access_module. Returns the name of module that is configured
1882 to be the activity access callback module.
1883
1884 * auto_repair. Returns true or false to indicate if Mnesia is
1885 configured to start the auto-repair facility on corrupted
1886 disc files.
1887
1888 * backup_module. Returns the name of the module that is con‐
1889 figured to be the backup callback module.
1890
1891 * checkpoints. Returns a list of the names of the checkpoints
1892 currently active on this node.
1893
1894 * event_module. Returns the name of the module that is the
1895 event handler callback module.
1896
1897 * db_nodes. Returns the nodes that make up the persistent
1898 database. Disc-less nodes are only included in the list of
1899 nodes if they explicitly have been added to the schema, for
1900 example, with mnesia:add_table_copy/3. The function can be
1901 started even if Mnesia is not yet running.
1902
1903 * debug. Returns the current debug level of Mnesia.
1904
1905 * directory. Returns the name of the Mnesia directory. It can
1906 be called even if Mnesia is not yet running.
1907
1908 * dump_log_load_regulation. Returns a boolean that tells if
1909 Mnesia is configured to regulate the dumper process load.
1910
1911 This feature is temporary and will be removed in future re‐
1912 leases.
1913
1914 * dump_log_time_threshold. Returns the time threshold for
1915 transaction log dumps in milliseconds.
1916
1917 * dump_log_update_in_place. Returns a boolean that tells if
1918 Mnesia is configured to perform the updates in the Dets
1919 files directly, or if the updates are to be performed in a
1920 copy of the Dets files.
1921
1922 * dump_log_write_threshold. Returns the write threshold for
1923 transaction log dumps as the number of writes to the trans‐
1924 action log.
1925
1926 * extra_db_nodes. Returns a list of extra db_nodes to be con‐
1927 tacted at startup.
1928
1929 * fallback_activated. Returns true if a fallback is activated,
1930 otherwise false.
1931
1932 * held_locks. Returns a list of all locks held by the local
1933 Mnesia lock manager.
1934
1935 * is_running. Returns yes or no to indicate if Mnesia is run‐
1936 ning. It can also return starting or stopping. Can be called
1937 even if Mnesia is not yet running.
1938
1939 * local_tables. Returns a list of all tables that are config‐
1940 ured to reside locally.
1941
1942 * lock_queue. Returns a list of all transactions that are
1943 queued for execution by the local lock manager.
1944
1945 * log_version. Returns the version number of the Mnesia trans‐
1946 action log format.
1947
1948 * master_node_tables. Returns a list of all tables with at
1949 least one master node.
1950
1951 * protocol_version. Returns the version number of the Mnesia
1952 inter-process communication protocol.
1953
1954 * running_db_nodes. Returns a list of nodes where Mnesia cur‐
1955 rently is running. This function can be called even if Mne‐
1956 sia is not yet running, but it then has slightly different
1957 semantics.
1958
1959 If Mnesia is down on the local node, the function returns
1960 those other db_nodes and extra_db_nodes that for the moment
1961 are operational.
1962
1963 If Mnesia is started, the function returns those nodes that
1964 Mnesia on the local node is fully connected to. Only those
1965 nodes that Mnesia has exchanged schema information with are
1966 included as running_db_nodes. After the merge of schemas,
1967 the local Mnesia system is fully operable and applications
1968 can perform access of remote replicas. Before the schema
1969 merge, Mnesia only operates locally. Sometimes there are
1970 more nodes included in the running_db_nodes list than all
1971 db_nodes and extra_db_nodes together.
1972
1973 * schema_location. Returns the initial schema location.
1974
1975 * subscribers. Returns a list of local processes currently
1976 subscribing to system events.
1977
1978 * tables. Returns a list of all locally known tables.
1979
1980 * transactions. Returns a list of all currently active local
1981 transactions.
1982
1983 * transaction_failures. Returns a number that indicates how
1984 many transactions have failed since Mnesia was started.
1985
1986 * transaction_commits. Returns a number that indicates how
1987 many transactions have terminated successfully since Mnesia
1988 was started.
1989
1990 * transaction_restarts. Returns a number that indicates how
1991 many transactions have been restarted since Mnesia was
1992 started.
1993
1994 * transaction_log_writes. Returns a number that indicates how
1995 many write operations that have been performed to the trans‐
1996 action log since startup.
1997
1998 * use_dir. Returns a boolean that indicates if the Mnesia di‐
1999 rectory is used or not. Can be started even if Mnesia is not
2000 yet running.
2001
2002 * version. Returns the current version number of Mnesia.
2003
2004 table(Tab :: table()) -> qlc:query_handle()
2005
2006 table(Tab :: table(), Options) -> qlc:query_handle()
2007
2008 Types:
2009
2010 Options = Option | [Option]
2011 Option = MnesiaOpt | QlcOption
2012 MnesiaOpt =
2013 {traverse, SelectOp} |
2014 {lock, lock_kind()} |
2015 {n_objects, integer() >= 0}
2016 SelectOp = select | {select, ets:match_spec()}
2017 QlcOption = {key_equality, '==' | '=:='}
2018
2019 Returns a Query List Comprehension (QLC) query handle, see the
2020 qlc(3) manual page in STDLIB. The module qlc implements a query
2021 language that can use Mnesia tables as sources of data. Calling
2022 mnesia:table/1,2 is the means to make the mnesia table Tab us‐
2023 able to QLC.
2024
2025 Option can contain Mnesia options or QLC options. Mnesia recog‐
2026 nizes the following options (any other option is forwarded to
2027 QLC).
2028
2029 * {lock, Lock}, where lock can be read or write. Default is
2030 read.
2031
2032 * {n_objects,Number}, where n_objects specifies (roughly) the
2033 number of objects returned from Mnesia to QLC. Queries to
2034 remote tables can need a larger chunk to reduce network
2035 overhead. By default, 100 objects at a time are returned.
2036
2037 * {traverse, SelectMethod}, where traverse determines the
2038 method to traverse the whole table (if needed). The default
2039 method is select.
2040
2041 There are two alternatives for select:
2042
2043 * select. The table is traversed by calling mnesia:select/4
2044 and mnesia:select/1. The match specification (the second ar‐
2045 gument of select/3) is assembled by QLC: simple filters are
2046 translated into equivalent match specifications. More com‐
2047 plicated filters need to be applied to all objects returned
2048 by select/3 given a match specification that matches all ob‐
2049 jects.
2050
2051 * {select, MatchSpec}. As for select, the table is traversed
2052 by calling mnesia:select/3 and mnesia:select/1. The differ‐
2053 ence is that the match specification is explicitly given.
2054 This is how to state match specifications that cannot easily
2055 be expressed within the syntax provided by QLC.
2056
2057 table_info(Tab :: table(), Item :: term()) -> Info :: term()
2058
2059 The table_info/2 function takes two arguments. The first is the
2060 name of a Mnesia table. The second is one of the following keys:
2061
2062 * all. Returns a list of all local table information. Each el‐
2063 ement is a {InfoKey, ItemVal} tuple.
2064
2065 New InfoItems can be added and old undocumented InfoItems
2066 can be removed without notice.
2067
2068 * access_mode. Returns the access mode of the table. The ac‐
2069 cess mode can be read_only or read_write.
2070
2071 * arity. Returns the arity of records in the table as speci‐
2072 fied in the schema.
2073
2074 * attributes. Returns the table attribute names that are spec‐
2075 ified in the schema.
2076
2077 * checkpoints. Returns the names of the currently active
2078 checkpoints, which involve this table on this node.
2079
2080 * cookie. Returns a table cookie, which is a unique system-
2081 generated identifier for the table. The cookie is used in‐
2082 ternally to ensure that two different table definitions us‐
2083 ing the same table name cannot accidentally be intermixed.
2084 The cookie is generated when the table is created initially.
2085
2086 * disc_copies. Returns the nodes where a disc_copy of the ta‐
2087 ble resides according to the schema.
2088
2089 * disc_only_copies. Returns the nodes where a disc_only_copy
2090 of the table resides according to the schema.
2091
2092 * index. Returns the list of index position integers for the
2093 table.
2094
2095 * load_node. Returns the name of the node that Mnesia loaded
2096 the table from. The structure of the returned value is un‐
2097 specified, but can be useful for debugging purposes.
2098
2099 * load_order. Returns the load order priority of the table. It
2100 is an integer and defaults to 0 (zero).
2101
2102 * load_reason. Returns the reason of why Mnesia decided to
2103 load the table. The structure of the returned value is un‐
2104 specified, but can be useful for debugging purposes.
2105
2106 * local_content. Returns true or false to indicate if the ta‐
2107 ble is configured to have locally unique content on each
2108 node.
2109
2110 * master_nodes. Returns the master nodes of a table.
2111
2112 * memory. Returns for ram_copies and disc_copies tables the
2113 number of words allocated in memory to the table on this
2114 node. For disc_only_copies tables the number of bytes stored
2115 on disc is returned.
2116
2117 * ram_copies. Returns the nodes where a ram_copy of the table
2118 resides according to the schema.
2119
2120 * record_name. Returns the record name, common for all records
2121 in the table.
2122
2123 * size. Returns the number of records inserted in the table.
2124
2125 * snmp. Returns the SNMP struct. [] means that the table cur‐
2126 rently has no SNMP properties.
2127
2128 * storage_type. Returns the local storage type of the table.
2129 It can be disc_copies, ram_copies, disc_only_copies, or the
2130 atom unknown. unknown is returned for all tables that only
2131 reside remotely.
2132
2133 * subscribers. Returns a list of local processes currently
2134 subscribing to local table events that involve this table on
2135 this node.
2136
2137 * type. Returns the table type, which is bag, set, or or‐
2138 dered_set.
2139
2140 * user_properties. Returns the user-associated table proper‐
2141 ties of the table. It is a list of the stored property
2142 records.
2143
2144 * version. Returns the current version of the table defini‐
2145 tion. The table version is incremented when the table defi‐
2146 nition is changed. The table definition can be incremented
2147 directly when it has been changed in a schema transaction,
2148 or when a committed table definition is merged with table
2149 definitions from other nodes during startup.
2150
2151 * where_to_read. Returns the node where the table can be read.
2152 If value nowhere is returned, either the table is not loaded
2153 or it resides at a remote node that is not running.
2154
2155 * where_to_write. Returns a list of the nodes that currently
2156 hold an active replica of the table.
2157
2158 * wild_pattern. Returns a structure that can be given to the
2159 various match functions for a certain table. A record tuple
2160 is where all record fields have value '_'.
2161
2162 transaction(Fun) -> t_result(Res)
2163
2164 transaction(Fun, Retries) -> t_result(Res)
2165
2166 transaction(Fun, Args :: [Arg :: term()]) -> t_result(Res)
2167
2168 transaction(Fun, Args :: [Arg :: term()], Retries) ->
2169 t_result(Res)
2170
2171 Types:
2172
2173 Fun = fun((...) -> Res)
2174 Retries = integer() >= 0 | infinity
2175
2176 Executes the functional object Fun with arguments Args as a
2177 transaction.
2178
2179 The code that executes inside the transaction can consist of a
2180 series of table manipulation functions. If something goes wrong
2181 inside the transaction as a result of a user error or a certain
2182 table not being available, the entire transaction is terminated
2183 and the function transaction/1 returns the tuple {aborted, Rea‐
2184 son}.
2185
2186 If all is going well, {atomic, ResultOfFun} is returned, where
2187 ResultOfFun is the value of the last expression in Fun.
2188
2189 A function that adds a family to the database can be written as
2190 follows if there is a structure {family, Father, Mother, Chil‐
2191 drenList}:
2192
2193 add_family({family, F, M, Children}) ->
2194 ChildOids = lists:map(fun oid/1, Children),
2195 Trans = fun() ->
2196 mnesia:write(F#person{children = ChildOids},
2197 mnesia:write(M#person{children = ChildOids},
2198 Write = fun(Child) -> mnesia:write(Child) end,
2199 lists:foreach(Write, Children)
2200 end,
2201 mnesia:transaction(Trans).
2202
2203 oid(Rec) -> {element(1, Rec), element(2, Rec)}.
2204
2205 This code adds a set of people to the database. Running this
2206 code within one transaction ensures that either the whole family
2207 is added to the database, or the whole transaction terminates.
2208 For example, if the last child is badly formatted, or the exe‐
2209 cuting process terminates because of an 'EXIT' signal while exe‐
2210 cuting the family code, the transaction terminates. Thus, the
2211 situation where half a family is added can never occur.
2212
2213 It is also useful to update the database within a transaction if
2214 several processes concurrently update the same records. For ex‐
2215 ample, the function raise(Name, Amount), which adds Amount to
2216 the salary field of a person, is to be implemented as follows:
2217
2218 raise(Name, Amount) ->
2219 mnesia:transaction(fun() ->
2220 case mnesia:wread({person, Name}) of
2221 [P] ->
2222 Salary = Amount + P#person.salary,
2223 P2 = P#person{salary = Salary},
2224 mnesia:write(P2);
2225 _ ->
2226 mnesia:abort("No such person")
2227 end
2228 end).
2229
2230 When this function executes within a transaction, several pro‐
2231 cesses running on different nodes can concurrently execute the
2232 function raise/2 without interfering with each other.
2233
2234 Since Mnesia detects deadlocks, a transaction can be restarted
2235 any number of times. This function attempts a restart as speci‐
2236 fied in Retries. Retries must be an integer greater than 0 or
2237 the atom infinity. Default is infinity.
2238
2239 transform_table(Tab :: table(), Fun, NewA :: [Attr], RecName) ->
2240 t_result(ok)
2241
2242 Types:
2243
2244 RecName = Attr = atom()
2245 Fun =
2246 fun((Record :: tuple()) -> Transformed :: tuple()) | ig‐
2247 nore
2248
2249 Applies argument Fun to all records in the table. Fun is a func‐
2250 tion that takes a record of the old type and returns a trans‐
2251 formed record of the new type. Argument Fun can also be the atom
2252 ignore, which indicates that only the metadata about the table
2253 is updated. Use of ignore is not recommended, but included as a
2254 possibility for the user do to an own transformation.
2255
2256 NewAttributeList and NewRecordName specify the attributes and
2257 the new record type of the converted table. Table name always
2258 remains unchanged. If record_name is changed, only the Mnesia
2259 functions that use table identifiers work, for example, mne‐
2260 sia:write/3 works, but not mnesia:write/1.
2261
2262 transform_table(Tab :: table(), Fun, NewA :: [Attr]) ->
2263 t_result(ok)
2264
2265 Types:
2266
2267 Attr = atom()
2268 Fun =
2269 fun((Record :: tuple()) -> Transformed :: tuple()) | ig‐
2270 nore
2271
2272 Calls mnesia:transform_table(Tab, Fun, NewAttributeList, Rec‐
2273 Name), where RecName is mnesia:table_info(Tab, record_name).
2274
2275 traverse_backup(Src :: term(), Dest :: term(), Fun, Acc) ->
2276 {ok, Acc} | {error, Reason :: term()}
2277
2278 traverse_backup(Src :: term(),
2279 SrcMod :: module(),
2280 Dest :: term(),
2281 DestMod :: module(),
2282 Fun, Acc) ->
2283 {ok, Acc} | {error, Reason :: term()}
2284
2285 Types:
2286
2287 Fun = fun((Items, Acc) -> {Items, Acc})
2288
2289 Iterates over a backup, either to transform it into a new
2290 backup, or read it. The arguments are explained briefly here.
2291 For details, see the User's Guide.
2292
2293 * SourceMod and TargetMod are the names of the modules that
2294 actually access the backup media.
2295
2296 * Source and Target are opaque data used exclusively by mod‐
2297 ules SourceMod and TargetMod to initialize the backup media.
2298
2299 * Acc is an initial accumulator value.
2300
2301 * Fun(BackupItems, Acc) is applied to each item in the backup.
2302 The Fun must return a tuple {BackupItems,NewAcc}, where
2303 BackupItems is a list of valid backup items, and NewAcc is a
2304 new accumulator value. The returned backup items are written
2305 in the target backup.
2306
2307 * LastAcc is the last accumulator value. This is the last
2308 NewAcc value that was returned by Fun.
2309
2310 uninstall_fallback() -> result()
2311
2312 Calls the function mnesia:uninstall_fallback([{scope, global}]).
2313
2314 uninstall_fallback(Args) -> result()
2315
2316 Types:
2317
2318 Args = [{mnesia_dir, Dir :: string()}]
2319
2320 Deinstalls a fallback before it has been used to restore the
2321 database. This is normally a distributed operation that is ei‐
2322 ther performed on all nodes with disc resident schema, or none.
2323 Uninstallation of fallbacks requires Erlang to be operational on
2324 all involved nodes, but it does not matter if Mnesia is running
2325 or not. Which nodes that are considered as disc-resident nodes
2326 is determined from the schema information in the local fallback.
2327
2328 Args is a list of the following tuples:
2329
2330 * {module, BackupMod}. For semantics, see mnesia:install_fall‐
2331 back/2.
2332
2333 * {scope, Scope}. For semantics, see mnesia:install_fall‐
2334 back/2.
2335
2336 * {mnesia_dir, AlternateDir}. For semantics, see mnesia:in‐
2337 stall_fallback/2.
2338
2339 unsubscribe(What) -> {ok, node()} | {error, Reason :: term()}
2340
2341 Types:
2342
2343 What = system | activity | {table, table(), simple | de‐
2344 tailed}
2345
2346 Stops sending events of type EventCategory to the caller.
2347
2348 Node is the local node.
2349
2350 wait_for_tables(Tabs :: [Tab :: table()], TMO :: timeout()) ->
2351 result() | {timeout, [table()]}
2352
2353 Some applications need to wait for certain tables to be accessi‐
2354 ble to do useful work. mnesia:wait_for_tables/2 either hangs un‐
2355 til all tables in TabList are accessible, or until timeout is
2356 reached.
2357
2358 wread(Oid :: {Tab :: table(), Key :: term()}) -> [tuple()]
2359
2360 Calls the function mnesia:read(Tab, Key, write).
2361
2362 write(Record :: tuple()) -> ok
2363
2364 Calls the function mnesia:write(Tab, Record, write), where Tab
2365 is element(1, Record).
2366
2367 write(Tab :: table(),
2368 Record :: tuple(),
2369 LockKind :: write_locks()) ->
2370 ok
2371
2372 Writes record Record to table Tab.
2373
2374 The function returns ok, or terminates if an error occurs. For
2375 example, the transaction terminates if no person table exists.
2376
2377 The semantics of this function is context-sensitive. For de‐
2378 tails, see mnesia:activity/4. In transaction-context, it ac‐
2379 quires a lock of type LockKind. The lock types write and
2380 sticky_write are supported.
2381
2382 write_lock_table(Tab :: table()) -> ok
2383
2384 Calls the function mnesia:lock({table, Tab}, write).
2385
2387 Mnesia reads the following application configuration parameters:
2388
2389 * -mnesia access_module Module. The name of the Mnesia activity ac‐
2390 cess callback module. Default is mnesia.
2391
2392 * -mnesia auto_repair true | false. This flag controls if Mnesia au‐
2393 tomatically tries to repair files that have not been properly
2394 closed. Default is true.
2395
2396 * -mnesia backup_module Module. The name of the Mnesia backup call‐
2397 back module. Default is mnesia_backup.
2398
2399 * -mnesia debug Level. Controls the debug level of Mnesia. The possi‐
2400 ble values are as follows:
2401
2402 none:
2403 No trace outputs. This is the default.
2404
2405 verbose:
2406 Activates tracing of important debug events. These events gener‐
2407 ate {mnesia_info, Format, Args} system events. Processes can sub‐
2408 scribe to these events with mnesia:subscribe/1. The events are
2409 always sent to the Mnesia event handler.
2410
2411 debug:
2412 Activates all events at the verbose level plus full trace of all
2413 debug events. These debug events generate {mnesia_info, Format,
2414 Args} system events. Processes can subscribe to these events with
2415 mnesia:subscribe/1. The events are always sent to the Mnesia
2416 event handler. On this debug level, the Mnesia event handler
2417 starts subscribing to updates in the schema table.
2418
2419 trace:
2420 Activates all events at the debug level. On this level, the Mne‐
2421 sia event handler starts subscribing to updates on all Mnesia ta‐
2422 bles. This level is intended only for debugging small toy sys‐
2423 tems, as many large events can be generated.
2424
2425 false:
2426 An alias for none.
2427
2428 true:
2429 An alias for debug.
2430
2431 * -mnesia core_dir Directory. The name of the directory where Mnesia
2432 core files is stored, or false. Setting it implies that also RAM-
2433 only nodes generate a core file if a crash occurs.
2434
2435 * -mnesia dc_dump_limit Number. Controls how often disc_copies tables
2436 are dumped from memory. Tables are dumped when filesize(Log) >
2437 (filesize(Tab)/Dc_dump_limit). Lower values reduce CPU overhead but
2438 increase disk space and startup times. Default is 4.
2439
2440 * -mnesia dir Directory. The name of the directory where all Mnesia
2441 data is stored. The directory name must be unique for the current
2442 node. Two nodes must never share the the same Mnesia directory. The
2443 results are unpredictable.
2444
2445 * -mnesia dump_disc_copies_at_startup true | false. If set to false,
2446 this disables the dumping of disc_copies tables during startup
2447 while tables are being loaded. The default is true.
2448
2449 * -mnesia dump_log_load_regulation true | false. Controls if log
2450 dumps are to be performed as fast as possible, or if the dumper is
2451 to do its own load regulation. Default is false.
2452
2453 This feature is temporary and will be removed in a future release
2454
2455 * -mnesia dump_log_update_in_place true | false. Controls if log
2456 dumps are performed on a copy of the original data file, or if the
2457 log dump is performed on the original data file. Default is true
2458
2459 *
2460
2461
2462 -mnesia dump_log_write_threshold Max. Max is an integer that speci‐
2463 fies the maximum number of writes allowed to the transaction log
2464 before a new dump of the log is performed. Default is 100 log
2465 writes.
2466
2467 *
2468
2469
2470 -mnesia dump_log_time_threshold Max. Max is an integer that speci‐
2471 fies the dump log interval in milliseconds. Default is 3 minutes.
2472 If a dump has not been performed within dump_log_time_threshold
2473 milliseconds, a new dump is performed regardless of the number of
2474 writes performed.
2475
2476 * -mnesia event_module Module. The name of the Mnesia event handler
2477 callback module. Default is mnesia_event.
2478
2479 * -mnesia extra_db_nodes Nodes specifies a list of nodes, in addition
2480 to the ones found in the schema, with which Mnesia is also to es‐
2481 tablish contact. Default is [] (empty list).
2482
2483 * -mnesia fallback_error_function {UserModule, UserFunc}. Specifies a
2484 user-supplied callback function, which is called if a fallback is
2485 installed and Mnesia goes down on another node. Mnesia calls the
2486 function with one argument, the name of the dying node, for exam‐
2487 ple, UserModule:UserFunc(DyingNode). Mnesia must be restarted, oth‐
2488 erwise the database can be inconsistent. The default behavior is to
2489 terminate Mnesia.
2490
2491 * -mnesia max_wait_for_decision Timeout. Specifies how long Mnesia
2492 waits for other nodes to share their knowledge about the outcome of
2493 an unclear transaction. By default, Timeout is set to the atom in‐
2494 finity. This implies that if Mnesia upon startup detects a "heavy‐
2495 weight transaction" whose outcome is unclear, the local Mnesia
2496 waits until Mnesia is started on some (in the worst case all) of
2497 the other nodes that were involved in the interrupted transaction.
2498 This is a rare situation, but if it occurs, Mnesia does not guess
2499 if the transaction on the other nodes was committed or terminated.
2500 Mnesia waits until it knows the outcome and then acts accordingly.
2501
2502 If Timeout is set to an integer value in milliseconds, Mnesia
2503 forces "heavyweight transactions" to be finished, even if the out‐
2504 come of the transaction for the moment is unclear. After Timeout
2505 milliseconds, Mnesia commits or terminates the transaction and con‐
2506 tinues with the startup. This can lead to a situation where the
2507 transaction is committed on some nodes and terminated on other
2508 nodes. If the transaction is a schema transaction, the inconsis‐
2509 tency can be fatal.
2510
2511 * -mnesia no_table_loaders NUMBER. Specifies the number of parallel
2512 table loaders during start. More loaders can be good if the network
2513 latency is high or if many tables contain few records. Default is
2514 2.
2515
2516 * -mnesia send_compressed Level. Specifies the level of compression
2517 to be used when copying a table from the local node to another one.
2518 Default is 0.
2519
2520 Level must be an integer in the interval [0, 9], where 0 means no
2521 compression and 9 means maximum compression. Before setting it to a
2522 non-zero value, ensure that the remote nodes understand this con‐
2523 figuration.
2524
2525 * -mnesia max_transfer_size Number. Specifies the estimated size in
2526 bytes of a single packet of data to be used when copying a table
2527 from the local node to another one. Default is 64000.
2528
2529 * -mnesia schema_location Loc. Controls where Mnesia looks for its
2530 schema. Parameter Loc can be one of the following atoms:
2531
2532 disc:
2533 Mandatory disc. The schema is assumed to be located in the Mnesia
2534 directory. If the schema cannot be found, Mnesia refuses to
2535 start. This is the old behavior.
2536
2537 ram:
2538 Mandatory RAM. The schema resides in RAM only. At startup, a tiny
2539 new schema is generated. This default schema only contains the
2540 definition of the schema table and only resides on the local
2541 node. Since no other nodes are found in the default schema, con‐
2542 figuration parameter extra_db_nodes must be used to let the node
2543 share its table definitions with other nodes.
2544
2545 Parameter extra_db_nodes can also be used on disc based nodes.
2546
2547 opt_disc:
2548 Optional disc. The schema can reside on disc or in RAM. If the
2549 schema is found on disc, Mnesia starts as a disc-based node and
2550 the storage type of the schema table is disc_copies. If no schema
2551 is found on disc, Mnesia starts as a disc-less node and the stor‐
2552 age type of the schema table is ram_copies. Default value for the
2553 application parameter is opt_disc.
2554
2555 First, the SASL application parameters are checked, then the command-
2556 line flags are checked, and finally, the default value is chosen.
2557
2559 application(3), dets(3), disk_log(3), ets(3), mnesia_registry(3),
2560 qlc(3)
2561
2562
2563
2564Ericsson AB mnesia 4.20 mnesia(3)