Skip to content

Set tables

Set tables store one value per key. An entry is one key-value pair. If you insert a pair with an existing key, it replaces that key's value. Use set tables for caches, configuration, and key lookup.

Set tables are provided by the slate/set module and correspond to the set table type in Erlang's DETS.

The examples below manage users' ages in one table. Run the snippets in order within one function, keeping the handle open until the closing step. The final options section shows separate ways to reopen the saved file.

Create the parent directory before opening the table. Use a new file path if data/users.dets already contains data. open uses AutoRepair and ReadWrite.

import gleam/dynamic/decode
import slate
import slate/set
let assert Ok(table) = set.open("data/users.dets",
key_decoder: decode.string, value_decoder: decode.int)

Keep table for the following operations. For short-lived application tasks, use with_table to attempt cleanup when the callback returns.

Store Alice's age, then add the other users. The batch includes a new age for Alice, so it replaces her first value:

// Insert a single key-value pair (overwrites if key exists)
let assert Ok(Nil) = set.insert(table, "alice", 41)
// Batch insert multiple pairs
let assert Ok(Nil) = set.insert_list(table, [
#("alice", 42),
#("bob", 37),
#("charlie", 25),
])

A plain insert can replace a user by accident. When a new user must not replace an existing one, use insert_new. It inserts only if the key does not exist, and it returns Error(KeyAlreadyPresent) if the key exists:

let assert Ok(Nil) = set.insert_new(table, "carol", 42)
let assert Error(slate.KeyAlreadyPresent) = set.insert_new(table, "carol", 99)

The table now holds four users. Read Alice's age, and check whether a user exists before you need their value:

// Get the value for a key (returns Error(NotFound) if missing)
let assert Ok(42) = set.lookup(table, key: "alice")
let assert Error(slate.NotFound) = set.lookup(table, key: "unknown")
// Check if a key exists without retrieving the value
let assert Ok(True) = set.member(table, key: "alice")
let assert Ok(False) = set.member(table, key: "unknown")

Remove Alice by key and Bob only if his stored age still matches:

// Delete a single key
let assert Ok(Nil) = set.delete_key(table, key: "alice")
// Delete only if both the key and value match
let assert Ok(Nil) = set.delete_object(table, key: "bob", value: 37)

Carol and Charlie remain in the table. Fold over their ages to get a total of 67, or count their two entries:

// Get all entries in an unspecified order (loads the entire table into memory)
let assert Ok(entries) = set.to_list(table)
// Fold over entries in an unspecified order to compute a result
let assert Ok(total) = set.fold(table, from: 0, with: fn(acc, _key, value) {
acc + value
})
// Get the number of stored entries
let assert Ok(count) = set.size(table)

Carol has a birthday. You could look up her age, add one, and insert the result, but another process can write between those steps. update_counter changes an integer value in one atomic operation and returns the new value:

let assert Ok(43) = set.update_counter(table, "carol", 1)
// A negative increment decreases the value
let assert Ok(42) = set.update_counter(table, "carol", -1)
let assert Ok(43) = set.update_counter(table, "carol", 1)

Carol's new age is not necessarily on disk yet. DETS saves after an idle period, not at fixed intervals during continuous use. When an update must be on disk before you continue, call sync and handle its result. sync writes pending updates without closing the table:

let assert Ok(Nil) = set.sync(table)
// Pending updates are written to disk; the table remains open

The table still holds Carol and Charlie. info reports that count together with the size and location of the file:

let assert Ok(info) = set.info(table)
// info.file_size - size of the file on disk in bytes
// info.object_count - number of entries
// info.file_path - absolute path of the table file

file_path uses the normalized path from open; it does not resolve symlinks. For the 2.0 record change, see migration guidance.

You are done with the table, so close the handle. Closing writes all pending updates to disk:

let assert Ok(Nil) = set.close(table)

Closing alone keeps Carol and Charlie for the next open. To discard all entries instead, call set.delete_all(table) before closing.

The data is now in data/users.dets. When you open the file again, you can also select a repair policy and an access mode.

A file that did not close cleanly can need repair. The repair policy selects what happens in that case. Make a backup before you repair a file with data you need to keep. Repair does not guarantee recovery of all data.

Choose one of these calls. The repair policy has no effect if the table is already open.

import slate.{AutoRepair, ForceRepair, NoRepair}
import gleam/dynamic/decode
// Default: auto-repair if needed
let assert Ok(table) = set.open_with(path: "data/users.dets", repair: AutoRepair,
key_decoder: decode.string, value_decoder: decode.int)
// Repair even if the file was closed properly
let assert Ok(table) = set.open_with(path: "data/users.dets", repair: ForceRepair,
key_decoder: decode.string, value_decoder: decode.int)
// Return NeedsRepair if the file requires repair
let assert Ok(table) = set.open_with(path: "data/users.dets", repair: NoRepair,
key_decoder: decode.string, value_decoder: decode.int)

Close the handle from whichever call you choose when you finish:

let assert Ok(Nil) = set.close(table)

To read Carol's saved age without a risk of changing the file, open it with ReadOnly. This mode prevents writes through the table handle, and the file must exist:

import slate.{AutoRepair, ReadOnly}
import gleam/dynamic/decode
let assert Ok(table) = set.open_with_access(path: "data/users.dets",
repair: AutoRepair, access: ReadOnly,
key_decoder: decode.string, value_decoder: decode.int)
let assert Ok(43) = set.lookup(table, key: "carol")
// set.insert(table, "carol", 44) would return Error(AccessDenied(context))
let assert Ok(Nil) = set.close(table)