Table of Contents
API Reference
Detailed documentation for every method on the Store type.
New
func New(dbPath string) (*Store, error)
Opens or creates a SQLite database at dbPath. Use ":memory:" for an ephemeral in-memory store (useful for tests).
On creation, the function:
- Opens the SQLite connection via
modernc.org/sqlite(pure Go, no CGO) - Enables WAL journal mode for concurrent read performance
- Creates the
kvtable if it does not exist
// File-backed store
s, err := store.New("/home/user/.config/myapp/data.db")
// In-memory store for testing
s, err := store.New(":memory:")
Schema
CREATE TABLE IF NOT EXISTS kv (
grp TEXT NOT NULL,
key TEXT NOT NULL,
value TEXT NOT NULL,
PRIMARY KEY (grp, key)
)
The composite primary key (grp, key) ensures uniqueness within each group while allowing the same key name across different groups.
Close
func (s *Store) Close() error
Closes the underlying SQLite connection. Always defer this after opening:
s, err := store.New("app.db")
if err != nil {
log.Fatal(err)
}
defer s.Close()
Get
func (s *Store) Get(group, key string) (string, error)
Retrieves a single value. Returns store.ErrNotFound (wrapped) if the key does not exist:
val, err := s.Get("settings", "theme")
if errors.Is(err, store.ErrNotFound) {
val = "default"
}
Set
func (s *Store) Set(group, key, value string) error
Stores a value using UPSERT semantics (INSERT ... ON CONFLICT DO UPDATE). If the key already exists in the group, its value is overwritten:
_ = s.Set("session", "token", "abc123")
_ = s.Set("session", "token", "xyz789") // Overwrites
val, _ := s.Get("session", "token")
// val == "xyz789"
Delete
func (s *Store) Delete(group, key string) error
Removes a single key from a group. No error is returned if the key does not exist:
_ = s.Delete("session", "token")
DeleteGroup
func (s *Store) DeleteGroup(group string) error
Removes all keys in a group in a single operation:
_ = s.Set("cache", "a", "1")
_ = s.Set("cache", "b", "2")
_ = s.DeleteGroup("cache")
count, _ := s.Count("cache")
// count == 0
Count
func (s *Store) Count(group string) (int, error)
Returns the number of keys in a group:
count, err := s.Count("config")
fmt.Printf("%d keys in config\n", count)
GetAll
func (s *Store) GetAll(group string) (map[string]string, error)
Retrieves all key-value pairs in a group as a map:
_ = s.Set("env", "APP_NAME", "Core")
_ = s.Set("env", "APP_DEBUG", "true")
all, err := s.GetAll("env")
// all == map[string]string{"APP_NAME": "Core", "APP_DEBUG": "true"}
Returns an empty map (not nil) if the group has no keys.
ErrNotFound
var ErrNotFound = errors.New("store: not found")
Sentinel error returned by Get when the requested key does not exist. Use errors.Is for checking:
_, err := s.Get("group", "missing")
if errors.Is(err, store.ErrNotFound) {
// Handle missing key
}
The actual error message includes the group and key for debugging: store.Get: group/missing: store: not found.
See also: Home | Template-Rendering