rosedb

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 14, 2021 License: MIT Imports: 22 Imported by: 5

README

rosedb_ico.png

 Go Report Card GitHub top language GitHub stars codecov CodeFactor Go Reference Mentioned in Awesome Go

English | 简体中文

rosedb is a fast, stable and embedded key-value (k-v) database based on bitcask. Its on-disk files are organized as WAL(Write Ahead Log) in LSM trees, optimizing for write throughput. rosedb supports a variety of data structures such as string, list, hash, set and sorted set.

rosedb is written in pure Go, easy to understand and use.

Our vision is to build an efficient k-v storage engine for Go-based applications. Feel free to give us any advices, and also please give us a star ✨,that helps a lot, thanks!

Stargazers over time

Features

  • Supports all common data structures : string, list, hash, set, zset.
  • Easy to embed (import "github.com/roseduan/rosedb").
  • Low latency and high throughput (see Benchmark).
  • Has built-in parallel execution of data modification on many provided data structures.
  • Comes with rosedb-cli for command line access, that is compatible with redis-cli.
  • Supports TTL-based key eviction.
  • Supports prefix scan and range scan for string keys.
  • Support transaction, ACID features.

Usage

Cli example

Navigate to rosedb/cmd/server and run main.go

Xnip2021-04-14_14-33-11.png

Open a new terminal, navigate to rosedb/cmd/cli, and run main.go

Xnip2021-04-14_14-35-50.png

Or you can just use redis-cli or any other redis client:

2021-05-14 上午11.19.24.png

Embedding example

Import rosedb in the application:

import "github.com/roseduan/rosedb"

Open a connection to the database:

package main

import (
	"github.com/roseduan/rosedb"
	"log"
)

func main() {
	config := rosedb.DefaultConfig()
	db, err := rosedb.Open(config)
	
	if err != nil {
		log.Fatal(err)
	}
	
  // don`t forget to close!
	defer db.Close()
	
	//...
}

Deploy and run on Docker

docker build -t="rosedb:v1.2.9" .
docker run --name=rosedb -itd -p 5200:5200 rosedb:v1.2.9
docker exec -it rosedb sh

$ rosedb-cli
127.0.0.1:5200>set hello rosedb
OK
127.0.0.1:5200>get hello
rosedb

Command

String

  • Set
  • SetNx
  • Get
  • GetSet
  • Append
  • StrLen
  • StrExists
  • StrRem
  • PrefixScan
  • RangeScan
  • Expire
  • Persist
  • TTL

List

  • LPush
  • RPush
  • LPop
  • RPop
  • LIndex
  • LRem
  • LInsert
  • LSet
  • LTrim
  • LRange
  • LLen
  • LKeyExists
  • LValExists

Hash

  • HSet
  • HSetNx
  • HGet
  • HGetAll
  • HDel
  • HExists
  • HLen
  • HKeys
  • HVals

Set

  • SAdd
  • SPop
  • SIsMember
  • SRandMember
  • SRem
  • SMove
  • SCard
  • SMembers
  • SUnion
  • SDiff

Zset

  • ZAdd
  • ZScore
  • ZCard
  • ZRank
  • ZRevRank
  • ZIncrBy
  • ZRange
  • ZRangeWithScores
  • ZRevRange
  • ZRevRangeWithScores
  • ZRem
  • ZGetByRank
  • ZRevGetByRank
  • ZScoreRange
  • ZRevScoreRange

TODO

see here.

Benchmark

Environment

  • Go version:1.14.4
  • OS: macOS Catalina 10.15.7
  • CPU: 2.6GHz 6-Core Intel Core i7
  • Memory: 16 GB 2667 MHz DDR4
  • Code: rosedb-bench
  • Other databases for comparison:
    • Badger
    • GoLevelDB
    • Pudge

Result

1,000,000 iterations

go test -bench=. -benchtime=1000000x
badger 2021/05/16 21:59:53 INFO: All 0 tables opened in 0s
badger 2021/05/16 21:59:53 INFO: Discard stats nextEmptySlot: 0
badger 2021/05/16 21:59:53 INFO: Set nextTxnTs to 0
goos: darwin
goarch: amd64
pkg: rosedb-bench
BenchmarkPutValue_BadgerDB-12                    1000000             11518 ns/op            2110 B/op         46 allocs/op
BenchmarkGetValue_BadgerDB-12                    1000000              3547 ns/op            1172 B/op         20 allocs/op
BenchmarkPutValue_GoLevelDB-12                   1000000              4659 ns/op             352 B/op          9 allocs/op
BenchmarkGetValue_GoLevelDB-12                   1000000              2838 ns/op             814 B/op         13 allocs/op
BenchmarkPutValue_Pudge-12                       1000000              8512 ns/op             791 B/op         22 allocs/op
BenchmarkGetValue_Pudge-12                       1000000              1253 ns/op             200 B/op          6 allocs/op
BenchmarkPutValue_RoseDB_KeyValRam-12            1000000              4371 ns/op             566 B/op         11 allocs/op
BenchmarkGetValue_RoseDB_KeyValRam-12            1000000               481 ns/op              56 B/op          3 allocs/op
BenchmarkPutValue_RoseDB_KeyOnlyRam-12           1000000              4255 ns/op             566 B/op         11 allocs/op
BenchmarkGetValue_RoseDB_KeyOnlyRam-12           1000000              2986 ns/op             312 B/op          8 allocs/op
PASS
ok      rosedb-bench    46.388s

2,500,000 iterations

go test -bench=. -benchtime=2500000x
badger 2021/05/16 22:06:08 INFO: All 0 tables opened in 0s
badger 2021/05/16 22:06:08 INFO: Discard stats nextEmptySlot: 0
badger 2021/05/16 22:06:08 INFO: Set nextTxnTs to 0
goos: darwin
goarch: amd64
pkg: rosedb-bench
BenchmarkPutValue_BadgerDB-12                    2500000             11660 ns/op            2150 B/op         46 allocs/op
BenchmarkGetValue_BadgerDB-12                    2500000              4180 ns/op            1222 B/op         21 allocs/op
BenchmarkPutValue_GoLevelDB-12                   2500000              4637 ns/op             336 B/op          9 allocs/op
BenchmarkGetValue_GoLevelDB-12                   2500000              2942 ns/op             817 B/op         14 allocs/op
BenchmarkPutValue_Pudge-12                       2500000              9238 ns/op             763 B/op         22 allocs/op
BenchmarkGetValue_Pudge-12                       2500000              1275 ns/op             200 B/op          6 allocs/op
BenchmarkPutValue_RoseDB_KeyValRam-12            2500000              4474 ns/op             566 B/op         11 allocs/op
BenchmarkGetValue_RoseDB_KeyValRam-12            2500000               525 ns/op              56 B/op          3 allocs/op
BenchmarkPutValue_RoseDB_KeyOnlyRam-12           2500000              4294 ns/op             566 B/op         11 allocs/op
BenchmarkGetValue_RoseDB_KeyOnlyRam-12           2500000              3038 ns/op             312 B/op          8 allocs/op
PASS
ok      rosedb-bench    119.529s

Conclusion

Badger

Stable read and write performance. Write: 11000+ ns/op. Read: 4000+ ns/op.

GoLevelDB

Write performance is almost 2.5x that of Badger. Read is almost 3000 ns/op, a little faster than that of Badger.

Pudge

Write performance is between that of GoLevelDB and Badger, almost 8500 ns/op. Read is very fast and stable, almost twice as fast as that of GoLevelDB.

RoseDB

Write performance is stable, almost the same as that of GoLevelDB, 2.5x that of Badger.

In KeyValueRamMode, since the values are all in memory, it is the fastest of all.

In KeyOnlyRamMode, it is almost the same as GoLevelDB.

Contributing

If you are intrested in contributing to rosedb, please see here: CONTRIBUTING

Contact me

If you have any questions, you can contact me by email: roseduan520@gmail.com

License

rosedb is licensed under the term of the MIT License

Documentation

Index

Constants

View Source
const (
	// DefaultAddr default rosedb server address and port.
	DefaultAddr = "127.0.0.1:5200"

	// DefaultDirPath default rosedb data dir.
	DefaultDirPath = "/tmp/rosedb_server"

	// DefaultBlockSize default db file size: 16mb.
	// If reach the size, db file will never be opened for writing.
	DefaultBlockSize = 16 * 1024 * 1024

	// DefaultMaxKeySize default max key size: 1mb.
	DefaultMaxKeySize = uint32(1 * 1024 * 1024)

	// DefaultMaxValueSize default max value size: 8mb.
	DefaultMaxValueSize = uint32(8 * 1024 * 1024)

	// DefaultReclaimThreshold default disk files reclaim threshold: 64.
	// This means that it will be reclaimed when there are at least 64 archived files on disk.
	DefaultReclaimThreshold = 64
)
View Source
const (
	StringSet uint16 = iota
	StringRem
	StringExpire
	StringPersist
)

The operations of a String Type, will be a part of Entry, the same for the other four types.

View Source
const (
	ListLPush uint16 = iota
	ListRPush
	ListLPop
	ListRPop
	ListLRem
	ListLInsert
	ListLSet
	ListLTrim
	ListLClear
	ListLExpire
)

The operations of List.

View Source
const (
	HashHSet uint16 = iota
	HashHDel
	HashHClear
	HashHExpire
)

The operations of Hash.

View Source
const (
	SetSAdd uint16 = iota
	SetSRem
	SetSMove
	SetSClear
	SetSExpire
)

The operations of Set.

View Source
const (
	ZSetZAdd uint16 = iota
	ZSetZRem
	ZSetZClear
	ZSetZExpire
)

The operations of Sorted Set.

View Source
const (

	// Separator of the extra info, some commands can`t contains it.
	ExtraSeparator = "\\0"

	// DataStructureNum the num of different data structures, there are five now(string, list, hash, set, zset).
	DataStructureNum = 5
)

Variables

View Source
var (
	// ErrEmptyKey the key is empty
	ErrEmptyKey = errors.New("rosedb: the key is empty")

	// ErrKeyNotExist key not exist
	ErrKeyNotExist = errors.New("rosedb: key not exist")

	// ErrKeyTooLarge the key too large
	ErrKeyTooLarge = errors.New("rosedb: key exceeded the max length")

	// ErrValueTooLarge the value too large
	ErrValueTooLarge = errors.New("rosedb: value exceeded the max length")

	// ErrNilIndexer the indexer is nil
	ErrNilIndexer = errors.New("rosedb: indexer is nil")

	// ErrCfgNotExist the config is not exist
	ErrCfgNotExist = errors.New("rosedb: the config file not exist")

	// ErrReclaimUnreached not ready to reclaim
	ErrReclaimUnreached = errors.New("rosedb: unused space not reach the threshold")

	// ErrExtraContainsSeparator extra contains separator
	ErrExtraContainsSeparator = errors.New("rosedb: extra contains separator \\0")

	// ErrInvalidTTL ttl is invalid
	ErrInvalidTTL = errors.New("rosedb: invalid ttl")

	// ErrKeyExpired the key is expired
	ErrKeyExpired = errors.New("rosedb: key is expired")

	// ErrDBisReclaiming reclaim and single reclaim can`t execute at the same time.
	ErrDBisReclaiming = errors.New("rosedb: can`t do reclaim and single reclaim at the same time")

	// ErrDBIsClosed db can`t be used after closed.
	ErrDBIsClosed = errors.New("rosedb: db is closed, reopen it")

	// ErrTxIsFinished tx is finished.
	ErrTxIsFinished = errors.New("rosedb: transaction is finished, create a new one")

	// ErrActiveFileIsNil active file is nil.
	ErrActiveFileIsNil = errors.New("rosedb: active file is nil")
)

Functions

This section is empty.

Types

type ArchivedFiles

type ArchivedFiles map[DataType]map[uint32]*storage.DBFile

ArchivedFiles define the archived files, which mean these files can only be read. and will never be opened for writing.

type Config

type Config struct {
	Addr    string `json:"addr" toml:"addr"`         // server address
	DirPath string `json:"dir_path" toml:"dir_path"` // rosedb dir path of db file
	// Deprecated: don`t edit the option, it will be removed in future release.
	BlockSize    int64                `json:"block_size" toml:"block_size"` // each db file size
	RwMethod     storage.FileRWMethod `json:"rw_method" toml:"rw_method"`   // db file read and write method
	IdxMode      DataIndexMode        `json:"idx_mode" toml:"idx_mode"`     // data index mode
	MaxKeySize   uint32               `json:"max_key_size" toml:"max_key_size"`
	MaxValueSize uint32               `json:"max_value_size" toml:"max_value_size"`

	// Sync is whether to sync writes from the OS buffer cache through to actual disk.
	// If false, and the machine crashes, then some recent writes may be lost.
	//
	// Note that if it is just the process that crashes (and the machine does not) then no writes will be lost.
	//
	// The default value is false.
	Sync bool `json:"sync" toml:"sync"`

	ReclaimThreshold int `json:"reclaim_threshold" toml:"reclaim_threshold"` // threshold to reclaim disk
}

Config the opening options of rosedb.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig get the default config.

type DataIndexMode

type DataIndexMode int

DataIndexMode the data index mode.

const (
	// KeyValueMemMode key and value are both in memory, read operation will be very fast in this mode.
	// Because there is no disk seek, just get value from the corresponding data structures in memory.
	// This mode is suitable for scenarios where the value are relatively small.
	KeyValueMemMode DataIndexMode = iota

	// KeyOnlyMemMode only key in memory, there is a disk seek while getting a value.
	// Because values are in db file on disk.
	KeyOnlyMemMode
)

type DataType

type DataType = uint16

DataType Define the data structure type.

const (
	String DataType = iota
	List
	Hash
	Set
	ZSet
)

Five different data types, support String, List, Hash, Set, Sorted Set right now.

type Expires added in v1.2.8

type Expires map[DataType]map[string]int64

Expires saves the expire info of different keys.

type HashIdx

type HashIdx struct {
	// contains filtered or unexported fields
}

HashIdx hash index.

type ListIdx

type ListIdx struct {
	// contains filtered or unexported fields
}

ListIdx the list index.

type LockMgr added in v1.2.9

type LockMgr struct {
	// contains filtered or unexported fields
}

LockMgr is a lock manager that manages read and write operations of different data structures. It is also be used to manage transaction.

func (*LockMgr) Lock added in v1.2.9

func (lm *LockMgr) Lock(dTypes ...DataType) func()

Lock locks the rw of dTypes for writing.

func (*LockMgr) RLock added in v1.2.9

func (lm *LockMgr) RLock(dTypes ...DataType) func()

RLock locks the rw of dTypes for reading.

type RoseDB

type RoseDB struct {
	// contains filtered or unexported fields
}

RoseDB the rosedb struct, represents a db instance.

func Open

func Open(config Config) (*RoseDB, error)

Open a rosedb instance. You must call Close after using it.

func Reopen

func Reopen(path string) (*RoseDB, error)

Reopen the db according to the specific config path.

func (*RoseDB) Append

func (db *RoseDB) Append(key interface{}, value string) (err error)

Append if key already exists and is a string, this command appends the value at the end of the string. If key does not exist it is created and set as an empty string, so Append will be similar to Set in this special case.

func (*RoseDB) Backup

func (db *RoseDB) Backup(dir string) (err error)

Backup copy the database directory for backup.

func (*RoseDB) Close

func (db *RoseDB) Close() (err error)

Close db and save relative configs.

func (*RoseDB) Expire

func (db *RoseDB) Expire(key interface{}, duration int64) (err error)

Expire set the expiration time of the key.

func (*RoseDB) Get

func (db *RoseDB) Get(key, dest interface{}) error

Get get the value of key. If the key does not exist an error is returned.

func (*RoseDB) GetSet

func (db *RoseDB) GetSet(key, value, dest interface{}) (err error)

GetSet set key to value and returns the old value stored at key. If the key not exist, return an err.

func (*RoseDB) HClear added in v1.2.8

func (db *RoseDB) HClear(key []byte) (err error)

HClear clear the key in hash.

func (*RoseDB) HDel

func (db *RoseDB) HDel(key []byte, field ...[]byte) (res int, err error)

HDel removes the specified fields from the hash stored at key. Specified fields that do not exist within this hash are ignored. If key does not exist, it is treated as an empty hash and this command returns false.

func (*RoseDB) HExists

func (db *RoseDB) HExists(key, field []byte) (ok bool)

HExists returns if field is an existing field in the hash stored at key.

func (*RoseDB) HExpire added in v1.2.8

func (db *RoseDB) HExpire(key []byte, duration int64) (err error)

HExpire set expired time for a hash key.

func (*RoseDB) HGet

func (db *RoseDB) HGet(key, field []byte) []byte

HGet returns the value associated with field in the hash stored at key.

func (*RoseDB) HGetAll

func (db *RoseDB) HGetAll(key []byte) [][]byte

HGetAll returns all fields and values of the hash stored at key. In the returned value, every field name is followed by its value, so the length of the reply is twice the size of the hash.

func (*RoseDB) HKeyExists added in v1.2.8

func (db *RoseDB) HKeyExists(key []byte) (ok bool)

HKeyExists returns if the key is existed in hash.

func (*RoseDB) HKeys

func (db *RoseDB) HKeys(key []byte) (val []string)

HKeys returns all field names in the hash stored at key.

func (*RoseDB) HLen

func (db *RoseDB) HLen(key []byte) int

HLen returns the number of fields contained in the hash stored at key.

func (*RoseDB) HSet

func (db *RoseDB) HSet(key []byte, field []byte, value []byte) (res int, err error)

HSet sets field in the hash stored at key to value. If key does not exist, a new key holding a hash is created. If field already exists in the hash, it is overwritten. Return num of elements in hash of the specified key.

func (*RoseDB) HSetNx

func (db *RoseDB) HSetNx(key, field, value []byte) (res int, err error)

HSetNx Sets field in the hash stored at key to value, only if field does not yet exist. If key does not exist, a new key holding a hash is created. If field already exists, this operation has no effect. Return if the operation is successful.

func (*RoseDB) HTTL added in v1.2.8

func (db *RoseDB) HTTL(key []byte) (ttl int64)

HTTL return time to live for the key.

func (*RoseDB) HVals added in v1.2.8

func (db *RoseDB) HVals(key []byte) (val [][]byte)

HVals returns all values in the hash stored at key.

func (*RoseDB) LClear added in v1.2.8

func (db *RoseDB) LClear(key []byte) (err error)

LClear clear a specified key.

func (*RoseDB) LExpire added in v1.2.8

func (db *RoseDB) LExpire(key []byte, duration int64) (err error)

LExpire set expired time for a specified key of List.

func (*RoseDB) LIndex

func (db *RoseDB) LIndex(key []byte, idx int) []byte

LIndex returns the element at index index in the list stored at key. The index is zero-based, so 0 means the first element, 1 the second element and so on. Negative indices can be used to designate elements starting at the tail of the list. Here, -1 means the last element, -2 means the penultimate and so forth.

func (*RoseDB) LInsert

func (db *RoseDB) LInsert(key string, option list.InsertOption, pivot, val []byte) (count int, err error)

LInsert inserts element in the list stored at key either before or after the reference value pivot.

func (*RoseDB) LKeyExists added in v1.2.8

func (db *RoseDB) LKeyExists(key []byte) (ok bool)

LKeyExists check if the key of a List exists.

func (*RoseDB) LLen

func (db *RoseDB) LLen(key []byte) int

LLen returns the length of the list stored at key. If key does not exist, it is interpreted as an empty list and 0 is returned.

func (*RoseDB) LPop

func (db *RoseDB) LPop(key []byte) ([]byte, error)

LPop removes and returns the first elements of the list stored at key.

func (*RoseDB) LPush

func (db *RoseDB) LPush(key []byte, values ...[]byte) (res int, err error)

LPush insert all the specified values at the head of the list stored at key. If key does not exist, it is created as empty list before performing the push operations.

func (*RoseDB) LRange

func (db *RoseDB) LRange(key []byte, start, end int) ([][]byte, error)

LRange returns the specified elements of the list stored at key. The offsets start and stop are zero-based indexes, with 0 being the first element of the list (the head of the list), 1 being the next element and so on. These offsets can also be negative numbers indicating offsets starting at the end of the list. For example, -1 is the last element of the list, -2 the penultimate, and so on.

func (*RoseDB) LRem

func (db *RoseDB) LRem(key, value []byte, count int) (int, error)

LRem removes the first count occurrences of elements equal to element from the list stored at key. The count argument influences the operation in the following ways: count > 0: Remove elements equal to element moving from head to tail. count < 0: Remove elements equal to element moving from tail to head. count = 0: Remove all elements equal to element.

func (*RoseDB) LSet

func (db *RoseDB) LSet(key []byte, idx int, val []byte) (ok bool, err error)

LSet sets the list element at index to element. returns whether is successful.

func (*RoseDB) LTTL added in v1.2.8

func (db *RoseDB) LTTL(key []byte) (ttl int64)

LTTL return time to live.

func (*RoseDB) LTrim

func (db *RoseDB) LTrim(key []byte, start, end int) error

LTrim trim an existing list so that it will contain only the specified range of elements specified. Both start and stop are zero-based indexes, where 0 is the first element of the list (the head), 1 the next element and so on.

func (*RoseDB) LValExists added in v1.2.8

func (db *RoseDB) LValExists(key []byte, val []byte) (ok bool)

LValExists check if the val exists in a specified List stored at key.

func (*RoseDB) MarkCommit added in v1.2.9

func (db *RoseDB) MarkCommit(txId uint64) (err error)

MarkCommit write the tx id into txn file.

func (*RoseDB) NewTransaction added in v1.2.9

func (db *RoseDB) NewTransaction() *Txn

NewTransaction create a new transaction, don`t support concurrent execution of transactions now. So you can only open a read-write transaction at the same time. For read-only transactions, you can execute multiple, and any write operations will be omitted.

func (*RoseDB) Persist

func (db *RoseDB) Persist(key interface{}) (err error)

Persist clear expiration time.

func (*RoseDB) PrefixScan

func (db *RoseDB) PrefixScan(prefix string, limit, offset int) (val []interface{}, err error)

PrefixScan find the value corresponding to all matching keys based on the prefix. limit and offset control the range of value. if limit is negative, all matched values will return.

func (*RoseDB) RPop

func (db *RoseDB) RPop(key []byte) ([]byte, error)

Removes and returns the last elements of the list stored at key.

func (*RoseDB) RPush

func (db *RoseDB) RPush(key []byte, values ...[]byte) (res int, err error)

RPush insert all the specified values at the tail of the list stored at key. If key does not exist, it is created as empty list before performing the push operation.

func (*RoseDB) RangeScan

func (db *RoseDB) RangeScan(start, end interface{}) (val []interface{}, err error)

RangeScan find range of values from start to end.

func (*RoseDB) Reclaim

func (db *RoseDB) Reclaim() (err error)

Reclaim reclaim db files`s redundant space in disk. Reclaim operation will read all archived files, iterate all entries and find the valid. Then rewrite the valid entries to new db files. So the time required for reclaim operation depend on the number of entries, you`d better execute it in low peak period.

func (*RoseDB) Remove added in v1.2.9

func (db *RoseDB) Remove(key interface{}) error

Remove remove the value stored at key.

func (*RoseDB) SAdd

func (db *RoseDB) SAdd(key []byte, members ...[]byte) (res int, err error)

SAdd add the specified members to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members.

func (*RoseDB) SCard

func (db *RoseDB) SCard(key []byte) int

SCard returns the set cardinality (number of elements) of the set stored at key.

func (*RoseDB) SClear added in v1.2.8

func (db *RoseDB) SClear(key []byte) (err error)

SClear clear the specified key in set.

func (*RoseDB) SDiff

func (db *RoseDB) SDiff(keys ...[]byte) (val [][]byte)

SDiff returns the members of the set resulting from the difference between the first set and all the successive sets.

func (*RoseDB) SExpire added in v1.2.8

func (db *RoseDB) SExpire(key []byte, duration int64) (err error)

SExpire set expired time for the key in set.

func (*RoseDB) SIsMember

func (db *RoseDB) SIsMember(key, member []byte) bool

SIsMember returns if member is a member of the set stored at key.

func (*RoseDB) SKeyExists added in v1.2.8

func (db *RoseDB) SKeyExists(key []byte) (ok bool)

SKeyExists returns if the key exists.

func (*RoseDB) SMembers

func (db *RoseDB) SMembers(key []byte) (val [][]byte)

SMembers returns all the members of the set value stored at key.

func (*RoseDB) SMove

func (db *RoseDB) SMove(src, dst, member []byte) error

SMove move member from the set at source to the set at destination.

func (*RoseDB) SPop

func (db *RoseDB) SPop(key []byte, count int) (values [][]byte, err error)

SPop removes and returns one or more random members from the set value store at key.

func (*RoseDB) SRandMember

func (db *RoseDB) SRandMember(key []byte, count int) [][]byte

SRandMember returns a random element from the set value stored at key. count > 0: if count less than set`s card, returns an array containing count different elements. if count greater than set`s card, the entire set will be returned. count < 0: the command is allowed to return the same element multiple times, and in this case, the number of returned elements is the absolute value of the specified count.

func (*RoseDB) SRem

func (db *RoseDB) SRem(key []byte, members ...[]byte) (res int, err error)

SRem remove the specified members from the set stored at key. Specified members that are not a member of this set are ignored. If key does not exist, it is treated as an empty set and this command returns 0.

func (*RoseDB) STTL added in v1.2.8

func (db *RoseDB) STTL(key []byte) (ttl int64)

STTL return time to live for the key in set.

func (*RoseDB) SUnion

func (db *RoseDB) SUnion(keys ...[]byte) (val [][]byte)

SUnion returns the members of the set resulting from the union of all the given sets.

func (*RoseDB) Set

func (db *RoseDB) Set(key, value interface{}) error

Set set key to hold the string value. If key already holds a value, it is overwritten. Any previous time to live associated with the key is discarded on successful Set operation.

func (*RoseDB) SetEx added in v1.2.9

func (db *RoseDB) SetEx(key, value interface{}, duration int64) (err error)

SetEx set key to hold the string value and set key to timeout after a given number of seconds.

func (*RoseDB) SetNx

func (db *RoseDB) SetNx(key, value interface{}) (ok bool, err error)

SetNx is short for "Set if not exists", set key to hold string value if key does not exist. In that case, it is equal to Set. When key already holds a value, no operation is performed.

func (*RoseDB) SingleReclaim added in v1.2.8

func (db *RoseDB) SingleReclaim(fileId uint32) (err error)

SingleReclaim reclaim a single db file`s space according to the param fileId. File id is the non-zero part of a db file`s name prefix, such as 000000000.data.str (fileId is 0), 000000101.data.str (fileId is 101), etc. Only support String type now.

func (*RoseDB) StrExists

func (db *RoseDB) StrExists(key interface{}) bool

StrExists check whether the key exists.

func (*RoseDB) Sync

func (db *RoseDB) Sync() (err error)

Persist the db files.

func (*RoseDB) TTL

func (db *RoseDB) TTL(key interface{}) (ttl int64)

TTL Time to live.

func (*RoseDB) Txn added in v1.2.9

func (db *RoseDB) Txn(fn func(tx *Txn) error) (err error)

Txn execute a transaction including read and write. If no error is returned from the function then the transaction is committed. If an error is returned then the entire transaction is rollback.

func (*RoseDB) TxnView added in v1.2.9

func (db *RoseDB) TxnView(fn func(tx *Txn) error) (err error)

TxnView execute a transaction including read only.

func (*RoseDB) ZAdd

func (db *RoseDB) ZAdd(key []byte, score float64, member []byte) error

ZAdd adds the specified member with the specified score to the sorted set stored at key.

func (*RoseDB) ZCard

func (db *RoseDB) ZCard(key []byte) int

ZCard returns the sorted set cardinality (number of elements) of the sorted set stored at key.

func (*RoseDB) ZClear added in v1.2.8

func (db *RoseDB) ZClear(key []byte) (err error)

ZClear clear the specified key in zset.

func (*RoseDB) ZExpire added in v1.2.8

func (db *RoseDB) ZExpire(key []byte, duration int64) (err error)

ZExpire set expired time for the key in zset.

func (*RoseDB) ZGetByRank

func (db *RoseDB) ZGetByRank(key []byte, rank int) []interface{}

ZGetByRank get the member at key by rank, the rank is ordered from lowest to highest. The rank of lowest is 0 and so on.

func (*RoseDB) ZIncrBy

func (db *RoseDB) ZIncrBy(key []byte, increment float64, member []byte) (float64, error)

ZIncrBy increments the score of member in the sorted set stored at key by increment. If member does not exist in the sorted set, it is added with increment as its score (as if its previous score was 0.0). If key does not exist, a new sorted set with the specified member as its sole member is created.

func (*RoseDB) ZKeyExists added in v1.2.8

func (db *RoseDB) ZKeyExists(key []byte) (ok bool)

ZKeyExists check if the key exists in zset.

func (*RoseDB) ZRange

func (db *RoseDB) ZRange(key []byte, start, stop int) []interface{}

ZRange returns the specified range of elements in the sorted set stored at key.

func (*RoseDB) ZRangeWithScores added in v1.2.8

func (db *RoseDB) ZRangeWithScores(key []byte, start, stop int) []interface{}

ZRangeWithScores returns the specified range of elements in the sorted set stored at key.

func (*RoseDB) ZRank

func (db *RoseDB) ZRank(key, member []byte) int64

ZRank returns the rank of member in the sorted set stored at key, with the scores ordered from low to high. The rank (or index) is 0-based, which means that the member with the lowest score has rank 0.

func (*RoseDB) ZRem

func (db *RoseDB) ZRem(key, member []byte) (ok bool, err error)

ZRem removes the specified members from the sorted set stored at key. Non existing members are ignored. An error is returned when key exists and does not hold a sorted set.

func (*RoseDB) ZRevGetByRank

func (db *RoseDB) ZRevGetByRank(key []byte, rank int) []interface{}

ZRevGetByRank get the member at key by rank, the rank is ordered from highest to lowest. The rank of highest is 0 and so on.

func (*RoseDB) ZRevRange

func (db *RoseDB) ZRevRange(key []byte, start, stop int) []interface{}

ZRevRange returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the highest to the lowest score. Descending lexicographical order is used for elements with equal score.

func (*RoseDB) ZRevRangeWithScores added in v1.2.8

func (db *RoseDB) ZRevRangeWithScores(key []byte, start, stop int) []interface{}

ZRevRangeWithScores returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the highest to the lowest score. Descending lexicographical order is used for elements with equal score.

func (*RoseDB) ZRevRank

func (db *RoseDB) ZRevRank(key, member []byte) int64

ZRevRank returns the rank of member in the sorted set stored at key, with the scores ordered from high to low. The rank (or index) is 0-based, which means that the member with the highest score has rank 0.

func (*RoseDB) ZRevScoreRange

func (db *RoseDB) ZRevScoreRange(key []byte, max, min float64) []interface{}

ZRevScoreRange returns all the elements in the sorted set at key with a score between max and min (including elements with score equal to max or min). In contrary to the default ordering of sorted sets, for this command the elements are considered to be ordered from high to low scores.

func (*RoseDB) ZScore

func (db *RoseDB) ZScore(key, member []byte) (ok bool, score float64)

ZScore returns the score of member in the sorted set at key.

func (*RoseDB) ZScoreRange

func (db *RoseDB) ZScoreRange(key []byte, min, max float64) []interface{}

ZScoreRange returns all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max). The elements are considered to be ordered from low to high scores.

func (*RoseDB) ZTTL added in v1.2.8

func (db *RoseDB) ZTTL(key []byte) (ttl int64)

ZTTL return time to live of the key.

type SetIdx

type SetIdx struct {
	// contains filtered or unexported fields
}

SetIdx the set idx

type StrIdx

type StrIdx struct {
	// contains filtered or unexported fields
}

StrIdx string index.

type Txn added in v1.2.9

type Txn struct {
	// contains filtered or unexported fields
}

Txn is a rosedb Transaction. You can begin a read-write transaction by calling Txn, and read-only transaction by calling TxnView. Transaction will be committed or rollback automatically in method Txn and TxnView.

func (*Txn) Append added in v1.2.9

func (tx *Txn) Append(key interface{}, value string) (err error)

Append see db_str.go:Append

func (*Txn) Commit added in v1.2.9

func (tx *Txn) Commit() (err error)

Commit commit the transaction.

func (*Txn) Get added in v1.2.9

func (tx *Txn) Get(key, dest interface{}) (err error)

Get see db_str.go:Get

func (*Txn) GetSet added in v1.2.9

func (tx *Txn) GetSet(key, value, dest interface{}) (err error)

GetSet see db_str.go:GetSet

func (*Txn) HDel added in v1.2.9

func (tx *Txn) HDel(key interface{}, fields ...interface{}) (err error)

HDel see db_hash.go:HDel

func (*Txn) HExists added in v1.2.9

func (tx *Txn) HExists(key, field interface{}) (ok bool)

HExists see db_hash.go:HExists

func (*Txn) HGet added in v1.2.9

func (tx *Txn) HGet(key, field, dest interface{}) (err error)

HGet see db_hash.go:HGet

func (*Txn) HSet added in v1.2.9

func (tx *Txn) HSet(key, field, value interface{}) (err error)

HSet see db_hash.go:HSet

func (*Txn) HSetNx added in v1.2.9

func (tx *Txn) HSetNx(key, field, value interface{}) (err error)

HSetNx see db_hash.go:HSetNx

func (*Txn) LPush added in v1.2.9

func (tx *Txn) LPush(key interface{}, values ...interface{}) (err error)

LPush see db_list.go:LPush

func (*Txn) RPush added in v1.2.9

func (tx *Txn) RPush(key interface{}, values ...interface{}) (err error)

RPush see db_list.go:RPush

func (*Txn) Remove added in v1.2.9

func (tx *Txn) Remove(key interface{}) (err error)

Remove see db_str.go:Remove

func (*Txn) Rollback added in v1.2.9

func (tx *Txn) Rollback()

Rollback finished current transaction.

func (*Txn) SAdd added in v1.2.9

func (tx *Txn) SAdd(key interface{}, members ...interface{}) (err error)

SAdd see db_set.go:SAdd

func (*Txn) SIsMember added in v1.2.9

func (tx *Txn) SIsMember(key, member interface{}) (ok bool)

SIsMember see db_set.go:SIsMember

func (*Txn) SRem added in v1.2.9

func (tx *Txn) SRem(key interface{}, members ...[]interface{}) (err error)

SRem see db_set.go:SRem

func (*Txn) Set added in v1.2.9

func (tx *Txn) Set(key, value interface{}) (err error)

Set see db_str.go:Set

func (*Txn) SetEx added in v1.2.9

func (tx *Txn) SetEx(key, value interface{}, duration int64) (err error)

SetEx see db_str.go:SetEx

func (*Txn) SetNx added in v1.2.9

func (tx *Txn) SetNx(key, value interface{}) (ok bool, err error)

SetNx see db_str.go:SetNx

func (*Txn) StrExists added in v1.2.9

func (tx *Txn) StrExists(key interface{}) (ok bool)

StrExists see db_str.go:StrExists

func (*Txn) ZAdd added in v1.2.9

func (tx *Txn) ZAdd(key interface{}, score float64, member interface{}) (err error)

ZScore see db_zset.go/ZAdd

func (*Txn) ZRem added in v1.2.9

func (tx *Txn) ZRem(key, member interface{}) (err error)

ZRem see db_zset.go/ZRem

func (*Txn) ZScore added in v1.2.9

func (tx *Txn) ZScore(key, member interface{}) (exist bool, score float64, err error)

ZScore see db_zset.go/ZScore

type TxnFile added in v1.2.9

type TxnFile struct {
	File   *os.File // file.
	Offset int64    // write offset.
}

TxnFile a single file in disk to save committed transaction ids.

type TxnMeta added in v1.2.9

type TxnMeta struct {
	// MaxTxId the max tx id now.
	MaxTxId uint64

	// ActiveTxIds committed tx ids in active files.
	ActiveTxIds *sync.Map

	// CommittedTxIds save the transaction ids that has been successfully committed.
	CommittedTxIds map[uint64]struct{}
	// contains filtered or unexported fields
}

TxnMeta represents some transaction info while tx is running.

func LoadTxnMeta added in v1.2.9

func LoadTxnMeta(path string) (txnMeta *TxnMeta, err error)

LoadTxnMeta load txn meta info, committed tx id.

type ZsetIdx

type ZsetIdx struct {
	// contains filtered or unexported fields
}

ZsetIdx the zset idx.

Directories

Path Synopsis
cmd
cli
ds
set

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL