Skip to content

Quick start

Use this guide in an existing Gleam application. You will save two entries, stop the application, and read the entries in a second run.

From your project directory, run:

Terminal window
gleam add shelf
mkdir -p /tmp/shelf-quick-start

This example uses a temporary directory. For application data you need to keep, choose a directory that survives system cleanup.

Replace your application's main module with:

import gleam/dynamic/decode
import gleam/io
import shelf/set
pub fn main() -> Nil {
let assert Ok(table) =
set.open(
name: "users",
path: "users.dets",
base_directory: "/tmp/shelf-quick-start",
key: decode.string,
value: decode.int,
)
let assert Ok(Nil) = set.insert(into: table, key: "alice", value: 42)
let assert Ok(Nil) = set.insert(into: table, key: "bob", value: 99)
let assert Ok(42) = set.lookup(from: table, key: "alice")
let assert Ok(Nil) = set.save(table)
let assert Ok(Nil) = set.close(table)
io.println("Saved users to DETS.")
}

Run gleam run. The application prints Saved users to DETS. and exits. Writes use ETS in the default WriteBack mode. save() snapshots them to DETS; successful close() also saves before releasing the table.

Replace the main module with this version, which does not insert any data:

import gleam/dynamic/decode
import gleam/io
import shelf/set
pub fn main() -> Nil {
let assert Ok(table) =
set.open(
name: "users",
path: "users.dets",
base_directory: "/tmp/shelf-quick-start",
key: decode.string,
value: decode.int,
)
let assert Ok(42) = set.lookup(from: table, key: "alice")
let assert Ok(99) = set.lookup(from: table, key: "bob")
let assert Ok(Nil) = set.close(table)
io.println("Saved users loaded from DETS.")
}

Run gleam run again. The message Saved users loaded from DETS. confirms that the second application loaded the saved entries. Your decoders checked their keys and values before they reached ETS.

The let assert statements make this small example stop on an error. In application code, handle the returned Result so you can report or recover from storage errors.

Use set tables for one value per key, or bag tables for distinct values under one key. To decide when changes reach DETS and what survives a crash, read write modes. For save, reload, sync, and close behavior, see persistence operations.