Skip to content
immudb docker run -d --net host -it --name immudb codenotary/immudb:latest

Embedding immudb

There are cases where you don’t want a separate server but embed immudb directly in the same application process, as a library.

immudb already provides an embeddable key-value store in the embedded package. The following example shows how to create or open a store, write some data and read it back.

 1package main
 2
 3import (
 4	"context"
 5	"fmt"
 6	"log"
 7
 8	"github.com/codenotary/immudb/embedded/store"
 9)
10
11func handleErr(err error) {
12	if err != nil {
13		log.Fatal(err)
14	}
15}
16
17func main() {
18	// create/open immudb store at specified path
19	st, err := store.Open("data", store.DefaultOptions())
20	handleErr(err)
21
22	// close the store to free resources
23	defer st.Close()
24
25	// create a transaction
26	tx, err := st.NewTx(context.Background(), &store.TxOptions{Mode: store.ReadWriteTx})
27	handleErr(err)
28
29	// ensure tx is closed (it won't affect committed tx)
30	defer tx.Cancel()
31
32	// write key-value pair into the tx context, no change will be applied yet
33	err = tx.Set([]byte("hello"), nil, []byte("immutable-world!"))
34	handleErr(err)
35
36	// transaction is committed and changes are applied
37	hdr, err := tx.Commit(context.Background())
38	handleErr(err)
39
40	fmt.Printf("tx %d successfully committed\n", hdr.ID)
41
42	// fetch the latest entry of a key
43	// dsue to performance considerations, only metadata, hash, and size are returned at first
44	valRef, err := st.Get([]byte("hello"))
45	handleErr(err)
46
47	// read the actual value
48	val, err := valRef.Resolve()
49	handleErr(err)
50
51	fmt.Printf("key '%s' = '%s' found at tx %d (%d key-updates)\n", []byte("hello"), val, valRef.Tx(), valRef.HC())
52}
Edit this page on GitHub Last updated