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