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 before starting the Erlang  runtime
30       system. This hard limit has been removed, but it is currently useful to
31       set the ERL_MAX_ETS_TABLES anyway. It should be set to  an  approximate
32       of  the maximum amount of tables used. This since an internal table for
33       named tables is sized using this  value.  If  large  amounts  of  named
34       tables  are used and ERL_MAX_ETS_TABLES hasn't been increased, the per‐
35       formance of named table lookup will degrade.
36
37
38       Notice that there is no automatic garbage collection for  tables.  Even
39       if there are no references to a table from any process, it is not auto‐
40       matically destroyed unless the owner process terminates. To  destroy  a
41       table  explicitly,  use  function  delete/1.  The  default owner is the
42       process that created the table. To transfer table ownership at  process
43       termination, use option heir or call give_away/3.
44
45       Some implementation details:
46
47         * In  the  current  implementation,  every  object insert and look-up
48           operation results in a copy of the object.
49
50         * '$end_of_table' is not to be used as a key, as this atom is used to
51           mark the end of the table when using functions first/1 and next/2.
52
53       Notice  the  subtle  difference  between  matching and comparing equal,
54       which is demonstrated by table types set and ordered_set:
55
56         * Two Erlang terms match if they are of the same type  and  have  the
57           same  value,  so that 1 matches 1, but not 1.0 (as 1.0 is a float()
58           and not an integer()).
59
60         * Two Erlang terms compare equal if they either are of the same  type
61           and  value,  or  if  both  are numeric types and extend to the same
62           value, so that 1 compares equal to both 1 and 1.0.
63
64         * The ordered_set works on the Erlang term order and no defined order
65           exists  between an integer() and a float() that extends to the same
66           value. Hence the key 1 and the key 1.0 are regarded as equal in  an
67           ordered_set table.
68

FAILURE

70       The  functions  in this module exits with reason badarg if any argument
71       has the wrong format, if the table identifier is  invalid,  or  if  the
72       operation  is  denied because of table access rights (protected or pri‐
73       vate).
74

CONCURRENCY

76       This module provides some limited support for  concurrent  access.  All
77       updates  to  single  objects  are guaranteed to be both atomic and iso‐
78       lated. This means that an updating operation to a single object  either
79       succeeds or fails completely without any effect (atomicity) and that no
80       intermediate results of the update can be seen by other processes (iso‐
81       lation).  Some  functions that update many objects state that they even
82       guarantee atomicity and isolation for the entire operation. In database
83       terms the isolation level can be seen as "serializable", as if all iso‐
84       lated operations are carried out serially, one after  the  other  in  a
85       strict order.
86
87       No  other  support is available within this module that would guarantee
88       consistency between objects. However, function safe_fixtable/2  can  be
89       used  to guarantee that a sequence of first/1 and next/2 calls traverse
90       the table without errors and that each existing object in the table  is
91       visited  exactly once, even if another (or the same) process simultane‐
92       ously deletes or inserts objects into the table. Nothing else is  guar‐
93       anteed;  in particular objects that are inserted or deleted during such
94       a traversal can be visited once or not at all.  Functions  that  inter‐
95       nally traverse over a table, like select and match, give the same guar‐
96       antee as safe_fixtable.
97

MATCH SPECIFICATIONS

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

DATA TYPES

104       access() = public | protected | private
105
106       continuation()
107
108              Opaque  continuation  used  by  select/1,3,  select_reverse/1,3,
109              match/1,3, and match_object/1,3.
110
111       match_spec() = [{match_pattern(), [term()], [term()]}]
112
113              A match specification, see above.
114
115       comp_match_spec()
116
117              A compiled match specification.
118
119       match_pattern() = atom() | tuple()
120
121       tab() = atom() | tid()
122
123       tid()
124
125              A table identifier, as returned by new/2.
126
127       type() = set | ordered_set | bag | duplicate_bag
128

EXPORTS

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