Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

erlang

elixir

ets

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

like image 227
Arun Dhyani Avatar asked Aug 30 '18 10:08

Arun Dhyani


2 Answers

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
like image 106
Dogbert Avatar answered Oct 24 '22 04:10

Dogbert


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

like image 22
Clinton Avatar answered Oct 24 '22 06:10

Clinton