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