Leavitt/pkg/core/db.go

122 lines
2.6 KiB
Go

/*
Copyright © 2022 Sameer Rahmani <lxsameer@gnu.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package core
import (
"io"
"github.com/cockroachdb/pebble"
log "github.com/sirupsen/logrus"
)
type DB struct {
connection *pebble.DB
}
var FILE int8 = 0
var ITEM int8 = 1
var TYPE int8 = 2
var TAG int8 = 4
func tagFor(value []byte, objType int8) []byte {
// Just to make the stupid go-critic to shutup
tmp := value
tmp = append(tmp, byte(objType))
return tmp
}
func CreateDB(path string) (*DB, error) {
log.Debugf("Opening up the state db at '%s'", path)
db, err := pebble.Open(path, nil)
if err != nil {
return nil, err
}
return &DB{
connection: db,
}, nil
}
func (db *DB) Set(k []byte, v []byte, item int8) error {
taggedKey := tagFor(k, item)
return db.connection.Set(taggedKey, v, pebble.Sync)
}
func (db *DB) SetItem(k []byte, v []byte) error {
return db.Set(k, v, ITEM)
}
func (db *DB) SetType(k []byte, v []byte) error {
return db.Set(k, v, TYPE)
}
func (db *DB) SetTAG(k []byte, v []byte) error {
return db.Set(k, v, TAG)
}
func (db *DB) SetFile(k []byte, v []byte) error {
return db.Set(k, v, FILE)
}
func (db *DB) GetString(k string) ([]byte, error) {
v, closer, err := db.connection.Get([]byte(k))
if err != nil {
return nil, err
}
defer closer.Close()
return v, nil
}
func (db *DB) Get(k []byte, defaultValue *[]byte) ([]byte, io.Closer, error) {
v, closer, err := db.connection.Get(k)
if err == pebble.ErrNotFound {
var defaultV []byte
if defaultValue != nil {
defaultV = *defaultValue
}
return defaultV, closer, nil
}
return v, closer, err
}
func (db *DB) GetItem(k []byte, defaultValue *[]byte) ([]byte, io.Closer, error) {
return db.Get(k, defaultValue)
}
func (db *DB) GetStringOrDefault(k string, default_ interface{}) (interface{}, error) {
v, closer, err := db.connection.Get([]byte(k))
if err == pebble.ErrNotFound {
return default_, nil
}
if err != nil {
return nil, err
}
defer closer.Close()
return v, nil
}
func (db *DB) Close() error {
return db.connection.Close()
}