Repository navigation
Expand file tree
/
Copy pathmnesia.erl
More file actions
6293 lines (5528 loc) · 225 KB
/
Copy pathmnesia.erl
File metadata and controls
6293 lines (5528 loc) · 225 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%%
%% %CopyrightBegin%
%%
%% SPDX-License-Identifier: Apache-2.0
%%
%% Copyright Ericsson AB 1996-2026. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
%%
%% This module exports the public interface of the Mnesia DBMS engine
-module(mnesia).
-moduledoc """
A distributed key-value DBMS
The following are some of the most important and attractive capabilities
provided by Mnesia:
- A relational/object hybrid data model that is suitable for telecommunications
applications.
- A DBMS query language, Query List Comprehension (QLC) as an add-on library.
- Persistence. Tables can be coherently kept on disc and in the main memory.
- Replication. Tables can be replicated at several nodes.
- Atomic transactions. A series of table manipulation operations can be grouped
into a single atomic transaction.
- Location transparency. Programs can be written without knowledge of the actual
data location.
- Extremely fast real-time data searches.
- Schema manipulation routines. The DBMS can be reconfigured at runtime without
stopping the system.
This Reference Manual describes the Mnesia API. This includes functions that
define and manipulate Mnesia tables.
All functions in this Reference Manual can be used in any combination with
queries using the list comprehension notation. For information about the query
notation, see the `m:qlc` manual page in STDLIB.
Data in Mnesia is organized as a set of tables. Each table has a name that must
be an atom. Each table is made up of Erlang records. The user is responsible for
the record definitions. Each table also has a set of properties. The following
are some of the properties that are associated with each table:
- `type`. Each table can have `set`, `ordered_set`, or `bag` semantics. Notice
that currently `ordered_set` is not supported for `disc_only_copies`.
If a table is of type `set`, each key leads to either one or zero records.
If a new item is inserted with the same key as an existing record, the old
record is overwritten. However, if a table is of type `bag`, each key can map
to several records. All records in type `bag` tables are unique, only the keys
can be duplicated.
- `record_name`. All records stored in a table must have the same name. The
records must be instances of the same record type.
- `ram_copies`. A table can be replicated on a number of Erlang nodes. Property
`ram_copies` specifies a list of Erlang nodes where RAM copies are kept. These
copies can be dumped to disc at regular intervals. However, updates to these
copies are not written to disc on a transaction basis.
- `disc_copies`. This property specifies a list of Erlang nodes where the table
is kept in RAM and on disc. All updates of the table are performed in the
actual table and are also logged to disc. If a table is of type `disc_copies`
at a certain node, the entire table is resident in RAM memory and on disc.
Each transaction performed on the table is appended to a `LOG` file and
written into the RAM table.
- `disc_only_copies`. Some, or all, table replicas can be kept on disc only.
These replicas are considerably slower than the RAM-based replicas.
- `index`. This is a list of attribute names, or integers, which specify the
tuple positions on which Mnesia is to build and maintain an extra index table.
- `local_content`. When an application requires tables whose contents are local
to each node, `local_content` tables can be used. The table name is known to
all Mnesia nodes, but its content is unique on each node. This means that
access to such a table must be done locally. Set field `local_content` to
`true` to enable the `local_content` behavior. Default is `false`.
- `majority`. This attribute is `true` or `false`; default is `false`. When
`true`, a majority of the table replicas must be available for an update to
succeed. Majority checking can be enabled on tables with mission-critical
data, where it is vital to avoid inconsistencies because of network splits.
- `snmp`. Each (set-based) Mnesia table can be automatically turned into a
Simple Network Management Protocol (SNMP) ordered table as well. This property
specifies the types of the SNMP keys.
- `attributes`. The names of the attributes for the records that are inserted in
the table.
For information about the complete set of table properties and their details,
see `mnesia:create_table/2`.
This Reference Manual uses a table of persons to illustrate various examples.
The following record definition is assumed:
```erlang
-record(person, {name,
age = 0,
address = unknown,
salary = 0,
children = []}),
```
The first record attribute is the primary key, or key for short.
The function descriptions are sorted in alphabetical order. It is recommended to
start to read about `mnesia:create_table/2`, `mnesia:lock/2`, and
`mnesia:activity/4` before you continue and learn about the rest.
Writing or deleting in transaction-context creates a local copy of each modified
record during the transaction. During iteration, that is, `mnesia:foldl/4`,
`mnesia:foldr/4`, `mnesia:next/2`, `mnesia:prev/2`, and `mnesia:snmp_get_next_index/2`, Mnesia
compensates for every written or deleted record, which can reduce the
performance.
If possible, avoid writing or deleting records in the same transaction before
iterating over the table.
## Configuration Parameters
[](){: #configuration_parameters }
Mnesia reads the following application configuration parameters:
- `-mnesia access_module Module`. The name of the Mnesia activity access
callback module. Default is `mnesia`.
- `-mnesia auto_repair true | false`. This flag controls if Mnesia automatically
tries to repair files that have not been properly closed. Default is `true`.
- `-mnesia backup_module Module`. The name of the Mnesia backup callback module.
Default is `mnesia_backup`.
- `-mnesia debug Level`. Controls the debug level of Mnesia. The possible values
are as follows:
- **`none`** - No trace outputs. This is the default.
- **`verbose`** - Activates tracing of important debug events. These events
generate `{mnesia_info, Format, Args}` system events. Processes can
subscribe to these events with `mnesia:subscribe/1`. The events are always
sent to the Mnesia event handler.
- **`debug`** - Activates all events at the verbose level plus full trace of
all debug events. These debug events generate `{mnesia_info, Format, Args}`
system events. Processes can subscribe to these events with
`mnesia:subscribe/1`. The events are always sent to the Mnesia event
handler. On this debug level, the Mnesia event handler starts subscribing to
updates in the schema table.
- **`trace`** - Activates all events at the debug level. On this level, the
Mnesia event handler starts subscribing to updates on all Mnesia tables.
This level is intended only for debugging small toy systems, as many large
events can be generated.
- **`false`** - An alias for none.
- **`true`** - An alias for debug.
- `-mnesia core_dir Directory`. The name of the directory where Mnesia core
files is stored, or false. Setting it implies that also RAM-only nodes
generate a core file if a crash occurs.
- `-mnesia dc_dump_limit Number`. Controls how often `disc_copies` tables are
dumped from memory. Tables are dumped when
`filesize(Log) > (filesize(Tab)/Dc_dump_limit)`. Lower values reduce CPU
overhead but increase disk space and startup times. Default is 4.
- `-mnesia dir Directory`. The name of the directory where all Mnesia data is
stored. The directory name must be unique for the current node. Two nodes must
never share the the same Mnesia directory. The results are unpredictable.
- `-mnesia dump_disc_copies_at_startup true | false`. If set to false, this
disables the dumping of `disc_copies` tables during startup while tables are
being loaded. The default is true.
- `-mnesia dump_log_load_regulation true | false`. Controls if log dumps are to
be performed as fast as possible, or if the dumper is to do its own load
regulation. Default is `false`.
This feature is temporary and will be removed in a future release
- `-mnesia dump_log_update_in_place true | false`. Controls if log dumps are
performed on a copy of the original data file, or if the log dump is performed
on the original data file. Default is `true`
- [](){: #dump_log_write_threshold } `-mnesia dump_log_write_threshold Max`.
`Max` is an integer that specifies the maximum number of writes allowed to the
transaction log before a new dump of the log is performed. Default is `1000`
log writes.
- [](){: #dump_log_time_threshold } `-mnesia dump_log_time_threshold Max`. `Max`
is an integer that specifies the dump log interval in milliseconds. Default is
3 minutes. If a dump has not been performed within `dump_log_time_threshold`
milliseconds, a new dump is performed regardless of the number of writes
performed.
- `-mnesia event_module Module`. The name of the Mnesia event handler callback
module. Default is `mnesia_event`.
- `-mnesia extra_db_nodes Nodes` specifies a list of nodes, in addition to the
ones found in the schema, with which Mnesia is also to establish contact.
Default is `[]` (empty list).
- `-mnesia fallback_error_function {UserModule, UserFunc}`. Specifies a
user-supplied callback function, which is called if a fallback is installed
and Mnesia goes down on another node. Mnesia calls the function with one
argument, the name of the dying node, for example,
`UserModule:UserFunc(DyingNode)`. Mnesia must be restarted, otherwise the
database can be inconsistent. The default behavior is to terminate Mnesia.
- `-mnesia max_wait_for_decision Timeout`. Specifies how long Mnesia waits for
other nodes to share their knowledge about the outcome of an unclear
transaction. By default, `Timeout` is set to the atom `infinity`. This implies
that if Mnesia upon startup detects a "heavyweight transaction" whose outcome
is unclear, the local Mnesia waits until Mnesia is started on some (in the
worst case all) of the other nodes that were involved in the interrupted
transaction. This is a rare situation, but if it occurs, Mnesia does not guess
if the transaction on the other nodes was committed or terminated. Mnesia
waits until it knows the outcome and then acts accordingly.
If `Timeout` is set to an integer value in milliseconds, Mnesia forces
"heavyweight transactions" to be finished, even if the outcome of the
transaction for the moment is unclear. After `Timeout` milliseconds, Mnesia
commits or terminates the transaction and continues with the startup. This can
lead to a situation where the transaction is committed on some nodes and
terminated on other nodes. If the transaction is a schema transaction, the
inconsistency can be fatal.
- `-mnesia no_table_loaders NUMBER`. Specifies the number of parallel table
loaders during start. More loaders can be good if the network latency is high
or if many tables contain few records. Default is `2`.
- `-mnesia send_compressed Level`. Specifies the level of compression to be used
when copying a table from the local node to another one. Default is `0`.
`Level` must be an integer in the interval `[0, 9]`, where `0` means no
compression and `9` means maximum compression. Before setting it to a non-zero
value, ensure that the remote nodes understand this configuration.
- `-mnesia max_transfer_size Number`. Specifies the estimated size in bytes of a
single packet of data to be used when copying a table from the local node to
another one. Default is `64000`.
- `-mnesia schema_location Loc`. Controls where Mnesia looks for its schema.
Parameter `Loc` can be one of the following atoms:
- **`disc`** - Mandatory disc. The schema is assumed to be located in the
Mnesia directory. If the schema cannot be found, Mnesia refuses to start.
This is the old behavior.
- **`ram`** - Mandatory RAM. The schema resides in RAM only. At startup, a
tiny new schema is generated. This default schema only contains the
definition of the schema table and only resides on the local node. Since no
other nodes are found in the default schema, configuration parameter
`extra_db_nodes` must be used to let the node share its table definitions
with other nodes.
Parameter `extra_db_nodes` can also be used on disc based nodes.
- **`opt_disc`** - Optional disc. The schema can reside on disc or in RAM. If
the schema is found on disc, Mnesia starts as a disc-based node and the
storage type of the schema table is `disc_copies`. If no schema is found on
disc, Mnesia starts as a disc-less node and the storage type of the schema
table is `ram_copies`. Default value for the application parameter is
`opt_disc`.
First, the SASL application parameters are checked, then the command-line flags
are checked, and finally, the default value is chosen.
### See Also
`m:application`, `m:dets`, `m:disk_log`, `m:ets`, `m:qlc`
""".
%-behaviour(mnesia_access).
-export([
%% Start, stop and debugging
start/0, start/1, stop/0, % Not for public use
set_debug_level/1, lkill/0, kill/0, % Not for public use
ms/0,
change_config/2,
%% Activity mgt
abort/1, transaction/1, transaction/2, transaction/3,
sync_transaction/1, sync_transaction/2, sync_transaction/3,
async_dirty/1, async_dirty/2, sync_dirty/1, sync_dirty/2, ets/1, ets/2,
activity/2, activity/3, activity/4, % Not for public use
is_transaction/0,
%% Access within an activity - Lock acquisition
lock/2, lock/4,
lock_table/2,
read_lock_table/1,
write_lock_table/1,
%% Access within an activity - Updates
write/1, s_write/1, write/3, write/5,
delete/1, s_delete/1, delete/3, delete/5,
delete_object/1, s_delete_object/1, delete_object/3, delete_object/5,
%% Access within an activity - Reads
read/1, read/2, wread/1, read/3, read/5,
match_object/1, match_object/3, match_object/5,
select/1,select/2,select/3,select/4,select/5,select/6,
select_reverse/1,select_reverse/2,select_reverse/3,select_reverse/4,
select_reverse/5,select_reverse/6,
all_keys/1, all_keys/4,
index_match_object/2, index_match_object/4, index_match_object/6,
index_read/3, index_read/6,
first/1, next/2, last/1, prev/2,
first/3, next/4, last/3, prev/4,
%% Iterators within an activity
foldl/3, foldl/4, foldr/3, foldr/4,
%% Dirty access regardless of activities - Updates
dirty_write/1, dirty_write/2,
dirty_delete/1, dirty_delete/2,
dirty_delete_object/1, dirty_delete_object/2,
dirty_update_counter/2, dirty_update_counter/3,
%% Dirty access regardless of activities - Read
dirty_read/1, dirty_read/2,
dirty_select/2,
dirty_select_reverse/2,
dirty_match_object/1, dirty_match_object/2, dirty_all_keys/1,
dirty_index_match_object/2, dirty_index_match_object/3,
dirty_index_read/3, dirty_slot/2,
dirty_first/1, dirty_next/2, dirty_last/1, dirty_prev/2,
%% Info
table_info/2, table_info/4, schema/0, schema/1,
error_description/1, info/0, system_info/1,
system_info/0, % Not for public use
%% Database mgt
create_schema/1, create_schema/2, delete_schema/1,
add_backend_type/2,
backup/1, backup/2, traverse_backup/4, traverse_backup/6,
install_fallback/1, install_fallback/2,
uninstall_fallback/0, uninstall_fallback/1,
activate_checkpoint/1, deactivate_checkpoint/1,
backup_checkpoint/2, backup_checkpoint/3, restore/2,
%% Table mgt
create_table/1, create_table/2, delete_table/1,
add_table_copy/3, del_table_copy/2, move_table_copy/3,
add_table_index/2, del_table_index/2,
transform_table/3, transform_table/4,
change_table_copy_type/3, change_table_majority/2,
read_table_property/2, write_table_property/2, delete_table_property/2,
change_table_frag/2,
clear_table/1, clear_table/4,
%% Table load
dump_tables/1, wait_for_tables/2, force_load_table/1,
change_table_access_mode/2, change_table_load_order/2,
set_master_nodes/1, set_master_nodes/2,
%% Misc admin
dump_log/0, sync_log/0,
subscribe/1, unsubscribe/1, report_event/1,
%% Snmp
snmp_open_table/2, snmp_close_table/1,
snmp_get_row/2, snmp_get_next_index/2, snmp_get_mnesia_key/2,
%% Textfile access
load_textfile/1, dump_to_textfile/1,
%% QLC functions
table/1, table/2,
%% Mnemosyne exclusive
get_activity_id/0, put_activity_id/1, % Not for public use
%% Mnesia internal functions
dirty_rpc/4, % Not for public use
has_var/1, fun_select/7, fun_select/10, select_cont/3, dirty_sel_init/5,
foldl/6, foldr/6,
%% Module internal callback functions
raw_table_info/2, % Not for public use
remote_dirty_match_object/2, % Not for public use
remote_dirty_select/2, % Not for public use
remote_dirty_select_reverse/2 % Not for public use
]).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-include("mnesia.hrl").
-import(mnesia_lib, [verbose/2]).
-type create_option() ::
{'access_mode', 'read_write' | 'read_only'} |
{'attributes', [atom()]} |
{'disc_copies', [node()]} |
{'disc_only_copies', [node()]} |
{'index', [index_attr()]} |
{'load_order', non_neg_integer()} |
{'majority', boolean()} |
{'ram_copies', [node()]} |
{'record_name', atom()} |
{'snmp', SnmpStruct::term()} |
{'storage_properties', [{Backend::module(), [BackendProp::_]}]} |
{'type', 'set' | 'ordered_set' | 'bag'} |
{'local_content', boolean()} |
{'user_properties', proplists:proplist()} |
{'frag_properties', [frag_prop()]}.
-type t_result(Res) :: {'atomic', Res} | {'aborted', Reason::term()}.
-type result() :: 'ok' | {'error', Reason::term()}.
-type activity() :: 'ets' | 'async_dirty' | 'sync_dirty' | 'transaction' | 'sync_transaction' |
{'transaction', Retries::non_neg_integer()} |
{'sync_transaction', Retries::non_neg_integer()}.
-type table() :: atom().
-type storage_type() :: 'ram_copies' | 'disc_copies' | 'disc_only_copies'.
-type index_attr() :: atom() | non_neg_integer() | {atom()}.
-type write_locks() :: 'write' | 'sticky_write'.
-type read_locks() :: 'read'.
-type lock_kind() :: write_locks() | read_locks().
-type frag_prop() :: {'n_fragments', pos_integer()} |
{'node_pool', [node()]} |
{'n_ram_copies', non_neg_integer()} |
{'n_disc_copies', non_neg_integer()} |
{'n_disc_only_copies', non_neg_integer()} |
{'foreign_key', 'undefined' | {table(), atom()}} |
{'hash_module', atom()} |
{'hash_state', term()}.
-type change_frag_prop() :: 'deactivate' |
{'activate', [frag_prop()]} |
{'add_frag', [node()] | [{node(), non_neg_integer()}]} |
'del_frag' |
{'add_node', node()} |
{'del_node', node()}.
-type select_continuation() :: term().
-type snmp_struct() :: [{atom(), snmp_type() | tuple_of(snmp_type())}].
-type snmp_type() :: 'fix_string' | 'string' | 'integer'.
-type tuple_of(_T) :: tuple().
-type config_key() :: 'extra_db_nodes' | 'dc_dump_limit'.
-type config_value() :: [node()] | number().
-type config_result() :: {'ok', config_value()} | {'error', term()}.
-type debug_level() :: 'none' | 'verbose' | 'debug' | 'trace'.
-define(DEFAULT_ACCESS, ?MODULE).
%% Select
-define(PATTERN_TO_OBJECT_MATCH_SPEC(Pat), [{Pat,[],['$_']}]).
-define(PATTERN_TO_BINDINGS_MATCH_SPEC(Pat), [{Pat,[],['$$']}]).
%% Local function in order to avoid external function call
val(Var) ->
case ?catch_val_and_stack(Var) of
{'EXIT', Stacktrace} -> mnesia_lib:other_val(Var, Stacktrace);
Value -> Value
end.
is_dollar_digits(Var) ->
case atom_to_list(Var) of
[$$ | Digs] ->
is_digits(Digs);
_ ->
false
end.
is_digits([Dig | Tail]) ->
if
$0 =< Dig, Dig =< $9 ->
is_digits(Tail);
true ->
false
end;
is_digits([]) ->
true.
-doc false.
has_var(X) when is_atom(X) ->
if
X == '_' ->
true;
is_atom(X) ->
is_dollar_digits(X);
true ->
false
end;
has_var(X) when is_tuple(X) ->
e_has_var(X, tuple_size(X));
has_var([H|T]) ->
case has_var(H) of
false -> has_var(T);
Other -> Other
end;
has_var(_) -> false.
e_has_var(_, 0) -> false;
e_has_var(X, Pos) ->
case has_var(element(Pos, X))of
false -> e_has_var(X, Pos-1);
Other -> Other
end.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Start and stop
-doc """
Start a local Mnesia system.
Mnesia startup is asynchronous. The function call `mnesia:start()` returns the
atom `ok` and then starts to initialize the different tables. Depending on the
size of the database, this can take some time, and the application programmer
must wait for the tables that the application needs before they can be used.
This is achieved by using the function `mnesia:wait_for_tables/2`.
The startup procedure for a set of Mnesia nodes is a fairly complicated
operation. A Mnesia system consists of a set of nodes, with Mnesia started
locally on all participating nodes. Normally, each node has a directory where
all the Mnesia files are written. This directory is referred to as the Mnesia
directory. Mnesia can also be started on disc-less nodes. For more information
about disc-less nodes, see `mnesia:create_schema/1` and the User's Guide.
The set of nodes that makes up a Mnesia system is kept in a schema. Mnesia nodes
can be added to or removed from the schema. The initial schema is normally
created on disc with the function `mnesia:create_schema/1`. On disc-less nodes,
a tiny default schema is generated each time Mnesia is started. During the
startup procedure, Mnesia exchanges schema information between the nodes to
verify that the table definitions are compatible.
Each schema has a unique cookie, which can be regarded as a unique schema
identifier. The cookie must be the same on all nodes where Mnesia is supposed to
run. For details, see the User's Guide.
The schema file and all other files that Mnesia needs are kept in the Mnesia
directory. The command-line option `-mnesia dir Dir` can be used to specify the
location of this directory to the Mnesia system. If no such command-line option
is found, the name of the directory defaults to `Mnesia.Node`.
`application:start(mnesia)` can also be used.
""".
-spec start() -> result().
start() ->
start([]).
start_() ->
{Time , Res} = timer:tc(application, start, [?APPLICATION, temporary]),
Secs = Time div 1000000,
case Res of
ok ->
verbose("Mnesia started, ~p seconds~n",[ Secs]),
ok;
{error, {already_started, mnesia}} ->
verbose("Mnesia already started, ~p seconds~n",[ Secs]),
ok;
{error, R} ->
verbose("Mnesia failed to start, ~p seconds: ~p~n",[ Secs, R]),
{error, R}
end.
-doc false.
-spec start([{Option::atom(), Value::_}]) -> result().
start(ExtraEnv) when is_list(ExtraEnv) ->
case mnesia_lib:ensure_loaded(?APPLICATION) of
ok ->
patched_start(ExtraEnv);
Error ->
Error
end;
start(ExtraEnv) ->
{error, {badarg, ExtraEnv}}.
patched_start([{Env, Val} | Tail]) when is_atom(Env) ->
case mnesia_monitor:patch_env(Env, Val) of
{error, Reason} ->
{error, Reason};
_NewVal ->
patched_start(Tail)
end;
patched_start([Head | _]) ->
{error, {bad_type, Head}};
patched_start([]) ->
start_().
-doc """
Stop Mnesia locally on the current node.
`application:stop(mnesia)` can also be used.
""".
-spec stop() -> 'stopped' | {'error', term()}.
stop() ->
case application:stop(?APPLICATION) of
ok -> stopped;
{error, {not_started, ?APPLICATION}} -> stopped;
Other -> Other
end.
-doc """
Change a configuration setting.
`Config` is to be an atom of the following configuration parameters:
- **`extra_db_nodes`** - `Value` is a list of nodes that Mnesia is to try to
connect to. `ReturnValue` is those nodes in `Value` that Mnesia is connected
to.
Notice that this function must only be used to connect to newly started RAM
nodes (N.D.R.S.N.) with an empty schema. If, for example, this function is
used after the network has been partitioned, it can lead to inconsistent
tables.
Notice that Mnesia can be connected to other nodes than those returned in
`ReturnValue`.
- **`dc_dump_limit`** - `Value` is a number. See the description in
[Section Configuration Parameters](`m:mnesia#configuration_parameters`).
`ReturnValue` is the new value. Notice that this configuration parameter is
not persistent. It is lost when Mnesia has stopped.
## Examples
```erlang
1> mnesia:change_config(dc_dump_limit, 8).
{ok,8}
```
""".
-spec change_config(Config, Value) -> ReturnValue when
Config :: config_key(),
Value :: config_value(),
ReturnValue :: config_result().
change_config(extra_db_nodes, Ns) when is_list(Ns) ->
mnesia_controller:connect_nodes(Ns);
change_config(dc_dump_limit, N) when is_number(N), N > 0 ->
case mnesia_lib:is_running() of
yes ->
mnesia_lib:set(dc_dump_limit, N),
{ok, N};
_ ->
{error, {not_started, ?APPLICATION}}
end;
change_config(BadKey, _BadVal) ->
{error, {badarg, BadKey}}.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Debugging
-doc """
Change the internal debug level of Mnesia.
For details, see Section Configuration Parameters](`m:mnesia#configuration_parameters`).
## Examples
```erlang
1> mnesia:set_debug_level(verbose).
none
2> mnesia:set_debug_level(none).
verbose
```
""".
-spec set_debug_level(Level :: debug_level()) ->
OldLevel :: debug_level().
set_debug_level(Level) ->
mnesia_subscr:set_debug_level(Level).
-doc false.
lkill() ->
mnesia_sup:kill().
-doc false.
kill() ->
rpc:multicall(mnesia_sup, kill, []).
-doc false.
ms() ->
[
mnesia_sup,
mnesia_kernel_sup,
mnesia_checkpoint_sup,
mnesia_snmp_sup,
mnesia_ext_sup,
mnesia,
mnesia_app,
mnesia_backup,
mnesia_bup,
mnesia_checkpoint,
mnesia_controller,
mnesia_dumper,
mnesia_loader,
mnesia_frag,
mnesia_frag_hash,
mnesia_index,
mnesia_late_loader,
mnesia_lib,
mnesia_log,
mnesia_schema,
mnesia_snmp_hook,
mnesia_subscr,
mnesia_text,
mnesia_tm,
mnesia_recover,
mnesia_locker,
%% Keep these last in the list, so
%% mnesia_sup kills these last
mnesia_monitor,
mnesia_event
].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Activity mgt
-doc """
Terminate the current transaction.
Makes the transaction silently return the tuple `{aborted, Reason}`. Termination
of a Mnesia transaction means that an exception is thrown to an enclosing
`catch`. Thus, the expression `catch mnesia:abort(x)` does not terminate the
transaction.
## Examples
```erlang
1> mnesia:transaction(fun() -> mnesia:abort(cancel_reason) end).
{aborted,cancel_reason}
```
""".
-spec abort(Reason::term()) -> no_return().
abort(Reason = {aborted, _}) ->
exit(Reason);
abort(Reason) ->
exit({aborted, Reason}).
-doc """
Return true if inside a transaction context.
When this function is executed inside a transaction-context, it returns `true`,
otherwise `false`.
## Examples
```erlang
1> mnesia:is_transaction().
false
2> mnesia:transaction(fun mnesia:is_transaction/0).
{atomic,true}
```
""".
-spec is_transaction() -> boolean().
is_transaction() ->
case get(mnesia_activity_state) of
{_, Tid, _Ts} when element(1,Tid) == tid ->
true;
_ ->
false
end.
-doc(#{equiv => transaction(Fun, [], infinity)}).
-spec transaction(Fun) -> t_result(Res) when
Fun :: fun(() -> Res).
transaction(Fun) ->
transaction(get(mnesia_activity_state), Fun, [], infinity, ?DEFAULT_ACCESS, async).
-doc(#{equiv => transaction/3}).
-spec transaction(Fun, Retries) -> t_result(Res) when
Fun :: fun(() -> Res),
Retries :: non_neg_integer() | 'infinity';
(Fun, Args::[Arg::_]) -> t_result(Res) when
Fun :: fun((...) -> Res).
transaction(Fun, Retries) when is_integer(Retries), Retries >= 0 ->
transaction(get(mnesia_activity_state), Fun, [], Retries, ?DEFAULT_ACCESS, async);
transaction(Fun, Retries) when Retries == infinity ->
transaction(get(mnesia_activity_state), Fun, [], Retries, ?DEFAULT_ACCESS, async);
transaction(Fun, Args) ->
transaction(get(mnesia_activity_state), Fun, Args, infinity, ?DEFAULT_ACCESS, async).
-doc """
Execute `Fun` with arguments `Args` as a transaction.
The code that executes inside the transaction can consist of a series of table
manipulation functions. If something goes wrong inside the transaction as a
result of a user error or a certain table not being available, the entire
transaction is terminated and the function [`transaction/1`](`transaction/1`)
returns the tuple `{aborted, Reason}`.
If all is going well, `{atomic, Res}` is returned, where `Res`
is the value of the last expression in `Fun`.
A function that adds a family to the database can be written as follows if there
is a structure `{family, Father, Mother, ChildrenList}`:
```erlang
add_family({family, Father, Mother, ChildrenList}) ->
ChildOids = lists:map(fun oid/1, ChildrenList),
Trans = fun() ->
mnesia:write(Father#person{children = ChildOids}),
mnesia:write(Mother#person{children = ChildOids}),
Write = fun(Child) -> mnesia:write(Child) end,
lists:foreach(Write, ChildrenList)
end,
mnesia:transaction(Trans).
oid(Rec) -> {element(1, Rec), element(2, Rec)}.
```
This code adds a set of people to the database. Running this code within one
transaction ensures that either the whole family is added to the database, or
the whole transaction terminates. For example, if the last child is badly
formatted, or the executing process terminates because of an `'EXIT'` signal
while executing the family code, the transaction terminates. Thus, the situation
where half a family is added can never occur.
It is also useful to update the database within a transaction if several
processes concurrently update the same records. For example, the function
`raise(Name, Amount)`, which adds `Amount` to the salary field of a person, is
to be implemented as follows:
```erlang
raise(Name, Amount) ->
mnesia:transaction(fun() ->
case mnesia:wread({person, Name}) of
[P] ->
Salary = Amount + P#person.salary,
P2 = P#person{salary = Salary},
mnesia:write(P2);
_ ->
mnesia:abort("No such person")
end
end).
```
When this function executes within a transaction, several processes running on
different nodes can concurrently execute the function `raise/2` without
interfering with each other.
Since Mnesia detects deadlocks, a transaction can be restarted any number of
times and therefore the `Fun` shall not have any side effects such as waiting
for specific messages. This function attempts a restart as many times as
specified in `Retries`. `Retries` must be an integer greater than 0 or the atom
`infinity`, default is `infinity`. Mnesia uses `exit` exceptions to signal that
a transaction needs to be restarted, thus a `Fun` must not catch `exit`
exceptions with reason `{aborted, term()}`.
## Examples
```erlang
1> mnesia:create_table(doctest_transaction, [{attributes, [name, age]}, {ram_copies, [node()]}]).
{atomic,ok}
2> mnesia:transaction(
fun(Table, Key) ->
mnesia:write(Table, {Table, Key, 30}, write),
mnesia:read(Table, Key, read)
end,
[doctest_transaction, alice],
infinity).
{atomic,[{doctest_transaction,alice,30}]}
```
""".
-spec transaction(Fun, Args, Retries) -> t_result(Res) when
Fun :: fun((...) -> Res),
Args :: [Arg::_],
Retries :: non_neg_integer() | 'infinity'.
transaction(Fun, Args, Retries) ->
transaction(get(mnesia_activity_state), Fun, Args, Retries, ?DEFAULT_ACCESS, async).
-doc(#{equiv => sync_transaction(Fun, [], infinity)}).
-spec sync_transaction(Fun) -> t_result(Res) when
Fun :: fun(() -> Res).
sync_transaction(Fun) ->
transaction(get(mnesia_activity_state), Fun, [], infinity, ?DEFAULT_ACCESS, sync).
-doc(#{equiv => sync_transaction/3}).
-spec sync_transaction(Fun, Retries) -> t_result(Res) when
Fun :: fun(() -> Res) | fun((...) -> Res),
Retries :: non_neg_integer() | 'infinity';
(Fun, Args :: [Arg::_]) -> t_result(Res) when
Fun :: fun((...) -> Res).
sync_transaction(Fun, Retries) when is_integer(Retries), Retries >= 0 ->
transaction(get(mnesia_activity_state), Fun, [], Retries, ?DEFAULT_ACCESS, sync);
sync_transaction(Fun, Retries) when Retries == infinity ->
transaction(get(mnesia_activity_state), Fun, [], Retries, ?DEFAULT_ACCESS, sync);
sync_transaction(Fun, Args) ->
transaction(get(mnesia_activity_state), Fun, Args, infinity, ?DEFAULT_ACCESS, sync).
-doc """
Synchronously execute a transaction.
Waits until data have been committed and logged to disk (if disk is used) on
every involved node before it returns, otherwise it behaves as
`mnesia:transaction/[1,2,3]`.
This functionality can be used to avoid that one process overloads a database on
another node.
## Examples
```erlang
1> mnesia:create_table(doctest_sync_transaction, [{attributes, [name, age]}, {ram_copies, [node()]}]).
{atomic,ok}
2> [mnesia:dirty_write(doctest_sync_transaction, Person) ||
Person <- [{doctest_sync_transaction, alice, 30},
{doctest_sync_transaction, bob, 25},
{doctest_sync_transaction, carol, 35}]].
[ok,ok,ok]
3> mnesia:sync_transaction(
fun(Table, Key) -> mnesia:read(Table, Key, read) end,
[doctest_sync_transaction, alice],
infinity).
{atomic,[{doctest_sync_transaction,alice,30}]}
```
""".
-spec sync_transaction(Fun, [Arg::_], Retries) -> t_result(Res) when
Fun :: fun((...) -> Res),
Retries :: non_neg_integer() | 'infinity'.
sync_transaction(Fun, Args, Retries) ->
transaction(get(mnesia_activity_state), Fun, Args, Retries, ?DEFAULT_ACCESS, sync).
transaction(State, Fun, Args, Retries, Mod, Kind)
when is_function(Fun), is_list(Args), Retries == infinity, is_atom(Mod) ->
mnesia_tm:transaction(State, Fun, Args, Retries, Mod, Kind);
transaction(State, Fun, Args, Retries, Mod, Kind)
when is_function(Fun), is_list(Args), is_integer(Retries), Retries >= 0, is_atom(Mod) ->
mnesia_tm:transaction(State, Fun, Args, Retries, Mod, Kind);
transaction(_State, Fun, Args, Retries, Mod, _Kind) ->
{aborted, {badarg, Fun, Args, Retries, Mod}}.
non_transaction(State, Fun, Args, ActivityKind, Mod)
when is_function(Fun), is_list(Args), is_atom(Mod) ->
mnesia_tm:non_transaction(State, Fun, Args, ActivityKind, Mod);
non_transaction(_State, Fun, Args, _ActivityKind, _Mod) ->
{aborted, {badarg, Fun, Args}}.
-doc(#{equiv => async_dirty(Fun, [])}).
-spec async_dirty(Fun) -> Res | no_return() when
Fun :: fun(() -> Res).
async_dirty(Fun) ->
async_dirty(Fun, []).
-doc """
Call the `Fun` in a context that is not protected by a transaction.
The Mnesia function calls performed in the `Fun` are mapped to the
corresponding dirty functions. This still involves logging,
replication, and subscriptions, but there is no locking, local
transaction storage, or commit protocols involved. Checkpoint
retainers and indexes are updated, but they are updated dirty. As for
normal `mnesia:dirty_*` operations, the operations are performed
semi-asynchronously. For details, see `mnesia:activity/4` and the
User's Guide.
The Mnesia tables can be manipulated without using transactions. This has some
serious disadvantages, but is considerably faster, as the transaction manager is
not involved and no locks are set. A dirty operation does, however, guarantee a
certain level of consistency, and the dirty operations cannot return garbled
records. All dirty operations provide location transparency to the programmer,
and a program does not have to be aware of the whereabouts of a certain table to
function.
Notice that it is more than ten times more efficient to read records dirty than
within a transaction.
Depending on the application, it can be a good idea to use the dirty functions
for certain operations. Almost all Mnesia functions that can be called within
transactions have a dirty equivalent, which is much more efficient.
However, notice that there is a risk that the database can be left in an
inconsistent state if dirty operations are used to update it. Dirty operations
are only to be used for performance reasons when it is absolutely necessary.
Notice that calling (nesting) `mnesia:[a]sync_dirty` inside a
transaction-context inherits the transaction semantics.
## Examples
```erlang
1> mnesia:create_table(doctest_async_dirty, [{attributes, [name, age]}, {ram_copies, [node()]}]).
{atomic,ok}
2> mnesia:async_dirty(
fun(Table, Key) ->
[mnesia:write(Table, Person, write) ||
Person <- [{Table, Key, 30}, {Table, bob, 25}]],
mnesia:read(Table, Key, read) ++
mnesia:match_object(Table, {Table, '_', 25}, read)
end,
[doctest_async_dirty, alice]).
[{doctest_async_dirty,alice,30},{doctest_async_dirty,bob,25}]
```
""".
-spec async_dirty(Fun, [Arg::_]) -> Res | no_return() when
Fun :: fun((...) -> Res).
async_dirty(Fun, Args) ->
non_transaction(get(mnesia_activity_state), Fun, Args, async_dirty, ?DEFAULT_ACCESS).
-doc(#{equiv => sync_dirty/2}).
-spec sync_dirty(Fun) -> Res | no_return() when
Fun :: fun(() -> Res).
sync_dirty(Fun) ->
sync_dirty(Fun, []).
-doc """
Call the `Fun` in a context that is not protected by a transaction.
The Mnesia function calls performed in the `Fun` are mapped to the corresponding dirty
functions. It is performed in almost the same context as