Skip to content

Instantly share code, notes, and snippets.

@alg
Created July 29, 2018 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alg/b6680f5e51e744b5a852856a1a683431 to your computer and use it in GitHub Desktop.
Save alg/b6680f5e51e744b5a852856a1a683431 to your computer and use it in GitHub Desktop.
DETS example
defmodule Server do
use Bitwise
require Record
Record.defrecord :server, id: nil, ip: nil, username: nil, password: nil
def from_id(id) do
ip = "127.#{band(id >>> 16, 0xff)}.#{band(id >>> 8, 0xff)}.#{band(id, 0xff)}"
server(id: id, ip: ip, username: "username_#{band(id, 0xff)}", password: "password")
end
end
defmodule DetsTest do
use ExUnit.Case
require Server
@count 1_000_000
test "foo" do
{:ok, db} = :dets.open_file(:foo_db, [{:auto_save, 1000}, {:keypos, Server.server(:id) + 1}, {:file, './foo_db.dets'}])
# Insert records if the count is wrong
if :dets.info(db)[:size] < @count do
data = Enum.map(1..@count, &Server.from_id/1)
:dets.insert(db, data)
end
# Output dets table info
IO.inspect :dets.info(db)
# Find server with ID=1234
rec = :dets.lookup(db, 1234)
IO.inspect rec
# Find IDs of servers sharing username = "username_210"
# Returns the array of IDs (notice the $1 saying the first field
# should be in the first place of the resulting record)
recs = :dets.match(db, {:server, :"$1", :_, "username_210", :_})
IO.puts "Found #{length(recs)} records"
IO.inspect recs
# Find all records of servers sharing username = "username_210"
# Returns the array of full records
recs = :dets.match_object(db, {:server, :_, :_, "username_210", :_})
# We turn tuples into Elixir records before display this time
IO.puts "Found #{length(recs)} records"
IO.inspect Enum.map(recs, &(Server.server(&1)))
:dets.close(db)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment