Home > database >  How to generate id by AUTO_INCREMENT in ETS?
How to generate id by AUTO_INCREMENT in ETS?

Time:01-11

I tried to write a wrapper for ets with which you can read and write structures in etc, question is: how to make id to be generated automatically

  defmodule StructTable do
     defstruct  id: 0, data: nil

     def create_table do
       :ets.new(__MODULE__, [:orderedset, :named_table, {:keypos, 1}])
     end

     def insert_into_table(%__MODULE__{ id: id, data: data}) do
       if hd(:ets.lookup(__MODULE__, id)) == false do
          :ets.insert(__MODULE__, {id,data})
         else "already exists"
       end
     end

     def select_data(iid) do
       hd(:ets.lookup(__MODULE__, iid))
     end

     def select_all do
       :ets.tab2list(__MODULE__)
     end

  end

CodePudding user response:

There may be a better way, but it looks like your access to the table is the default "protected" where only the owner process can write to it, so I would tend to have the ETS table wrapped in an owner GenServer that all the writes go through (the table would get created when the GenServer is started). Then the GenServer state maintains the index sequence--when it receives a struct to insert it applies the current index before insertion and increments the sequence in its state.

  • Related