gorocksdb

package module
v0.0.0-...-9e50596 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2018 License: MIT Imports: 6 Imported by: 2

README

A Go wrapper for RocksDB with utilities for better performance and extensions.

Build Status GoDoc codecov Go Report Card

Install

You'll need to build RocksDB v5.8+ on your machine. Future RocksDB versions will have separate branches.

Additional features

GoBufferIterator

GoBufferIterator is an iterator that that uses the original iterator but does less cgo calls due to prefetching data in a go byte slice. This is useful if you range over a large number of KVs and can give you a large performance boost.


	readaheadByteSize := uint64(1024 * 1024)
	readaheadCnt := uint64(1024)
	iter := db.NewIterator(readOptions)
	goitr := NewGoBufferIteratorFromIterator(iter, readaheadByteSize, readaheadCnt, false, IteratorSortOrder_Asc)

Extensions

To extend functionality and mainly to reduce cgo calls.

ẀriteBatch


	// PutVCF queues multiple key-value pairs in a column family.
	PutVCF(cf *ColumnFamilyHandle, keys, values [][]byte)

	// PutVCFs queues multiple key-value pairs in column families.
	PutVCFs(cfs []*ColumnFamilyHandle, keys, values [][]byte)

MultiIterator

Its purpose is to iterate with multiple iterators at once.

Package /extension/events does provide a MultiIterator for "topics with events" -> TopicEventMultiIterator. An example can be found here.

The standard MultiIterator can be used for example: You have "topics" in your RocksDB which do store "events" and share a common suffix length. i.e. 8bytes Topic ID, 8bytes Event ID (16 byte is the key). You want to "combine" some topics and iterate through those by ascending event id up to eventID9.


	ro1 := NewDefaultReadOptions()
	ro1.SetIterateUpperBound([]byte("topicID1eventID9"))

	ro2 := NewDefaultReadOptions()
	ro2.SetIterateUpperBound([]byte("topicID2eventID9"))

	ro3 := NewDefaultReadOptions()
	ro3.SetIterateUpperBound([]byte("topicID3eventID9"))

	it1 := db.NewIterator(ro1)
	it2 := db.NewIterator(ro2)
	it3 := db.NewIterator(ro3)

	itrs = []*Iterator{
		it1, it2, it3,
	}

	readaheadSize := uint64(1024 * 1024)
	readaheadCnt := uint64(3)
	prefixLen := uint64(8)
	multiitr = NewFixedPrefixedMultiIteratorFromIterators(readaheadSize, readaheadCnt, true, itrs, prefixLen)

	for multiitr.Seek(seekKeys); multiitr.Valid(); multiitr.Next() {
		k, v := multiitr.KeyValue()
		itrIdx := multiitr.IteratorIndex() // describes which of the iterators in "itrs" provides k, v
	}

Or: You have "topics" in your RocksDB which do store "events" and share a common suffix length. i.e. 8bytes Topic ID, 8bytes Event ID (16 byte is the key). You want to "combine" some topics and iterate through those by ascending event id up to eventID9. For the suffix type of MultiIterator you need an appropriate comparator.

	
	suffixLen := uint64(8) // our Event ID key part which always has to be 8 bytes here.
	multiitr = NewFixedSuffixMultiIteratorFromIterators(readaheadSize, readaheadCnt, true, itrs, suffixLen)

Please be aware that your DB / column family needs the appropriate comparator! If you use the standard comparator (BytewiseComparator) all keys MUST have same length.

Examples

TopicEventMultiIterator.

Thanks

Thanks to gorocksdb where this is forked from originally.

Documentation

Overview

Package gorocksdb provides the ability to create and access RocksDB databases.

gorocksdb.OpenDb opens and creates databases.

bbto := gorocksdb.NewDefaultBlockBasedTableOptions()
bbto.SetBlockCache(gorocksdb.NewLRUCache(3 << 30))
opts := gorocksdb.NewDefaultOptions()
opts.SetBlockBasedTableFactory(bbto)
opts.SetCreateIfMissing(true)
db, err := gorocksdb.OpenDb(opts, "/path/to/db")

The DB struct returned by OpenDb provides DB.Get, DB.Put, DB.Merge and DB.Delete to modify and query the database.

ro := gorocksdb.NewDefaultReadOptions()
wo := gorocksdb.NewDefaultWriteOptions()
// if ro and wo are not used again, be sure to Close them.
err = db.Put(wo, []byte("foo"), []byte("bar"))
...
value, err := db.Get(ro, []byte("foo"))
defer value.Free()
...
err = db.Delete(wo, []byte("foo"))

For bulk reads, use an Iterator. If you want to avoid disturbing your live traffic while doing the bulk read, be sure to call SetFillCache(false) on the ReadOptions you use when creating the Iterator.

ro := gorocksdb.NewDefaultReadOptions()
ro.SetFillCache(false)
it := db.NewIterator(ro)
defer it.Close()
it.Seek([]byte("foo"))
for it = it; it.Valid(); it.Next() {
	key := it.Key()
	value := it.Value()
	fmt.Printf("Key: %v Value: %v\n", key.Data(), value.Data())
	key.Free()
	value.Free()
}
if err := it.Err(); err != nil {
	...
}

Batched, atomic writes can be performed with a WriteBatch and DB.Write.

wb := gorocksdb.NewWriteBatch()
// defer wb.Close or use wb.Clear and reuse.
wb.Delete([]byte("foo"))
wb.Put([]byte("foo"), []byte("bar"))
wb.Put([]byte("bar"), []byte("foo"))
err := db.Write(wo, wb)

If your working dataset does not fit in memory, you'll want to add a bloom filter to your database. NewBloomFilter and BlockBasedTableOptions.SetFilterPolicy is what you want. NewBloomFilter is amount of bits in the filter to use per key in your database.

filter := gorocksdb.NewBloomFilter(10)
bbto := gorocksdb.NewDefaultBlockBasedTableOptions()
bbto.SetFilterPolicy(filter)
opts.SetBlockBasedTableFactory(bbto)
db, err := gorocksdb.OpenDb(opts, "/path/to/db")

If you're using a custom comparator in your code, be aware you may have to make your own filter policy object.

This documentation is not a complete discussion of RocksDB. Please read the RocksDB documentation <http://rocksdb.org/> for information on its operation. You'll find lots of goodies there.

Index

Constants

Compression types.

View Source
const (
	LevelCompactionStyle     = CompactionStyle(C.rocksdb_level_compaction)
	UniversalCompactionStyle = CompactionStyle(C.rocksdb_universal_compaction)
	FIFOCompactionStyle      = CompactionStyle(C.rocksdb_fifo_compaction)
)

Compaction styles.

View Source
const (
	NoneCompactionAccessPattern       = CompactionAccessPattern(0)
	NormalCompactionAccessPattern     = CompactionAccessPattern(1)
	SequentialCompactionAccessPattern = CompactionAccessPattern(2)
	WillneedCompactionAccessPattern   = CompactionAccessPattern(3)
)

Access patterns for compaction.

View Source
const (
	DebugInfoLogLevel = InfoLogLevel(0)
	InfoInfoLogLevel  = InfoLogLevel(1)
	WarnInfoLogLevel  = InfoLogLevel(2)
	ErrorInfoLogLevel = InfoLogLevel(3)
	FatalInfoLogLevel = InfoLogLevel(4)
)

Log leves.

View Source
const (
	// KBinarySearchIndexType is a space efficient index block that is optimized for
	// binary-search-based index.
	KBinarySearchIndexType = 0
	// KHashSearchIndexType is a hash index, if enabled, will do the hash lookup when
	// `Options.prefix_extractor` is provided.
	KHashSearchIndexType = 1
	// KTwoLevelIndexSearchIndexType is
	// a two-level index implementation. Both levels are binary search indexes.
	KTwoLevelIndexSearchIndexType = 2
)

Compaction stop style types.

View Source
const (
	// ReadAllTier reads data in memtable, block cache, OS cache or storage.
	ReadAllTier = ReadTier(0)
	// BlockCacheTier reads data in memtable or block cache.
	BlockCacheTier = ReadTier(1)
)

Variables

This section is empty.

Functions

func ByteSlicesToUintptrsAndSizeTSlices

func ByteSlicesToUintptrsAndSizeTSlices(values [][]byte) (ptrs []uintptr, sizes []C.size_t)

ByteSlicesToUintptrsAndSizeTSlices uses the values data as pointers and lengths as sizes.

func CFsToCCFs

func CFsToCCFs(cfs []*ColumnFamilyHandle) (ccfs []*C.rocksdb_column_family_handle_t)

CFsToCCFs returns a slice of cfss *C.rocksdb_column_family_handle_t types.

func CfreeByteSlice

func CfreeByteSlice(b []byte)

CfreeByteSlice frees the underlying C memory.

func DestroyDBPaths

func DestroyDBPaths(dbpaths []*DBPath)

DestroyDBPaths deallocates all DBPath objects in dbpaths.

func DestroyDb

func DestroyDb(name string, opts *Options) error

DestroyDb removes a database entirely, removing everything from the filesystem.

func ListColumnFamilies

func ListColumnFamilies(opts *Options, name string) ([]string, error)

ListColumnFamilies lists the names of the column families in the DB.

func OpenDbColumnFamilies

func OpenDbColumnFamilies(
	opts *Options,
	name string,
	cfNames []string,
	cfOpts []*Options,
) (*DB, []*ColumnFamilyHandle, error)

OpenDbColumnFamilies opens a database with the specified column families.

func OpenDbForReadOnlyColumnFamilies

func OpenDbForReadOnlyColumnFamilies(
	opts *Options,
	name string,
	cfNames []string,
	cfOpts []*Options,
	errorIfLogFileExist bool,
) (*DB, []*ColumnFamilyHandle, error)

OpenDbForReadOnlyColumnFamilies opens a database with the specified column families in read only mode.

func RepairDb

func RepairDb(name string, opts *Options) error

RepairDb repairs a database.

func SetBytesSliceHeader

func SetBytesSliceHeader(pData *[]byte, ptr uintptr, len, cap int)

SetBytesSliceHeader is a helper method to set the header of a slice.

Types

type BackupEngine

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

BackupEngine is a reusable handle to a RocksDB Backup, created by OpenBackupEngine.

func OpenBackupEngine

func OpenBackupEngine(opts *Options, path string) (*BackupEngine, error)

OpenBackupEngine opens a backup engine with specified options.

func (*BackupEngine) Close

func (b *BackupEngine) Close()

Close close the backup engine and cleans up state The backups already taken remain on storage.

func (*BackupEngine) CreateNewBackup

func (b *BackupEngine) CreateNewBackup(db *DB) error

CreateNewBackup takes a new backup from db.

func (*BackupEngine) GetInfo

func (b *BackupEngine) GetInfo() *BackupEngineInfo

GetInfo gets an object that gives information about the backups that have already been taken

func (*BackupEngine) RestoreDBFromLatestBackup

func (b *BackupEngine) RestoreDBFromLatestBackup(dbDir, walDir string, ro *RestoreOptions) error

RestoreDBFromLatestBackup restores the latest backup to dbDir. walDir is where the write ahead logs are restored to and usually the same as dbDir.

func (*BackupEngine) UnsafeGetBackupEngine

func (b *BackupEngine) UnsafeGetBackupEngine() unsafe.Pointer

UnsafeGetBackupEngine returns the underlying c backup engine.

type BackupEngineInfo

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

BackupEngineInfo represents the information about the backups in a backup engine instance. Use this to get the state of the backup like number of backups and their ids and timestamps etc.

func (*BackupEngineInfo) Destroy

func (b *BackupEngineInfo) Destroy()

Destroy destroys the backup engine info instance.

func (*BackupEngineInfo) GetBackupId

func (b *BackupEngineInfo) GetBackupId(index int) int64

GetBackupId gets an id that uniquely identifies a backup regardless of its position.

func (*BackupEngineInfo) GetCount

func (b *BackupEngineInfo) GetCount() int

GetCount gets the number backsup available.

func (*BackupEngineInfo) GetNumFiles

func (b *BackupEngineInfo) GetNumFiles(index int) int32

GetNumFiles gets the number of files in the backup index.

func (*BackupEngineInfo) GetSize

func (b *BackupEngineInfo) GetSize(index int) int64

GetSize get the size of the backup in bytes.

func (*BackupEngineInfo) GetTimestamp

func (b *BackupEngineInfo) GetTimestamp(index int) int64

GetTimestamp gets the timestamp at which the backup index was taken.

type BlockBasedTableOptions

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

BlockBasedTableOptions represents block-based table options.

func NewDefaultBlockBasedTableOptions

func NewDefaultBlockBasedTableOptions() *BlockBasedTableOptions

NewDefaultBlockBasedTableOptions creates a default BlockBasedTableOptions object.

func NewNativeBlockBasedTableOptions

func NewNativeBlockBasedTableOptions(c *C.rocksdb_block_based_table_options_t) *BlockBasedTableOptions

NewNativeBlockBasedTableOptions creates a BlockBasedTableOptions object.

func (*BlockBasedTableOptions) Destroy

func (opts *BlockBasedTableOptions) Destroy()

Destroy deallocates the BlockBasedTableOptions object.

func (*BlockBasedTableOptions) SetBlockCache

func (opts *BlockBasedTableOptions) SetBlockCache(cache *Cache)

SetBlockCache sets the control over blocks (user data is stored in a set of blocks, and a block is the unit of reading from disk).

If set, use the specified cache for blocks. If nil, rocksdb will auoptsmatically create and use an 8MB internal cache. Default: nil

func (*BlockBasedTableOptions) SetBlockCacheCompressed

func (opts *BlockBasedTableOptions) SetBlockCacheCompressed(cache *Cache)

SetBlockCacheCompressed sets the cache for compressed blocks. If nil, rocksdb will not use a compressed block cache. Default: nil

func (*BlockBasedTableOptions) SetBlockRestartInterval

func (opts *BlockBasedTableOptions) SetBlockRestartInterval(blockRestartInterval int)

SetBlockRestartInterval sets the number of keys between restart points for delta encoding of keys. This parameter can be changed dynamically. Most clients should leave this parameter alone. Default: 16

func (*BlockBasedTableOptions) SetBlockSize

func (opts *BlockBasedTableOptions) SetBlockSize(blockSize int)

SetBlockSize sets the approximate size of user data packed per block. Note that the block size specified here corresponds opts uncompressed data. The actual size of the unit read from disk may be smaller if compression is enabled. This parameter can be changed dynamically. Default: 4K

func (*BlockBasedTableOptions) SetBlockSizeDeviation

func (opts *BlockBasedTableOptions) SetBlockSizeDeviation(blockSizeDeviation int)

SetBlockSizeDeviation sets the block size deviation. This is used opts close a block before it reaches the configured 'block_size'. If the percentage of free space in the current block is less than this specified number and adding a new record opts the block will exceed the configured block size, then this block will be closed and the new record will be written opts the next block. Default: 10

func (*BlockBasedTableOptions) SetCacheIndexAndFilterBlocks

func (opts *BlockBasedTableOptions) SetCacheIndexAndFilterBlocks(value bool)

SetCacheIndexAndFilterBlocks is indicating if we'd put index/filter blocks to the block cache. If not specified, each "table reader" object will pre-load index/filter block during table initialization. Default: false

func (*BlockBasedTableOptions) SetFilterPolicy

func (opts *BlockBasedTableOptions) SetFilterPolicy(fp FilterPolicy)

SetFilterPolicy sets the filter policy opts reduce disk reads. Many applications will benefit from passing the result of NewBloomFilterPolicy() here. Default: nil

func (*BlockBasedTableOptions) SetIndexType

func (opts *BlockBasedTableOptions) SetIndexType(value IndexType)

SetIndexType sets the index type used for this table. kBinarySearch: A space efficient index block that is optimized for binary-search-based index.

kHashSearch: The hash index, if enabled, will do the hash lookup when `Options.prefix_extractor` is provided.

kTwoLevelIndexSearch: A two-level index implementation. Both levels are binary search indexes. Default: kBinarySearch

func (*BlockBasedTableOptions) SetNoBlockCache

func (opts *BlockBasedTableOptions) SetNoBlockCache(value bool)

SetNoBlockCache specify whether block cache should be used or not. Default: false

func (*BlockBasedTableOptions) SetPinL0FilterAndIndexBlocksInCache

func (opts *BlockBasedTableOptions) SetPinL0FilterAndIndexBlocksInCache(value bool)

SetPinL0FilterAndIndexBlocksInCache sets cache_index_and_filter_blocks. If is true and the below is true (hash_index_allow_collision), then filter and index blocks are stored in the cache, but a reference is held in the "table reader" object so the blocks are pinned and only evicted from cache when the table reader is freed.

func (*BlockBasedTableOptions) SetWholeKeyFiltering

func (opts *BlockBasedTableOptions) SetWholeKeyFiltering(value bool)

SetWholeKeyFiltering specify if whole keys in the filter (not just prefixes) should be placed. This must generally be true for gets opts be efficient. Default: true

type Cache

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

Cache is a cache used to store data read from data in memory.

func NewLRUCache

func NewLRUCache(capacity int) *Cache

NewLRUCache creates a new LRU Cache object with the capacity given.

func NewNativeCache

func NewNativeCache(c *C.rocksdb_cache_t) *Cache

NewNativeCache creates a Cache object.

func (*Cache) Destroy

func (c *Cache) Destroy()

Destroy deallocates the Cache object.

func (*Cache) GetPinnedUsage

func (c *Cache) GetPinnedUsage() int

GetPinnedUsage returns the Cache pinned memory usage.

func (*Cache) GetUsage

func (c *Cache) GetUsage() int

GetUsage returns the Cache memory usage.

type Checkpoint

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

Checkpoint provides Checkpoint functionality. Checkpoints provide persistent snapshots of RocksDB databases.

func NewNativeCheckpoint

func NewNativeCheckpoint(c *C.rocksdb_checkpoint_t) *Checkpoint

NewNativeCheckpoint creates a new checkpoint.

func (*Checkpoint) CreateCheckpoint

func (checkpoint *Checkpoint) CreateCheckpoint(checkpointDir string, logSizeForFlush uint64) error

CreateCheckpoint builds an openable snapshot of RocksDB on the same disk, which accepts an output directory on the same disk, and under the directory (1) hard-linked SST files pointing to existing live SST files SST files will be copied if output directory is on a different filesystem (2) a copied manifest files and other files The directory should not already exist and will be created by this API. The directory will be an absolute path logSizeForFlush: if the total log file size is equal or larger than this value, then a flush is triggered for all the column families. The default value is 0, which means flush is always triggered. If you move away from the default, the checkpoint may not contain up-to-date data if WAL writing is not always enabled. Flush will always trigger if it is 2PC.

func (*Checkpoint) Destroy

func (checkpoint *Checkpoint) Destroy()

Destroy deallocates the Checkpoint object.

type ColumnFamilyHandle

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

ColumnFamilyHandle represents a handle to a ColumnFamily.

func NewNativeColumnFamilyHandle

func NewNativeColumnFamilyHandle(c *C.rocksdb_column_family_handle_t) *ColumnFamilyHandle

NewNativeColumnFamilyHandle creates a ColumnFamilyHandle object.

func (*ColumnFamilyHandle) Destroy

func (h *ColumnFamilyHandle) Destroy()

Destroy calls the destructor of the underlying column family handle.

func (*ColumnFamilyHandle) UnsafeGetCFHandler

func (h *ColumnFamilyHandle) UnsafeGetCFHandler() unsafe.Pointer

UnsafeGetCFHandler returns the underlying c column family handle.

type CompactionAccessPattern

type CompactionAccessPattern uint

CompactionAccessPattern specifies the access patern in compaction.

type CompactionFilter

type CompactionFilter interface {
	// If the Filter function returns false, it indicates
	// that the kv should be preserved, while a return value of true
	// indicates that this key-value should be removed from the
	// output of the compaction. The application can inspect
	// the existing value of the key and make decision based on it.
	//
	// When the value is to be preserved, the application has the option
	// to modify the existing value and pass it back through a new value.
	// To retain the previous value, simply return nil
	//
	// If multithreaded compaction is being used *and* a single CompactionFilter
	// instance was supplied via SetCompactionFilter, this the Filter function may be
	// called from different threads concurrently. The application must ensure
	// that the call is thread-safe.
	Filter(level int, key, val []byte) (remove bool, newVal []byte)

	// The name of the compaction filter, for logging
	Name() string
}

A CompactionFilter can be used to filter keys during compaction time.

func NewNativeCompactionFilter

func NewNativeCompactionFilter(c *C.rocksdb_compactionfilter_t) CompactionFilter

NewNativeCompactionFilter creates a CompactionFilter object.

type CompactionStyle

type CompactionStyle uint

CompactionStyle specifies the compaction style.

type Comparator

type Comparator interface {
	// Three-way comparison. Returns value:
	//   < 0 iff "a" < "b",
	//   == 0 iff "a" == "b",
	//   > 0 iff "a" > "b"
	Compare(a, b []byte) int

	// The name of the comparator.
	Name() string
}

A Comparator object provides a total order across slices that are used as keys in an sstable or a database.

func NewNativeComparator

func NewNativeComparator(c *C.rocksdb_comparator_t) Comparator

NewNativeComparator creates a Comparator object.

type CompressionOptions

type CompressionOptions struct {
	WindowBits   int
	Level        int
	Strategy     int
	MaxDictBytes int
}

CompressionOptions represents options for different compression algorithms like Zlib.

func NewCompressionOptions

func NewCompressionOptions(windowBits, level, strategy, maxDictBytes int) *CompressionOptions

NewCompressionOptions creates a CompressionOptions object.

func NewDefaultCompressionOptions

func NewDefaultCompressionOptions() *CompressionOptions

NewDefaultCompressionOptions creates a default CompressionOptions object.

type CompressionType

type CompressionType uint

CompressionType specifies the block compression. DB contents are stored in a set of blocks, each of which holds a sequence of key,value pairs. Each block may be compressed before being stored in a file. The following enum describes which compression method (if any) is used to compress a block.

type DB

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

DB is a reusable handle to a RocksDB database on disk, created by Open.

func OpenDb

func OpenDb(opts *Options, name string) (*DB, error)

OpenDb opens a database with the specified options.

func OpenDbForReadOnly

func OpenDbForReadOnly(opts *Options, name string, errorIfLogFileExist bool) (*DB, error)

OpenDbForReadOnly opens a database with the specified options for readonly usage.

func (*DB) Close

func (db *DB) Close()

Close closes the database.

func (*DB) CompactRange

func (db *DB) CompactRange(r Range)

CompactRange runs a manual compaction on the Range of keys given. This is not likely to be needed for typical usage.

func (*DB) CompactRangeCF

func (db *DB) CompactRangeCF(cf *ColumnFamilyHandle, r Range)

CompactRangeCF runs a manual compaction on the Range of keys given on the given column family. This is not likely to be needed for typical usage.

func (*DB) CreateColumnFamily

func (db *DB) CreateColumnFamily(opts *Options, name string) (*ColumnFamilyHandle, error)

CreateColumnFamily create a new column family.

func (*DB) Delete

func (db *DB) Delete(opts *WriteOptions, key []byte) error

Delete removes the data associated with the key from the database.

func (*DB) DeleteCF

func (db *DB) DeleteCF(opts *WriteOptions, cf *ColumnFamilyHandle, key []byte) error

DeleteCF removes the data associated with the key from the database and column family.

func (*DB) DeleteFile

func (db *DB) DeleteFile(name string)

DeleteFile deletes the file name from the db directory and update the internal state to reflect that. Supports deletion of sst and log files only. 'name' must be path relative to the db directory. eg. 000001.sst, /archive/000003.log.

func (*DB) DisableFileDeletions

func (db *DB) DisableFileDeletions() error

DisableFileDeletions disables file deletions and should be used when backup the database.

func (*DB) DropColumnFamily

func (db *DB) DropColumnFamily(c *ColumnFamilyHandle) error

DropColumnFamily drops a column family.

func (*DB) EnableFileDeletions

func (db *DB) EnableFileDeletions(force bool) error

EnableFileDeletions enables file deletions for the database.

func (*DB) Flush

func (db *DB) Flush(opts *FlushOptions) error

Flush triggers a manuel flush for the database.

func (*DB) Get

func (db *DB) Get(opts *ReadOptions, key []byte) ([]byte, error)

Get returns the data associated with the key from the database.

func (*DB) GetApproximateSizes

func (db *DB) GetApproximateSizes(ranges []Range) []uint64

GetApproximateSizes returns the approximate number of bytes of file system space used by one or more key ranges.

The keys counted will begin at Range.Start and end on the key before Range.Limit.

func (*DB) GetApproximateSizesCF

func (db *DB) GetApproximateSizesCF(cf *ColumnFamilyHandle, ranges []Range) []uint64

GetApproximateSizesCF returns the approximate number of bytes of file system space used by one or more key ranges in the column family.

The keys counted will begin at Range.Start and end on the key before Range.Limit.

func (*DB) GetBytes

func (db *DB) GetBytes(opts *ReadOptions, key []byte) ([]byte, error)

GetBytes is like Get but returns a copy of the data.

func (*DB) GetCF

func (db *DB) GetCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) ([]byte, error)

GetCF returns the data associated with the key from the database and column family.

func (*DB) GetLiveFilesMetaData

func (db *DB) GetLiveFilesMetaData() []LiveFileMetadata

GetLiveFilesMetaData returns a list of all table files with their level, start key and end key.

func (*DB) GetProperty

func (db *DB) GetProperty(propName string) string

GetProperty returns the value of a database property.

func (*DB) GetPropertyCF

func (db *DB) GetPropertyCF(propName string, cf *ColumnFamilyHandle) string

GetPropertyCF returns the value of a database property.

func (*DB) IngestExternalFile

func (db *DB) IngestExternalFile(filePaths []string, opts *IngestExternalFileOptions) error

IngestExternalFile loads a list of external SST files.

func (*DB) IngestExternalFileCF

func (db *DB) IngestExternalFileCF(handle *ColumnFamilyHandle, filePaths []string, opts *IngestExternalFileOptions) error

IngestExternalFileCF loads a list of external SST files for a column family.

func (*DB) Merge

func (db *DB) Merge(opts *WriteOptions, key []byte, value []byte) error

Merge merges the data associated with the key with the actual data in the database.

func (*DB) MergeCF

func (db *DB) MergeCF(opts *WriteOptions, cf *ColumnFamilyHandle, key []byte, value []byte) error

MergeCF merges the data associated with the key with the actual data in the database and column family.

func (*DB) Name

func (db *DB) Name() string

Name returns the name of the database.

func (*DB) NewCheckpoint

func (db *DB) NewCheckpoint() (*Checkpoint, error)

NewCheckpoint creates a new Checkpoint for this db.

func (*DB) NewIterator

func (db *DB) NewIterator(opts *ReadOptions) *Iterator

NewIterator returns an Iterator over the the database that uses the ReadOptions given.

func (*DB) NewIteratorCF

func (db *DB) NewIteratorCF(opts *ReadOptions, cf *ColumnFamilyHandle) *Iterator

NewIteratorCF returns an Iterator over the the database and column family that uses the ReadOptions given.

func (*DB) NewIteratorsCF

func (db *DB) NewIteratorsCF(opts *ReadOptions, cfs []*ColumnFamilyHandle) ([]*Iterator, error)

NewIteratorsCF returns Iterators over the the database and column families that uses the ReadOptions given. len of the returned iterators is the len of cfs.

func (*DB) NewSnapshot

func (db *DB) NewSnapshot() *Snapshot

NewSnapshot creates a new snapshot of the database.

func (*DB) Put

func (db *DB) Put(opts *WriteOptions, key, value []byte) error

Put writes data associated with a key to the database.

func (*DB) PutCF

func (db *DB) PutCF(opts *WriteOptions, cf *ColumnFamilyHandle, key, value []byte) error

PutCF writes data associated with a key to the database and column family.

func (*DB) ReleaseSnapshot

func (db *DB) ReleaseSnapshot(snapshot *Snapshot)

ReleaseSnapshot releases the snapshot and its resources.

func (*DB) UnsafeGetDB

func (db *DB) UnsafeGetDB() unsafe.Pointer

UnsafeGetDB returns the underlying c rocksdb instance.

func (*DB) Write

func (db *DB) Write(opts *WriteOptions, batch *WriteBatch) error

Write writes a WriteBatch to the database

type DBPath

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

DBPath represents options for a dbpath.

func NewDBPath

func NewDBPath(path string, targetSize uint64) *DBPath

NewDBPath creates a DBPath object with the given path and target_size.

func NewDBPathsFromData

func NewDBPathsFromData(paths []string, targetSizes []uint64) []*DBPath

NewDBPathsFromData creates a slice with allocated DBPath objects from paths and targetSizes.

func NewNativeDBPath

func NewNativeDBPath(c *C.rocksdb_dbpath_t) *DBPath

NewNativeDBPath creates a DBPath object.

func (*DBPath) Destroy

func (dbpath *DBPath) Destroy()

Destroy deallocates the DBPath object.

type Env

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

Env is a system call environment used by a database.

func NewDefaultEnv

func NewDefaultEnv() *Env

NewDefaultEnv creates a default environment.

func NewNativeEnv

func NewNativeEnv(c *C.rocksdb_env_t) *Env

NewNativeEnv creates a Environment object.

func (*Env) Destroy

func (env *Env) Destroy()

Destroy deallocates the Env object.

func (*Env) SetBackgroundThreads

func (env *Env) SetBackgroundThreads(n int)

SetBackgroundThreads sets the number of background worker threads of a specific thread pool for this environment. 'LOW' is the default pool. Default: 1

func (*Env) SetHighPriorityBackgroundThreads

func (env *Env) SetHighPriorityBackgroundThreads(n int)

SetHighPriorityBackgroundThreads sets the size of the high priority thread pool that can be used to prevent compactions from stalling memtable flushes.

type EnvOptions

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

EnvOptions represents options for env.

func NewDefaultEnvOptions

func NewDefaultEnvOptions() *EnvOptions

NewDefaultEnvOptions creates a default EnvOptions object.

func NewNativeEnvOptions

func NewNativeEnvOptions(c *C.rocksdb_envoptions_t) *EnvOptions

NewNativeEnvOptions creates a EnvOptions object.

func (*EnvOptions) Destroy

func (opts *EnvOptions) Destroy()

Destroy deallocates the EnvOptions object.

type FIFOCompactionOptions

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

FIFOCompactionOptions represent all of the available options for FIFO compaction.

func NewDefaultFIFOCompactionOptions

func NewDefaultFIFOCompactionOptions() *FIFOCompactionOptions

NewDefaultFIFOCompactionOptions creates a default FIFOCompactionOptions object.

func NewNativeFIFOCompactionOptions

func NewNativeFIFOCompactionOptions(c *C.rocksdb_fifo_compaction_options_t) *FIFOCompactionOptions

NewNativeFIFOCompactionOptions creates a native FIFOCompactionOptions object.

func (*FIFOCompactionOptions) Destroy

func (opts *FIFOCompactionOptions) Destroy()

Destroy deallocates the FIFOCompactionOptions object.

func (*FIFOCompactionOptions) SetMaxTableFilesSize

func (opts *FIFOCompactionOptions) SetMaxTableFilesSize(value uint64)

SetMaxTableFilesSize sets the max table file size. Once the total sum of table files reaches this, we will delete the oldest table file Default: 1GB

type FilterPolicy

type FilterPolicy interface {
	// keys contains a list of keys (potentially with duplicates)
	// that are ordered according to the user supplied comparator.
	CreateFilter(keys [][]byte) []byte

	// "filter" contains the data appended by a preceding call to
	// CreateFilter(). This method must return true if
	// the key was in the list of keys passed to CreateFilter().
	// This method may return true or false if the key was not on the
	// list, but it should aim to return false with a high probability.
	KeyMayMatch(key []byte, filter []byte) bool

	// Return the name of this policy.
	Name() string
}

FilterPolicy is a factory type that allows the RocksDB database to create a filter, such as a bloom filter, which will used to reduce reads.

func NewBloomFilter

func NewBloomFilter(bitsPerKey int) FilterPolicy

NewBloomFilter returns a new filter policy that uses a bloom filter with approximately the specified number of bits per key. A good value for bits_per_key is 10, which yields a filter with ~1% false positive rate.

Note: if you are using a custom comparator that ignores some parts of the keys being compared, you must not use NewBloomFilterPolicy() and must provide your own FilterPolicy that also ignores the corresponding parts of the keys. For example, if the comparator ignores trailing spaces, it would be incorrect to use a FilterPolicy (like NewBloomFilterPolicy) that does not ignore trailing spaces in keys.

func NewNativeFilterPolicy

func NewNativeFilterPolicy(c *C.rocksdb_filterpolicy_t) FilterPolicy

NewNativeFilterPolicy creates a FilterPolicy object.

type FlushOptions

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

FlushOptions represent all of the available options when manual flushing the database.

func NewDefaultFlushOptions

func NewDefaultFlushOptions() *FlushOptions

NewDefaultFlushOptions creates a default FlushOptions object.

func NewNativeFlushOptions

func NewNativeFlushOptions(c *C.rocksdb_flushoptions_t) *FlushOptions

NewNativeFlushOptions creates a FlushOptions object.

func (*FlushOptions) Destroy

func (opts *FlushOptions) Destroy()

Destroy deallocates the FlushOptions object.

func (*FlushOptions) SetWait

func (opts *FlushOptions) SetWait(value bool)

SetWait specify if the flush will wait until the flush is done. Default: true

type IndexType

type IndexType uint

IndexType specifies the index type that will be used for this table.

type InfoLogLevel

type InfoLogLevel uint

InfoLogLevel describes the log level.

type IngestExternalFileOptions

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

IngestExternalFileOptions represents available options when ingesting external files.

func NewDefaultIngestExternalFileOptions

func NewDefaultIngestExternalFileOptions() *IngestExternalFileOptions

NewDefaultIngestExternalFileOptions creates a default IngestExternalFileOptions object.

func NewNativeIngestExternalFileOptions

func NewNativeIngestExternalFileOptions(c *C.rocksdb_ingestexternalfileoptions_t) *IngestExternalFileOptions

NewNativeIngestExternalFileOptions creates a IngestExternalFileOptions object.

func (*IngestExternalFileOptions) Destroy

func (opts *IngestExternalFileOptions) Destroy()

Destroy deallocates the IngestExternalFileOptions object.

func (*IngestExternalFileOptions) SetAllowBlockingFlush

func (opts *IngestExternalFileOptions) SetAllowBlockingFlush(flag bool)

SetAllowBlockingFlush sets allow_blocking_flush. If set to false and the file key range overlaps with the memtable key range (memtable flush required), IngestExternalFile will fail. Default to true.

func (*IngestExternalFileOptions) SetAllowGlobalSeqNo

func (opts *IngestExternalFileOptions) SetAllowGlobalSeqNo(flag bool)

SetAllowGlobalSeqNo sets allow_global_seqno. If set to false,IngestExternalFile() will fail if the file key range overlaps with existing keys or tombstones in the DB. Default true.

func (*IngestExternalFileOptions) SetMoveFiles

func (opts *IngestExternalFileOptions) SetMoveFiles(flag bool)

SetMoveFiles specifies if it should move the files instead of copying them. Default to false.

func (*IngestExternalFileOptions) SetSnapshotConsistency

func (opts *IngestExternalFileOptions) SetSnapshotConsistency(flag bool)

SetSnapshotConsistency if specifies the consistency. If set to false, an ingested file key could appear in existing snapshots that were created before the file was ingested. Default to true.

type Iterator

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

Iterator provides a way to seek to specific keys and iterate through the keyspace from that point, as well as access the values of those keys.

For example:

     it := db.NewIterator(readOpts)
     defer it.Close()

     it.Seek([]byte("foo"))
		for ; it.Valid(); it.Next() {
         fmt.Printf("Key: %v Value: %v\n", it.Key().Data(), it.Value().Data())
		}

     if err := it.Err(); err != nil {
         return err
     }

func NewNativeIterator

func NewNativeIterator(c unsafe.Pointer) *Iterator

NewNativeIterator creates a Iterator object.

func (*Iterator) Close

func (iter *Iterator) Close()

Close closes the iterator.

func (*Iterator) Err

func (iter *Iterator) Err() error

Err returns nil if no errors happened during iteration, or the actual error otherwise.

func (*Iterator) Key

func (iter *Iterator) Key() []byte

Key returns the key the iterator currently holds.

func (*Iterator) KeyValue

func (iter *Iterator) KeyValue() ([]byte, []byte)

KeyValue returns the key and the value the iterator currently holds.

func (*Iterator) Next

func (iter *Iterator) Next()

Next moves the iterator to the next sequential key in the database.

func (*Iterator) NextValidKeyValue

func (iter *Iterator) NextValidKeyValue() (bool, []byte, []byte)

NextValidKeyValue invokes Next() returns Valid() and the key and the value the iterator currently holds.

func (*Iterator) NextValidPKeyValueSlices

func (iter *Iterator) NextValidPKeyValueSlices(pkey *[]byte, pval *[]byte) bool

NextValidPKeyValueSlices invokes Next() returns Valid() and the key and the value the iterator currently holds.

func (*Iterator) Prev

func (iter *Iterator) Prev()

Prev moves the iterator to the previous sequential key in the database.

func (*Iterator) PrevValidKeyValue

func (iter *Iterator) PrevValidKeyValue() (bool, []byte, []byte)

PrevValidKeyValue invokes Prev() returns Valid() and the key and the value the iterator currently holds.

func (*Iterator) Seek

func (iter *Iterator) Seek(key []byte)

Seek moves the iterator to the position greater than or equal to the key.

func (*Iterator) SeekForPrev

func (iter *Iterator) SeekForPrev(key []byte)

SeekForPrev moves the iterator to the last key that less than or equal to the target key, in contrast with Seek.

func (*Iterator) SeekToFirst

func (iter *Iterator) SeekToFirst()

SeekToFirst moves the iterator to the first key in the database.

func (*Iterator) SeekToLast

func (iter *Iterator) SeekToLast()

SeekToLast moves the iterator to the last key in the database.

func (*Iterator) UnsafeGetIterator

func (iter *Iterator) UnsafeGetIterator() *C.rocksdb_iterator_t

UnsafeGetIterator returns the underlying c iterator handle.

func (*Iterator) UnsafeGetUnsafeIterator

func (iter *Iterator) UnsafeGetUnsafeIterator() unsafe.Pointer

UnsafeGetUnsafeIterator returns the underlying c iterator handle.

func (*Iterator) Valid

func (iter *Iterator) Valid() bool

Valid returns false only when an Iterator has iterated past either the first or the last key in the database.

func (*Iterator) ValidForPrefix

func (iter *Iterator) ValidForPrefix(prefix []byte) bool

ValidForPrefix returns false only when an Iterator has iterated past the first or the last key in the database or the specified prefix.

func (*Iterator) ValidKeyValue

func (iter *Iterator) ValidKeyValue() (bool, []byte, []byte)

ValidKeyValue returns Valid() and the key and the value the iterator currently holds.

func (*Iterator) ValidKeyValueSlices

func (iter *Iterator) ValidKeyValueSlices() (bool, []byte, []byte)

ValidKeyValueSlices returns Valid() and the key and the value the iterator currently holds.

func (*Iterator) Value

func (iter *Iterator) Value() []byte

Value returns the value in the database the iterator currently holds.

type LiveFileMetadata

type LiveFileMetadata struct {
	Name        string
	Level       int
	Size        int64
	SmallestKey []byte
	LargestKey  []byte
}

LiveFileMetadata is a metadata which is associated with each SST file.

type MergeOperator

type MergeOperator interface {
	// Gives the client a way to express the read -> modify -> write semantics
	// key:           The key that's associated with this merge operation.
	//                Client could multiplex the merge operator based on it
	//                if the key space is partitioned and different subspaces
	//                refer to different types of data which have different
	//                merge operation semantics.
	// existingValue: null indicates that the key does not exist before this op.
	// operands:      the sequence of merge operations to apply, front() first.
	//
	// Return true on success.
	//
	// All values passed in will be client-specific values. So if this method
	// returns false, it is because client specified bad data or there was
	// internal corruption. This will be treated as an error by the library.
	FullMerge(key, existingValue []byte, operands [][]byte) ([]byte, bool)

	// This function performs merge(left_op, right_op)
	// when both the operands are themselves merge operation types
	// that you would have passed to a db.Merge() call in the same order
	// (i.e.: db.Merge(key,left_op), followed by db.Merge(key,right_op)).
	//
	// PartialMerge should combine them into a single merge operation.
	// The return value should be constructed such that a call to
	// db.Merge(key, new_value) would yield the same result as a call
	// to db.Merge(key, left_op) followed by db.Merge(key, right_op).
	//
	// If it is impossible or infeasible to combine the two operations, return false.
	// The library will internally keep track of the operations, and apply them in the
	// correct order once a base-value (a Put/Delete/End-of-Database) is seen.
	PartialMerge(key, leftOperand, rightOperand []byte) ([]byte, bool)

	// The name of the MergeOperator.
	Name() string
}

A MergeOperator specifies the SEMANTICS of a merge, which only client knows. It could be numeric addition, list append, string concatenation, edit data structure, ... , anything. The library, on the other hand, is concerned with the exercise of this interface, at the right time (during get, iteration, compaction...)

Please read the RocksDB documentation <http://rocksdb.org/> for more details and example implementations.

func NewNativeMergeOperator

func NewNativeMergeOperator(c *C.rocksdb_mergeoperator_t) MergeOperator

NewNativeMergeOperator creates a MergeOperator object.

type Options

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

Options represent all of the available options when opening a database with Open.

func NewDefaultOptions

func NewDefaultOptions() *Options

NewDefaultOptions creates the default Options.

func NewNativeOptions

func NewNativeOptions(c *C.rocksdb_options_t) *Options

NewNativeOptions creates a Options object.

func (*Options) Destroy

func (opts *Options) Destroy()

Destroy deallocates the Options object.

func (*Options) EnableStatistics

func (opts *Options) EnableStatistics()

EnableStatistics enable statistics.

func (*Options) IncreaseParallelism

func (opts *Options) IncreaseParallelism(totalThreads int)

IncreaseParallelism sets the parallelism.

By default, RocksDB uses only one background thread for flush and compaction. Calling this function will set it up such that total of `total_threads` is used. Good value for `total_threads` is the number of cores. You almost definitely want to call this function if your system is bottlenecked by RocksDB.

func (*Options) OptimizeForPointLookup

func (opts *Options) OptimizeForPointLookup(blockCacheSizeMb uint64)

OptimizeForPointLookup optimize the DB for point lookups.

Use this if you don't need to keep the data sorted, i.e. you'll never use an iterator, only Put() and Get() API calls

If you use this with rocksdb >= 5.0.2, you must call `SetAllowConcurrentMemtableWrites(false)` to avoid an assertion error immediately on opening the db.

func (*Options) OptimizeLevelStyleCompaction

func (opts *Options) OptimizeLevelStyleCompaction(memtableMemoryBudget uint64)

OptimizeLevelStyleCompaction optimize the DB for leveld compaction.

Default values for some parameters in ColumnFamilyOptions are not optimized for heavy workloads and big datasets, which means you might observe write stalls under some conditions. As a starting point for tuning RocksDB options, use the following two functions: * OptimizeLevelStyleCompaction -- optimizes level style compaction * OptimizeUniversalStyleCompaction -- optimizes universal style compaction Universal style compaction is focused on reducing Write Amplification Factor for big data sets, but increases Space Amplification. You can learn more about the different styles here: https://github.com/facebook/rocksdb/wiki/Rocksdb-Architecture-Guide Make sure to also call IncreaseParallelism(), which will provide the biggest performance gains. Note: we might use more memory than memtable_memory_budget during high write rate period

func (*Options) OptimizeUniversalStyleCompaction

func (opts *Options) OptimizeUniversalStyleCompaction(memtableMemoryBudget uint64)

OptimizeUniversalStyleCompaction optimize the DB for universal compaction. See note on OptimizeLevelStyleCompaction.

func (*Options) PrepareForBulkLoad

func (opts *Options) PrepareForBulkLoad()

PrepareForBulkLoad prepare the DB for bulk loading.

All data will be in level 0 without any automatic compaction. It's recommended to manually call CompactRange(NULL, NULL) before reading from the database, because otherwise the read can be very slow.

func (*Options) SetAccessHintOnCompactionStart

func (opts *Options) SetAccessHintOnCompactionStart(value CompactionAccessPattern)

SetAccessHintOnCompactionStart specifies the file access pattern once a compaction is started.

It will be applied to all input files of a compaction. Default: NormalCompactionAccessPattern

func (*Options) SetAdviseRandomOnOpen

func (opts *Options) SetAdviseRandomOnOpen(value bool)

SetAdviseRandomOnOpen specifies whether we will hint the underlying file system that the file access pattern is random, when a sst file is opened. Default: true

func (*Options) SetAllowConcurrentMemtableWrites

func (opts *Options) SetAllowConcurrentMemtableWrites(allow bool)

SetAllowConcurrentMemtableWrites sets whether to allow concurrent memtable writes. Conccurent writes are not supported by all memtable factories (currently only SkipList memtables). As of rocksdb 5.0.2 you must call `SetAllowConcurrentMemtableWrites(false)` if you use `OptimizeForPointLookup`.

func (*Options) SetAllowMmapReads

func (opts *Options) SetAllowMmapReads(value bool)

SetAllowMmapReads enable/disable mmap reads for reading sst tables. Default: false

func (*Options) SetAllowMmapWrites

func (opts *Options) SetAllowMmapWrites(value bool)

SetAllowMmapWrites enable/disable mmap writes for writing sst tables. Default: false

func (*Options) SetArenaBlockSize

func (opts *Options) SetArenaBlockSize(value int)

SetArenaBlockSize sets the size of one block in arena memory allocation.

If <= 0, a proper value is automatically calculated (usually 1/10 of writer_buffer_size). Default: 0

func (*Options) SetBlockBasedTableFactory

func (opts *Options) SetBlockBasedTableFactory(value *BlockBasedTableOptions)

SetBlockBasedTableFactory sets the block based table factory.

func (*Options) SetBloomLocality

func (opts *Options) SetBloomLocality(value uint32)

SetBloomLocality sets the bloom locality.

Control locality of bloom filter probes to improve cache miss rate. This option only applies to memtable prefix bloom and plaintable prefix bloom. It essentially limits the max number of cache lines each bloom filter check can touch. This optimization is turned off when set to 0. The number should never be greater than number of probes. This option can boost performance for in-memory workload but should use with care since it can cause higher false positive rate. Default: 0

func (*Options) SetBytesPerSync

func (opts *Options) SetBytesPerSync(value uint64)

SetBytesPerSync sets the bytes per sync.

Allows OS to incrementally sync files to disk while they are being written, asynchronously, in the background. Issue one request for every bytes_per_sync written. Default: 0 (disabled)

func (*Options) SetCompactionFilter

func (opts *Options) SetCompactionFilter(value CompactionFilter)

SetCompactionFilter sets the specified compaction filter which will be applied on compactions. Default: nil

func (*Options) SetCompactionStyle

func (opts *Options) SetCompactionStyle(value CompactionStyle)

SetCompactionStyle sets the compaction style. Default: LevelCompactionStyle

func (*Options) SetComparator

func (opts *Options) SetComparator(value Comparator)

SetComparator sets the comparator which define the order of keys in the table. Default: a comparator that uses lexicographic byte-wise ordering

func (*Options) SetComparatorUnsafe

func (opts *Options) SetComparatorUnsafe(ptr unsafe.Pointer)

SetComparatorUnsafe sets the comparator with an unsafe.Pointer.

func (*Options) SetCompression

func (opts *Options) SetCompression(value CompressionType)

SetCompression sets the compression algorithm. Default: SnappyCompression, which gives lightweight but fast compression.

func (*Options) SetCompressionOptions

func (opts *Options) SetCompressionOptions(value *CompressionOptions)

SetCompressionOptions sets different options for compression algorithms. Default: nil

func (*Options) SetCompressionPerLevel

func (opts *Options) SetCompressionPerLevel(value ...CompressionType)

SetCompressionPerLevel sets different compression algorithm per level.

Different levels can have different compression policies. There are cases where most lower levels would like to quick compression algorithm while the higher levels (which have more data) use compression algorithms that have better compression but could be slower. This array should have an entry for each level of the database. This array overrides the value specified in the previous field 'compression'.

func (*Options) SetCreateIfMissing

func (opts *Options) SetCreateIfMissing(value bool)

SetCreateIfMissing specifies whether the database should be created if it is missing. Default: false

func (*Options) SetCreateIfMissingColumnFamilies

func (opts *Options) SetCreateIfMissingColumnFamilies(value bool)

SetCreateIfMissingColumnFamilies specifies whether the column families should be created if they are missing.

func (*Options) SetDBPaths

func (opts *Options) SetDBPaths(dbpaths []*DBPath)

SetDBPaths sets the DBPaths of the options.

A list of paths where SST files can be put into, with its target size. Newer data is placed into paths specified earlier in the vector while older data gradually moves to paths specified later in the vector.

For example, you have a flash device with 10GB allocated for the DB, as well as a hard drive of 2TB, you should config it to be:

[{"/flash_path", 10GB}, {"/hard_drive", 2TB}]

The system will try to guarantee data under each path is close to but not larger than the target size. But current and future file sizes used by determining where to place a file are based on best-effort estimation, which means there is a chance that the actual size under the directory is slightly more than target size under some workloads. User should give some buffer room for those cases.

If none of the paths has sufficient room to place a file, the file will be placed to the last path anyway, despite to the target size.

Placing newer data to earlier paths is also best-efforts. User should expect user files to be placed in higher levels in some extreme cases.

If left empty, only one path will be used, which is db_name passed when opening the DB. Default: empty

func (*Options) SetDbLogDir

func (opts *Options) SetDbLogDir(value string)

SetDbLogDir specifies the absolute info LOG dir.

If it is empty, the log files will be in the same dir as data. If it is non empty, the log files will be in the specified dir, and the db data dir's absolute path will be used as the log file name's prefix. Default: empty

func (*Options) SetDbWriteBufferSize

func (opts *Options) SetDbWriteBufferSize(value int)

SetDbWriteBufferSize sets the amount of data to build up in memtables across all column families before writing to disk.

This is distinct from write_buffer_size, which enforces a limit for a single memtable.

This feature is disabled by default. Specify a non-zero value to enable it.

Default: 0 (disabled)

func (*Options) SetDeleteObsoleteFilesPeriodMicros

func (opts *Options) SetDeleteObsoleteFilesPeriodMicros(value uint64)

SetDeleteObsoleteFilesPeriodMicros sets the periodicity when obsolete files get deleted.

The files that get out of scope by compaction process will still get automatically delete on every compaction, regardless of this setting. Default: 6 hours

func (*Options) SetDisableAutoCompactions

func (opts *Options) SetDisableAutoCompactions(value bool)

SetDisableAutoCompactions enable/disable automatic compactions.

Manual compactions can still be issued on this database. Default: false

func (*Options) SetEnv

func (opts *Options) SetEnv(value *Env)

SetEnv sets the specified object to interact with the environment, e.g. to read/write files, schedule background work, etc. Default: DefaultEnv

func (*Options) SetErrorIfExists

func (opts *Options) SetErrorIfExists(value bool)

SetErrorIfExists specifies whether an error should be raised if the database already exists. Default: false

func (*Options) SetFIFOCompactionOptions

func (opts *Options) SetFIFOCompactionOptions(value *FIFOCompactionOptions)

SetFIFOCompactionOptions sets the options for FIFO compaction style. Default: nil

func (*Options) SetHardPendingCompactionBytesLimit

func (opts *Options) SetHardPendingCompactionBytesLimit(value uint64)

SetHardPendingCompactionBytesLimit sets the bytes threshold at which all writes are stopped if estimated bytes needed to be compaction exceed this threshold.

Default: 256GB

func (*Options) SetHardRateLimit

func (opts *Options) SetHardRateLimit(value float64)

SetHardRateLimit sets the hard rate limit.

Puts are delayed 1ms at a time when any level has a compaction score that exceeds hard_rate_limit. This is ignored when <= 1.0. Default: 0.0 (disabled)

func (*Options) SetHashLinkListRep

func (opts *Options) SetHashLinkListRep(bucketCount int)

SetHashLinkListRep sets a hashed linked list as MemTableRep.

It contains a fixed array of buckets, each pointing to a sorted single linked list (null if the bucket is empty).

bucketCount: number of fixed array buckets

func (*Options) SetHashSkipListRep

func (opts *Options) SetHashSkipListRep(bucketCount int, skiplistHeight, skiplistBranchingFactor int32)

SetHashSkipListRep sets a hash skip list as MemTableRep.

It contains a fixed array of buckets, each pointing to a skiplist (null if the bucket is empty).

bucketCount: number of fixed array buckets skiplistHeight: the max height of the skiplist skiplistBranchingFactor: probabilistic size ratio between adjacent

link lists in the skiplist

func (*Options) SetInfoLogLevel

func (opts *Options) SetInfoLogLevel(value InfoLogLevel)

SetInfoLogLevel sets the info log level. Default: InfoInfoLogLevel

func (*Options) SetInplaceUpdateNumLocks

func (opts *Options) SetInplaceUpdateNumLocks(value int)

SetInplaceUpdateNumLocks sets the number of locks used for inplace update. Default: 10000, if inplace_update_support = true, else 0.

func (*Options) SetInplaceUpdateSupport

func (opts *Options) SetInplaceUpdateSupport(value bool)

SetInplaceUpdateSupport enable/disable thread-safe inplace updates.

Requires updates if * key exists in current memtable * new sizeof(new_value) <= sizeof(old_value) * old_value for that key is a put i.e. kTypeValue Default: false.

func (*Options) SetIsFdCloseOnExec

func (opts *Options) SetIsFdCloseOnExec(value bool)

SetIsFdCloseOnExec enable/dsiable child process inherit open files. Default: true

func (*Options) SetKeepLogFileNum

func (opts *Options) SetKeepLogFileNum(value int)

SetKeepLogFileNum sets the maximal info log files to be kept. Default: 1000

func (*Options) SetLevel0FileNumCompactionTrigger

func (opts *Options) SetLevel0FileNumCompactionTrigger(value int)

SetLevel0FileNumCompactionTrigger sets the number of files to trigger level-0 compaction.

A value <0 means that level-0 compaction will not be triggered by number of files at all. Default: 4

func (*Options) SetLevel0SlowdownWritesTrigger

func (opts *Options) SetLevel0SlowdownWritesTrigger(value int)

SetLevel0SlowdownWritesTrigger sets the soft limit on number of level-0 files.

We start slowing down writes at this point. A value <0 means that no writing slow down will be triggered by number of files in level-0. Default: 8

func (*Options) SetLevel0StopWritesTrigger

func (opts *Options) SetLevel0StopWritesTrigger(value int)

SetLevel0StopWritesTrigger sets the maximum number of level-0 files. We stop writes at this point. Default: 12

func (*Options) SetLogFileTimeToRoll

func (opts *Options) SetLogFileTimeToRoll(value int)

SetLogFileTimeToRoll sets the time for the info log file to roll (in seconds).

If specified with non-zero value, log file will be rolled if it has been active longer than `log_file_time_to_roll`. Default: 0 (disabled)

func (*Options) SetManifestPreallocationSize

func (opts *Options) SetManifestPreallocationSize(value int)

SetManifestPreallocationSize sets the number of bytes to preallocate (via fallocate) the manifest files.

Default is 4mb, which is reasonable to reduce random IO as well as prevent overallocation for mounts that preallocate large amounts of data (such as xfs's allocsize option). Default: 4mb

func (*Options) SetMaxBackgroundCompactions

func (opts *Options) SetMaxBackgroundCompactions(value int)

SetMaxBackgroundCompactions sets the maximum number of concurrent background jobs, submitted to the default LOW priority thread pool Default: 1

func (*Options) SetMaxBackgroundFlushes

func (opts *Options) SetMaxBackgroundFlushes(value int)

SetMaxBackgroundFlushes sets the maximum number of concurrent background memtable flush jobs, submitted to the HIGH priority thread pool.

By default, all background jobs (major compaction and memtable flush) go to the LOW priority pool. If this option is set to a positive number, memtable flush jobs will be submitted to the HIGH priority pool. It is important when the same Env is shared by multiple db instances. Without a separate pool, long running major compaction jobs could potentially block memtable flush jobs of other db instances, leading to unnecessary Put stalls. Default: 0

func (*Options) SetMaxBytesForLevelBase

func (opts *Options) SetMaxBytesForLevelBase(value uint64)

SetMaxBytesForLevelBase sets the maximum total data size for a level.

It is the max total for level-1. Maximum number of bytes for level L can be calculated as (max_bytes_for_level_base) * (max_bytes_for_level_multiplier ^ (L-1))

For example, if max_bytes_for_level_base is 20MB, and if max_bytes_for_level_multiplier is 10, total data size for level-1 will be 20MB, total file size for level-2 will be 200MB, and total file size for level-3 will be 2GB. Default: 10MB

func (*Options) SetMaxBytesForLevelMultiplier

func (opts *Options) SetMaxBytesForLevelMultiplier(value float64)

SetMaxBytesForLevelMultiplier sets the max Bytes for level multiplier. Default: 10

func (*Options) SetMaxBytesForLevelMultiplierAdditional

func (opts *Options) SetMaxBytesForLevelMultiplierAdditional(value []int)

SetMaxBytesForLevelMultiplierAdditional sets different max-size multipliers for different levels.

These are multiplied by max_bytes_for_level_multiplier to arrive at the max-size of each level. Default: 1 for each level

func (*Options) SetMaxCompactionBytes

func (opts *Options) SetMaxCompactionBytes(value uint64)

SetMaxCompactionBytes sets the maximum number of bytes in all compacted files. We try to limit number of bytes in one compaction to be lower than this threshold. But it's not guaranteed. Value 0 will be sanitized. Default: result.target_file_size_base * 25

func (*Options) SetMaxFileOpeningThreads

func (opts *Options) SetMaxFileOpeningThreads(value int)

SetMaxFileOpeningThreads sets the maximum number of file opening threads. If max_open_files is -1, DB will open all files on DB::Open(). You can use this option to increase the number of threads used to open the files. Default: 16

func (*Options) SetMaxLogFileSize

func (opts *Options) SetMaxLogFileSize(value int)

SetMaxLogFileSize sets the maximal size of the info log file.

If the log file is larger than `max_log_file_size`, a new info log file will be created. If max_log_file_size == 0, all logs will be written to one log file. Default: 0

func (*Options) SetMaxManifestFileSize

func (opts *Options) SetMaxManifestFileSize(value uint64)

SetMaxManifestFileSize sets the maximal manifest file size until is rolled over. The older manifest file be deleted. Default: MAX_INT so that roll-over does not take place.

func (*Options) SetMaxMemCompactionLevel

func (opts *Options) SetMaxMemCompactionLevel(value int)

SetMaxMemCompactionLevel sets the maximum level to which a new compacted memtable is pushed if it does not create overlap.

We try to push to level 2 to avoid the relatively expensive level 0=>1 compactions and to avoid some expensive manifest file operations. We do not push all the way to the largest level since that can generate a lot of wasted disk space if the same key space is being repeatedly overwritten. Default: 2

func (*Options) SetMaxOpenFiles

func (opts *Options) SetMaxOpenFiles(value int)

SetMaxOpenFiles sets the number of open files that can be used by the DB.

You may need to increase this if your database has a large working set (budget one open file per 2MB of working set). Default: 1000

func (*Options) SetMaxSequentialSkipInIterations

func (opts *Options) SetMaxSequentialSkipInIterations(value uint64)

SetMaxSequentialSkipInIterations specifies whether an iteration->Next() sequentially skips over keys with the same user-key or not.

This number specifies the number of keys (with the same userkey) that will be sequentially skipped before a reseek is issued. Default: 8

func (*Options) SetMaxSuccessiveMerges

func (opts *Options) SetMaxSuccessiveMerges(value int)

SetMaxSuccessiveMerges sets the maximum number of successive merge operations on a key in the memtable.

When a merge operation is added to the memtable and the maximum number of successive merges is reached, the value of the key will be calculated and inserted into the memtable instead of the merge operation. This will ensure that there are never more than max_successive_merges merge operations in the memtable. Default: 0 (disabled)

func (*Options) SetMaxTotalWalSize

func (opts *Options) SetMaxTotalWalSize(value uint64)

SetMaxTotalWalSize sets the maximum total wal size in bytes. Once write-ahead logs exceed this size, we will start forcing the flush of column families whose memtables are backed by the oldest live WAL file (i.e. the ones that are causing all the space amplification). If set to 0 (default), we will dynamically choose the WAL size limit to be [sum of all write_buffer_size * max_write_buffer_number] * 4 Default: 0

func (*Options) SetMaxWriteBufferNumber

func (opts *Options) SetMaxWriteBufferNumber(value int)

SetMaxWriteBufferNumber sets the maximum number of write buffers that are built up in memory.

The default is 2, so that when 1 write buffer is being flushed to storage, new writes can continue to the other write buffer. Default: 2

func (*Options) SetMemtableHugePageSize

func (opts *Options) SetMemtableHugePageSize(value int)

SetMemtableHugePageSize sets the page size for huge page for arena used by the memtable. If <=0, it won't allocate from huge page but from malloc. Users are responsible to reserve huge pages for it to be allocated. For example:

sysctl -w vm.nr_hugepages=20

See linux doc Documentation/vm/hugetlbpage.txt If there isn't enough free huge page available, it will fall back to malloc.

Dynamically changeable through SetOptions() API

func (*Options) SetMemtableVectorRep

func (opts *Options) SetMemtableVectorRep()

SetMemtableVectorRep sets a MemTableRep which is backed by a vector.

On iteration, the vector is sorted. This is useful for workloads where iteration is very rare and writes are generally not issued after reads begin.

func (*Options) SetMergeOperator

func (opts *Options) SetMergeOperator(value MergeOperator)

SetMergeOperator sets the merge operator which will be called if a merge operations are used. Default: nil

func (*Options) SetMinLevelToCompress

func (opts *Options) SetMinLevelToCompress(value int)

SetMinLevelToCompress sets the start level to use compression.

func (*Options) SetMinWriteBufferNumberToMerge

func (opts *Options) SetMinWriteBufferNumberToMerge(value int)

SetMinWriteBufferNumberToMerge sets the minimum number of write buffers that will be merged together before writing to storage.

If set to 1, then all write buffers are flushed to L0 as individual files and this increases read amplification because a get request has to check in all of these files. Also, an in-memory merge may result in writing lesser data to storage if there are duplicate records in each of these individual write buffers. Default: 1

func (*Options) SetNumLevels

func (opts *Options) SetNumLevels(value int)

SetNumLevels sets the number of levels for this database. Default: 7

func (*Options) SetParanoidChecks

func (opts *Options) SetParanoidChecks(value bool)

SetParanoidChecks enable/disable paranoid checks.

If true, the implementation will do aggressive checking of the data it is processing and will stop early if it detects any errors. This may have unforeseen ramifications: for example, a corruption of one DB entry may cause a large number of entries to become unreadable or for the entire DB to become unopenable. If any of the writes to the database fails (Put, Delete, Merge, Write), the database will switch to read-only mode and fail all other Write operations. Default: false

func (*Options) SetPlainTableFactory

func (opts *Options) SetPlainTableFactory(keyLen uint32, bloomBitsPerKey int, hashTableRatio float64, indexSparseness int)

SetPlainTableFactory sets a plain table factory with prefix-only seek.

For this factory, you need to set prefix_extractor properly to make it work. Look-up will starts with prefix hash lookup for key prefix. Inside the hash bucket found, a binary search is executed for hash conflicts. Finally, a linear search is used.

keyLen: plain table has optimization for fix-sized keys,

which can be specified via keyLen.

bloomBitsPerKey: the number of bits used for bloom filer per prefix. You

may disable it by passing a zero.

hashTableRatio: the desired utilization of the hash table used for prefix

hashing. hashTableRatio = number of prefixes / #buckets
in the hash table

indexSparseness: inside each prefix, need to build one index record for how

many keys for binary search inside each hash bucket.

func (*Options) SetPrefixExtractor

func (opts *Options) SetPrefixExtractor(value SliceTransform)

SetPrefixExtractor sets the prefic extractor.

If set, use the specified function to determine the prefixes for keys. These prefixes will be placed in the filter. Depending on the workload, this can reduce the number of read-IOP cost for scans when a prefix is passed via ReadOptions to db.NewIterator(). Default: nil

func (*Options) SetPurgeRedundantKvsWhileFlush

func (opts *Options) SetPurgeRedundantKvsWhileFlush(value bool)

SetPurgeRedundantKvsWhileFlush enable/disable purging of duplicate/deleted keys when a memtable is flushed to storage. Default: true

func (*Options) SetRateLimitDelayMaxMilliseconds

func (opts *Options) SetRateLimitDelayMaxMilliseconds(value uint)

SetRateLimitDelayMaxMilliseconds sets the max time a put will be stalled when hard_rate_limit is enforced. If 0, then there is no limit. Default: 1000

func (*Options) SetRateLimiter

func (opts *Options) SetRateLimiter(rateLimiter *RateLimiter)

SetRateLimiter sets the rate limiter of the options. Use to control write rate of flush and compaction. Flush has higher priority than compaction. Rate limiting is disabled if nullptr. If rate limiter is enabled, bytes_per_sync is set to 1MB by default. Default: nullptr

func (*Options) SetSkipLogErrorOnRecovery

func (opts *Options) SetSkipLogErrorOnRecovery(value bool)

SetSkipLogErrorOnRecovery enable/disable skipping of log corruption error on recovery (If client is ok with losing most recent changes) Default: false

func (*Options) SetSoftPendingCompactionBytesLimit

func (opts *Options) SetSoftPendingCompactionBytesLimit(value uint64)

SetSoftPendingCompactionBytesLimit sets the threshold at which all writes will be slowed down to at least delayed_write_rate if estimated bytes needed to be compaction exceed this threshold.

Default: 64GB

func (*Options) SetSoftRateLimit

func (opts *Options) SetSoftRateLimit(value float64)

SetSoftRateLimit sets the soft rate limit.

Puts are delayed 0-1 ms when any level has a compaction score that exceeds soft_rate_limit. This is ignored when == 0.0. CONSTRAINT: soft_rate_limit <= hard_rate_limit. If this constraint does not hold, RocksDB will set soft_rate_limit = hard_rate_limit Default: 0.0 (disabled)

func (*Options) SetStatsDumpPeriodSec

func (opts *Options) SetStatsDumpPeriodSec(value uint)

SetStatsDumpPeriodSec sets the stats dump period in seconds.

If not zero, dump stats to LOG every stats_dump_period_sec Default: 3600 (1 hour)

func (*Options) SetTableCacheNumshardbits

func (opts *Options) SetTableCacheNumshardbits(value int)

SetTableCacheNumshardbits sets the number of shards used for table cache. Default: 4

func (*Options) SetTableCacheRemoveScanCountLimit

func (opts *Options) SetTableCacheRemoveScanCountLimit(value int)

SetTableCacheRemoveScanCountLimit sets the count limit during a scan.

During data eviction of table's LRU cache, it would be inefficient to strictly follow LRU because this piece of memory will not really be released unless its refcount falls to zero. Instead, make two passes: the first pass will release items with refcount = 1, and if not enough space releases after scanning the number of elements specified by this parameter, we will remove items in LRU order. Default: 16

func (*Options) SetTargetFileSizeBase

func (opts *Options) SetTargetFileSizeBase(value uint64)

SetTargetFileSizeBase sets the target file size for compaction.

Target file size is per-file size for level-1. Target file size for level L can be calculated by target_file_size_base * (target_file_size_multiplier ^ (L-1))

For example, if target_file_size_base is 2MB and target_file_size_multiplier is 10, then each file on level-1 will be 2MB, and each file on level 2 will be 20MB, and each file on level-3 will be 200MB. Default: 2MB

func (*Options) SetTargetFileSizeMultiplier

func (opts *Options) SetTargetFileSizeMultiplier(value int)

SetTargetFileSizeMultiplier sets the target file size multiplier for compaction. Default: 1

func (*Options) SetUniversalCompactionOptions

func (opts *Options) SetUniversalCompactionOptions(value *UniversalCompactionOptions)

SetUniversalCompactionOptions sets the options needed to support Universal Style compactions. Default: nil

func (*Options) SetUseAdaptiveMutex

func (opts *Options) SetUseAdaptiveMutex(value bool)

SetUseAdaptiveMutex enable/disable adaptive mutex, which spins in the user space before resorting to kernel.

This could reduce context switch when the mutex is not heavily contended. However, if the mutex is hot, we could end up wasting spin time. Default: false

func (*Options) SetUseDirectIOForFlushAndCompaction

func (opts *Options) SetUseDirectIOForFlushAndCompaction(value bool)

SetUseDirectIOForFlushAndCompaction enable/disable direct I/O mode (O_DIRECT) for both reads and writes in background flush and compactions When true, new_table_reader_for_compaction_inputs is forced to true. Default: false

func (*Options) SetUseDirectReads

func (opts *Options) SetUseDirectReads(value bool)

SetUseDirectReads enable/disable direct I/O mode (O_DIRECT) for reads Default: false

func (*Options) SetUseFsync

func (opts *Options) SetUseFsync(value bool)

SetUseFsync enable/disable fsync.

If true, then every store to stable storage will issue a fsync. If false, then every store to stable storage will issue a fdatasync. This parameter should be set to true while storing data to filesystem like ext3 that can lose files after a reboot. Default: false

func (*Options) SetWALTtlSeconds

func (opts *Options) SetWALTtlSeconds(value uint64)

SetWALTtlSeconds sets the WAL ttl in seconds.

The following two options affect how archived logs will be deleted.

  1. If both set to 0, logs will be deleted asap and will not get into the archive.
  2. If wal_ttl_seconds is 0 and wal_size_limit_mb is not 0, WAL files will be checked every 10 min and if total size is greater then wal_size_limit_mb, they will be deleted starting with the earliest until size_limit is met. All empty files will be deleted.
  3. If wal_ttl_seconds is not 0 and wall_size_limit_mb is 0, then WAL files will be checked every wal_ttl_seconds / 2 and those that are older than wal_ttl_seconds will be deleted.
  4. If both are not 0, WAL files will be checked every 10 min and both checks will be performed with ttl being first.

Default: 0

func (*Options) SetWalDir

func (opts *Options) SetWalDir(value string)

SetWalDir specifies the absolute dir path for write-ahead logs (WAL).

If it is empty, the log files will be in the same dir as data. If it is non empty, the log files will be in the specified dir, When destroying the db, all log files and the dir itopts is deleted. Default: empty

func (*Options) SetWalSizeLimitMb

func (opts *Options) SetWalSizeLimitMb(value uint64)

SetWalSizeLimitMb sets the WAL size limit in MB.

If total size of WAL files is greater then wal_size_limit_mb, they will be deleted starting with the earliest until size_limit is met Default: 0

func (*Options) SetWriteBufferSize

func (opts *Options) SetWriteBufferSize(value int)

SetWriteBufferSize sets the amount of data to build up in memory (backed by an unsorted log on disk) before converting to a sorted on-disk file.

Larger values increase performance, especially during bulk loads. Up to max_write_buffer_number write buffers may be held in memory at the same time, so you may wish to adjust this parameter to control memory usage. Also, a larger write buffer will result in a longer recovery time the next time the database is opened. Default: 4MB

type Range

type Range struct {
	Start []byte
	Limit []byte
}

Range is a range of keys in the database. GetApproximateSizes calls with it begin at the key Start and end right before the key Limit.

type RateLimiter

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

RateLimiter is used to control write rate of flush and compaction.

func NewNativeRateLimiter

func NewNativeRateLimiter(c *C.rocksdb_ratelimiter_t) *RateLimiter

NewNativeRateLimiter creates a native RateLimiter object.

func NewRateLimiter

func NewRateLimiter(rateBytesPerSec, refillPeriodUs int64, fairness int32) *RateLimiter

NewRateLimiter creates a default RateLimiter object.

func (*RateLimiter) Destroy

func (rl *RateLimiter) Destroy()

Destroy deallocates the RateLimiter object.

type ReadOptions

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

ReadOptions represent all of the available options when reading from a database.

func NewDefaultReadOptions

func NewDefaultReadOptions() *ReadOptions

NewDefaultReadOptions creates a default ReadOptions object.

func NewDefaultReadOptionsSetupQuick

func NewDefaultReadOptionsSetupQuick(
	verifyChecksums, fillCache, tailing bool, upperBound []byte, readaheadSize uint64, pinData bool) *ReadOptions

NewDefaultReadOptionsSetupQuick creates a default ReadOptions object with the given parameters.

func NewNativeReadOptions

func NewNativeReadOptions(c *C.rocksdb_readoptions_t) *ReadOptions

NewNativeReadOptions creates a ReadOptions object.

func (*ReadOptions) Destroy

func (opts *ReadOptions) Destroy()

Destroy deallocates the ReadOptions object.

func (*ReadOptions) SetFillCache

func (opts *ReadOptions) SetFillCache(value bool)

SetFillCache specify whether the "data block"/"index block"/"filter block" read for this iteration should be cached in memory? Callers may wish to set this field to false for bulk scans. Default: true

func (*ReadOptions) SetIterateUpperBound

func (opts *ReadOptions) SetIterateUpperBound(upperBound []byte)

SetIterateUpperBound specifies "iterate_upper_bound", which defines the extent upto which the forward iterator can returns entries. Once the bound is reached, Valid() will be false. "iterate_upper_bound" is exclusive ie the bound value is not a valid entry. If iterator_extractor is not null, the Seek target and iterator_upper_bound need to have the same prefix. This is because ordering is not guaranteed outside of prefix domain. There is no lower bound on the iterator. If needed, that can be easily implemented. Default: nullptr If you set an upper bound and keep your Iterator open, you must take care that you do hold a reference to the ReadOptions. Otherwise the upperBound might get garbage collected and the Iterator might not work as expected.

func (*ReadOptions) SetPinData

func (opts *ReadOptions) SetPinData(value bool)

SetPinData specifies the value of "pin_data". If true, it keeps the blocks loaded by the iterator pinned in memory as long as the iterator is not deleted, If used when reading from tables created with BlockBasedTableOptions::use_delta_encoding = false, Iterator's property "rocksdb.iterator.is-key-pinned" is guaranteed to return 1. Default: false

func (*ReadOptions) SetReadTier

func (opts *ReadOptions) SetReadTier(value ReadTier)

SetReadTier specify if this read request should process data that ALREADY resides on a particular cache. If the required data is not found at the specified cache, then Status::Incomplete is returned. Default: ReadAllTier

func (*ReadOptions) SetReadaheadSize

func (opts *ReadOptions) SetReadaheadSize(size uint64)

SetReadaheadSize sets the read ahead size for new iterators. If non-zero, NewIterator will create a new table reader which performs reads of the given size. Using a large size (> 2MB) can improve the performance of forward iteration on spinning disks. Default: 0

func (*ReadOptions) SetSnapshot

func (opts *ReadOptions) SetSnapshot(snap *Snapshot)

SetSnapshot sets the snapshot which should be used for the read. The snapshot must belong to the DB that is being read and must not have been released. Default: nil

func (*ReadOptions) SetTailing

func (opts *ReadOptions) SetTailing(value bool)

SetTailing specify if to create a tailing iterator. A special iterator that has a view of the complete database (i.e. it can also be used to read newly added data) and is optimized for sequential reads. It will return records that were inserted into the database after the creation of the iterator. Default: false

func (*ReadOptions) SetTotalOrderSeek

func (opts *ReadOptions) SetTotalOrderSeek(value bool)

SetTotalOrderSeek enables a total order seek regardless of index format (e.g. hash index) used in the table. Some table format (e.g. plain table) may not support this option. If true when calling Get(), we also skip prefix bloom when reading from block based table. It provides a way to read existing data after changing implementation of prefix extractor.

func (*ReadOptions) SetVerifyChecksums

func (opts *ReadOptions) SetVerifyChecksums(value bool)

SetVerifyChecksums speciy if all data read from underlying storage will be verified against corresponding checksums. Default: false

func (*ReadOptions) UnsafeGetReadOptions

func (opts *ReadOptions) UnsafeGetReadOptions() unsafe.Pointer

UnsafeGetReadOptions returns the underlying c read options object.

type ReadTier

type ReadTier uint

ReadTier controls fetching of data during a read request. An application can issue a read request (via Get/Iterators) and specify if that read should process data that ALREADY resides on a specified cache level. For example, if an application specifies BlockCacheTier then the Get call will process data that is already processed in the memtable or the block cache. It will not page in data from the OS cache or data that resides in storage.

type RestoreOptions

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

RestoreOptions captures the options to be used during restoration of a backup.

func NewRestoreOptions

func NewRestoreOptions() *RestoreOptions

NewRestoreOptions creates a RestoreOptions instance.

func (*RestoreOptions) Destroy

func (ro *RestoreOptions) Destroy()

Destroy destroys this RestoreOptions instance.

func (*RestoreOptions) SetKeepLogFiles

func (ro *RestoreOptions) SetKeepLogFiles(v int)

SetKeepLogFiles is used to set or unset the keep_log_files option If true, restore won't overwrite the existing log files in wal_dir. It will also move all log files from archive directory to wal_dir. By default, this is false.

type SSTFileWriter

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

SSTFileWriter is used to create sst files that can be added to database later. All keys in files generated by SstFileWriter will have sequence number = 0.

func NewSSTFileWriter

func NewSSTFileWriter(opts *EnvOptions, dbOpts *Options) *SSTFileWriter

NewSSTFileWriter creates an SSTFileWriter object.

func (*SSTFileWriter) Add

func (w *SSTFileWriter) Add(key, value []byte) error

Add adds key, value to currently opened file. REQUIRES: key is after any previously added key according to comparator.

func (*SSTFileWriter) Destroy

func (w *SSTFileWriter) Destroy()

Destroy destroys the SSTFileWriter object.

func (*SSTFileWriter) Finish

func (w *SSTFileWriter) Finish() error

Finish finishes writing to sst file and close file.

func (*SSTFileWriter) Open

func (w *SSTFileWriter) Open(path string) error

Open prepares SstFileWriter to write into file located at "path".

type SliceTransform

type SliceTransform interface {
	// Transform a src in domain to a dst in the range.
	Transform(src []byte) []byte

	// Determine whether this is a valid src upon the function applies.
	InDomain(src []byte) bool

	// Determine whether dst=Transform(src) for some src.
	InRange(src []byte) bool

	// Return the name of this transformation.
	Name() string
}

A SliceTransform can be used as a prefix extractor.

func NewFixedPrefixTransform

func NewFixedPrefixTransform(prefixLen int) SliceTransform

NewFixedPrefixTransform creates a new fixed prefix transform.

func NewNativeSliceTransform

func NewNativeSliceTransform(c *C.rocksdb_slicetransform_t) SliceTransform

NewNativeSliceTransform creates a SliceTransform object.

type Snapshot

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

Snapshot provides a consistent view of read operations in a DB.

func NewNativeSnapshot

func NewNativeSnapshot(c *C.rocksdb_snapshot_t) *Snapshot

NewNativeSnapshot creates a Snapshot object.

type Transaction

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

Transaction is used with TransactionDB for transaction support.

func NewNativeTransaction

func NewNativeTransaction(c *C.rocksdb_transaction_t) *Transaction

NewNativeTransaction creates a Transaction object.

func (*Transaction) Commit

func (transaction *Transaction) Commit() error

Commit commits the transaction to the database.

func (*Transaction) Delete

func (transaction *Transaction) Delete(key []byte) error

Delete removes the data associated with the key from the transaction.

func (*Transaction) Destroy

func (transaction *Transaction) Destroy()

Destroy deallocates the transaction object.

func (*Transaction) Get

func (transaction *Transaction) Get(opts *ReadOptions, key []byte) ([]byte, error)

Get returns the data associated with the key from the database given this transaction.

func (*Transaction) NewIterator

func (transaction *Transaction) NewIterator(opts *ReadOptions) *Iterator

NewIterator returns an Iterator over the database that uses the ReadOptions given.

func (*Transaction) Put

func (transaction *Transaction) Put(key, value []byte) error

Put writes data associated with a key to the transaction.

func (*Transaction) Rollback

func (transaction *Transaction) Rollback() error

Rollback performs a rollback on the transaction.

type TransactionDB

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

TransactionDB is a reusable handle to a RocksDB transactional database on disk, created by OpenTransactionDb.

func OpenTransactionDb

func OpenTransactionDb(
	opts *Options,
	transactionDBOpts *TransactionDBOptions,
	name string,
) (*TransactionDB, error)

OpenTransactionDb opens a database with the specified options.

func (*TransactionDB) Close

func (db *TransactionDB) Close()

Close closes the database.

func (*TransactionDB) Delete

func (db *TransactionDB) Delete(opts *WriteOptions, key []byte) error

Delete removes the data associated with the key from the database.

func (*TransactionDB) Get

func (db *TransactionDB) Get(opts *ReadOptions, key []byte) ([]byte, error)

Get returns the data associated with the key from the database.

func (*TransactionDB) NewCheckpoint

func (db *TransactionDB) NewCheckpoint() (*Checkpoint, error)

NewCheckpoint creates a new Checkpoint for this db.

func (*TransactionDB) NewSnapshot

func (db *TransactionDB) NewSnapshot() *Snapshot

NewSnapshot creates a new snapshot of the database.

func (*TransactionDB) Put

func (db *TransactionDB) Put(opts *WriteOptions, key, value []byte) error

Put writes data associated with a key to the database.

func (*TransactionDB) ReleaseSnapshot

func (db *TransactionDB) ReleaseSnapshot(snapshot *Snapshot)

ReleaseSnapshot releases the snapshot and its resources.

func (*TransactionDB) TransactionBegin

func (db *TransactionDB) TransactionBegin(
	opts *WriteOptions,
	transactionOpts *TransactionOptions,
	oldTransaction *Transaction,
) *Transaction

TransactionBegin begins a new transaction with the WriteOptions and TransactionOptions given.

type TransactionDBOptions

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

TransactionDBOptions represent all of the available options when opening a transactional database with OpenTransactionDb.

func NewDefaultTransactionDBOptions

func NewDefaultTransactionDBOptions() *TransactionDBOptions

NewDefaultTransactionDBOptions creates a default TransactionDBOptions object.

func NewNativeTransactionDBOptions

func NewNativeTransactionDBOptions(c *C.rocksdb_transactiondb_options_t) *TransactionDBOptions

NewNativeTransactionDBOptions creates a TransactionDBOptions object.

func (*TransactionDBOptions) Destroy

func (opts *TransactionDBOptions) Destroy()

Destroy deallocates the TransactionDBOptions object.

func (*TransactionDBOptions) SetDefaultLockTimeout

func (opts *TransactionDBOptions) SetDefaultLockTimeout(defaultLockTimeout int64)

SetDefaultLockTimeout if posititve, specifies the wait timeout in milliseconds when writing a key OUTSIDE of a transaction (ie by calling DB::Put(),Merge(),Delete(),Write() directly). If 0, no waiting is done if a lock cannot instantly be acquired. If negative, there is no timeout and will block indefinitely when acquiring a lock.

Not using a timeout can lead to deadlocks. Currently, there is no deadlock-detection to recover from a deadlock. While DB writes cannot deadlock with other DB writes, they can deadlock with a transaction. A negative timeout should only be used if all transactions have a small expiration set.

func (*TransactionDBOptions) SetMaxNumLocks

func (opts *TransactionDBOptions) SetMaxNumLocks(maxNumLocks int64)

SetMaxNumLocks sets the maximum number of keys that can be locked at the same time per column family. If the number of locked keys is greater than max_num_locks, transaction writes (or GetForUpdate) will return an error. If this value is not positive, no limit will be enforced.

func (*TransactionDBOptions) SetNumStripes

func (opts *TransactionDBOptions) SetNumStripes(numStripes uint64)

SetNumStripes sets the concurrency level. Increasing this value will increase the concurrency by dividing the lock table (per column family) into more sub-tables, each with their own separate mutex.

func (*TransactionDBOptions) SetTransactionLockTimeout

func (opts *TransactionDBOptions) SetTransactionLockTimeout(txnLockTimeout int64)

SetTransactionLockTimeout if positive, specifies the default wait timeout in milliseconds when a transaction attempts to lock a key if not specified by TransactionOptions::lock_timeout.

If 0, no waiting is done if a lock cannot instantly be acquired. If negative, there is no timeout. Not using a timeout is not recommended as it can lead to deadlocks. Currently, there is no deadlock-detection to recover from a deadlock.

type TransactionOptions

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

TransactionOptions represent all of the available options options for a transaction on the database.

func NewDefaultTransactionOptions

func NewDefaultTransactionOptions() *TransactionOptions

NewDefaultTransactionOptions creates a default TransactionOptions object.

func NewNativeTransactionOptions

func NewNativeTransactionOptions(c *C.rocksdb_transaction_options_t) *TransactionOptions

NewNativeTransactionOptions creates a TransactionOptions object.

func (*TransactionOptions) Destroy

func (opts *TransactionOptions) Destroy()

Destroy deallocates the TransactionOptions object.

func (*TransactionOptions) SetDeadlockDetect

func (opts *TransactionOptions) SetDeadlockDetect(value bool)

SetDeadlockDetect to true means that before acquiring locks, this transaction will check if doing so will cause a deadlock. If so, it will return with Status::Busy. The user should retry their transaction.

func (*TransactionOptions) SetDeadlockDetectDepth

func (opts *TransactionOptions) SetDeadlockDetectDepth(depth int64)

SetDeadlockDetectDepth sets the number of traversals to make during deadlock detection.

func (*TransactionOptions) SetExpiration

func (opts *TransactionOptions) SetExpiration(expiration int64)

SetExpiration sets the Expiration duration in milliseconds. If non-negative, transactions that last longer than this many milliseconds will fail to commit. If not set, a forgotten transaction that is never committed, rolled back, or deleted will never relinquish any locks it holds. This could prevent keys from being written by other writers.

func (*TransactionOptions) SetLockTimeout

func (opts *TransactionOptions) SetLockTimeout(lockTimeout int64)

SetLockTimeout positive, specifies the wait timeout in milliseconds when a transaction attempts to lock a key. If 0, no waiting is done if a lock cannot instantly be acquired. If negative, TransactionDBOptions::transaction_lock_timeout will be used

func (*TransactionOptions) SetMaxWriteBatchSize

func (opts *TransactionOptions) SetMaxWriteBatchSize(size uint64)

SetMaxWriteBatchSize sets the maximum number of bytes used for the write batch. 0 means no limit.

func (*TransactionOptions) SetSetSnapshot

func (opts *TransactionOptions) SetSetSnapshot(value bool)

SetSetSnapshot to true is the same as calling Transaction::SetSnapshot().

type UniversalCompactionOptions

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

UniversalCompactionOptions represent all of the available options for universal compaction.

func NewDefaultUniversalCompactionOptions

func NewDefaultUniversalCompactionOptions() *UniversalCompactionOptions

NewDefaultUniversalCompactionOptions creates a default UniversalCompactionOptions object.

func NewNativeUniversalCompactionOptions

func NewNativeUniversalCompactionOptions(c *C.rocksdb_universal_compaction_options_t) *UniversalCompactionOptions

NewNativeUniversalCompactionOptions creates a UniversalCompactionOptions object.

func (*UniversalCompactionOptions) Destroy

func (opts *UniversalCompactionOptions) Destroy()

Destroy deallocates the UniversalCompactionOptions object.

func (*UniversalCompactionOptions) SetCompressionSizePercent

func (opts *UniversalCompactionOptions) SetCompressionSizePercent(value int)

SetCompressionSizePercent sets the percentage of compression size.

If this option is set to be -1, all the output files will follow compression type specified.

If this option is not negative, we will try to make sure compressed size is just above this value. In normal cases, at least this percentage of data will be compressed. When we are compacting to a new file, here is the criteria whether it needs to be compressed: assuming here are the list of files sorted by generation time:

A1...An B1...Bm C1...Ct

where A1 is the newest and Ct is the oldest, and we are going to compact B1...Bm, we calculate the total size of all the files as total_size, as well as the total size of C1...Ct as total_C, the compaction output file will be compressed iff

total_C / total_size < this percentage

Default: -1

func (*UniversalCompactionOptions) SetMaxMergeWidth

func (opts *UniversalCompactionOptions) SetMaxMergeWidth(value uint)

SetMaxMergeWidth sets the maximum number of files in a single compaction run. Default: UINT_MAX

func (*UniversalCompactionOptions) SetMaxSizeAmplificationPercent

func (opts *UniversalCompactionOptions) SetMaxSizeAmplificationPercent(value uint)

SetMaxSizeAmplificationPercent sets the size amplification. It is defined as the amount (in percentage) of additional storage needed to store a single byte of data in the database. For example, a size amplification of 2% means that a database that contains 100 bytes of user-data may occupy upto 102 bytes of physical storage. By this definition, a fully compacted database has a size amplification of 0%. Rocksdb uses the following heuristic to calculate size amplification: it assumes that all files excluding the earliest file contribute to the size amplification. Default: 200, which means that a 100 byte database could require upto 300 bytes of storage.

func (*UniversalCompactionOptions) SetMinMergeWidth

func (opts *UniversalCompactionOptions) SetMinMergeWidth(value uint)

SetMinMergeWidth sets the minimum number of files in a single compaction run. Default: 2

func (*UniversalCompactionOptions) SetSizeRatio

func (opts *UniversalCompactionOptions) SetSizeRatio(value uint)

SetSizeRatio sets the percentage flexibility while comparing file size. If the candidate file(s) size is 1% smaller than the next file's size, then include next file into this candidate set. Default: 1

func (*UniversalCompactionOptions) SetStopStyle

func (opts *UniversalCompactionOptions) SetStopStyle(value UniversalCompactionStopStyle)

SetStopStyle sets the algorithm used to stop picking files into a single compaction run. Default: CompactionStopStyleTotalSize

type UniversalCompactionStopStyle

type UniversalCompactionStopStyle uint

UniversalCompactionStopStyle describes a algorithm used to make a compaction request stop picking new files into a single compaction run.

type WriteBatch

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

WriteBatch is a batching of Puts, Merges and Deletes.

func NewNativeWriteBatch

func NewNativeWriteBatch(c *C.rocksdb_writebatch_t) *WriteBatch

NewNativeWriteBatch create a WriteBatch object.

func NewWriteBatch

func NewWriteBatch() *WriteBatch

NewWriteBatch create a WriteBatch object.

func WriteBatchFrom

func WriteBatchFrom(data []byte) *WriteBatch

WriteBatchFrom creates a write batch from a serialized WriteBatch.

func (*WriteBatch) Clear

func (wb *WriteBatch) Clear()

Clear removes all the enqueued Put and Deletes.

func (*WriteBatch) Count

func (wb *WriteBatch) Count() int

Count returns the number of updates in the batch.

func (*WriteBatch) Data

func (wb *WriteBatch) Data() []byte

Data returns the serialized version of this batch.

func (*WriteBatch) Delete

func (wb *WriteBatch) Delete(key []byte)

Delete queues a deletion of the data at key.

func (*WriteBatch) DeleteCF

func (wb *WriteBatch) DeleteCF(cf *ColumnFamilyHandle, key []byte)

DeleteCF queues a deletion of the data at key in a column family.

func (*WriteBatch) DeleteVCF

func (wb *WriteBatch) DeleteVCF(cf *ColumnFamilyHandle, keys [][]byte)

DeleteVCF queues deletions of the data at keys in a column family.

func (*WriteBatch) DeleteVCFs

func (wb *WriteBatch) DeleteVCFs(cfs []*ColumnFamilyHandle, keys [][]byte)

DeleteVCFs queues deletions of the data at keys in column families.

func (*WriteBatch) Destroy

func (wb *WriteBatch) Destroy()

Destroy deallocates the WriteBatch object.

func (*WriteBatch) Merge

func (wb *WriteBatch) Merge(key, value []byte)

Merge queues a merge of "value" with the existing value of "key".

func (*WriteBatch) MergeCF

func (wb *WriteBatch) MergeCF(cf *ColumnFamilyHandle, key, value []byte)

MergeCF queues a merge of "value" with the existing value of "key" in a column family.

func (*WriteBatch) NewIterator

func (wb *WriteBatch) NewIterator() *WriteBatchIterator

NewIterator returns a iterator to iterate over the records in the batch.

func (*WriteBatch) Put

func (wb *WriteBatch) Put(key, value []byte)

Put queues a key-value pair.

func (*WriteBatch) PutCF

func (wb *WriteBatch) PutCF(cf *ColumnFamilyHandle, key, value []byte)

PutCF queues a key-value pair in a column family.

func (*WriteBatch) PutVCF

func (wb *WriteBatch) PutVCF(cf *ColumnFamilyHandle, keys, values [][]byte)

PutVCF queues multiple key-value pairs in a column family.

func (*WriteBatch) PutVCFs

func (wb *WriteBatch) PutVCFs(cfs []*ColumnFamilyHandle, keys, values [][]byte)

PutVCFs queues multiple key-value pairs in a column family.

type WriteBatchIterator

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

WriteBatchIterator represents a iterator to iterator over records.

func (*WriteBatchIterator) Error

func (iter *WriteBatchIterator) Error() error

Error returns the error if the iteration is failed.

func (*WriteBatchIterator) Next

func (iter *WriteBatchIterator) Next() bool

Next returns the next record. Returns false if no further record exists.

func (*WriteBatchIterator) Record

func (iter *WriteBatchIterator) Record() *WriteBatchRecord

Record returns the current record.

type WriteBatchRecord

type WriteBatchRecord struct {
	Key   []byte
	Value []byte
	Type  WriteBatchRecordType
}

WriteBatchRecord represents a record inside a WriteBatch.

type WriteBatchRecordType

type WriteBatchRecordType byte

WriteBatchRecordType describes the type of a batch record.

const (
	WriteBatchRecordTypeDeletion WriteBatchRecordType = 0x0
	WriteBatchRecordTypeValue    WriteBatchRecordType = 0x1
	WriteBatchRecordTypeMerge    WriteBatchRecordType = 0x2
	WriteBatchRecordTypeLogData  WriteBatchRecordType = 0x3
)

Types of batch records.

type WriteOptions

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

WriteOptions represent all of the available options when writing to a database.

func NewDefaultWriteOptions

func NewDefaultWriteOptions() *WriteOptions

NewDefaultWriteOptions creates a default WriteOptions object.

func NewNativeWriteOptions

func NewNativeWriteOptions(c *C.rocksdb_writeoptions_t) *WriteOptions

NewNativeWriteOptions creates a WriteOptions object.

func (*WriteOptions) Destroy

func (opts *WriteOptions) Destroy()

Destroy deallocates the WriteOptions object.

func (*WriteOptions) DisableWAL

func (opts *WriteOptions) DisableWAL(value bool)

DisableWAL sets whether WAL should be active or not. If true, writes will not first go to the write ahead log, and the write may got lost after a crash. Default: false

func (*WriteOptions) SetSync

func (opts *WriteOptions) SetSync(value bool)

SetSync sets the sync mode. If true, the write will be flushed from the operating system buffer cache before the write is considered complete. If this flag is true, writes will be slower. Default: false

Directories

Path Synopsis
extension

Jump to

Keyboard shortcuts

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