View Source ETS.Bag (ets v0.9.0)

Module for creating and interacting with :ets tables of the type :bag and :duplicate_bag.

Bags contain "records" which are tuples. Bags are configured with a key position via the keypos: integer option. If not specified, the default key position is 1. The element of the tuple record at the key position is that records key. For example, setting the keypos to 2 means the key of an inserted record {:a, :b} is :b:

iex> {:ok, bag} = Bag.new(keypos: 2)
iex> Bag.add!(bag, {:a, :b})
iex> Bag.lookup(bag, :a)
{:ok, []}
iex> Bag.lookup(bag, :b)
{:ok, [{:a, :b}]}

When a record is added to the table with add_new will only add the record if a matching key doesn't already exist.

examples

Examples

iex> {:ok, bag} = Bag.new()
iex> Bag.add_new!(bag, {:a, :b, :c})
iex> Bag.to_list!(bag)
[{:a, :b, :c}]
iex> Bag.add_new!(bag, {:d, :e, :f})
iex> Bag.to_list!(bag)
[{:d, :e, :f}, {:a, :b, :c}]
iex> Bag.add_new!(bag, {:a, :g, :h})
iex> Bag.to_list!(bag)
[{:d, :e, :f}, {:a, :b, :c}]

add and add_new take either a single tuple or a list of tuple records. When adding multiple records, they are added in an atomic an isolated manner. add_new doesn't add any records if any of the new keys already exist in the bag.

By default, Bags allow duplicate records (each element of the tuple record is identical). To prevent duplicate records, set the duplicate: false opt when creating the Bag (if you want to prevent duplicate keys, use an ETS.Set instead). Note that duplicate: false will increase the time it takes to add records as the table must be checked for duplicates prior to insert. duplicate: true maps to the :ets table type :duplicate_bag, duplicate: false maps to :bag.

working-with-named-tables

Working with named tables

The functions on ETS.Bag require that you pass in an ETS.Bag as the first argument. In some design patterns, you may have the table name but an instance of an ETS.Bag may not be available to you. If this is the case, you should use wrap_existing/1 to turn your table name atom into an ETS.Bag. For example, a GenServer that handles writes within the server, but reads in the client process would be implemented like this:

defmodule MyExampleGenServer do
  use GenServer
  alias ETS.Bag

  # Client Functions

  def get_roles_for_user(user_id) do
    :my_role_table
    |> Bag.wrap_existing!()
    |> Bag.lookup!(user_id)
    |> Enum.map(&elem(&1, 1))
  end

  def add_role_for_user(user_id, role) do
    GenServer.call(__MODULE__, {:add_role_for_user, user_id, role})
  end

  # Server Functions

  def init(_) do
    {:ok, %{bag: Bag.new!(name: :my_role_table)}}
  end

  def handle_call({:add_role_for_user, user_id, role}, _from, %{bag: bag}) do
    Bag.add(bag, {user_id, role})
  end
end

Link to this section Summary

Functions

Waits to accept ownership of a table after it is given away. Successful receipt will return {:ok, %{bag: bag, from: from, gift: gift}} where from is the pid of the previous owner, and gift is any additional metadata sent with the table.

For processes which may receive ownership of a Bag unexpectedly - either via give_away/3 or by being named the Bag's heir (see new/1) - the module should include at least one accept clause. For example, if we want a server to inherit Bags after their previous owner dies

Adds tuple record or list of tuple records to table.

Same as add/3 but unwraps or raises on error.

Same as add/2 but doesn't add any records if one of the given keys already exists.

Same as add_new/2 but unwraps or raises on error.

Deletes specified Bag.

Deletes record with specified key in specified Bag.

Same as delete/1 but unwraps or raises on error.

Same as delete/2 but unwraps or raises on error.

Deletes all records in specified Bag.

Same as delete_all/1 but unwraps or raises on error.

Returns underlying :ets table reference.

Same as get_table/1 but unwraps or raises on error

Transfers ownership of a Bag to another process.

Same as give_away/3 but unwraps or raises on error.

Determines if specified key exists in specified bag.

Same as has_key/2 but unwraps or raises on error.

Returns information on the bag.

Same as info/1 but unwraps or raises on error.

Returns list of records with specified key.

Same as lookup/3 but unwraps or raises on error.

Returns list of elements in specified position of records with specified key.

Same as lookup_element/3 but unwraps or raises on error.

Matches next bag of records from a match/3 or match/1 continuation.

Returns records in the Bag that match the specified pattern.

Same as match/2 but limits number of results to the specified limit.

Same as match/1 but unwraps or raises on error.

Same as match/2 but unwraps or raises on error.

Same as match/3 but unwraps or raises on error.

Deletes all records that match the given pattern.

Same as match_delete/2 but unwraps or raises on error.

Matches next records from a match/3 or match/1 continuation.

Returns full records that match the specified pattern.

Same as match/2 but limits number of results to the specified limit.

Same as match_object/1 but unwraps or raises on error.

Same as match_object/2 but unwraps or raises on error.

Same as match_object/3 but unwraps or raises on error.

Creates new bag module with the specified options.

Same as new/1 but unwraps or raises on error.

Returns records in the specified Bag that match the specified match specification.

Same as select/2 but unwraps or raises on error.

Deletes records in the specified Bag that match the specified match specification.

Same as select_delete/2 but unwraps or raises on error.

Returns contents of table as a list.

Same as to_list/1 but unwraps or raises on error.

Wraps an existing :ets :bag or :duplicate_bag in a Bag struct.

Same as wrap_existing/1 but unwraps or raises on error.

Link to this section Types

Specs

bag_options() :: [ETS.Base.option() | {:duplicate, boolean()}]

Specs

t() :: %ETS.Bag{
  duplicate: boolean(),
  info: keyword(),
  table: ETS.table_reference()
}

Link to this section Functions

Link to this function

accept(timeout \\ :infinity)

View Source

Waits to accept ownership of a table after it is given away. Successful receipt will return {:ok, %{bag: bag, from: from, gift: gift}} where from is the pid of the previous owner, and gift is any additional metadata sent with the table.

A timeout may be given in milliseconds, which will return {:error, :timeout} if reached.

See give_away/3 for more information.

Link to this macro

accept(id, table, from, state, list)

View Source (macro)

For processes which may receive ownership of a Bag unexpectedly - either via give_away/3 or by being named the Bag's heir (see new/1) - the module should include at least one accept clause. For example, if we want a server to inherit Bags after their previous owner dies:

defmodule Receiver do
  use GenServer
  alias ETS.Bag
  require ETS.Bag

  ...

  Bag.accept :owner_crashed, bag, _from, state do
    new_state = Map.update!(state, :crashed_bags, &[bag | &1])
    {:noreply, new_state}
  end

The first argument is a unique identifier which should match either the "heir_data" in new/1, or the "gift" in give_away/3. The other arguments declare the variables which may be used in the do block: the received Bag, the pid of the previous owner, and the current state of the process.

The return value should be in the form {:noreply, new_state}, or one of the similar returns expected by handle_info/handle_cast.

Specs

add(t(), tuple() | [tuple()]) :: {:ok, t()} | {:error, any()}

Adds tuple record or list of tuple records to table.

If Bag has duplicate: false, will overwrite duplicate records (full tuple must match, not just key).

Inserts multiple records in an atomic and isolated manner.

examples

Examples

iex> {:ok, bag} = Bag.new()
iex> {:ok, _} = Bag.add(bag, [{:a, :b, :c}, {:d, :e, :f}])
iex> {:ok, _} = Bag.add(bag, {:a, :h, :i})
iex> {:ok, _} = Bag.add(bag, {:d, :x, :y})
iex> {:ok, _} = Bag.add(bag, {:d, :e, :f})
iex> Bag.to_list(bag)
{:ok, [{:d, :e, :f}, {:d, :x, :y}, {:d, :e, :f}, {:a, :b, :c}, {:a, :h, :i}]}

iex> {:ok, bag} = Bag.new(duplicate: false)
iex> {:ok, _} = Bag.add(bag, [{:a, :b, :c}, {:d, :e, :f}])
iex> {:ok, _} = Bag.add(bag, {:a, :h, :i})
iex> {:ok, _} = Bag.add(bag, {:d, :x, :y})
iex> {:ok, _} = Bag.add(bag, {:d, :e, :f}) # won't insert due to duplicate: false
iex> Bag.to_list(bag)
{:ok, [{:d, :e, :f}, {:d, :x, :y}, {:a, :b, :c}, {:a, :h, :i}]}
Link to this function

add!(bag, record_or_records)

View Source

Specs

add!(t(), tuple() | [tuple()]) :: t()

Same as add/3 but unwraps or raises on error.

Specs

add_new(t(), tuple() | [tuple()]) :: {:ok, t()} | {:error, any()}

Same as add/2 but doesn't add any records if one of the given keys already exists.

examples

Examples

iex> bag = Bag.new!()
iex> {:ok, _} = Bag.add_new(bag, [{:a, :b, :c}, {:d, :e, :f}])
iex> {:ok, _} = Bag.add_new(bag, [{:a, :x, :y}, {:g, :h, :i}]) # skips due to duplicate :a key
iex> {:ok, _} = Bag.add_new(bag, {:d, :z, :zz}) # skips due to duplicate :d key
iex> Bag.to_list!(bag)
[{:d, :e, :f}, {:a, :b, :c}]
Link to this function

add_new!(bag, record_or_records)

View Source

Specs

add_new!(t(), tuple() | [tuple()]) :: t()

Same as add_new/2 but unwraps or raises on error.

Specs

delete(t()) :: {:ok, t()} | {:error, any()}

Deletes specified Bag.

examples

Examples

iex> {:ok, bag} = Bag.new()
iex> {:ok, _} = Bag.info(bag, true)
iex> {:ok, _} = Bag.delete(bag)
iex> Bag.info(bag, true)
{:error, :table_not_found}

Specs

delete(t(), any()) :: {:ok, t()} | {:error, any()}

Deletes record with specified key in specified Bag.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.add(bag, {:a, :b, :c})
iex> Bag.delete(bag, :a)
iex> Bag.lookup!(bag, :a)
[]

Specs

delete!(t()) :: t()

Same as delete/1 but unwraps or raises on error.

Specs

delete!(t(), any()) :: t()

Same as delete/2 but unwraps or raises on error.

Specs

delete_all(t()) :: {:ok, t()} | {:error, any()}

Deletes all records in specified Bag.

examples

Examples

iex> bag = Bag.new!()
iex> bag
iex> |> Bag.add!({:a, :b, :c})
iex> |> Bag.add!({:b, :b, :c})
iex> |> Bag.add!({:c, :b, :c})
iex> |> Bag.to_list!()
[{:c, :b, :c}, {:b, :b, :c}, {:a, :b, :c}]
iex> Bag.delete_all(bag)
iex> Bag.to_list!(bag)
[]

Specs

delete_all!(t()) :: t()

Same as delete_all/1 but unwraps or raises on error.

Specs

get_table(t()) :: {:ok, ETS.table_reference()}

Returns underlying :ets table reference.

For use in functions that are not yet implemented. If you find yourself using this, please consider submitting a PR to add the necessary function to ETS.

examples

Examples

iex> bag = Bag.new!(name: :my_ets_table)
iex> {:ok, table} = Bag.get_table(bag)
iex> info = :ets.info(table)
iex> info[:name]
:my_ets_table

Specs

get_table!(t()) :: ETS.table_reference()

Same as get_table/1 but unwraps or raises on error

Link to this function

give_away(bag, pid, gift \\ [])

View Source

Specs

give_away(t(), pid(), any()) :: {:ok, t()} | {:error, any()}

Transfers ownership of a Bag to another process.

examples

Examples

iex> bag = Bag.new!()
iex> receiver_pid = spawn(fn -> Bag.accept() end)
iex> Bag.give_away(bag, receiver_pid)
{:ok, bag}

iex> bag = Bag.new!()
iex> dead_pid = ETS.TestUtils.dead_pid()
iex> Bag.give_away(bag, dead_pid)
{:error, :recipient_not_alive}
Link to this function

give_away!(bag, pid, gift \\ [])

View Source

Specs

give_away!(t(), pid(), any()) :: t()

Same as give_away/3 but unwraps or raises on error.

Specs

has_key(t(), any()) :: {:ok, boolean()} | {:error, any()}

Determines if specified key exists in specified bag.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.has_key(bag, :key)
{:ok, false}
iex> Bag.add(bag, {:key, :value})
iex> Bag.has_key(bag, :key)
{:ok, true}

Specs

has_key!(t(), any()) :: boolean()

Same as has_key/2 but unwraps or raises on error.

Link to this function

info(bag, force_update \\ false)

View Source

Specs

info(t(), boolean()) :: {:ok, keyword()} | {:error, any()}

Returns information on the bag.

Second parameter forces updated information from ets, default (false) uses in-struct cached information. Force should be used when requesting size and memory.

examples

Examples

iex> {:ok, bag} = Bag.new(duplicate: false, keypos: 3, read_concurrency: true, compressed: false)
iex> {:ok, info} = Bag.info(bag)
iex> info[:read_concurrency]
true
iex> {:ok, _} = Bag.add(bag, {:a, :b, :c})
iex> {:ok, info} = Bag.info(bag)
iex> info[:size]
0
iex> {:ok, info} = Bag.info(bag, true)
iex> info[:size]
1
Link to this function

info!(bag, force_update \\ false)

View Source

Specs

info!(t(), boolean()) :: keyword()

Same as info/1 but unwraps or raises on error.

Specs

lookup(t(), any()) :: {:ok, [tuple()]} | {:error, any()}

Returns list of records with specified key.

examples

Examples

iex> Bag.new!()
iex> |> Bag.add!({:a, :b, :c})
iex> |> Bag.add!({:d, :e, :f})
iex> |> Bag.add!({:d, :e, :g})
iex> |> Bag.lookup(:d)
{:ok, [{:d, :e, :f}, {:d, :e, :g}]}

Specs

lookup!(t(), any()) :: [tuple()]

Same as lookup/3 but unwraps or raises on error.

Link to this function

lookup_element(bag, key, pos)

View Source

Specs

lookup_element(t(), any(), non_neg_integer()) ::
  {:ok, [any()]} | {:error, any()}

Returns list of elements in specified position of records with specified key.

examples

Examples

iex> Bag.new!()
iex> |> Bag.add!({:a, :b, :c})
iex> |> Bag.add!({:d, :e, :f})
iex> |> Bag.add!({:d, :h, :i})
iex> |> Bag.lookup_element(:d, 2)
{:ok, [:e, :h]}
Link to this function

lookup_element!(bag, key, pos)

View Source

Specs

lookup_element!(t(), any(), non_neg_integer()) :: [any()]

Same as lookup_element/3 but unwraps or raises on error.

Specs

match(any()) :: {:ok, {[tuple()], any() | :end_of_table}} | {:error, any()}

Matches next bag of records from a match/3 or match/1 continuation.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.add!(bag, [{:a, :b, :c, :d}, {:e, :b, :f, :g}, {:h, :b, :i, :j}])
iex> {:ok, {results, continuation}} = Bag.match(bag, {:"$1", :b, :"$2", :_}, 2)
iex> results
[[:e, :f], [:a, :c]]
iex> {:ok, {records2, continuation2}} = Bag.match(continuation)
iex> records2
[[:h, :i]]
iex> continuation2
:end_of_table

Specs

match(t(), ETS.match_pattern()) :: {:ok, [tuple()]} | {:error, any()}

Returns records in the Bag that match the specified pattern.

For more information on the match pattern, see the erlang documentation

examples

Examples

iex> Bag.new!()
iex> |> Bag.add!([{:a, :b, :c, :d}, {:e, :c, :f, :g}, {:h, :b, :i, :j}])
iex> |> Bag.match({:"$1", :b, :"$2", :_})
{:ok, [[:h, :i], [:a, :c]]}
Link to this function

match(bag, pattern, limit)

View Source

Specs

match(t(), ETS.match_pattern(), non_neg_integer()) ::
  {:ok, {[tuple()], any() | :end_of_table}} | {:error, any()}

Same as match/2 but limits number of results to the specified limit.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.add!(bag, [{:a, :b, :c, :d}, {:e, :b, :f, :g}, {:h, :b, :i, :j}])
iex> {:ok, {results, _continuation}} = Bag.match(bag, {:"$1", :b, :"$2", :_}, 2)
iex> results
[[:e, :f], [:a, :c]]

Specs

match!(any()) :: {[tuple()], any() | :end_of_table}

Same as match/1 but unwraps or raises on error.

Specs

match!(t(), ETS.match_pattern()) :: [tuple()]

Same as match/2 but unwraps or raises on error.

Link to this function

match!(bag, pattern, limit)

View Source

Specs

match!(t(), ETS.match_pattern(), non_neg_integer()) ::
  {[tuple()], any() | :end_of_table}

Same as match/3 but unwraps or raises on error.

Link to this function

match_delete(bag, pattern)

View Source

Specs

match_delete(t(), ETS.match_pattern()) :: {:ok, t()} | {:error, any()}

Deletes all records that match the given pattern.

Always returns :ok, regardless of whether anything was deleted or not.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.add!(bag, [{:a, :b, :c, :d}, {:e, :b, :f, :g}, {:a, :i, :j, :k}])
iex> Bag.match_delete(bag, {:_, :b, :_, :_})
{:ok, bag}
iex> Bag.to_list!(bag)
[{:a, :i, :j, :k}]
Link to this function

match_delete!(bag, pattern)

View Source

Specs

match_delete!(t(), ETS.match_pattern()) :: t()

Same as match_delete/2 but unwraps or raises on error.

Link to this function

match_object(continuation)

View Source

Specs

match_object(any()) ::
  {:ok, {[tuple()], any() | :end_of_table}} | {:error, any()}

Matches next records from a match/3 or match/1 continuation.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.add!(bag, [{:a, :b, :c}, {:a, :b, :d}, {:a, :b, :e}, {:f, :b, :g}])
iex> {:ok, {results, continuation}} = Bag.match_object(bag, {:"$1", :b, :_}, 2)
iex> results
[{:a, :b, :d}, {:a, :b, :e}]
iex> {:ok, {results2, continuation2}} = Bag.match_object(continuation)
iex> results2
[{:f, :b, :g}, {:a, :b, :c}]
iex> {:ok, {[], :end_of_table}} = Bag.match_object(continuation2)
Link to this function

match_object(bag, pattern)

View Source

Specs

match_object(t(), ETS.match_pattern()) :: {:ok, [tuple()]} | {:error, any()}

Returns full records that match the specified pattern.

For more information on the match pattern, see the erlang documentation

examples

Examples

iex> Bag.new!()
iex> |> Bag.add!([{:a, :b, :c, :d}, {:e, :c, :f, :g}, {:h, :b, :i, :j}])
iex> |> Bag.match_object({:"$1", :b, :"$2", :_})
{:ok, [{:h, :b, :i, :j}, {:a, :b, :c, :d}]}
Link to this function

match_object(bag, pattern, limit)

View Source

Specs

match_object(t(), ETS.match_pattern(), non_neg_integer()) ::
  {:ok, {[tuple()], any() | :end_of_table}} | {:error, any()}

Same as match/2 but limits number of results to the specified limit.

examples

Examples

iex> bag = Bag.new!()
iex> Bag.add!(bag, [{:a, :b, :c, :d}, {:e, :b, :f, :g}, {:h, :b, :i, :j}])
iex> {:ok, {results, _continuation}} = Bag.match_object(bag, {:"$1", :b, :"$2", :_}, 2)
iex> results
[{:e, :b, :f, :g}, {:a, :b, :c, :d}]
Link to this function

match_object!(continuation)

View Source

Specs

match_object!(any()) :: {[tuple()], any() | :end_of_table}

Same as match_object/1 but unwraps or raises on error.

Link to this function

match_object!(bag, pattern)

View Source

Specs

match_object!(t(), ETS.match_pattern()) :: [tuple()]

Same as match_object/2 but unwraps or raises on error.

Link to this function

match_object!(bag, pattern, limit)

View Source

Specs

match_object!(t(), ETS.match_pattern(), non_neg_integer()) ::
  {[tuple()], any() | :end_of_table}

Same as match_object/3 but unwraps or raises on error.

Specs

new(bag_options()) :: {:error, any()} | {:ok, t()}

Creates new bag module with the specified options.

Note that the underlying :ets table will be attached to the process that calls new and will be destroyed if that process dies.

Possible options:

  • name: when specified, creates a named table with the specified name
  • duplicate: when true, allows multiple identical records. (default true)
  • protection: :private, :protected, :public (default :protected)
  • heir: :none | {heir_pid, heir_data} (default :none)
  • keypos: integer (default 1)
  • read_concurrency: boolean (default false)
  • write_concurrency: boolean (default false)
  • compressed: boolean (default false)

examples

Examples

iex> {:ok, bag} = Bag.new(duplicate: false, keypos: 3, read_concurrency: true, compressed: false)
iex> Bag.info!(bag)[:read_concurrency]
true

# Named :ets tables via the name keyword
iex> {:ok, bag} = Bag.new(name: :my_ets_table)
iex> Bag.info!(bag)[:name]
:my_ets_table

Specs

new!(bag_options()) :: t()

Same as new/1 but unwraps or raises on error.

Specs

select(t(), ETS.match_spec()) :: {:ok, [tuple()]} | {:error, any()}

Returns records in the specified Bag that match the specified match specification.

For more information on the match specification, see the erlang documentation

examples

Examples

iex> Bag.new!()
iex> |> Bag.add!([{:a, :b, :c, :d}, {:e, :c, :f, :g}, {:h, :b, :i, :j}])
iex> |> Bag.select([{{:"$1", :b, :"$2", :_},[],[:"$$"]}])
{:ok, [[:h, :i], [:a, :c]]}

Specs

select!(t(), ETS.match_spec()) :: [tuple()]

Same as select/2 but unwraps or raises on error.

Link to this function

select_delete(bag, spec)

View Source

Specs

select_delete(t(), ETS.match_spec()) ::
  {:ok, non_neg_integer()} | {:error, any()}

Deletes records in the specified Bag that match the specified match specification.

For more information on the match specification, see the erlang documentation

examples

Examples

iex> bag = Bag.new!()
iex> bag
iex> |> Bag.add!([{:a, :b, :c, :d}, {:e, :c, :f, :g}, {:h, :b, :c, :h}])
iex> |> Bag.select_delete([{{:"$1", :b, :"$2", :_},[{:"==", :"$2", :c}],[true]}])
{:ok, 2}
iex> Bag.to_list!(bag)
[{:e, :c, :f, :g}]
Link to this function

select_delete!(bag, spec)

View Source

Specs

select_delete!(t(), ETS.match_spec()) :: non_neg_integer()

Same as select_delete/2 but unwraps or raises on error.

Specs

to_list(t()) :: {:ok, [tuple()]} | {:error, any()}

Returns contents of table as a list.

examples

Examples

iex> Bag.new!()
iex> |> Bag.add!({:a, :b, :c})
iex> |> Bag.add!({:d, :e, :f})
iex> |> Bag.add!({:d, :e, :f})
iex> |> Bag.to_list()
{:ok, [{:d, :e, :f}, {:d, :e, :f}, {:a, :b, :c}]}

Specs

to_list!(t()) :: [tuple()]

Same as to_list/1 but unwraps or raises on error.

Link to this function

wrap_existing(table_identifier)

View Source

Specs

wrap_existing(ETS.table_identifier()) :: {:ok, t()} | {:error, any()}

Wraps an existing :ets :bag or :duplicate_bag in a Bag struct.

examples

Examples

iex> :ets.new(:my_ets_table, [:bag, :named_table])
iex> {:ok, bag} = Bag.wrap_existing(:my_ets_table)
iex> Bag.info!(bag)[:name]
:my_ets_table
Link to this function

wrap_existing!(table_identifier)

View Source

Specs

wrap_existing!(ETS.table_identifier()) :: t()

Same as wrap_existing/1 but unwraps or raises on error.