How to check if a named table exists or not in ETS Erlang/Elixir
Asked Answered
R

4

8

I want to create a table in ets if it does not exists . How can I check if this named exists or not ?

Rosyrot answered 30/8, 2018 at 10:36 Comment(1)
I recommend to create it in try..catch expression.Southland
S
15

You can use :ets.whereis/1. It will return :undefined if the named table does not exist:

iex(1)> :ets.new :foo, [:named_table]
:foo
iex(2)> :ets.whereis :foo
#Reference<0.2091350666.119668737.256142>
iex(3)> :ets.whereis :bar
:undefined
Southwards answered 30/8, 2018 at 10:41 Comment(3)
iex(14)> :ets.new :foo, [:named_table] :foo iex(15)> :ets.whereis :foo ** (UndefinedFunctionError) function :ets.whereis/1 is undefined or private (stdlib) :ets.whereis(:foo)Rosyrot
What version of Erlang are you on? You can also try :ets.info(:foo).Southwards
ets:whereis was introduced in Erlang/OTP 21.0.Eph
I
1

If you're on an older version of Erlang, you can create a lookup function:

def lookup(server, name) do
  case :ets.lookup(server, name) do
    [{^name, pid}] -> {:ok, pid}
    [] -> :error
  end
end

Information taken from: https://elixir-lang.org/getting-started/mix-otp/ets.html

Inapprehensive answered 1/9, 2018 at 15:1 Comment(2)
This will raise a badarg error if the table doesn't exist.Eph
Yep. That is true.Inapprehensive
D
1

Your best best is just to see if the table is in the list of all tables. A check as simple as this should be good:

lists:member(table_name,ets:all())

This returns a simple boolean() that you can use in a case to base actions on.

Deity answered 12/3, 2019 at 17:4 Comment(0)
D
0

This should do the trick:

def create_table? do 
  if Enum.member?(:ets.all(), :my_table) == false do
      :ets.new(:my_table, [:public, :named_table])
  end
end
Dextroamphetamine answered 2/6, 2020 at 2:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.