1ets(3) Erlang Module Definition ets(3)
2
3
4
6 ets - Built-in term storage.
7
9 This module is an interface to the Erlang built-in term storage BIFs.
10 These provide the ability to store very large quantities of data in an
11 Erlang runtime system, and to have constant access time to the data.
12 (In the case of ordered_set, see below, access time is proportional to
13 the logarithm of the number of stored objects.)
14
15 Data is organized as a set of dynamic tables, which can store tuples.
16 Each table is created by a process. When the process terminates, the
17 table is automatically destroyed. Every table has access rights set at
18 creation.
19
20 Tables are divided into four different types, set, ordered_set, bag,
21 and duplicate_bag. A set or ordered_set table can only have one object
22 associated with each key. A bag or duplicate_bag table can have many
23 objects associated with each key.
24
25 Note:
26 The number of tables stored at one Erlang node used to be limited. This
27 is no longer the case (except by memory usage). The previous default
28 limit was about 1400 tables and could be increased by setting the envi‐
29 ronment variable ERL_MAX_ETS_TABLES or the command line option +e
30 before starting the Erlang runtime system. This hard limit has been
31 removed, but it is currently useful to set the ERL_MAX_ETS_TABLES any‐
32 way. It should be set to an approximate of the maximum amount of tables
33 used. This since an internal table for named tables is sized using this
34 value. If large amounts of named tables are used and ERL_MAX_ETS_TABLES
35 hasn't been increased, the performance of named table lookup will
36 degrade.
37
38
39 Notice that there is no automatic garbage collection for tables. Even
40 if there are no references to a table from any process, it is not auto‐
41 matically destroyed unless the owner process terminates. To destroy a
42 table explicitly, use function delete/1. The default owner is the
43 process that created the table. To transfer table ownership at process
44 termination, use option heir or call give_away/3.
45
46 Some implementation details:
47
48 * In the current implementation, every object insert and look-up
49 operation results in a copy of the object.
50
51 * '$end_of_table' is not to be used as a key, as this atom is used to
52 mark the end of the table when using functions first/1 and next/2.
53
54 Notice the subtle difference between matching and comparing equal,
55 which is demonstrated by table types set and ordered_set:
56
57 * Two Erlang terms match if they are of the same type and have the
58 same value, so that 1 matches 1, but not 1.0 (as 1.0 is a float()
59 and not an integer()).
60
61 * Two Erlang terms compare equal if they either are of the same type
62 and value, or if both are numeric types and extend to the same
63 value, so that 1 compares equal to both 1 and 1.0.
64
65 * The ordered_set works on the Erlang term order and no defined order
66 exists between an integer() and a float() that extends to the same
67 value. Hence the key 1 and the key 1.0 are regarded as equal in an
68 ordered_set table.
69
71 The functions in this module exits with reason badarg if any argument
72 has the wrong format, if the table identifier is invalid, or if the
73 operation is denied because of table access rights (protected or pri‐
74 vate).
75
77 This module provides some limited support for concurrent access. All
78 updates to single objects are guaranteed to be both atomic and iso‐
79 lated. This means that an updating operation to a single object either
80 succeeds or fails completely without any effect (atomicity) and that no
81 intermediate results of the update can be seen by other processes (iso‐
82 lation). Some functions that update many objects state that they even
83 guarantee atomicity and isolation for the entire operation. In database
84 terms the isolation level can be seen as "serializable", as if all iso‐
85 lated operations are carried out serially, one after the other in a
86 strict order.
87
89 There are different ways to traverse through the objects of a table.
90
91 * Single-step traversal one key at at time, using first/1, next/2,
92 last/1 and prev/2.
93
94 * Search with simple match patterns, using match/1/2/3,
95 match_delete/2 and match_object/1/2/3.
96
97 * Search with more powerful match specifications, using select/1/2/3,
98 select_count/2, select_delete/2, select_replace/2 and
99 select_reverse/1/2/3.
100
101 * Table conversions, using tab2file/2/3 and tab2list/1.
102
103 None of these ways of table traversal will guarantee a consistent table
104 snapshot if the table is also updated during the traversal. Moreover,
105 traversals not done in a safe way, on tables where keys are inserted or
106 deleted during the traversal, may yield the following undesired
107 effects:
108
109 * Any key may be missed.
110
111 * Any key may be found more than once.
112
113 * The traversal may fail with badarg exception if keys are deleted.
114
115 A table traversal is safe if either
116
117 * the table is of type ordered_set.
118
119 * the entire table traversal is done within one ETS function call.
120
121 * function safe_fixtable/2 is used to keep the table fixated during
122 the entire traversal.
123
124 Note:
125 Even though the access of a single object is always guaranteed to be
126 atomic and isolated, each traversal through a table to find the next
127 key is not done with such guarantees. This is often not a problem, but
128 may cause rare subtle "unexpected" effects if a concurrent process
129 inserts objects during a traversal. For example, consider one process
130 doing
131
132 ets:new(t, [ordered_set, named_table]),
133 ets:insert(t, {1}),
134 ets:insert(t, {2}),
135 ets:insert(t, {3}),
136
137
138 A concurrent call to ets:first(t), done by another process, may then in
139 rare cases return 2 even though 2 has never existed in the table
140 ordered as the first key. In the same way, a concurrent call to
141 ets:next(t, 1) may return 3 even though 3 never existed in the table
142 ordered directly after 1.
143
144 Effects like this are improbable but possible. The probability will
145 further be reduced (if not vanish) if table option write_concurrency is
146 not enabled. This can also only be a potential concern for ordered_set
147 where the traversal order is defined.
148
149
150 Traversals using match and select functions may not need to scan the
151 entire table depending on how the key is specified. A match pattern
152 with a fully bound key (without any match variables) will optimize the
153 operation to a single key lookup without any table traversal at all.
154 For ordered_set a partially bound key will limit the traversal to only
155 scan a subset of the table based on term order. A partially bound key
156 is either a list or a tuple with a prefix that is fully bound. Example:
157
158 1> T = ets:new(t,[ordered_set]), ets:insert(T, {"555-1234", "John Smith"}).
159 true
160 2> %% Efficient search of all with area code 555
161 2> ets:match(T,{[$5,$5,$5,$- |'$1'],'$2'}).
162 [["1234","John Smith"]]
163
164
166 Some of the functions use a match specification, match_spec. For a
167 brief explanation, see select/2. For a detailed description, see sec‐
168 tion Match Specifications in Erlang in ERTS User's Guide.
169
171 access() = public | protected | private
172
173 continuation()
174
175 Opaque continuation used by select/1,3, select_reverse/1,3,
176 match/1,3, and match_object/1,3.
177
178 match_spec() = [{match_pattern(), [term()], [term()]}]
179
180 A match specification, see above.
181
182 comp_match_spec()
183
184 A compiled match specification.
185
186 match_pattern() = atom() | tuple()
187
188 tab() = atom() | tid()
189
190 tid()
191
192 A table identifier, as returned by new/2.
193
194 type() = set | ordered_set | bag | duplicate_bag
195
197 all() -> [Tab]
198
199 Types:
200
201 Tab = tab()
202
203 Returns a list of all tables at the node. Named tables are spec‐
204 ified by their names, unnamed tables are specified by their ta‐
205 ble identifiers.
206
207 There is no guarantee of consistency in the returned list.
208 Tables created or deleted by other processes "during" the
209 ets:all() call either are or are not included in the list. Only
210 tables created/deleted before ets:all() is called are guaranteed
211 to be included/excluded.
212
213 delete(Tab) -> true
214
215 Types:
216
217 Tab = tab()
218
219 Deletes the entire table Tab.
220
221 delete(Tab, Key) -> true
222
223 Types:
224
225 Tab = tab()
226 Key = term()
227
228 Deletes all objects with key Key from table Tab.
229
230 delete_all_objects(Tab) -> true
231
232 Types:
233
234 Tab = tab()
235
236 Delete all objects in the ETS table Tab. The operation is guar‐
237 anteed to be atomic and isolated.
238
239 delete_object(Tab, Object) -> true
240
241 Types:
242
243 Tab = tab()
244 Object = tuple()
245
246 Delete the exact object Object from the ETS table, leaving
247 objects with the same key but other differences (useful for type
248 bag). In a duplicate_bag table, all instances of the object are
249 deleted.
250
251 file2tab(Filename) -> {ok, Tab} | {error, Reason}
252
253 Types:
254
255 Filename = file:name()
256 Tab = tab()
257 Reason = term()
258
259 Reads a file produced by tab2file/2 or tab2file/3 and creates
260 the corresponding table Tab.
261
262 Equivalent to file2tab(Filename, []).
263
264 file2tab(Filename, Options) -> {ok, Tab} | {error, Reason}
265
266 Types:
267
268 Filename = file:name()
269 Tab = tab()
270 Options = [Option]
271 Option = {verify, boolean()}
272 Reason = term()
273
274 Reads a file produced by tab2file/2 or tab2file/3 and creates
275 the corresponding table Tab.
276
277 The only supported option is {verify,boolean()}. If verification
278 is turned on (by specifying {verify,true}), the function uses
279 whatever information is present in the file to assert that the
280 information is not damaged. How this is done depends on which
281 extended_info was written using tab2file/3.
282
283 If no extended_info is present in the file and {verify,true} is
284 specified, the number of objects written is compared to the size
285 of the original table when the dump was started. This can make
286 verification fail if the table was public and objects were added
287 or removed while the table was dumped to file. To avoid this
288 problem, either do not verify files dumped while updated simul‐
289 taneously or use option {extended_info, [object_count]} to
290 tab2file/3, which extends the information in the file with the
291 number of objects written.
292
293 If verification is turned on and the file was written with
294 option {extended_info, [md5sum]}, reading the file is slower and
295 consumes radically more CPU time than otherwise.
296
297 {verify,false} is the default.
298
299 first(Tab) -> Key | '$end_of_table'
300
301 Types:
302
303 Tab = tab()
304 Key = term()
305
306 Returns the first key Key in table Tab. For an ordered_set ta‐
307 ble, the first key in Erlang term order is returned. For other
308 table types, the first key according to the internal order of
309 the table is returned. If the table is empty, '$end_of_table' is
310 returned.
311
312 To find subsequent keys in the table, use next/2.
313
314 foldl(Function, Acc0, Tab) -> Acc1
315
316 Types:
317
318 Function = fun((Element :: term(), AccIn) -> AccOut)
319 Tab = tab()
320 Acc0 = Acc1 = AccIn = AccOut = term()
321
322 Acc0 is returned if the table is empty. This function is similar
323 to lists:foldl/3. The table elements are traversed in an unspec‐
324 ified order, except for ordered_set tables, where they are tra‐
325 versed first to last.
326
327 If Function inserts objects into the table, or another process
328 inserts objects into the table, those objects can (depending on
329 key ordering) be included in the traversal.
330
331 foldr(Function, Acc0, Tab) -> Acc1
332
333 Types:
334
335 Function = fun((Element :: term(), AccIn) -> AccOut)
336 Tab = tab()
337 Acc0 = Acc1 = AccIn = AccOut = term()
338
339 Acc0 is returned if the table is empty. This function is similar
340 to lists:foldr/3. The table elements are traversed in an unspec‐
341 ified order, except for ordered_set tables, where they are tra‐
342 versed last to first.
343
344 If Function inserts objects into the table, or another process
345 inserts objects into the table, those objects can (depending on
346 key ordering) be included in the traversal.
347
348 from_dets(Tab, DetsTab) -> true
349
350 Types:
351
352 Tab = tab()
353 DetsTab = dets:tab_name()
354
355 Fills an already created ETS table with the objects in the
356 already opened Dets table DetsTab. Existing objects in the ETS
357 table are kept unless overwritten.
358
359 If any of the tables does not exist or the Dets table is not
360 open, a badarg exception is raised.
361
362 fun2ms(LiteralFun) -> MatchSpec
363
364 Types:
365
366 LiteralFun = function()
367 MatchSpec = match_spec()
368
369 Pseudo function that by a parse_transform translates LiteralFun
370 typed as parameter in the function call to a match specifica‐
371 tion. With "literal" is meant that the fun must textually be
372 written as the parameter of the function, it cannot be held in a
373 variable that in turn is passed to the function.
374
375 The parse transform is provided in the ms_transform module and
376 the source must include file ms_transform.hrl in STDLIB for this
377 pseudo function to work. Failing to include the hrl file in the
378 source results in a runtime error, not a compile time error. The
379 include file is easiest included by adding line
380 -include_lib("stdlib/include/ms_transform.hrl"). to the source
381 file.
382
383 The fun is very restricted, it can take only a single parameter
384 (the object to match): a sole variable or a tuple. It must use
385 the is_ guard tests. Language constructs that have no represen‐
386 tation in a match specification (if, case, receive, and so on)
387 are not allowed.
388
389 The return value is the resulting match specification.
390
391 Example:
392
393 1> ets:fun2ms(fun({M,N}) when N > 3 -> M end).
394 [{{'$1','$2'},[{'>','$2',3}],['$1']}]
395
396 Variables from the environment can be imported, so that the fol‐
397 lowing works:
398
399 2> X=3.
400 3
401 3> ets:fun2ms(fun({M,N}) when N > X -> M end).
402 [{{'$1','$2'},[{'>','$2',{const,3}}],['$1']}]
403
404 The imported variables are replaced by match specification const
405 expressions, which is consistent with the static scoping for
406 Erlang funs. However, local or global function calls cannot be
407 in the guard or body of the fun. Calls to built-in match speci‐
408 fication functions is of course allowed:
409
410 4> ets:fun2ms(fun({M,N}) when N > X, my_fun(M) -> M end).
411 Error: fun containing local Erlang function calls
412 ('my_fun' called in guard) cannot be translated into match_spec
413 {error,transform_error}
414 5> ets:fun2ms(fun({M,N}) when N > X, is_atom(M) -> M end).
415 [{{'$1','$2'},[{'>','$2',{const,3}},{is_atom,'$1'}],['$1']}]
416
417 As shown by the example, the function can be called from the
418 shell also. The fun must be literally in the call when used from
419 the shell as well.
420
421 Warning:
422 If the parse_transform is not applied to a module that calls
423 this pseudo function, the call fails in runtime (with a badarg).
424 The ets module exports a function with this name, but it is
425 never to be called except when using the function in the shell.
426 If the parse_transform is properly applied by including header
427 file ms_transform.hrl, compiled code never calls the function,
428 but the function call is replaced by a literal match specifica‐
429 tion.
430
431
432 For more information, see ms_transform(3).
433
434 give_away(Tab, Pid, GiftData) -> true
435
436 Types:
437
438 Tab = tab()
439 Pid = pid()
440 GiftData = term()
441
442 Make process Pid the new owner of table Tab. If successful, mes‐
443 sage {'ETS-TRANSFER',Tab,FromPid,GiftData} is sent to the new
444 owner.
445
446 The process Pid must be alive, local, and not already the owner
447 of the table. The calling process must be the table owner.
448
449 Notice that this function does not affect option heir of the ta‐
450 ble. A table owner can, for example, set heir to itself, give
451 the table away, and then get it back if the receiver terminates.
452
453 i() -> ok
454
455 Displays information about all ETS tables on a terminal.
456
457 i(Tab) -> ok
458
459 Types:
460
461 Tab = tab()
462
463 Browses table Tab on a terminal.
464
465 info(Tab) -> InfoList | undefined
466
467 Types:
468
469 Tab = tab()
470 InfoList = [InfoTuple]
471 InfoTuple =
472 {compressed, boolean()} |
473 {heir, pid() | none} |
474 {id, tid()} |
475 {keypos, integer() >= 1} |
476 {memory, integer() >= 0} |
477 {name, atom()} |
478 {named_table, boolean()} |
479 {node, node()} |
480 {owner, pid()} |
481 {protection, access()} |
482 {size, integer() >= 0} |
483 {type, type()} |
484 {write_concurrency, boolean()} |
485 {read_concurrency, boolean()}
486
487 Returns information about table Tab as a list of tuples. If Tab
488 has the correct type for a table identifier, but does not refer
489 to an existing ETS table, undefined is returned. If Tab is not
490 of the correct type, a badarg exception is raised.
491
492 {compressed, boolean()}:
493 Indicates if the table is compressed.
494
495 {heir, pid() | none}:
496 The pid of the heir of the table, or none if no heir is set.
497
498 {id,tid()}:
499 The table identifier.
500
501 {keypos, integer() >= 1}:
502 The key position.
503
504 {memory, integer() >= 0:
505 The number of words allocated to the table.
506
507 {name, atom()}:
508 The table name.
509
510 {named_table, boolean()}:
511 Indicates if the table is named.
512
513 {node, node()}:
514 The node where the table is stored. This field is no longer
515 meaningful, as tables cannot be accessed from other nodes.
516
517 {owner, pid()}:
518 The pid of the owner of the table.
519
520 {protection,access()}:
521 The table access rights.
522
523 {size, integer() >= 0:
524 The number of objects inserted in the table.
525
526 {type,type()}:
527 The table type.
528
529 {read_concurrency, boolean()}:
530 Indicates whether the table uses read_concurrency or not.
531
532 {write_concurrency, boolean()}:
533 Indicates whether the table uses write_concurrency.
534
535 info(Tab, Item) -> Value | undefined
536
537 Types:
538
539 Tab = tab()
540 Item =
541 binary | compressed | fixed | heir | id | keypos | memory
542 |
543 name | named_table | node | owner | protection |
544 safe_fixed |
545 safe_fixed_monotonic_time | size | stats | type |
546 write_concurrency | read_concurrency
547 Value = term()
548
549 Returns the information associated with Item for table Tab, or
550 returns undefined if Tab does not refer an existing ETS table.
551 If Tab is not of the correct type, or if Item is not one of the
552 allowed values, a badarg exception is raised.
553
554 In addition to the {Item,Value} pairs defined for info/1, the
555 following items are allowed:
556
557 * Item=binary, Value=BinInfo
558
559 BinInfo is a list containing miscellaneous information about
560 binaries kept by the table. This Item can be changed or
561 removed without prior notice. In the current implementation
562 BinInfo is a list of tuples {BinaryId,BinarySize,BinaryRefc‐
563 Count}.
564
565 * Item=fixed, Value=boolean()
566
567 Indicates if the table is fixed by any process.
568
569 *
570
571
572 Item=safe_fixed|safe_fixed_monotonic_time, Value={Fixation‐
573 Time,Info}|false
574
575 If the table is fixed using safe_fixtable/2, the call
576 returns a tuple where FixationTime is the last time when the
577 table changed from unfixed to fixed.
578
579 The format and value of FixationTime depends on Item:
580
581 safe_fixed:
582 FixationTime corresponds to the result returned by
583 erlang:timestamp/0 at the time of fixation. Notice that
584 when the system uses single or multi time warp modes this
585 can produce strange results, as the use of safe_fixed is
586 not time warp safe. Time warp safe code must use
587 safe_fixed_monotonic_time instead.
588
589 safe_fixed_monotonic_time:
590 FixationTime corresponds to the result returned by
591 erlang:monotonic_time/0 at the time of fixation. The use
592 of safe_fixed_monotonic_time is time warp safe.
593
594 Info is a possibly empty lists of tuples {Pid,RefCount}, one
595 tuple for every process the table is fixed by now. RefCount
596 is the value of the reference counter and it keeps track of
597 how many times the table has been fixed by the process.
598
599 Table fixations are not limited to safe_fixtable/2. Tempo‐
600 rary fixations may also be done by for example traversing
601 functions like select and match. Such table fixations are
602 automatically released before the corresponding functions
603 returns, but they may be seen by a concurrent call to
604 ets:info(T,safe_fixed|safe_fixed_monotonic_time).
605
606 If the table is not fixed at all, the call returns false.
607
608 * Item=stats, Value=tuple()
609
610 Returns internal statistics about tables on an internal for‐
611 mat used by OTP test suites. Not for production use.
612
613 init_table(Tab, InitFun) -> true
614
615 Types:
616
617 Tab = tab()
618 InitFun = fun((Arg) -> Res)
619 Arg = read | close
620 Res = end_of_input | {Objects :: [term()], InitFun} | term()
621
622 Replaces the existing objects of table Tab with objects created
623 by calling the input function InitFun, see below. This function
624 is provided for compatibility with the dets module, it is not
625 more efficient than filling a table by using insert/2.
626
627 When called with argument read, the function InitFun is assumed
628 to return end_of_input when there is no more input, or {Objects,
629 Fun}, where Objects is a list of objects and Fun is a new input
630 function. Any other value Value is returned as an error {error,
631 {init_fun, Value}}. Each input function is called exactly once,
632 and if an error occur, the last function is called with argument
633 close, the reply of which is ignored.
634
635 If the table type is set and more than one object exists with a
636 given key, one of the objects is chosen. This is not necessarily
637 the last object with the given key in the sequence of objects
638 returned by the input functions. This holds also for duplicated
639 objects stored in tables of type bag.
640
641 insert(Tab, ObjectOrObjects) -> true
642
643 Types:
644
645 Tab = tab()
646 ObjectOrObjects = tuple() | [tuple()]
647
648 Inserts the object or all of the objects in list ObjectOrObjects
649 into table Tab.
650
651 * If the table type is set and the key of the inserted objects
652 matches the key of any object in the table, the old object
653 is replaced.
654
655 * If the table type is ordered_set and the key of the inserted
656 object compares equal to the key of any object in the table,
657 the old object is replaced.
658
659 * If the list contains more than one object with matching keys
660 and the table type is set, one is inserted, which one is not
661 defined. The same holds for table type ordered_set if the
662 keys compare equal.
663
664 The entire operation is guaranteed to be atomic and isolated,
665 even when a list of objects is inserted.
666
667 insert_new(Tab, ObjectOrObjects) -> boolean()
668
669 Types:
670
671 Tab = tab()
672 ObjectOrObjects = tuple() | [tuple()]
673
674 Same as insert/2 except that instead of overwriting objects with
675 the same key (for set or ordered_set) or adding more objects
676 with keys already existing in the table (for bag and dupli‐
677 cate_bag), false is returned.
678
679 If ObjectOrObjects is a list, the function checks every key
680 before inserting anything. Nothing is inserted unless all keys
681 present in the list are absent from the table. Like insert/2,
682 the entire operation is guaranteed to be atomic and isolated.
683
684 is_compiled_ms(Term) -> boolean()
685
686 Types:
687
688 Term = term()
689
690 Checks if a term represent a valid compiled match specification.
691 A compiled match specifications is only valid on the Erlang node
692 where it was compiled by calling match_spec_compile/1.
693
694 Note:
695 Before STDLIB 3.4 (OTP 20.0) compiled match specifications did
696 not have an external representation. If passed through
697 binary_to_term(term_to_binary(CMS)) or sent to another node and
698 back, the result was always an empty binary <<>>.
699
700 After STDLIB 3.4 (OTP 20.0) compiled match specifications have
701 an external representation as a node specific reference to the
702 original compiled match specification. If passed through
703 binary_to_term(term_to_binary(CMS)) or sent to another node and
704 back, the result may or may not be a valid compiled match speci‐
705 fication depending on if the original compiled match specifica‐
706 tion was still alive.
707
708
709 last(Tab) -> Key | '$end_of_table'
710
711 Types:
712
713 Tab = tab()
714 Key = term()
715
716 Returns the last key Key according to Erlang term order in table
717 Tab of type ordered_set. For other table types, the function is
718 synonymous to first/1. If the table is empty, '$end_of_table' is
719 returned.
720
721 To find preceding keys in the table, use prev/2.
722
723 lookup(Tab, Key) -> [Object]
724
725 Types:
726
727 Tab = tab()
728 Key = term()
729 Object = tuple()
730
731 Returns a list of all objects with key Key in table Tab.
732
733 * For tables of type set, bag, or duplicate_bag, an object is
734 returned only if the specified key matches the key of the
735 object in the table.
736
737 * For tables of type ordered_set, an object is returned if the
738 specified key compares equal to the key of an object in the
739 table.
740
741 The difference is the same as between =:= and ==.
742
743 As an example, one can insert an object with integer() 1 as a
744 key in an ordered_set and get the object returned as a result of
745 doing a lookup/2 with float() 1.0 as the key to search for.
746
747 For tables of type set or ordered_set, the function returns
748 either the empty list or a list with one element, as there can‐
749 not be more than one object with the same key. For tables of
750 type bag or duplicate_bag, the function returns a list of arbi‐
751 trary length.
752
753 Notice that the time order of object insertions is preserved;
754 the first object inserted with the specified key is the first in
755 the resulting list, and so on.
756
757 Insert and lookup times in tables of type set, bag, and dupli‐
758 cate_bag are constant, regardless of the table size. For the
759 ordered_set datatype, time is proportional to the (binary) loga‐
760 rithm of the number of objects.
761
762 lookup_element(Tab, Key, Pos) -> Elem
763
764 Types:
765
766 Tab = tab()
767 Key = term()
768 Pos = integer() >= 1
769 Elem = term() | [term()]
770
771 For a table Tab of type set or ordered_set, the function returns
772 the Pos:th element of the object with key Key.
773
774 For tables of type bag or duplicate_bag, the functions returns a
775 list with the Pos:th element of every object with key Key.
776
777 If no object with key Key exists, the function exits with reason
778 badarg.
779
780 The difference between set, bag, and duplicate_bag on one hand,
781 and ordered_set on the other, regarding the fact that
782 ordered_set view keys as equal when they compare equal whereas
783 the other table types regard them equal only when they match,
784 holds for lookup_element/3.
785
786 match(Continuation) -> {[Match], Continuation} | '$end_of_table'
787
788 Types:
789
790 Match = [term()]
791 Continuation = continuation()
792
793 Continues a match started with match/3. The next chunk of the
794 size specified in the initial match/3 call is returned together
795 with a new Continuation, which can be used in subsequent calls
796 to this function.
797
798 When there are no more objects in the table, '$end_of_table' is
799 returned.
800
801 match(Tab, Pattern) -> [Match]
802
803 Types:
804
805 Tab = tab()
806 Pattern = match_pattern()
807 Match = [term()]
808
809 Matches the objects in table Tab against pattern Pattern.
810
811 A pattern is a term that can contain:
812
813 * Bound parts (Erlang terms)
814
815 * '_' that matches any Erlang term
816
817 * Pattern variables '$N', where N=0,1,...
818
819 The function returns a list with one element for each matching
820 object, where each element is an ordered list of pattern vari‐
821 able bindings, for example:
822
823 6> ets:match(T, '$1'). % Matches every object in table
824 [[{rufsen,dog,7}],[{brunte,horse,5}],[{ludde,dog,5}]]
825 7> ets:match(T, {'_',dog,'$1'}).
826 [[7],[5]]
827 8> ets:match(T, {'_',cow,'$1'}).
828 []
829
830 If the key is specified in the pattern, the match is very effi‐
831 cient. If the key is not specified, that is, if it is a variable
832 or an underscore, the entire table must be searched. The search
833 time can be substantial if the table is very large.
834
835 For tables of type ordered_set, the result is in the same order
836 as in a first/next traversal.
837
838 match(Tab, Pattern, Limit) ->
839 {[Match], Continuation} | '$end_of_table'
840
841 Types:
842
843 Tab = tab()
844 Pattern = match_pattern()
845 Limit = integer() >= 1
846 Match = [term()]
847 Continuation = continuation()
848
849 Works like match/2, but returns only a limited (Limit) number of
850 matching objects. Term Continuation can then be used in subse‐
851 quent calls to match/1 to get the next chunk of matching
852 objects. This is a space-efficient way to work on objects in a
853 table, which is faster than traversing the table object by
854 object using first/1 and next/2.
855
856 If the table is empty, '$end_of_table' is returned.
857
858 Use safe_fixtable/2 to guarantee safe traversal for subsequent
859 calls to match/1.
860
861 match_delete(Tab, Pattern) -> true
862
863 Types:
864
865 Tab = tab()
866 Pattern = match_pattern()
867
868 Deletes all objects that match pattern Pattern from table Tab.
869 For a description of patterns, see match/2.
870
871 match_object(Continuation) ->
872 {[Object], Continuation} | '$end_of_table'
873
874 Types:
875
876 Object = tuple()
877 Continuation = continuation()
878
879 Continues a match started with match_object/3. The next chunk of
880 the size specified in the initial match_object/3 call is
881 returned together with a new Continuation, which can be used in
882 subsequent calls to this function.
883
884 When there are no more objects in the table, '$end_of_table' is
885 returned.
886
887 match_object(Tab, Pattern) -> [Object]
888
889 Types:
890
891 Tab = tab()
892 Pattern = match_pattern()
893 Object = tuple()
894
895 Matches the objects in table Tab against pattern Pattern. For a
896 description of patterns, see match/2. The function returns a
897 list of all objects that match the pattern.
898
899 If the key is specified in the pattern, the match is very effi‐
900 cient. If the key is not specified, that is, if it is a variable
901 or an underscore, the entire table must be searched. The search
902 time can be substantial if the table is very large.
903
904 For tables of type ordered_set, the result is in the same order
905 as in a first/next traversal.
906
907 match_object(Tab, Pattern, Limit) ->
908 {[Object], Continuation} | '$end_of_table'
909
910 Types:
911
912 Tab = tab()
913 Pattern = match_pattern()
914 Limit = integer() >= 1
915 Object = tuple()
916 Continuation = continuation()
917
918 Works like match_object/2, but only returns a limited (Limit)
919 number of matching objects. Term Continuation can then be used
920 in subsequent calls to match_object/1 to get the next chunk of
921 matching objects. This is a space-efficient way to work on
922 objects in a table, which is faster than traversing the table
923 object by object using first/1 and next/2.
924
925 If the table is empty, '$end_of_table' is returned.
926
927 Use safe_fixtable/2 to guarantee safe traversal for subsequent
928 calls to match_object/1.
929
930 match_spec_compile(MatchSpec) -> CompiledMatchSpec
931
932 Types:
933
934 MatchSpec = match_spec()
935 CompiledMatchSpec = comp_match_spec()
936
937 Transforms a match specification into an internal representation
938 that can be used in subsequent calls to match_spec_run/2. The
939 internal representation is opaque. To check the validity of a
940 compiled match specification, use is_compiled_ms/1.
941
942 If term MatchSpec cannot be compiled (does not represent a valid
943 match specification), a badarg exception is raised.
944
945 Note:
946 This function has limited use in normal code. It is used by the
947 dets module to perform the dets:select() operations.
948
949
950 match_spec_run(List, CompiledMatchSpec) -> list()
951
952 Types:
953
954 List = [term()]
955 CompiledMatchSpec = comp_match_spec()
956
957 Executes the matching specified in a compiled match specifica‐
958 tion on a list of terms. Term CompiledMatchSpec is to be the
959 result of a call to match_spec_compile/1 and is hence the inter‐
960 nal representation of the match specification one wants to use.
961
962 The matching is executed on each element in List and the func‐
963 tion returns a list containing all results. If an element in
964 List does not match, nothing is returned for that element. The
965 length of the result list is therefore equal or less than the
966 length of parameter List.
967
968 Example:
969
970 The following two calls give the same result (but certainly not
971 the same execution time):
972
973 Table = ets:new...
974 MatchSpec = ...
975 % The following call...
976 ets:match_spec_run(ets:tab2list(Table),
977 ets:match_spec_compile(MatchSpec)),
978 % ...gives the same result as the more common (and more efficient)
979 ets:select(Table, MatchSpec),
980
981 Note:
982 This function has limited use in normal code. It is used by the
983 dets module to perform the dets:select() operations and by Mne‐
984 sia during transactions.
985
986
987 member(Tab, Key) -> boolean()
988
989 Types:
990
991 Tab = tab()
992 Key = term()
993
994 Works like lookup/2, but does not return the objects. Returns
995 true if one or more elements in the table has key Key, otherwise
996 false.
997
998 new(Name, Options) -> tid() | atom()
999
1000 Types:
1001
1002 Name = atom()
1003 Options = [Option]
1004 Option =
1005 Type | Access | named_table |
1006 {keypos, Pos} |
1007 {heir, Pid :: pid(), HeirData} |
1008 {heir, none} |
1009 Tweaks
1010 Type = type()
1011 Access = access()
1012 Tweaks =
1013 {write_concurrency, boolean()} |
1014 {read_concurrency, boolean()} |
1015 compressed
1016 Pos = integer() >= 1
1017 HeirData = term()
1018
1019 Creates a new table and returns a table identifier that can be
1020 used in subsequent operations. The table identifier can be sent
1021 to other processes so that a table can be shared between differ‐
1022 ent processes within a node.
1023
1024 Parameter Options is a list of options that specifies table
1025 type, access rights, key position, and whether the table is
1026 named. Default values are used for omitted options. This means
1027 that not specifying any options ([]) is the same as specifying
1028 [set, protected, {keypos,1}, {heir,none}, {write_concur‐
1029 rency,false}, {read_concurrency,false}].
1030
1031 set:
1032 The table is a set table: one key, one object, no order
1033 among objects. This is the default table type.
1034
1035 ordered_set:
1036 The table is a ordered_set table: one key, one object,
1037 ordered in Erlang term order, which is the order implied by
1038 the < and > operators. Tables of this type have a somewhat
1039 different behavior in some situations than tables of other
1040 types. Most notably, the ordered_set tables regard keys as
1041 equal when they compare equal, not only when they match.
1042 This means that to an ordered_set table, integer() 1 and
1043 float() 1.0 are regarded as equal. This also means that the
1044 key used to lookup an element not necessarily matches the
1045 key in the returned elements, if float()'s and integer()'s
1046 are mixed in keys of a table.
1047
1048 bag:
1049 The table is a bag table, which can have many objects, but
1050 only one instance of each object, per key.
1051
1052 duplicate_bag:
1053 The table is a duplicate_bag table, which can have many
1054 objects, including multiple copies of the same object, per
1055 key.
1056
1057 public:
1058 Any process can read or write to the table.
1059
1060 protected:
1061 The owner process can read and write to the table. Other
1062 processes can only read the table. This is the default set‐
1063 ting for the access rights.
1064
1065 private:
1066 Only the owner process can read or write to the table.
1067
1068 named_table:
1069 If this option is present, the table is registered under its
1070 Name which can then be used instead of the table identifier
1071 in subsequent operations.
1072
1073 The function will also return the Name instead of the table
1074 identifier. To get the table identifier of a named table,
1075 use whereis/1.
1076
1077 {keypos,Pos}:
1078 Specifies which element in the stored tuples to use as key.
1079 By default, it is the first element, that is, Pos=1. How‐
1080 ever, this is not always appropriate. In particular, we do
1081 not want the first element to be the key if we want to store
1082 Erlang records in a table.
1083
1084 Notice that any tuple stored in the table must have at least
1085 Pos number of elements.
1086
1087 {heir,Pid,HeirData} | {heir,none}:
1088 Set a process as heir. The heir inherits the table if the
1089 owner terminates. Message {'ETS-TRANS‐
1090 FER',tid(),FromPid,HeirData} is sent to the heir when that
1091 occurs. The heir must be a local process. Default heir is
1092 none, which destroys the table when the owner terminates.
1093
1094 {write_concurrency,boolean()}:
1095 Performance tuning. Defaults to false, in which case an
1096 operation that mutates (writes to) the table obtains exclu‐
1097 sive access, blocking any concurrent access of the same ta‐
1098 ble until finished. If set to true, the table is optimized
1099 to concurrent write access. Different objects of the same
1100 table can be mutated (and read) by concurrent processes.
1101 This is achieved to some degree at the expense of memory
1102 consumption and the performance of sequential access and
1103 concurrent reading.
1104
1105 Option write_concurrency can be combined with option
1106 read_concurrency. You typically want to combine these when
1107 large concurrent read bursts and large concurrent write
1108 bursts are common; for more information, see option
1109 read_concurrency.
1110
1111 Notice that this option does not change any guarantees about
1112 atomicity and isolation. Functions that makes such promises
1113 over many objects (like insert/2) gain less (or nothing)
1114 from this option.
1115
1116 The memory consumption inflicted by both write_concurrency
1117 and read_concurrency is a constant overhead per table for
1118 set, bag and duplicate_bag. For ordered_set the memory over‐
1119 head depends on the number of inserted objects and the
1120 amount of actual detected concurrency in runtime. The memory
1121 overhead can be especially large when both options are com‐
1122 bined.
1123
1124 Note:
1125 Prior to stdlib-3.7 (OTP-22.0) write_concurrency had no effect
1126 on ordered_set.
1127
1128
1129 {read_concurrency,boolean()}:
1130 Performance tuning. Defaults to false. When set to true, the
1131 table is optimized for concurrent read operations. When this
1132 option is enabled on a runtime system with SMP support, read
1133 operations become much cheaper; especially on systems with
1134 multiple physical processors. However, switching between
1135 read and write operations becomes more expensive.
1136
1137 You typically want to enable this option when concurrent
1138 read operations are much more frequent than write opera‐
1139 tions, or when concurrent reads and writes comes in large
1140 read and write bursts (that is, many reads not interrupted
1141 by writes, and many writes not interrupted by reads).
1142
1143 You typically do not want to enable this option when the
1144 common access pattern is a few read operations interleaved
1145 with a few write operations repeatedly. In this case, you
1146 would get a performance degradation by enabling this option.
1147
1148 Option read_concurrency can be combined with option
1149 write_concurrency. You typically want to combine these when
1150 large concurrent read bursts and large concurrent write
1151 bursts are common.
1152
1153 compressed:
1154 If this option is present, the table data is stored in a
1155 more compact format to consume less memory. However, it will
1156 make table operations slower. Especially operations that
1157 need to inspect entire objects, such as match and select,
1158 get much slower. The key element is not compressed.
1159
1160 next(Tab, Key1) -> Key2 | '$end_of_table'
1161
1162 Types:
1163
1164 Tab = tab()
1165 Key1 = Key2 = term()
1166
1167 Returns the next key Key2, following key Key1 in table Tab. For
1168 table type ordered_set, the next key in Erlang term order is
1169 returned. For other table types, the next key according to the
1170 internal order of the table is returned. If no next key exists,
1171 '$end_of_table' is returned.
1172
1173 To find the first key in the table, use first/1.
1174
1175 Unless a table of type set, bag, or duplicate_bag is fixated
1176 using safe_fixtable/2, a call to next/2 will fail if Key1 no
1177 longer exists in the table. For table type ordered_set, the
1178 function always returns the next key after Key1 in term order,
1179 regardless whether Key1 ever existed in the table.
1180
1181 prev(Tab, Key1) -> Key2 | '$end_of_table'
1182
1183 Types:
1184
1185 Tab = tab()
1186 Key1 = Key2 = term()
1187
1188 Returns the previous key Key2, preceding key Key1 according to
1189 Erlang term order in table Tab of type ordered_set. For other
1190 table types, the function is synonymous to next/2. If no previ‐
1191 ous key exists, '$end_of_table' is returned.
1192
1193 To find the last key in an ordered_set table, use last/1.
1194
1195 rename(Tab, Name) -> Name
1196
1197 Types:
1198
1199 Tab = tab()
1200 Name = atom()
1201
1202 Renames the named table Tab to the new name Name. Afterwards,
1203 the old name cannot be used to access the table. Renaming an
1204 unnamed table has no effect.
1205
1206 repair_continuation(Continuation, MatchSpec) -> Continuation
1207
1208 Types:
1209
1210 Continuation = continuation()
1211 MatchSpec = match_spec()
1212
1213 Restores an opaque continuation returned by select/3 or select/1
1214 if the continuation has passed through external term format
1215 (been sent between nodes or stored on disk).
1216
1217 The reason for this function is that continuation terms contain
1218 compiled match specifications and may therefore be invalidated
1219 if converted to external term format. Given that the original
1220 match specification is kept intact, the continuation can be
1221 restored, meaning it can once again be used in subsequent
1222 select/1 calls even though it has been stored on disk or on
1223 another node.
1224
1225 Examples:
1226
1227 The following sequence of calls may fail:
1228
1229 T=ets:new(x,[]),
1230 MS = ets:fun2ms(fun({N,_}=A) when (N rem 10) =:= 0 -> A end),
1231 {_,C} = ets:select(T, MS, 10),
1232 MaybeBroken = binary_to_term(term_to_binary(C)),
1233 ets:select(MaybeBroken).
1234
1235 The following sequence works, as the call to repair_continua‐
1236 tion/2 reestablishes the MaybeBroken continuation.
1237
1238 T=ets:new(x,[]),
1239 MS = ets:fun2ms(fun({N,_}=A) when (N rem 10) =:= 0 -> A end),
1240 {_,C} = ets:select(T,MS,10),
1241 MaybeBroken = binary_to_term(term_to_binary(C)),
1242 ets:select(ets:repair_continuation(MaybeBroken,MS)).
1243
1244 Note:
1245 This function is rarely needed in application code. It is used
1246 by Mnesia to provide distributed select/3 and select/1
1247 sequences. A normal application would either use Mnesia or keep
1248 the continuation from being converted to external format.
1249
1250 The actual behavior of compiled match specifications when recre‐
1251 ated from external format has changed and may change in future
1252 releases, but this interface remains for backward compatibility.
1253 See is_compiled_ms/1.
1254
1255
1256 safe_fixtable(Tab, Fix) -> true
1257
1258 Types:
1259
1260 Tab = tab()
1261 Fix = boolean()
1262
1263 Fixes a table of type set, bag, or duplicate_bag for safe tra‐
1264 versal using first/1 & next/2, match/3 & match/1, match_object/3
1265 & match_object/1, or select/3 & select/1.
1266
1267 A process fixes a table by calling safe_fixtable(Tab, true). The
1268 table remains fixed until the process releases it by calling
1269 safe_fixtable(Tab, false), or until the process terminates.
1270
1271 If many processes fix a table, the table remains fixed until all
1272 processes have released it (or terminated). A reference counter
1273 is kept on a per process basis, and N consecutive fixes requires
1274 N releases to release the table.
1275
1276 When a table is fixed, a sequence of first/1 and next/2 calls
1277 are guaranteed to succeed even if keys are removed during the
1278 traversal. The keys for objects inserted or deleted during a
1279 traversal may or may not be returned by next/2 depending on the
1280 ordering of keys within the table and if the key exists at the
1281 time next/2 is called.
1282
1283 Example:
1284
1285 clean_all_with_value(Tab,X) ->
1286 safe_fixtable(Tab,true),
1287 clean_all_with_value(Tab,X,ets:first(Tab)),
1288 safe_fixtable(Tab,false).
1289
1290 clean_all_with_value(Tab,X,'$end_of_table') ->
1291 true;
1292 clean_all_with_value(Tab,X,Key) ->
1293 case ets:lookup(Tab,Key) of
1294 [{Key,X}] ->
1295 ets:delete(Tab,Key);
1296 _ ->
1297 true
1298 end,
1299 clean_all_with_value(Tab,X,ets:next(Tab,Key)).
1300
1301 Notice that deleted objects are not freed from a fixed table
1302 until it has been released. If a process fixes a table but never
1303 releases it, the memory used by the deleted objects is never
1304 freed. The performance of operations on the table also degrades
1305 significantly.
1306
1307 To retrieve information about which processes have fixed which
1308 tables, use info(Tab, safe_fixed_monotonic_time). A system with
1309 many processes fixing tables can need a monitor that sends
1310 alarms when tables have been fixed for too long.
1311
1312 Notice that safe_fixtable/2 is not necessary for table type
1313 ordered_set and for traversals done by a single ETS function
1314 call, like select/2.
1315
1316 select(Continuation) -> {[Match], Continuation} | '$end_of_table'
1317
1318 Types:
1319
1320 Match = term()
1321 Continuation = continuation()
1322
1323 Continues a match started with select/3. The next chunk of the
1324 size specified in the initial select/3 call is returned together
1325 with a new Continuation, which can be used in subsequent calls
1326 to this function.
1327
1328 When there are no more objects in the table, '$end_of_table' is
1329 returned.
1330
1331 select(Tab, MatchSpec) -> [Match]
1332
1333 Types:
1334
1335 Tab = tab()
1336 MatchSpec = match_spec()
1337 Match = term()
1338
1339 Matches the objects in table Tab using a match specification.
1340 This is a more general call than match/2 and match_object/2
1341 calls. In its simplest form, the match specification is as fol‐
1342 lows:
1343
1344 MatchSpec = [MatchFunction]
1345 MatchFunction = {MatchHead, [Guard], [Result]}
1346 MatchHead = "Pattern as in ets:match"
1347 Guard = {"Guardtest name", ...}
1348 Result = "Term construct"
1349
1350 This means that the match specification is always a list of one
1351 or more tuples (of arity 3). The first element of the tuple is
1352 to be a pattern as described in match/2. The second element of
1353 the tuple is to be a list of 0 or more guard tests (described
1354 below). The third element of the tuple is to be a list contain‐
1355 ing a description of the value to return. In almost all normal
1356 cases, the list contains exactly one term that fully describes
1357 the value to return for each object.
1358
1359 The return value is constructed using the "match variables"
1360 bound in MatchHead or using the special match variables '$_'
1361 (the whole matching object) and '$$' (all match variables in a
1362 list), so that the following match/2 expression:
1363
1364 ets:match(Tab,{'$1','$2','$3'})
1365
1366 is exactly equivalent to:
1367
1368 ets:select(Tab,[{{'$1','$2','$3'},[],['$$']}])
1369
1370 And that the following match_object/2 call:
1371
1372 ets:match_object(Tab,{'$1','$2','$1'})
1373
1374 is exactly equivalent to
1375
1376 ets:select(Tab,[{{'$1','$2','$1'},[],['$_']}])
1377
1378 Composite terms can be constructed in the Result part either by
1379 simply writing a list, so that the following code:
1380
1381 ets:select(Tab,[{{'$1','$2','$3'},[],['$$']}])
1382
1383 gives the same output as:
1384
1385 ets:select(Tab,[{{'$1','$2','$3'},[],[['$1','$2','$3']]}])
1386
1387 That is, all the bound variables in the match head as a list. If
1388 tuples are to be constructed, one has to write a tuple of arity
1389 1 where the single element in the tuple is the tuple one wants
1390 to construct (as an ordinary tuple can be mistaken for a Guard).
1391
1392 Therefore the following call:
1393
1394 ets:select(Tab,[{{'$1','$2','$1'},[],['$_']}])
1395
1396 gives the same output as:
1397
1398 ets:select(Tab,[{{'$1','$2','$1'},[],[{{'$1','$2','$3'}}]}])
1399
1400 This syntax is equivalent to the syntax used in the trace pat‐
1401 terns (see the dbg(3)) module in Runtime_Tools.
1402
1403 The Guards are constructed as tuples, where the first element is
1404 the test name and the remaining elements are the test parame‐
1405 ters. To check for a specific type (say a list) of the element
1406 bound to the match variable '$1', one would write the test as
1407 {is_list, '$1'}. If the test fails, the object in the table does
1408 not match and the next MatchFunction (if any) is tried. Most
1409 guard tests present in Erlang can be used, but only the new ver‐
1410 sions prefixed is_ are allowed (is_float, is_atom, and so on).
1411
1412 The Guard section can also contain logic and arithmetic opera‐
1413 tions, which are written with the same syntax as the guard tests
1414 (prefix notation), so that the following guard test written in
1415 Erlang:
1416
1417 is_integer(X), is_integer(Y), X + Y < 4711
1418
1419 is expressed as follows (X replaced with '$1' and Y with '$2'):
1420
1421 [{is_integer, '$1'}, {is_integer, '$2'}, {'<', {'+', '$1', '$2'}, 4711}]
1422
1423 For tables of type ordered_set, objects are visited in the same
1424 order as in a first/next traversal. This means that the match
1425 specification is executed against objects with keys in the
1426 first/next order and the corresponding result list is in the
1427 order of that execution.
1428
1429 select(Tab, MatchSpec, Limit) ->
1430 {[Match], Continuation} | '$end_of_table'
1431
1432 Types:
1433
1434 Tab = tab()
1435 MatchSpec = match_spec()
1436 Limit = integer() >= 1
1437 Match = term()
1438 Continuation = continuation()
1439
1440 Works like select/2, but only returns a limited (Limit) number
1441 of matching objects. Term Continuation can then be used in sub‐
1442 sequent calls to select/1 to get the next chunk of matching
1443 objects. This is a space-efficient way to work on objects in a
1444 table, which is still faster than traversing the table object by
1445 object using first/1 and next/2.
1446
1447 If the table is empty, '$end_of_table' is returned.
1448
1449 Use safe_fixtable/2 to guarantee safe traversal for subsequent
1450 calls to select/1.
1451
1452 select_count(Tab, MatchSpec) -> NumMatched
1453
1454 Types:
1455
1456 Tab = tab()
1457 MatchSpec = match_spec()
1458 NumMatched = integer() >= 0
1459
1460 Matches the objects in table Tab using a match specification. If
1461 the match specification returns true for an object, that object
1462 considered a match and is counted. For any other result from the
1463 match specification the object is not considered a match and is
1464 therefore not counted.
1465
1466 This function can be described as a match_delete/2 function that
1467 does not delete any elements, but only counts them.
1468
1469 The function returns the number of objects matched.
1470
1471 select_delete(Tab, MatchSpec) -> NumDeleted
1472
1473 Types:
1474
1475 Tab = tab()
1476 MatchSpec = match_spec()
1477 NumDeleted = integer() >= 0
1478
1479 Matches the objects in table Tab using a match specification. If
1480 the match specification returns true for an object, that object
1481 is removed from the table. For any other result from the match
1482 specification the object is retained. This is a more general
1483 call than the match_delete/2 call.
1484
1485 The function returns the number of objects deleted from the ta‐
1486 ble.
1487
1488 Note:
1489 The match specification has to return the atom true if the
1490 object is to be deleted. No other return value gets the object
1491 deleted. So one cannot use the same match specification for
1492 looking up elements as for deleting them.
1493
1494
1495 select_replace(Tab, MatchSpec) -> NumReplaced
1496
1497 Types:
1498
1499 Tab = tab()
1500 MatchSpec = match_spec()
1501 NumReplaced = integer() >= 0
1502
1503 Matches the objects in the table Tab using a match specifica‐
1504 tion. For each matched object, the existing object is replaced
1505 with the match specification result.
1506
1507 The match-and-replace operation for each individual object is
1508 guaranteed to be atomic and isolated. The select_replace table
1509 traversal as a whole, like all other select functions, does not
1510 give such guarantees.
1511
1512 The match specifiction must be guaranteed to retain the key of
1513 any matched object. If not, select_replace will fail with badarg
1514 without updating any objects.
1515
1516 For the moment, due to performance and semantic constraints,
1517 tables of type bag are not yet supported.
1518
1519 The function returns the total number of replaced objects.
1520
1521 Example
1522
1523 For all 2-tuples with a list in second position, add atom
1524 'marker' first in the list:
1525
1526 1> T = ets:new(x,[]), ets:insert(T, {key, [1, 2, 3]}).
1527 true
1528 2> MS = ets:fun2ms(fun({K, L}) when is_list(L) -> {K, [marker | L]} end).
1529 [{{'$1','$2'},[{is_list,'$2'}],[{{'$1',[marker|'$2']}}]}]
1530 3> ets:select_replace(T, MS).
1531 1
1532 4> ets:tab2list(T).
1533 [{key,[marker,1,2,3]}]
1534
1535
1536 A generic single object compare-and-swap operation:
1537
1538 [Old] = ets:lookup(T, Key),
1539 New = update_object(Old),
1540 Success = (1 =:= ets:select_replace(T, [{Old, [], [{const, New}]}])),
1541
1542
1543 select_reverse(Continuation) ->
1544 {[Match], Continuation} | '$end_of_table'
1545
1546 Types:
1547
1548 Continuation = continuation()
1549 Match = term()
1550
1551 Continues a match started with select_reverse/3. For tables of
1552 type ordered_set, the traversal of the table continues to
1553 objects with keys earlier in the Erlang term order. The returned
1554 list also contains objects with keys in reverse order. For all
1555 other table types, the behavior is exactly that of select/1.
1556
1557 Example:
1558
1559 1> T = ets:new(x,[ordered_set]).
1560 2> [ ets:insert(T,{N}) || N <- lists:seq(1,10) ].
1561 3> {R0,C0} = ets:select_reverse(T,[{'_',[],['$_']}],4).
1562 4> R0.
1563 [{10},{9},{8},{7}]
1564 5> {R1,C1} = ets:select_reverse(C0).
1565 6> R1.
1566 [{6},{5},{4},{3}]
1567 7> {R2,C2} = ets:select_reverse(C1).
1568 8> R2.
1569 [{2},{1}]
1570 9> '$end_of_table' = ets:select_reverse(C2).
1571
1572 select_reverse(Tab, MatchSpec) -> [Match]
1573
1574 Types:
1575
1576 Tab = tab()
1577 MatchSpec = match_spec()
1578 Match = term()
1579
1580 Works like select/2, but returns the list in reverse order for
1581 table type ordered_set. For all other table types, the return
1582 value is identical to that of select/2.
1583
1584 select_reverse(Tab, MatchSpec, Limit) ->
1585 {[Match], Continuation} | '$end_of_table'
1586
1587 Types:
1588
1589 Tab = tab()
1590 MatchSpec = match_spec()
1591 Limit = integer() >= 1
1592 Match = term()
1593 Continuation = continuation()
1594
1595 Works like select/3, but for table type ordered_set traversing
1596 is done starting at the last object in Erlang term order and
1597 moves to the first. For all other table types, the return value
1598 is identical to that of select/3.
1599
1600 Notice that this is not equivalent to reversing the result list
1601 of a select/3 call, as the result list is not only reversed, but
1602 also contains the last Limit matching objects in the table, not
1603 the first.
1604
1605 setopts(Tab, Opts) -> true
1606
1607 Types:
1608
1609 Tab = tab()
1610 Opts = Opt | [Opt]
1611 Opt = {heir, pid(), HeirData} | {heir, none}
1612 HeirData = term()
1613
1614 Sets table options. The only allowed option to be set after the
1615 table has been created is heir. The calling process must be the
1616 table owner.
1617
1618 slot(Tab, I) -> [Object] | '$end_of_table'
1619
1620 Types:
1621
1622 Tab = tab()
1623 I = integer() >= 0
1624 Object = tuple()
1625
1626 This function is mostly for debugging purposes, Normally
1627 first/next or last/prev are to be used instead.
1628
1629 Returns all objects in slot I of table Tab. A table can be tra‐
1630 versed by repeatedly calling the function, starting with the
1631 first slot I=0 and ending when '$end_of_table' is returned. If
1632 argument I is out of range, the function fails with reason
1633 badarg.
1634
1635 Unless a table of type set, bag, or duplicate_bag is protected
1636 using safe_fixtable/2, a traversal can fail if concurrent
1637 updates are made to the table. For table type ordered_set, the
1638 function returns a list containing object I in Erlang term
1639 order.
1640
1641 tab2file(Tab, Filename) -> ok | {error, Reason}
1642
1643 Types:
1644
1645 Tab = tab()
1646 Filename = file:name()
1647 Reason = term()
1648
1649 Dumps table Tab to file Filename.
1650
1651 Equivalent to tab2file(Tab, Filename,[])
1652
1653 tab2file(Tab, Filename, Options) -> ok | {error, Reason}
1654
1655 Types:
1656
1657 Tab = tab()
1658 Filename = file:name()
1659 Options = [Option]
1660 Option = {extended_info, [ExtInfo]} | {sync, boolean()}
1661 ExtInfo = md5sum | object_count
1662 Reason = term()
1663
1664 Dumps table Tab to file Filename.
1665
1666 When dumping the table, some information about the table is
1667 dumped to a header at the beginning of the dump. This informa‐
1668 tion contains data about the table type, name, protection, size,
1669 version, and if it is a named table. It also contains notes
1670 about what extended information is added to the file, which can
1671 be a count of the objects in the file or a MD5 sum of the header
1672 and records in the file.
1673
1674 The size field in the header might not correspond to the number
1675 of records in the file if the table is public and records are
1676 added or removed from the table during dumping. Public tables
1677 updated during dump, and that one wants to verify when reading,
1678 needs at least one field of extended information for the read
1679 verification process to be reliable later.
1680
1681 Option extended_info specifies what extra information is written
1682 to the table dump:
1683
1684 object_count:
1685 The number of objects written to the file is noted in the
1686 file footer, so file truncation can be verified even if the
1687 file was updated during dump.
1688
1689 md5sum:
1690 The header and objects in the file are checksummed using the
1691 built-in MD5 functions. The MD5 sum of all objects is writ‐
1692 ten in the file footer, so that verification while reading
1693 detects the slightest bitflip in the file data. Using this
1694 costs a fair amount of CPU time.
1695
1696 Whenever option extended_info is used, it results in a file not
1697 readable by versions of ETS before that in STDLIB 1.15.1
1698
1699 If option sync is set to true, it ensures that the content of
1700 the file is written to the disk before tab2file returns.
1701 Defaults to {sync, false}.
1702
1703 tab2list(Tab) -> [Object]
1704
1705 Types:
1706
1707 Tab = tab()
1708 Object = tuple()
1709
1710 Returns a list of all objects in table Tab.
1711
1712 tabfile_info(Filename) -> {ok, TableInfo} | {error, Reason}
1713
1714 Types:
1715
1716 Filename = file:name()
1717 TableInfo = [InfoItem]
1718 InfoItem =
1719 {name, atom()} |
1720 {type, Type} |
1721 {protection, Protection} |
1722 {named_table, boolean()} |
1723 {keypos, integer() >= 0} |
1724 {size, integer() >= 0} |
1725 {extended_info, [ExtInfo]} |
1726 {version,
1727 {Major :: integer() >= 0, Minor :: integer() >= 0}}
1728 ExtInfo = md5sum | object_count
1729 Type = bag | duplicate_bag | ordered_set | set
1730 Protection = private | protected | public
1731 Reason = term()
1732
1733 Returns information about the table dumped to file by tab2file/2
1734 or tab2file/3.
1735
1736 The following items are returned:
1737
1738 name:
1739 The name of the dumped table. If the table was a named ta‐
1740 ble, a table with the same name cannot exist when the table
1741 is loaded from file with file2tab/2. If the table is not
1742 saved as a named table, this field has no significance when
1743 loading the table from file.
1744
1745 type:
1746 The ETS type of the dumped table (that is, set, bag, dupli‐
1747 cate_bag, or ordered_set). This type is used when loading
1748 the table again.
1749
1750 protection:
1751 The protection of the dumped table (that is, private, pro‐
1752 tected, or public). A table loaded from the file gets the
1753 same protection.
1754
1755 named_table:
1756 true if the table was a named table when dumped to file,
1757 otherwise false. Notice that when a named table is loaded
1758 from a file, there cannot exist a table in the system with
1759 the same name.
1760
1761 keypos:
1762 The keypos of the table dumped to file, which is used when
1763 loading the table again.
1764
1765 size:
1766 The number of objects in the table when the table dump to
1767 file started. For a public table, this number does not need
1768 to correspond to the number of objects saved to the file, as
1769 objects can have been added or deleted by another process
1770 during table dump.
1771
1772 extended_info:
1773 The extended information written in the file footer to allow
1774 stronger verification during table loading from file, as
1775 specified to tab2file/3. Notice that this function only
1776 tells which information is present, not the values in the
1777 file footer. The value is a list containing one or more of
1778 the atoms object_count and md5sum.
1779
1780 version:
1781 A tuple {Major,Minor} containing the major and minor version
1782 of the file format for ETS table dumps. This version field
1783 was added beginning with STDLIB 1.5.1. Files dumped with
1784 older versions return {0,0} in this field.
1785
1786 An error is returned if the file is inaccessible, badly damaged,
1787 or not produced with tab2file/2 or tab2file/3.
1788
1789 table(Tab) -> QueryHandle
1790
1791 table(Tab, Options) -> QueryHandle
1792
1793 Types:
1794
1795 Tab = tab()
1796 QueryHandle = qlc:query_handle()
1797 Options = [Option] | Option
1798 Option = {n_objects, NObjects} | {traverse, TraverseMethod}
1799 NObjects = default | integer() >= 1
1800 TraverseMethod =
1801 first_next | last_prev | select |
1802 {select, MatchSpec :: match_spec()}
1803
1804 Returns a Query List Comprehension (QLC) query handle. The qlc
1805 module provides a query language aimed mainly at Mnesia, but ETS
1806 tables, Dets tables, and lists are also recognized by QLC as
1807 sources of data. Calling table/1,2 is the means to make the ETS
1808 table Tab usable to QLC.
1809
1810 When there are only simple restrictions on the key position, QLC
1811 uses lookup/2 to look up the keys. When that is not possible,
1812 the whole table is traversed. Option traverse determines how
1813 this is done:
1814
1815 first_next:
1816 The table is traversed one key at a time by calling first/1
1817 and next/2.
1818
1819 last_prev:
1820 The table is traversed one key at a time by calling last/1
1821 and prev/2.
1822
1823 select:
1824 The table is traversed by calling select/3 and select/1.
1825 Option n_objects determines the number of objects returned
1826 (the third argument of select/3); the default is to return
1827 100 objects at a time. The match specification (the second
1828 argument of select/3) is assembled by QLC: simple filters
1829 are translated into equivalent match specifications while
1830 more complicated filters must be applied to all objects
1831 returned by select/3 given a match specification that
1832 matches all objects.
1833
1834 {select, MatchSpec}:
1835 As for select, the table is traversed by calling select/3
1836 and select/1. The difference is that the match specification
1837 is explicitly specified. This is how to state match specifi‐
1838 cations that cannot easily be expressed within the syntax
1839 provided by QLC.
1840
1841 Examples:
1842
1843 An explicit match specification is here used to traverse the ta‐
1844 ble:
1845
1846 9> true = ets:insert(Tab = ets:new(t, []), [{1,a},{2,b},{3,c},{4,d}]),
1847 MS = ets:fun2ms(fun({X,Y}) when (X > 1) or (X < 5) -> {Y} end),
1848 QH1 = ets:table(Tab, [{traverse, {select, MS}}]).
1849
1850 An example with an implicit match specification:
1851
1852 10> QH2 = qlc:q([{Y} || {X,Y} <- ets:table(Tab), (X > 1) or (X < 5)]).
1853
1854 The latter example is equivalent to the former, which can be
1855 verified using function qlc:info/1:
1856
1857 11> qlc:info(QH1) =:= qlc:info(QH2).
1858 true
1859
1860 qlc:info/1 returns information about a query handle, and in this
1861 case identical information is returned for the two query han‐
1862 dles.
1863
1864 take(Tab, Key) -> [Object]
1865
1866 Types:
1867
1868 Tab = tab()
1869 Key = term()
1870 Object = tuple()
1871
1872 Returns and removes a list of all objects with key Key in table
1873 Tab.
1874
1875 The specified Key is used to identify the object by either com‐
1876 paring equal the key of an object in an ordered_set table, or
1877 matching in other types of tables (for details on the differ‐
1878 ence, see lookup/2 and new/2).
1879
1880 test_ms(Tuple, MatchSpec) -> {ok, Result} | {error, Errors}
1881
1882 Types:
1883
1884 Tuple = tuple()
1885 MatchSpec = match_spec()
1886 Result = term()
1887 Errors = [{warning | error, string()}]
1888
1889 This function is a utility to test a match specification used in
1890 calls to select/2. The function both tests MatchSpec for "syn‐
1891 tactic" correctness and runs the match specification against
1892 object Tuple.
1893
1894 If the match specification is syntactically correct, the func‐
1895 tion either returns {ok,Result}, where Result is what would have
1896 been the result in a real select/2 call, or false if the match
1897 specification does not match object Tuple.
1898
1899 If the match specification contains errors, tuple {error,
1900 Errors} is returned, where Errors is a list of natural language
1901 descriptions of what was wrong with the match specification.
1902
1903 This is a useful debugging and test tool, especially when writ‐
1904 ing complicated select/2 calls.
1905
1906 See also: erlang:match_spec_test/3.
1907
1908 to_dets(Tab, DetsTab) -> DetsTab
1909
1910 Types:
1911
1912 Tab = tab()
1913 DetsTab = dets:tab_name()
1914
1915 Fills an already created/opened Dets table with the objects in
1916 the already opened ETS table named Tab. The Dets table is emp‐
1917 tied before the objects are inserted.
1918
1919 update_counter(Tab, Key, UpdateOp) -> Result
1920
1921 update_counter(Tab, Key, UpdateOp, Default) -> Result
1922
1923 update_counter(Tab, Key, X3 :: [UpdateOp]) -> [Result]
1924
1925 update_counter(Tab, Key, X3 :: [UpdateOp], Default) -> [Result]
1926
1927 update_counter(Tab, Key, Incr) -> Result
1928
1929 update_counter(Tab, Key, Incr, Default) -> Result
1930
1931 Types:
1932
1933 Tab = tab()
1934 Key = term()
1935 UpdateOp = {Pos, Incr} | {Pos, Incr, Threshold, SetValue}
1936 Pos = Incr = Threshold = SetValue = Result = integer()
1937 Default = tuple()
1938
1939 This function provides an efficient way to update one or more
1940 counters, without the trouble of having to look up an object,
1941 update the object by incrementing an element, and insert the
1942 resulting object into the table again. The operation is guaran‐
1943 teed to be atomic and isolated.
1944
1945 This function destructively update the object with key Key in
1946 table Tab by adding Incr to the element at position Pos. The new
1947 counter value is returned. If no position is specified, the ele‐
1948 ment directly following key (<keypos>+1) is updated.
1949
1950 If a Threshold is specified, the counter is reset to value Set‐
1951 Value if the following conditions occur:
1952
1953 * Incr is not negative (>= 0) and the result would be greater
1954 than (>) Threshold.
1955
1956 * Incr is negative (< 0) and the result would be less than (<)
1957 Threshold.
1958
1959 A list of UpdateOp can be supplied to do many update operations
1960 within the object. The operations are carried out in the order
1961 specified in the list. If the same counter position occurs more
1962 than once in the list, the corresponding counter is thus updated
1963 many times, each time based on the previous result. The return
1964 value is a list of the new counter values from each update oper‐
1965 ation in the same order as in the operation list. If an empty
1966 list is specified, nothing is updated and an empty list is
1967 returned. If the function fails, no updates are done.
1968
1969 The specified Key is used to identify the object by either
1970 matching the key of an object in a set table, or compare equal
1971 to the key of an object in an ordered_set table (for details on
1972 the difference, see lookup/2 and new/2).
1973
1974 If a default object Default is specified, it is used as the
1975 object to be updated if the key is missing from the table. The
1976 value in place of the key is ignored and replaced by the proper
1977 key value. The return value is as if the default object had not
1978 been used, that is, a single updated element or a list of them.
1979
1980 The function fails with reason badarg in the following situa‐
1981 tions:
1982
1983 * The table type is not set or ordered_set.
1984
1985 * No object with the correct key exists and no default object
1986 was supplied.
1987
1988 * The object has the wrong arity.
1989
1990 * The default object arity is smaller than <keypos>.
1991
1992 * Any field from the default object that is updated is not an
1993 integer.
1994
1995 * The element to update is not an integer.
1996
1997 * The element to update is also the key.
1998
1999 * Any of Pos, Incr, Threshold, or SetValue is not an integer.
2000
2001 update_element(Tab, Key, ElementSpec :: {Pos, Value}) -> boolean()
2002
2003 update_element(Tab, Key, ElementSpec :: [{Pos, Value}]) ->
2004 boolean()
2005
2006 Types:
2007
2008 Tab = tab()
2009 Key = term()
2010 Value = term()
2011 Pos = integer() >= 1
2012
2013 This function provides an efficient way to update one or more
2014 elements within an object, without the trouble of having to look
2015 up, update, and write back the entire object.
2016
2017 This function destructively updates the object with key Key in
2018 table Tab. The element at position Pos is given the value Value.
2019
2020 A list of {Pos,Value} can be supplied to update many elements
2021 within the same object. If the same position occurs more than
2022 once in the list, the last value in the list is written. If the
2023 list is empty or the function fails, no updates are done. The
2024 function is also atomic in the sense that other processes can
2025 never see any intermediate results.
2026
2027 Returns true if an object with key Key is found, otherwise
2028 false.
2029
2030 The specified Key is used to identify the object by either
2031 matching the key of an object in a set table, or compare equal
2032 to the key of an object in an ordered_set table (for details on
2033 the difference, see lookup/2 and new/2).
2034
2035 The function fails with reason badarg in the following situa‐
2036 tions:
2037
2038 * The table type is not set or ordered_set.
2039
2040 * Pos < 1.
2041
2042 * Pos > object arity.
2043
2044 * The element to update is also the key.
2045
2046 whereis(TableName) -> tid() | undefined
2047
2048 Types:
2049
2050 TableName = atom()
2051
2052 This function returns the tid() of the named table identified by
2053 TableName, or undefined if no such table exists. The tid() can
2054 be used in place of the table name in all operations, which is
2055 slightly faster since the name does not have to be resolved on
2056 each call.
2057
2058 If the table is deleted, the tid() will be invalid even if
2059 another named table is created with the same name.
2060
2061
2062
2063Ericsson AB stdlib 3.12.1 ets(3)