2
votes

I'm Erlang newbie. and I got a question about the ets tables.

I have two ets tables, and I need insert or delete values from both.

insert(V) ->
  ets:insert(table_test,V),
  ets:insert(table_cp,V).

delete(V)->
  ets:delete(table_test,V),
  ets:delete(table_cp,V). 

how can I guarantee the operation was success or failed in both?

for example, the insert operation, if there is something wrong at ets:insert(table_cp,V), shall I delete the value from talbe_test?

same to delete, if ets:delete(table_cp,V) failed, shall I re-insert the value ?

please help.

1
You say you are an Erlang newbie, but you already decided to avoid Mnesia? As @Amiramix's answer points out, Mnesia is the easiest way to have transaction semantics. It is built-in with Erlang, so no additional dependencies, and can be configured to be in-memory only (no filesystem access), if that is what you are trying to accomplish.marco.m

1 Answers

6
votes

What you are asking for is a transaction. ETS doesn't support transactions. Even if you don't insert the value in the other table if the first insert wasn't successful, you can't guarantee that you insert the second value if the first insert is successful because something may happen between those two writes, e.g. the process may die.

If you need transactions please consider mnesia which is built on top of ETS and provides support for transactions, even across distributed Erlang nodes.

It all depends how much you need to rely on the value being inserted to both or neither. If your application can survive (work correctly) with the value inserted only to one of those tables, or if it is able to correct the value if it's inserted incorrectly, then a programmatic handling of failures as you described may work fine. Otherwise ETS wouldn't be the right data structure.