Files
EdgeNode/internal/utils/kvstore/db.go

102 lines
1.9 KiB
Go
Raw Normal View History

// Copyright 2024 GoEdge CDN goedge.cdn@gmail.com. All rights reserved. Official site: https://goedge.cn .
package kvstore
import (
"errors"
2024-04-12 20:12:09 +08:00
"github.com/cockroachdb/pebble"
"sync"
)
type DB struct {
store *Store
name string
namespace string
tableMap map[string]TableInterface
2024-03-31 10:37:06 +08:00
mu sync.RWMutex
}
func NewDB(store *Store, dbName string) (*DB, error) {
if !IsValidName(dbName) {
return nil, errors.New("invalid database name '" + dbName + "'")
}
return &DB{
store: store,
name: dbName,
namespace: "$" + dbName + "$",
tableMap: map[string]TableInterface{},
}, nil
}
func (this *DB) AddTable(table TableInterface) {
table.SetNamespace([]byte(this.Namespace() + table.Name() + "$"))
table.SetDB(this)
2024-03-31 10:37:06 +08:00
this.mu.Lock()
defer this.mu.Unlock()
this.tableMap[table.Name()] = table
}
func (this *DB) Name() string {
return this.name
}
func (this *DB) Namespace() string {
return this.namespace
}
func (this *DB) Store() *Store {
return this.store
}
2024-04-12 20:12:09 +08:00
func (this *DB) Inspect(fn func(key []byte, value []byte)) error {
it, err := this.store.rawDB.NewIter(&pebble.IterOptions{
LowerBound: []byte(this.namespace),
UpperBound: append([]byte(this.namespace), 0xFF, 0xFF),
})
if err != nil {
return err
}
defer func() {
_ = it.Close()
}()
for it.First(); it.Valid(); it.Next() {
value, valueErr := it.ValueAndErr()
if valueErr != nil {
return valueErr
}
fn(it.Key(), value)
}
return nil
}
2024-04-02 19:54:04 +08:00
// Truncate the database
func (this *DB) Truncate() error {
this.mu.Lock()
defer this.mu.Unlock()
var start = []byte(this.Namespace())
return this.store.rawDB.DeleteRange(start, append(start, 0xFF), DefaultWriteOptions)
}
func (this *DB) Close() error {
2024-03-31 10:37:06 +08:00
this.mu.Lock()
defer this.mu.Unlock()
var lastErr error
for _, table := range this.tableMap {
err := table.Close()
if err != nil {
lastErr = err
}
}
return lastErr
}