1ets(3)                     Erlang Module Definition                     ets(3)
2
3
4

NAME

6       ets - Built-in term storage.
7

DESCRIPTION

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

FAILURE

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

CONCURRENCY

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

TABLE TRAVERSAL

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       Traversals  using  match  and select functions may not need to scan the
125       entire table depending on how the key is  specified.  A  match  pattern
126       with  a fully bound key (without any match variables) will optimize the
127       operation to a single key lookup without any table  traversal  at  all.
128       For  ordered_set a partially bound key will limit the traversal to only
129       scan a subset of the table based on term order. A partially  bound  key
130       is either a list or a tuple with a prefix that is fully bound. Example:
131
132       1> T = ets:new(t,[ordered_set]), ets:insert(T, {"555-1234", "John Smith"}).
133       true
134       2> %% Efficient search of all with area code 555
135       2> ets:match(T,{[$5,$5,$5,$- |'$1'],'$2'}).
136       [["1234","John Smith"]]
137
138

MATCH SPECIFICATIONS

140       Some  of  the  functions  use  a match specification, match_spec. For a
141       brief explanation, see select/2. For a detailed description,  see  sec‐
142       tion  Match Specifications in Erlang in ERTS User's Guide.
143

DATA TYPES

145       access() = public | protected | private
146
147       continuation()
148
149              Opaque  continuation  used  by  select/1,3,  select_reverse/1,3,
150              match/1,3, and match_object/1,3.
151
152       match_spec() = [{match_pattern(), [term()], [term()]}]
153
154              A match specification, see above.
155
156       comp_match_spec()
157
158              A compiled match specification.
159
160       match_pattern() = atom() | tuple()
161
162       tab() = atom() | tid()
163
164       tid()
165
166              A table identifier, as returned by new/2.
167
168       type() = set | ordered_set | bag | duplicate_bag
169

EXPORTS

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