-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
dets.erl
3954 lines (3579 loc) · 132 KB
/
dets.erl
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%
%%
%% Copyright Ericsson AB 1996-2024. 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%
%%
-module(dets).
-moduledoc """
A disk-based term storage.
This module provides a term storage on file. The stored terms, in this module
called _objects_, are tuples such that one element is defined to be the key. A
Dets _table_ is a collection of objects with the key at the same position stored
on a file.
This module is used by the Mnesia application, and is provided "as is" for users
who are interested in efficient storage of Erlang terms on disk only. Many
applications only need to store some terms in a file. Mnesia adds transactions,
queries, and distribution. The size of Dets files cannot exceed 2 GB. If larger
tables are needed, table fragmentation in Mnesia can be used.
Three types of Dets tables exist:
- `set`. A table of this type has at most one object with a given key. If an
object with a key already present in the table is inserted, the existing
object is overwritten by the new object.
- `bag`. A table of this type has zero or more different objects with a given
key.
- `duplicate_bag`. A table of this type has zero or more possibly matching
objects with a given key.
Dets tables must be opened before they can be updated or read, and when finished
they must be properly closed. If a table is not properly closed, Dets
automatically repairs the table. This can take a substantial time if the table
is large. A Dets table is closed when the process which opened the table
terminates. If many Erlang processes (users) open the same Dets table, they
share the table. The table is properly closed when all users have either
terminated or closed the table. Dets tables are not properly closed if the
Erlang runtime system terminates abnormally.
> #### Note {: .info }
>
> A `^C` command abnormally terminates an Erlang runtime system in a Unix
> environment with a break-handler.
As all operations performed by Dets are disk operations, it is important to
realize that a single look-up operation involves a series of disk seek and read
operations. The Dets functions are therefore much slower than the corresponding
`m:ets` functions, although Dets exports a similar interface.
Dets organizes data as a linear hash list and the hash list grows gracefully as
more data is inserted into the table. Space management on the file is performed
by what is called a buddy system. The current implementation keeps the entire
buddy system in RAM, which implies that if the table gets heavily fragmented,
quite some memory can be used up. The only way to defragment a table is to close
it and then open it again with option `repair` set to `force`.
Notice that type `ordered_set` in Ets is not yet provided by Dets, neither is
the limited support for concurrent updates that makes a sequence of `first` and
`next` calls safe to use on fixed ETS tables. Both these features may be
provided by Dets in a future release of Erlang/OTP. Until then, the Mnesia
application (or some user-implemented method for locking) must be used to
implement safe concurrency. Currently, no Erlang/OTP library has support for
ordered disk-based term storage.
All Dets functions return `{error, Reason}` if an error occurs (`first/1` and
`next/2` are exceptions, they exit the process with the error tuple). If badly
formed arguments are specified, all functions exit the process with a `badarg`
message.
## See Also
`m:ets`, `m:mnesia`, `m:qlc`
""".
%% Disk based linear hashing lookup dictionary.
%% Public.
-export([all/0,
bchunk/2,
close/1,
delete/2,
delete_all_objects/1,
delete_object/2,
first/1,
foldl/3,
foldr/3,
from_ets/2,
info/1,
info/2,
init_table/2,
init_table/3,
insert/2,
insert_new/2,
is_compatible_bchunk_format/2,
is_dets_file/1,
lookup/2,
match/1,
match/2,
match/3,
match_delete/2,
match_object/1,
match_object/2,
match_object/3,
member/2,
next/2,
open_file/1,
open_file/2,
pid2name/1,
repair_continuation/2,
safe_fixtable/2,
select/1,
select/2,
select/3,
select_delete/2,
slot/2,
sync/1,
table/1,
table/2,
to_ets/2,
traverse/2,
update_counter/3]).
%% Server export.
-export([start/0, stop/0]).
%% Internal exports.
-export([istart_link/1, init/2, internal_open/3, add_user/3,
internal_close/1, remove_user/2,
system_continue/3, system_terminate/4, system_code_change/4]).
%% Debug.
-export([file_info/1,
fsck/1,
fsck/2,
get_head_field/2,
view/1,
where/2,
verbose/0,
verbose/1
]).
%% Not documented, or not ready for publication.
-export([lookup_keys/2]).
-export_type([bindings_cont/0, cont/0, object_cont/0, select_cont/0,
tab_name/0]).
-compile({inline, [{einval,2},{badarg,2},{undefined,1},
{badarg_exit,2},{lookup_reply,2},
{pidof,1},{resp,2}]}).
-include_lib("kernel/include/file.hrl").
-include("dets.hrl").
%%% This is the implementation of the mnesia file storage. Each (non
%%% ram-copy) table is maintained in a corresponding .DAT file. The
%%% dat file is organized as a segmented linear hashlist. The head of
%%% the file with the split indicator, size etc is held in ram by the
%%% server at all times.
%%%
%% The method of hashing is the so called linear hashing algorithm
%% with segments.
%%
%% Linear hashing:
%%
%% - n indicates next bucket to split (initially zero);
%% - m is the size of the hash table
%% - initially next = m and n = 0
%%
%% - to insert:
%% - hash = key mod m
%% - if hash < n then hash = key mod 2m
%% - when the number of objects exceeds the initial size
%% of the hash table, each insertion of an object
%% causes bucket n to be split:
%% - add a new bucket to the end of the table
%% - redistribute the contents of bucket n
%% using hash = key mod 2m
%% - increment n
%% - if n = m then m = 2m, n = 0
%% - to search:
%% hash = key mod m
%% if hash < n then hash = key mod 2m
%% do linear scan of the bucket
%%
%%% If a file error occurs on a working dets file, update_mode is set
%%% to the error tuple. When in 'error' mode, the free lists are not
%%% written, and a repair is forced next time the file is opened.
-record(dets_cont, {
what :: 'undefined' | 'bchunk' | 'bindings' | 'object' | 'select',
no_objs :: 'default' | pos_integer(), % requested number of objects
bin :: 'eof' | binary(), % small chunk not consumed,
% or 'eof' at end-of-file
alloc :: binary() % the part of the file not yet scanned
| {From :: non_neg_integer(),
To :: non_neg_integer,
binary()},
tab :: tab_name(),
proc :: 'undefined' | pid(), % the pid of the Dets process
match_program :: 'true'
| 'undefined'
| {'match_spec', ets:compiled_match_spec()}
}).
-record(open_args, {
file :: list(),
type :: type(),
keypos :: keypos(),
repair :: 'force' | boolean(),
min_no_slots :: no_slots(),
max_no_slots :: no_slots(),
ram_file :: boolean(),
delayed_write :: cache_parms(),
auto_save :: auto_save(),
access :: access(),
debug :: boolean()
}).
-define(PATTERN_TO_OBJECT_MATCH_SPEC(Pat), [{Pat,[],['$_']}]).
-define(PATTERN_TO_BINDINGS_MATCH_SPEC(Pat), [{Pat,[],['$$']}]).
-define(PATTERN_TO_TRUE_MATCH_SPEC(Pat), [{Pat,[],[true]}]).
%%-define(DEBUGM(X, Y), io:format(X, Y)).
-define(DEBUGM(X, Y), true).
%%-define(DEBUGF(X,Y), io:format(X, Y)).
-define(DEBUGF(X,Y), void).
%%-define(PROFILE(C), C).
-define(PROFILE(C), void).
-doc "Opaque continuation used by `match/1` and `match/3`.".
-opaque bindings_cont() :: #dets_cont{}.
-doc "Opaque continuation used by `bchunk/2`.".
-opaque cont() :: #dets_cont{}.
-doc """
Match specifications, see section
[Match Specification in Erlang](`e:erts:match_spec.md`) in ERTS User's Guide and
the `m:ms_transform` module.
""".
-type match_spec() :: ets:match_spec().
-type object() :: tuple().
-doc "Opaque continuation used by `match_object/1` and `match_object/3`.".
-opaque object_cont() :: #dets_cont{}.
-doc "For a description of patterns, see `ets:match/2`.".
-type pattern() :: atom() | tuple().
-doc "Opaque continuation used by `select/1` and `select/3`.".
-opaque select_cont() :: #dets_cont{}.
%%% Some further debug code was added in R12B-1 (stdlib-1.15.1):
%%% - there is a new open_file() option 'debug';
%%% - there is a new OS environment variable 'DETS_DEBUG';
%%% - verbose(true) implies that info messages are written onto
%%% the error log whenever an unsafe traversal is started.
%%% The 'debug' mode (set by the open_file() option 'debug' or
%%% by os:putenv("DETS_DEBUG", "true")) implies that the results of
%%% calling pwrite() and pread() are tested to some extent. It also
%%% means a considerable overhead when it comes to RAM usage. The
%%% operation of Dets is also slowed down a bit. Note that in debug
%%% mode terms will be output on the error logger.
%%%----------------------------------------------------------------------
%%% API
%%%----------------------------------------------------------------------
-doc false.
add_user(Pid, Tab, Args) ->
req(Pid, {add_user, Tab, Args}).
-doc "Returns a list of the names of all open tables on this node.".
-spec all() -> [tab_name()].
all() ->
dets_server:all().
-doc """
Returns a list of objects stored in a table. The exact representation of the
returned objects is not public.
The lists of data can be used for initializing a table by specifying value
`bchunk` to option `format` of function `init_table/3`. The Mnesia application
uses this function for copying open tables.
Unless the table is protected using [`safe_fixtable/2`](`safe_fixtable/2`),
calls to [`bchunk/2`](`bchunk/2`) do possibly not work as expected if concurrent
updates are made to the table.
The first time [`bchunk/2`](`bchunk/2`) is called, an initial continuation, the
atom `start`, must be provided.
[`bchunk/2`](`bchunk/2`) returns a tuple `{Continuation2, Data}`, where `Data`
is a list of objects. `Continuation2` is another continuation that is to be
passed on to a subsequent call to [`bchunk/2`](`bchunk/2`). With a series of
calls to [`bchunk/2`](`bchunk/2`), all table objects can be extracted.
[`bchunk/2`](`bchunk/2`) returns `'$end_of_table'` when all objects are
returned, or `{error, Reason}` if an error occurs.
""".
-spec bchunk(Name, Continuation) ->
{Continuation2, Data} | '$end_of_table' | {'error', Reason} when
Name :: tab_name(),
Continuation :: 'start' | cont(),
Continuation2 :: cont(),
Data :: binary() | tuple(),
Reason :: term().
bchunk(Tab, start) ->
badarg(treq(Tab, {bchunk_init, Tab}), [Tab, start]);
bchunk(Tab, #dets_cont{what = bchunk, tab = Tab} = State) ->
badarg(treq(Tab, {bchunk, State}), [Tab, State]);
bchunk(Tab, Term) ->
erlang:error(badarg, [Tab, Term]).
-doc """
Closes a table. Only processes that have opened a table are allowed to close it.
All open tables must be closed before the system is stopped. If an attempt is
made to open a table that is not properly closed, Dets automatically tries to
repair it.
""".
-spec close(Name) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
Reason :: term().
close(Tab) ->
case dets_server:close(Tab) of
badarg -> % Should not happen.
{error, not_owner}; % Backwards compatibility...
Reply ->
Reply
end.
-doc "Deletes all objects with key `Key` from table `Name`.".
-spec delete(Name, Key) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
Key :: term(),
Reason :: term().
delete(Tab, Key) ->
badarg(treq(Tab, {delete_key, [Key]}), [Tab, Key]).
-doc """
Deletes all objects from a table in almost constant time. However, if the table
if fixed, [`delete_all_objects(T)`](`delete_all_objects/1`) is equivalent to
[`match_delete(T, '_')`](`match_delete/2`).
""".
-spec delete_all_objects(Name) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
Reason :: term().
delete_all_objects(Tab) ->
case treq(Tab, delete_all_objects) of
badarg ->
erlang:error(badarg, [Tab]);
fixed ->
match_delete(Tab, '_');
Reply ->
Reply
end.
-doc """
Deletes all instances of a specified object from a table. If a table is of type
`bag` or `duplicate_bag`, this function can be used to delete only some of the
objects with a specified key.
""".
-spec delete_object(Name, Object) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
Object :: object(),
Reason :: term().
delete_object(Tab, O) ->
badarg(treq(Tab, {delete_object, [O]}), [Tab, O]).
%% Backwards compatibility.
-doc false.
fsck(Fname, _Version) ->
fsck(Fname).
%% Given a filename, fsck it. Debug.
-doc false.
fsck(Fname) ->
catch begin
{ok, Fd, FH} = read_file_header(Fname, read, false),
?DEBUGF("FileHeader: ~p~n", [FH]),
case dets_v9:check_file_header(FH, Fd) of
{error, not_closed} ->
fsck(Fd, make_ref(), Fname, FH, default, default);
{ok, _Head} ->
fsck(Fd, make_ref(), Fname, FH, default, default);
Error ->
Error
end
end.
-doc """
Returns the first key stored in table `Name` according to the internal order of
the table, or `'$end_of_table'` if the table is empty.
Unless the table is protected using [`safe_fixtable/2`](`safe_fixtable/2`),
subsequent calls to `next/2` do possibly not work as expected if concurrent
updates are made to the table.
If an error occurs, the process is exited with an error tuple `{error, Reason}`.
The error tuple is not returned, as it cannot be distinguished from a key.
There are two reasons why [`first/1`](`first/1`) and [`next/2`](`next/2`) are
not to be used: they are not efficient, and they prevent the use of key
`'$end_of_table'`, as this atom is used to indicate the end of the table. If
possible, use functions [`match`](`match/1`),
[`match_object`](`match_object/1`), and [`select`](`select/1`) for traversing
tables.
""".
-spec first(Name) -> Key | '$end_of_table' when
Name :: tab_name(),
Key :: term().
first(Tab) ->
badarg_exit(treq(Tab, first), [Tab]).
-doc """
Calls `Function` on successive elements of table `Name` together with an extra
argument `AccIn`. The table elements are traversed in unspecified order.
`Function` must return a new accumulator that is passed to the next call. `Acc0`
is returned if the table is empty.
""".
-spec foldr(Function, Acc0, Name) -> Acc | {'error', Reason} when
Name :: tab_name(),
Function :: fun((Object :: object(), AccIn) -> AccOut),
Acc0 :: term(),
Acc :: term(),
AccIn :: term(),
AccOut :: term(),
Reason :: term().
foldr(Fun, Acc, Tab) ->
foldl(Fun, Acc, Tab).
-doc(#{equiv => foldr/3}).
-spec foldl(Function, Acc0, Name) -> Acc | {'error', Reason} when
Name :: tab_name(),
Function :: fun((Object :: object(), AccIn) -> AccOut),
Acc0 :: term(),
Acc :: term(),
AccIn :: term(),
AccOut :: term(),
Reason :: term().
foldl(Fun, Acc, Tab) ->
Ref = make_ref(),
badarg(do_traverse(Fun, Acc, Tab, Ref), [Fun, Acc, Tab]).
-doc """
Deletes all objects of table `Name` and then inserts all the objects of the ETS
table `EtsTab`. The objects are inserted in unspecified order. As
`ets:safe_fixtable/2` is called, the ETS table must be public or owned by the
calling process.
""".
-spec from_ets(Name, EtsTab) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
EtsTab :: ets:table(),
Reason :: term().
from_ets(DTab, ETab) ->
ets:safe_fixtable(ETab, true),
Spec = ?PATTERN_TO_OBJECT_MATCH_SPEC('_'),
LC = ets:select(ETab, Spec, 100),
InitFun = from_ets_fun(LC, ETab),
Reply = treq(DTab, {initialize, InitFun, term, default}),
ets:safe_fixtable(ETab, false),
case Reply of
{thrown, Thrown} -> throw(Thrown);
Else -> badarg(Else, [DTab, ETab])
end.
from_ets_fun(LC, ETab) ->
fun(close) ->
ok;
(read) when LC =:= '$end_of_table' ->
end_of_input;
(read) ->
{L, C} = LC,
{L, from_ets_fun(ets:select(C), ETab)}
end.
-doc """
Returns information about table `Name` as a list of tuples:
- `{file_size, integer() >= 0}}` \- The file size, in bytes.
- `{filename, ``t:file:name/0``}` \- The name of the file where objects are
stored.
- `{keypos, ``t:keypos/0``}` \- The key position.
- `{size, integer() >= 0}` \- The number of objects stored in the table.
- `{type, ``t:type/0``}` \- The table type.
""".
-spec info(Name) -> InfoList | 'undefined' when
Name :: tab_name(),
InfoList :: [InfoTuple],
InfoTuple :: {'file_size', non_neg_integer()}
| {'filename', file:name()}
| {'keypos', keypos()}
| {'size', non_neg_integer()}
| {'type', type()}.
info(Tab) ->
case catch dets_server:get_pid(Tab) of
{'EXIT', _Reason} ->
undefined;
Pid ->
undefined(req(Pid, info))
end.
-doc """
Returns the information associated with `Item` for table `Name`. In addition to
the `{Item, Value}` pairs defined for `info/1`, the following items are allowed:
- `{access, ``t:access/0``}` \- The access mode.
- `{auto_save, ``t:auto_save/0``}` \- The autosave interval.
- `{bchunk_format, binary()}` \- An opaque binary describing the format of the
objects returned by [`bchunk/2`](`bchunk/2`). The binary can be used as
argument to
[`is_compatible_bchunk_format/2`](`is_compatible_bchunk_format/2`).
- `{hash, Hash}` \- Describes which BIF is used to calculate the hash values of
the objects stored in the Dets table. Possible values of `Hash`:
- `phash` \- Implies that the `erlang:phash/2` BIF is used.
- `phash2` \- Implies that the `erlang:phash2/1` BIF is used.
- `{memory, integer() >= 0}` \- The file size, in bytes. The same value is
associated with item `file_size`.
- `{no_keys, integer >= 0()}` \- The number of different keys stored in the
table.
- `{no_objects, integer >= 0()}` \- The number of objects stored in the table.
- `{no_slots, {Min, Used, Max}}` \- The number of slots of the table. `Min` is
the minimum number of slots, `Used` is the number of currently used slots, and
`Max` is the maximum number of slots.
- `{owner, pid()}` \- The pid of the process that handles requests to the Dets
table.
- `{ram_file, boolean()}` \- Whether the table is kept in RAM.
- `{safe_fixed_monotonic_time, SafeFixed}` \- If the table is fixed, `SafeFixed`
is a tuple `{FixedAtTime, [{Pid,RefCount}]}`. `FixedAtTime` is the time when
the table was first fixed, and `Pid` is the pid of the process that fixes the
table `RefCount` times. There can be any number of processes in the list. If
the table is not fixed, `SafeFixed` is the atom `false`.
`FixedAtTime` corresponds to the result returned by `erlang:monotonic_time/0`
at the time of fixation. The use of `safe_fixed_monotonic_time` is
[time warp safe](`e:erts:time_correction.md#time-warp-safe-code`).
- `{safe_fixed, SafeFixed}` \- The same as
`{safe_fixed_monotonic_time, SafeFixed}` except the format and value of
`FixedAtTime`.
`FixedAtTime` corresponds to the result returned by `erlang:timestamp/0` at
the time of fixation. Notice that when the system uses single or multi
[time warp modes](`e:erts:time_correction.md#time-warp-modes`), this can
produce strange results. This is because the use of `safe_fixed` is not
[time warp safe](`e:erts:time_correction.md#time-warp-safe-code`). Time warp
safe code must use `safe_fixed_monotonic_time` instead.
""".
-spec info(Name, Item) -> Value | 'undefined' when
Name :: tab_name(),
Item :: 'access' | 'auto_save' | 'bchunk_format'
| 'hash' | 'file_size' | 'filename' | 'keypos' | 'memory'
| 'no_keys' | 'no_objects' | 'no_slots' | 'owner' | 'ram_file'
| 'safe_fixed' | 'safe_fixed_monotonic_time' | 'size' | 'type',
Value :: term().
info(Tab, owner) ->
case catch dets_server:get_pid(Tab) of
Pid when is_pid(Pid) ->
Pid;
_ ->
undefined
end;
info(Tab, users) -> % undocumented
case dets_server:users(Tab) of
[] ->
undefined;
Users ->
Users
end;
info(Tab, Tag) ->
case catch dets_server:get_pid(Tab) of
{'EXIT', _Reason} ->
undefined;
Pid ->
undefined(req(Pid, {info, Tag}))
end.
-doc(#{equiv => init_table(Name, InitFun, [])}).
-spec init_table(Name, InitFun) -> ok | {'error', Reason} when
Name :: tab_name(),
InitFun :: fun((Arg) -> Res),
Arg :: read | close,
Res :: end_of_input | {[object()], InitFun} | {Data, InitFun} | term(),
Reason :: term(),
Data :: binary() | tuple().
init_table(Tab, InitFun) ->
init_table(Tab, InitFun, []).
-doc """
Replaces the existing objects of table `Name` with objects created by calling
the input function `InitFun`.
The reason for using this function rather than calling [`insert/2`](`insert/2`)
is that of efficiency. Notice that the input functions are called by the process
that handles requests to the Dets table, not by the calling process.
When called with argument `read`, function `InitFun` is assumed to return
`end_of_input` when there is no more input, or `{Objects, Fun}`, where `Objects`
is a list of objects and `Fun` is a new input function. Any other value `Value`
is returned as an error `{error, {init_fun, Value}}`. Each input function is
called exactly once, and if an error occurs, the last function is called with
argument `close`, the reply of which is ignored.
If the table type is `set` and more than one object exists with a given key, one
of the objects is chosen. This is not necessarily the last object with the given
key in the sequence of objects returned by the input functions. Avoid duplicate
keys, otherwise the file becomes unnecessarily fragmented. This holds also for
duplicated objects stored in tables of type `bag`.
It is important that the table has a sufficient number of slots for the objects.
If not, the hash list starts to grow when [`init_table/2`](`init_table/2`)
returns, which significantly slows down access to the table for a period of
time. The minimum number of slots is set by the [`open_file/2`](`open_file/2`)
option `min_no_slots` and returned by the [`info/2`](`info/2`) item `no_slots`.
See also option `min_no_slots` below.
Argument `Options` is a list of `{Key, Val}` tuples, where the following values
are allowed:
- `{min_no_slots, no_slots()}` \- Specifies the estimated number of different
keys to be stored in the table. The [`open_file/2`](`open_file/2`) option with
the same name is ignored, unless the table is created, in which case
performance can be enhanced by supplying an estimate when initializing the
table.
- `{format, Format}` \- Specifies the format of the objects returned by function
`InitFun`. If `Format` is `term` (the default), `InitFun` is assumed to return
a list of tuples. If `Format` is `bchunk`, `InitFun` is assumed to return
`Data` as returned by `bchunk/2`. This option overrides option `min_no_slots`.
""".
-spec init_table(Name, InitFun, Options) -> ok | {'error', Reason} when
Name :: tab_name(),
InitFun :: fun((Arg) -> Res),
Arg :: read | close,
Res :: end_of_input | {[object()], InitFun} | {Data, InitFun} | term(),
Options :: Option | [Option],
Option :: {min_no_slots,no_slots()} | {format,term | bchunk},
Reason :: term(),
Data :: binary() | tuple().
init_table(Tab, InitFun, Options) when is_function(InitFun) ->
case options(Options, [format, min_no_slots]) of
{badarg,_} ->
erlang:error(badarg, [Tab, InitFun, Options]);
[Format, MinNoSlots] ->
case treq(Tab, {initialize, InitFun, Format, MinNoSlots}) of
{thrown, Thrown} -> throw(Thrown);
Else -> badarg(Else, [Tab, InitFun, Options])
end
end;
init_table(Tab, InitFun, Options) ->
erlang:error(badarg, [Tab, InitFun, Options]).
-doc """
Inserts one or more objects into the table `Name`. If there already exists an
object with a key matching the key of some of the given objects and the table
type is `set`, the old object will be replaced.
""".
-spec insert(Name, Objects) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
Objects :: object() | [object()],
Reason :: term().
insert(Tab, Objs) when is_list(Objs) ->
badarg(treq(Tab, {insert, Objs}), [Tab, Objs]);
insert(Tab, Obj) ->
badarg(treq(Tab, {insert, [Obj]}), [Tab, Obj]).
-doc """
Inserts one or more objects into table `Name`. If there already exists some
object with a key matching the key of any of the specified objects, the table is
not updated and `false` is returned. Otherwise the objects are inserted and
`true` returned.
""".
-spec insert_new(Name, Objects) -> boolean() | {'error', Reason} when
Name :: tab_name(),
Objects :: object() | [object()],
Reason :: term().
insert_new(Tab, Objs) when is_list(Objs) ->
badarg(treq(Tab, {insert_new, Objs}), [Tab, Objs]);
insert_new(Tab, Obj) ->
badarg(treq(Tab, {insert_new, [Obj]}), [Tab, Obj]).
-doc false.
internal_close(Pid) ->
req(Pid, close).
-doc false.
internal_open(Pid, Ref, Args) ->
req(Pid, {internal_open, Ref, Args}).
-doc """
Returns `true` if it would be possible to initialize table `Name`, using
`init_table/3` with option `{format, bchunk}`, with objects read with `bchunk/2`
from some table `T`, such that calling [`info(T, bchunk_format)`](`info/2`)
returns `BchunkFormat`.
""".
-spec is_compatible_bchunk_format(Name, BchunkFormat) -> boolean() when
Name :: tab_name(),
BchunkFormat :: binary().
is_compatible_bchunk_format(Tab, Term) ->
badarg(treq(Tab, {is_compatible_bchunk_format, Term}), [Tab, Term]).
-doc "Returns `true` if file `Filename` is a Dets table, otherwise `false`.".
-spec is_dets_file(Filename) -> boolean() | {'error', Reason} when
Filename :: file:name(),
Reason :: term().
is_dets_file(FileName) ->
case catch read_file_header(FileName, read, false) of
{ok, Fd, FH} ->
_ = file:close(Fd),
FH#fileheader.cookie =:= ?MAGIC;
{error, {tooshort, _}} ->
false;
{error, {not_a_dets_file, _}} ->
false;
Other ->
Other
end.
-doc """
Returns a list of all objects with key `Key` stored in table `Name`, for
example:
```erlang
2> dets:open_file(abc, [{type, bag}]).
{ok,abc}
3> dets:insert(abc, {1,2,3}).
ok
4> dets:insert(abc, {1,3,4}).
ok
5> dets:lookup(abc, 1).
[{1,2,3},{1,3,4}]
```
If the table type is `set`, the function returns either the empty list or a list
with one object, as there cannot be more than one object with a given key. If
the table type is `bag` or `duplicate_bag`, the function returns a list of
arbitrary length.
Notice that the order of objects returned is unspecified. In particular, the
order in which objects were inserted is not reflected.
""".
-spec lookup(Name, Key) -> Objects | {'error', Reason} when
Name :: tab_name(),
Key :: term(),
Objects :: [object()],
Reason :: term().
lookup(Tab, Key) ->
badarg(treq(Tab, {lookup_keys, [Key]}), [Tab, Key]).
%% Not public.
-doc false.
lookup_keys(Tab, Keys) ->
case catch lists:usort(Keys) of
UKeys when is_list(UKeys), UKeys =/= [] ->
badarg(treq(Tab, {lookup_keys, UKeys}), [Tab, Keys]);
_Else ->
erlang:error(badarg, [Tab, Keys])
end.
-doc """
Returns for each object of table `Name` that matches `Pattern` a list of
bindings in some unspecified order. For a description of patterns, see
`ets:match/2`. If the keypos'th element of `Pattern` is unbound, all table
objects are matched. If the keypos'th element is bound, only the objects with
the correct key are matched.
""".
-spec match(Name, Pattern) -> [Match] | {'error', Reason} when
Name :: tab_name(),
Pattern :: pattern(),
Match :: [term()],
Reason :: term().
match(Tab, Pat) ->
badarg(safe_match(Tab, Pat, bindings), [Tab, Pat]).
-doc """
Matches some or all objects of table `Name` and returns a non-empty list of the
bindings that match `Pattern` in some unspecified order. For a description of
patterns, see `ets:match/2`.
A tuple of the bindings and a continuation is returned, unless the table is
empty, in which case `'$end_of_table'` is returned. The continuation is to be
used when matching further objects by calling `match/1`.
If the keypos'th element of `Pattern` is bound, all table objects are matched.
If the keypos'th element is unbound, all table objects are matched, `N` objects
at a time, until at least one object matches or the end of the table is reached.
The default, indicated by giving `N` the value `default`, is to let the number
of objects vary depending on the sizes of the objects. All objects with the same
key are always matched at the same time, which implies that more than N objects
can sometimes be matched.
The table is always to be protected using `safe_fixtable/2` before calling
[`match/3`](`match/3`), otherwise errors can occur when calling
[`match/1`](`match/1`).
""".
-spec match(Name, Pattern, N) ->
{[Match], Continuation} | '$end_of_table' | {'error', Reason} when
Name :: tab_name(),
Pattern :: pattern(),
N :: 'default' | non_neg_integer(),
Continuation :: bindings_cont(),
Match :: [term()],
Reason :: term().
match(Tab, Pat, N) ->
badarg(init_chunk_match(Tab, Pat, bindings, N, no_safe), [Tab, Pat, N]).
-doc """
Matches some objects stored in a table and returns a non-empty list of the
bindings matching a specified pattern in some unspecified order. The table, the
pattern, and the number of objects that are matched are all defined by
`Continuation`, which has been returned by a previous call to
[`match/1`](`match/1`) or [`match/3`](`match/3`).
When all table objects are matched, `'$end_of_table'` is returned.
""".
-spec match(Continuation) ->
{[Match], Continuation2} | '$end_of_table' | {'error', Reason} when
Continuation :: bindings_cont(),
Continuation2 :: bindings_cont(),
Match :: [term()],
Reason :: term().
match(State) when State#dets_cont.what =:= bindings ->
badarg(chunk_match(State, no_safe), [State]);
match(Term) ->
erlang:error(badarg, [Term]).
-doc """
Deletes all objects that match `Pattern` from table `Name`. For a description of
patterns, see `ets:match/2`.
If the keypos'th element of `Pattern` is bound, only the objects with the
correct key are matched.
""".
-spec match_delete(Name, Pattern) -> 'ok' | {'error', Reason} when
Name :: tab_name(),
Pattern :: pattern(),
Reason :: term().
match_delete(Tab, Pat) ->
badarg(match_delete(Tab, Pat, delete), [Tab, Pat]).
match_delete(Tab, Pat, What) ->
case compile_match_spec(What, Pat) of
{Spec, MP} ->
case catch dets_server:get_pid(Tab) of
{'EXIT', _Reason} ->
badarg;
Proc ->
R = req(Proc, {match_delete_init, MP, Spec}),
do_match_delete(Proc, R, What, 0)
end;
badarg ->
badarg
end.
do_match_delete(_Proc, {done, N1}, select, N) ->
N + N1;
do_match_delete(_Proc, {done, _N1}, _What, _N) ->
ok;
do_match_delete(Proc, {cont, State, N1}, What, N) ->
do_match_delete(Proc, req(Proc, {match_delete, State}), What, N+N1);
do_match_delete(_Proc, Error, _What, _N) ->
Error.
-doc """
Returns a list of all objects of table `Name` that match `Pattern` in some
unspecified order. For a description of patterns, see `ets:match/2`.
If the keypos'th element of `Pattern` is unbound, all table objects are matched.
If the keypos'th element of `Pattern` is bound, only the objects with the
correct key are matched.
Using the `match_object` functions for traversing all table objects is more
efficient than calling [`first/1`](`first/1`) and [`next/2`](`next/2`) or
[`slot/2`](`slot/2`).
""".
-spec match_object(Name, Pattern) -> Objects | {'error', Reason} when
Name :: tab_name(),
Pattern :: pattern(),
Objects :: [object()],
Reason :: term().
match_object(Tab, Pat) ->
badarg(safe_match(Tab, Pat, object), [Tab, Pat]).
-doc """
Matches some or all objects stored in table `Name` and returns a non-empty list
of the objects that match `Pattern` in some unspecified order. For a description
of patterns, see `ets:match/2`.
A list of objects and a continuation is returned, unless the table is empty, in
which case `'$end_of_table'` is returned. The continuation is to be used when
matching further objects by calling `match_object/1`.
If the keypos'th element of `Pattern` is bound, all table objects are matched.
If the keypos'th element is unbound, all table objects are matched, `N` objects
at a time, until at least one object matches or the end of the table is reached.
The default, indicated by giving `N` the value `default`, is to let the number
of objects vary depending on the sizes of the objects. All matching objects with
the same key are always returned in the same reply, which implies that more than
N objects can sometimes be returned.
The table is always to be protected using `safe_fixtable/2` before calling
[`match_object/3`](`match_object/3`), otherwise errors can occur when calling
[`match_object/1`](`match_object/1`).
""".
-spec match_object(Name, Pattern, N) ->
{Objects, Continuation} | '$end_of_table' | {'error', Reason} when
Name :: tab_name(),
Pattern :: pattern(),
N :: 'default' | non_neg_integer(),
Continuation :: object_cont(),
Objects :: [object()],
Reason :: term().
match_object(Tab, Pat, N) ->
badarg(init_chunk_match(Tab, Pat, object, N, no_safe), [Tab, Pat, N]).
-doc """
Returns a non-empty list of some objects stored in a table that match a given
pattern in some unspecified order. The table, the pattern, and the number of
objects that are matched are all defined by `Continuation`, which has been
returned by a previous call to [`match_object/1`](`match_object/1`) or
[`match_object/3`](`match_object/3`).
When all table objects are matched, `'$end_of_table'` is returned.
""".
-spec match_object(Continuation) ->
{Objects, Continuation2} | '$end_of_table' | {'error', Reason} when
Continuation :: object_cont(),
Continuation2 :: object_cont(),
Objects :: [object()],
Reason :: term().
match_object(State) when State#dets_cont.what =:= object ->
badarg(chunk_match(State, no_safe), [State]);
match_object(Term) ->
erlang:error(badarg, [Term]).
-doc """
Works like `lookup/2`, but does not return the objects. Returns `true` if one or
more table elements has key `Key`, otherwise `false`.
""".
-spec member(Name, Key) -> boolean() | {'error', Reason} when
Name :: tab_name(),
Key :: term(),
Reason :: term().
member(Tab, Key) ->
badarg(treq(Tab, {member, Key}), [Tab, Key]).
-doc """
Returns either the key following `Key1` in table `Name` according to the
internal order of the table, or `'$end_of_table'` if there is no next key.
If an error occurs, the process is exited with an error tuple `{error, Reason}`.
To find the first key in the table, use `first/1`.
""".
-spec next(Name, Key1) -> Key2 | '$end_of_table' when
Name :: tab_name(),