datastore.gno

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