Search Apps Documentation Source Content File Folder Download Copy Actions Download State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

datastore.gno

1.52 Kb · 58 lines
 1// Package datastore provides support to store multiple collections of records.
 2package datastore
 3
 4import (
 5	"errors"
 6
 7	"gno.land/p/nt/bptree/v0"
 8)
 9
10// ErrStorageExists indicates that a storage exists with the same name.
11var ErrStorageExists = errors.New("a storage with the same name exists")
12
13// NewDatastore creates a new store.
14func NewDatastore() *Datastore {
15	return &Datastore{
16		storages: bptree.NewBPTree32(),
17	}
18}
19
20// Datastore is a store that can contain multiple named storages.
21// A storage is a collection of records.
22//
23// Example usage:
24//
25//	// Create an empty storage to store user records
26//	var db Datastore
27//	storage := db.CreateStorage("users")
28//
29//	// Get a storage that has been created before
30//	storage = db.GetStorage("profiles")
31type Datastore struct {
32	storages *bptree.BPTree // string(name) -> *Storage
33}
34
35// CreateStorage creates a new named storage within the data store.
36func (ds *Datastore) CreateStorage(name string, options ...StorageOption) *Storage {
37	if ds.storages.Has(name) {
38		return nil
39	}
40
41	s := NewStorage(name, options...)
42	ds.storages.Set(name, &s)
43	return &s
44}
45
46// HasStorage checks if data store contains a storage with a specific name.
47func (ds *Datastore) HasStorage(name string) bool {
48	return ds.storages.Has(name)
49}
50
51// GetStorage returns a storage that has been created with a specific name.
52// It returns nil when a storage with the specified name is not found.
53func (ds *Datastore) GetStorage(name string) *Storage {
54	if s, ok := ds.storages.Get(name).(*Storage); ok {
55		return s
56	}
57	return nil
58}