kvstore

package module
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 1, 2025 License: MIT Imports: 10 Imported by: 0

README

KVStore

GoDoc Go Report Card

KVStore is an Sqlite3-backed embedded local key value store for Go, focusing on simplicity and data integrity. It currently hardcodes the CGO-free Sqlite3 library github.com/ncruces/go-sqlite3 in WAL mode as backend.

Installation

go get https://github.com/rasteric/kvstore

Development takes place at the main branch so you need to make sure to always get a release, not the current state of main.

Quick Start

package main

import (
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/rasteric/kvstore"
)

func main() {
	db := kvstore.New()
	path, err := os.MkdirTemp("", "kvstore-test")
	if err != nil {
		panic(err)
	}
	err = db.Open(path)
	if err != nil {
		panic(err)
	}
	// make sure the test dir is cleaned up afterwards
	defer func() {
		err := db.Close()
		if err != nil {
			log.Println(err)
		}
		os.RemoveAll(path)
	}()

	// checking a key value pair doesn't exist
	if _, err := db.Get("hello"); errors.Is(err, kvstore.NotFoundErr) {
		fmt.Println(`there is no key "hello"`)
	} else {
		fmt.Println(err)
	}

	// setting a key value pair
	err = db.Set("example", "hello world!")
	if err != nil {
		panic(err)
	}

	// getting the value for a key
	s, err := db.Get("example")
	if err != nil {
		panic(err)
	}
	fmt.Println(s)

	// setting a default and key info
	err = db.SetDefault("example", "have a nice day!",
        kvstore.KeyInfo{Description: "an example key",
		Category: "testing"})
	if err != nil {
		panic(err)
	}

	// reverting a key value to its default
	if err := db.Revert("example"); err != nil {
		panic(err)
	}

	s, _ = db.Get("example")
	fmt.Println(s)
}

See the tests for more examples. Notice that kvstore.NotFoundErr is returned when a get operation fails. Since all kinds of errors can occur with file-based databases, this API was chosen instead of the more common value, ok:=db.Get(key) from maps and other key value stores. Check for the error with errors.Is(err,kvstore.NotFoundErr) to distinguish it from other errors. Use SetDefault to set a default, in case of which the default is returned if no value was set.

Documentation

All API calls are in the following interface:

type KeyValueStore interface {
	Open(path string) error                   // open the database at directory path
	Close() error                             // close the database
	Set(key string, value any) error          // set the key to the given value, which must be gob serializable
	Get(key string) (any, error)              // get the value for key, NotFoundErr if there is no key
	SetMany(map[string]any) error             // set all key-value pairs in the map in one transaction
	GetAll(limit int) (map[string]any, error) // get all key-value pairs as a map
	Revert(key string) error                  // revert key to its default
	Info(key string) (KeyInfo, bool)          // returns key information for a key if it is present
	Delete(key string) error                  // remove the key and value for the key
	DeleteMany(keys []string) error           // remove all the given keys in one transaction
	SetDefault(key string,                    // set a default and info for a key
		value any,
		info KeyInfo) error
}

The path argument to Open needs to be a directory whose name is the name you wish the database to have. This is so because the a key-value store may write more than one file, for example the write-ahead log in addition to the database. The actual sqlite database s called kvstore.sqlite in the default implementation.

Endoding

This library uses Go's gob encoding to encode values in the database. This means that you have to use gob.Register(mystruct{}) if you want to store values of custom struct mystruct in the key value database. It also means that all limitations of gob encoding apply to the values stored.

License

This library is MIT licensed and free for commercial and personal use as long as the license conditions are satisfied. See the accompanying LICENSE file for more information.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AlreadyOpenErr = errors.New(`database already open`)
View Source
var NoDefaultErr = errors.New(`no default value set for given key`)
View Source
var NotFoundErr = errors.New(`key not found`)
View Source
var NotOpenErr = errors.New(`key value store is closed`)

Functions

func MarshalBinary

func MarshalBinary(v any) ([]byte, error)

MarshalBinary uses gob encoding to marshal a value to a byte slice. To encode structs, use gob.Register(yourstruct{}) to register them.

func UnmarshalBinary

func UnmarshalBinary(b []byte) (any, error)

UnmarshalBinary assumes that a gob encoded byte slice is given and nmarshals it into a variable of the empty interface type, returns an error if the data is malformed.

Types

type KVStore

type KVStore struct {
	// contains filtered or unexported fields
}

KVStore implements KvStore interface with an sqlite database backend.

func New

func New() *KVStore

New creates a new key value store that is not yet opened.

func (*KVStore) Close

func (db *KVStore) Close() error

Close closes the database.

func (*KVStore) Delete

func (db *KVStore) Delete(key string) error

Delete removes the key and value from the key value store.

func (*KVStore) DeleteMany added in v1.1.0

func (db *KVStore) DeleteMany(keys []string) error

DeleteMany removes all given keys in one transaction.

func (*KVStore) Get

func (db *KVStore) Get(key string) (any, error)

Get gets the value for the given key, the default if no value for the key is stored but a default is present, and NotFoundErr if neither of them is present.

func (*KVStore) GetAll added in v1.1.0

func (db *KVStore) GetAll(limit int) (map[string]any, error)

GetAll returns all key-value pairs as a map. If limit is 0 or negative, all key value pairs are returned. Although this is usually not advisable, this method may be used in combination with SetMany to save and load maps, i.e., use the key value store merely for persistence and keep the data in memory.

func (*KVStore) Info

func (db *KVStore) Info(key string) (KeyInfo, bool)

Info attempts to obtain information about the given key, returns false if none can be found. This method will also return false if an error occurs.

func (*KVStore) Open

func (db *KVStore) Open(path string) error

Open a database at the path specified when the database was created, which holds all database files. If directories to path/name do not exist, they are created recursively with Unix permissions 0755.

func (*KVStore) Revert

func (db *KVStore) Revert(key string) error

Revert reverts the value for the given key to its default. If no default has been set, NoDefaultErr is returned.

func (*KVStore) Set

func (db *KVStore) Set(key string, value any) error

Set sets the value for the given key, overwriting an existing value for the key if there is one.

func (*KVStore) SetDefault

func (db *KVStore) SetDefault(key string, value any, info KeyInfo) error

SetDefault sets a default value for the given key, as well as info and category.

func (*KVStore) SetMany added in v1.1.0

func (db *KVStore) SetMany(pairs map[string]any) error

SetMany sets all pairs in the given map in one transaction.

type KeyInfo

type KeyInfo struct {
	Description string
	Category    string
}

KeyInfo is provides information about a key. This is useful for preference systems.

type KeyValueStore

type KeyValueStore interface {
	Open(path string) error                   // open the database at directory path
	Close() error                             // close the database
	Set(key string, value any) error          // set the key to the given value, which must be gob serializable
	Get(key string) (any, error)              // get the value for key, NotFoundErr if there is no key
	SetMany(map[string]any) error             // set all key-value pairs in the map in one transaction
	GetAll(limit int) (map[string]any, error) // get all key-value pairs as a map
	Revert(key string) error                  // revert key to its default
	Info(key string) (KeyInfo, bool)          // returns key information for a key if it is present
	Delete(key string) error                  // remove the key and value for the key
	DeleteMany(keys []string) error           // remove all the given keys in one transaction
	SetDefault(key string,
		value any,
		info KeyInfo) error
}

KeyValueStore is the interface for a key value database.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL