grocksdb

package module
v1.6.47 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2022 License: MIT Imports: 11 Imported by: 0

README

grocksdb, RocksDB wrapper for Go

Go Report Card Coverage Status godoc

This is a Fork from tecbot/gorocksdb. I respect the author work and community contribution. The LICENSE still remains as upstream.

Why I made a patched clone instead of PR:

  • Supports almost C API (unlike upstream). Catching up with latest version of Rocksdb as promise.
  • This fork contains no defer in codebase (my side project requires as less overhead as possible). This introduces loose convention of how/when to free c-mem, thus break the rule of tecbot/gorocksdb.

Install

Prerequisite
  • librocksdb
  • libsnappy
  • libz
  • liblz4
  • libzstd

Please follow this guide: https://github.com/facebook/rocksdb/blob/master/INSTALL.md to build above libs.

Build

After that, you can install and build grocksdb using the following commands:

go get -u github.com/linxGnu/grocksdb

CGO_CFLAGS="-I/path/to/rocksdb/include" \
CGO_LDFLAGS="-L/path/to/rocksdb -lrocksdb -lstdc++ -lm -lz -lsnappy -llz4 -lzstd" \
  go build

Or just:

go build // if prerequisites are in linker paths

Usage

See also: doc

API Support

Almost C API, excepts:

  • putv/mergev/deletev/delete_rangev
  • compaction_filter/compaction_filter_factory/compaction_filter_context
  • transactiondb_property_value/transactiondb_property_int
  • optimistictransactiondb_property_value/optimistictransactiondb_property_int

Documentation

Overview

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

grocksdb.OpenDb opens and creates databases.

bbto := grocksdb.NewDefaultBlockBasedTableOptions()
bbto.SetBlockCache(grocksdb.NewLRUCache(3 << 30))

opts := grocksdb.NewDefaultOptions()
opts.SetBlockBasedTableFactory(bbto)
opts.SetCreateIfMissing(true)

db, err := grocksdb.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 := grocksdb.NewDefaultReadOptions()
wo := grocksdb.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 := grocksdb.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 := grocksdb.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 := grocksdb.NewBloomFilter(10)
bbto := grocksdb.NewDefaultBlockBasedTableOptions()
bbto.SetFilterPolicy(filter)
opts.SetBlockBasedTableFactory(bbto)
db, err := grocksdb.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 (
	// TolerateCorruptedTailRecordsRecovery is original levelDB recovery
	// We tolerate incomplete record in trailing data on all logs
	// Use case : This is legacy behavior
	TolerateCorruptedTailRecordsRecovery = WALRecoveryMode(0)
	// AbsoluteConsistencyRecovery recover from clean shutdown
	// We don't expect to find any corruption in the WAL
	// Use case : This is ideal for unit tests and rare applications that
	// can require high consistency guarantee
	AbsoluteConsistencyRecovery = WALRecoveryMode(1)
	// PointInTimeRecovery recover to point-in-time consistency (default)
	// We stop the WAL playback on discovering WAL inconsistency
	// Use case : Ideal for systems that have disk controller cache like
	// hard disk, SSD without super capacitor that store related data
	PointInTimeRecovery = WALRecoveryMode(2)
	// SkipAnyCorruptedRecordsRecovery recovery after a disaster
	// We ignore any corruption in the WAL and try to salvage as much data as
	// possible
	// Use case : Ideal for last ditch effort to recover data or systems that
	// operate with low grade unrelated data
	SkipAnyCorruptedRecordsRecovery = WALRecoveryMode(3)
)

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

View Source
var ErrColumnFamilyMustMatch = fmt.Errorf("must provide the same number of column family names and options")

ErrColumnFamilyMustMatch indicates number of column family names and options must match.

Functions

func DestroyDBPaths

func DestroyDBPaths(dbpaths []*DBPath)

DestroyDBPaths deallocates all DBPath objects in dbpaths.

func DestroyDb

func DestroyDb(name string, opts *Options) (err error)

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

func ListColumnFamilies

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

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

func OpenDbAsSecondaryColumnFamilies

func OpenDbAsSecondaryColumnFamilies(
	opts *Options,
	name string,
	secondaryPath string,
	cfNames []string,
	cfOpts []*Options,
) (db *DB, cfHandles []*ColumnFamilyHandle, err error)

OpenDbAsSecondaryColumnFamilies opens database as secondary instance with column families. You can open a subset of column families in secondary mode. The `opts` specify the database specific options. The `name` argument specifies the name of the primary db that you have used to open the primary instance. The `secondaryPath` argument points to a directory where the secondary instance stores its info log. The `column_families` arguments specifieds a list of column families to open. If any of the column families does not exist, the function returns non-OK status.

func OpenDbColumnFamilies

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

OpenDbColumnFamilies opens a database with the specified column families.

func OpenDbColumnFamiliesWithTTL

func OpenDbColumnFamiliesWithTTL(
	opts *Options,
	name string,
	cfNames []string,
	cfOpts []*Options,
	ttls []C.int,
) (db *DB, cfHandles []*ColumnFamilyHandle, err error)

OpenDbColumnFamiliesWithTTL opens a database with the specified column families along with their ttls.

BEHAVIOUR: TTL is accepted in seconds (int32_t)Timestamp(creation) is suffixed to values in Put internally Expired TTL values deleted in compaction only:(Timestamp+ttl<time_now) Get/Iterator may return expired entries(compaction not run on them yet) Different TTL may be used during different Opens Example: Open1 at t=0 with ttl=4 and insert k1,k2, close at t=2

Open2 at t=3 with ttl=5. Now k1,k2 should be deleted at t>=5

read_only=true opens in the usual read-only mode. Compactions will not be

triggered(neither manual nor automatic), so no expired entries removed

CONSTRAINTS: Not specifying/passing or non-positive TTL behaves like TTL = infinity

func OpenDbForReadOnlyColumnFamilies

func OpenDbForReadOnlyColumnFamilies(
	opts *Options,
	name string,
	cfNames []string,
	cfOpts []*Options,
	errorIfWalFileExists bool,
) (db *DB, cfHandles []*ColumnFamilyHandle, err error)

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

func OpenOptimisticTransactionDbColumnFamilies

func OpenOptimisticTransactionDbColumnFamilies(
	opts *Options,
	name string,
	cfNames []string,
	cfOpts []*Options,
) (db *OptimisticTransactionDB, cfHandles []*ColumnFamilyHandle, err error)

OpenOptimisticTransactionDbColumnFamilies opens a database with the specified column families.

func OpenTransactionDbColumnFamilies

func OpenTransactionDbColumnFamilies(
	opts *Options,
	transactionDBOpts *TransactionDBOptions,
	name string,
	cfNames []string,
	cfOpts []*Options,
) (db *TransactionDB, cfHandles []*ColumnFamilyHandle, err error)

OpenTransactionDbColumnFamilies opens a database with the specified column families.

func RepairDb

func RepairDb(name string, opts *Options) (err error)

RepairDb repairs a database.

func SetPerfLevel

func SetPerfLevel(level PerfLevel)

SetPerfLevel sets the perf stats level for current thread.

func TestOptionBlobFile

func TestOptionBlobFile(t *testing.T)

Types

type BackupEngine

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

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

func CreateBackupEngine

func CreateBackupEngine(db *DB) (be *BackupEngine, err error)

CreateBackupEngine opens a backup engine from DB.

func OpenBackupEngine

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

OpenBackupEngine opens a backup engine with specified options.

func OpenBackupEngineWithOpt

func OpenBackupEngineWithOpt(opts *BackupableDBOptions, env *Env) (be *BackupEngine, err error)

OpenBackupEngineWithOpt 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() (err error)

CreateNewBackup takes a new backup from db.

func (*BackupEngine) CreateNewBackupFlush

func (b *BackupEngine) CreateNewBackupFlush(flushBeforeBackup bool) (err error)

CreateNewBackupFlush takes a new backup from db. Backup would be created after flushing.

func (*BackupEngine) GetInfo

func (b *BackupEngine) GetInfo() (infos []BackupInfo)

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

func (*BackupEngine) PurgeOldBackups

func (b *BackupEngine) PurgeOldBackups(numBackupsToKeep uint32) (err error)

PurgeOldBackups deletes old backups, where `numBackupsToKeep` is how many backups you’d like to keep.

func (*BackupEngine) RestoreDBFromBackup

func (b *BackupEngine) RestoreDBFromBackup(dbDir, walDir string, ro *RestoreOptions, backupID uint32) (err error)

RestoreDBFromBackup restores the backup (identified by its id) to dbDir. walDir is where the write ahead logs are restored to and usually the same as dbDir.

func (*BackupEngine) RestoreDBFromLatestBackup

func (b *BackupEngine) RestoreDBFromLatestBackup(dbDir, walDir string, ro *RestoreOptions) (err 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) VerifyBackup

func (b *BackupEngine) VerifyBackup(backupID uint32) (err error)

VerifyBackup verifies a backup by its id.

type BackupInfo

type BackupInfo struct {
	ID        uint32
	Timestamp int64
	Size      uint64
	NumFiles  uint32
}

BackupInfo represents the information about a backup.

type BackupableDBOptions

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

BackupableDBOptions represents options for backupable db.

func NewBackupableDBOptions

func NewBackupableDBOptions(backupDir string) *BackupableDBOptions

NewBackupableDBOptions

func (*BackupableDBOptions) BackupLogFiles

func (b *BackupableDBOptions) BackupLogFiles(flag bool)

BackupLogFiles if false, we won't backup log files. This option can be useful for backing up in-memory databases where log file are persisted, but table files are in memory.

Default: true

func (*BackupableDBOptions) Destroy

func (b *BackupableDBOptions) Destroy()

Destroy releases these options.

func (*BackupableDBOptions) DestroyOldData

func (b *BackupableDBOptions) DestroyOldData(flag bool)

DestroyOldData if true, it will delete whatever backups there are already

Default: false

func (*BackupableDBOptions) GetBackupRateLimit

func (b *BackupableDBOptions) GetBackupRateLimit() uint64

GetBackupRateLimit gets max bytes that can be transferred in a second during backup. If 0, go as fast as you can.

func (*BackupableDBOptions) GetCallbackTriggerIntervalSize

func (b *BackupableDBOptions) GetCallbackTriggerIntervalSize() uint64

GetCallbackTriggerIntervalSize gets size (N) during backup user can get callback every time next N bytes being copied.

func (*BackupableDBOptions) GetMaxBackgroundOperations

func (b *BackupableDBOptions) GetMaxBackgroundOperations() int

GetMaxBackgroundOperations gets max number of background threads will copy files for CreateNewBackup() and RestoreDBFromBackup()

func (*BackupableDBOptions) GetMaxValidBackupsToOpen

func (b *BackupableDBOptions) GetMaxValidBackupsToOpen() int

GetMaxValidBackupsToOpen gets max number of valid backup to open.

For BackupEngineReadOnly, Open() will open at most this many of the latest non-corrupted backups.

Note: this setting is ignored (behaves like INT_MAX) for any kind of writable BackupEngine because it would inhibit accounting for shared files for proper backup deletion, including purging any incompletely created backups on creation of a new backup.

func (*BackupableDBOptions) GetRestoreRateLimit

func (b *BackupableDBOptions) GetRestoreRateLimit() uint64

GetRestoreRateLimit gets max bytes that can be transferred in a second during restore. If 0, go as fast as you can

func (*BackupableDBOptions) GetShareFilesWithChecksumNaming

func (b *BackupableDBOptions) GetShareFilesWithChecksumNaming() ShareFilesNaming

GetShareFilesWithChecksumNaming gets naming option for share_files_with_checksum table files. See ShareFilesNaming for details.

func (*BackupableDBOptions) IsBackupLogFiles

func (b *BackupableDBOptions) IsBackupLogFiles() bool

IsBackupLogFiles if false, we won't backup log files. This option can be useful for backing up in-memory databases where log file are persisted, but table files are in memory.

func (*BackupableDBOptions) IsDestroyOldData

func (b *BackupableDBOptions) IsDestroyOldData() bool

IsDestroyOldData indicates if we should delete whatever backups there are already.

func (*BackupableDBOptions) IsShareTableFiles

func (b *BackupableDBOptions) IsShareTableFiles() bool

IsShareTableFiles returns if backup will assume that table files with same name have the same contents. This enables incremental backups and avoids unnecessary data copies.

If false, each backup will be on its own and will not share any data with other backups.

func (*BackupableDBOptions) IsSync

func (b *BackupableDBOptions) IsSync() bool

IsSync if true, we can guarantee you'll get consistent backup even on a machine crash/reboot. Backup process is slower with sync enabled.

If false, we don't guarantee anything on machine reboot. However, chances are some of the backups are consistent.

func (*BackupableDBOptions) SetBackupDir

func (b *BackupableDBOptions) SetBackupDir(dir string)

SetBackupDir sets where to keep the backup files. Has to be different than dbname_ Best to set this to dbname_ + "/backups".

func (*BackupableDBOptions) SetBackupRateLimit

func (b *BackupableDBOptions) SetBackupRateLimit(limit uint64)

SetBackupRateLimit sets max bytes that can be transferred in a second during backup. If 0, go as fast as you can.

Default: 0

func (*BackupableDBOptions) SetCallbackTriggerIntervalSize

func (b *BackupableDBOptions) SetCallbackTriggerIntervalSize(size uint64)

SetCallbackTriggerIntervalSize sets size (N) during backup user can get callback every time next N bytes being copied.

Default: N=4194304

func (*BackupableDBOptions) SetEnv

func (b *BackupableDBOptions) SetEnv(env *Env)

SetEnv to be used for backup file I/O. If it's nullptr, backups will be written out using DBs Env. If it's non-nullptr, backup's I/O will be performed using this object. If you want to have backups on HDFS, use HDFS Env here!

func (*BackupableDBOptions) SetMaxBackgroundOperations

func (b *BackupableDBOptions) SetMaxBackgroundOperations(v int)

SetMaxBackgroundOperations sets max number of background threads will copy files for CreateNewBackup() and RestoreDBFromBackup()

Default: 1

func (*BackupableDBOptions) SetMaxValidBackupsToOpen

func (b *BackupableDBOptions) SetMaxValidBackupsToOpen(val int)

SetMaxValidBackupsToOpen sets max number of valid backup to open.

For BackupEngineReadOnly, Open() will open at most this many of the latest non-corrupted backups.

Note: this setting is ignored (behaves like INT_MAX) for any kind of writable BackupEngine because it would inhibit accounting for shared files for proper backup deletion, including purging any incompletely created backups on creation of a new backup.

Default: INT_MAX

func (*BackupableDBOptions) SetRestoreRateLimit

func (b *BackupableDBOptions) SetRestoreRateLimit(limit uint64)

SetRestoreRateLimit sets max bytes that can be transferred in a second during restore. If 0, go as fast as you can

Default: 0

func (*BackupableDBOptions) SetShareFilesWithChecksumNaming

func (b *BackupableDBOptions) SetShareFilesWithChecksumNaming(val ShareFilesNaming)

SetShareFilesWithChecksumNaming sets naming option for share_files_with_checksum table files. See ShareFilesNaming for details.

Modifying this option cannot introduce a downgrade compatibility issue because RocksDB can read, restore, and delete backups using different file names, and it's OK for a backup directory to use a mixture of table file naming schemes.

However, modifying this option and saving more backups to the same directory can lead to the same file getting saved again to that directory, under the new shared name in addition to the old shared name.

Default: UseDBSessionID | FlagIncludeFileSize | FlagMatchInterimNaming

func (*BackupableDBOptions) SetSync

func (b *BackupableDBOptions) SetSync(flag bool)

SetSync if true, we can guarantee you'll get consistent backup even on a machine crash/reboot. Backup process is slower with sync enabled.

If false, we don't guarantee anything on machine reboot. However, chances are some of the backups are consistent.

Default: true

func (*BackupableDBOptions) ShareTableFiles

func (b *BackupableDBOptions) ShareTableFiles(flag bool)

ShareTableFiles if set to true, backup will assume that table files with same name have the same contents. This enables incremental backups and avoids unnecessary data copies.

If false, each backup will be on its own and will not share any data with other backups.

Default: true

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) SetCacheIndexAndFilterBlocksWithHighPriority

func (opts *BlockBasedTableOptions) SetCacheIndexAndFilterBlocksWithHighPriority(value bool)

SetCacheIndexAndFilterBlocksWithHighPriority if cache_index_and_filter_blocks is enabled, cache index and filter blocks with high priority. If set to true, depending on implementation of block cache, index and filter blocks may be less likely to be evicted than data blocks.

Default: true.

func (*BlockBasedTableOptions) SetDataBlockHashRatio

func (opts *BlockBasedTableOptions) SetDataBlockHashRatio(value float64)

SetDataBlockHashRatio is valid only when data_block_hash_index_type is KDataBlockIndexTypeBinarySearchAndHash.

Default value: 0.75

func (*BlockBasedTableOptions) SetDataBlockIndexType

func (opts *BlockBasedTableOptions) SetDataBlockIndexType(value DataBlockIndexType)

SetDataBlockIndexType sets data block index type

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) SetFormatVersion

func (opts *BlockBasedTableOptions) SetFormatVersion(value int)

SetFormatVersion set format version. We currently have five options: 0 -- This version is currently written out by all RocksDB's versions by default. Can be read by really old RocksDB's. Doesn't support changing checksum (default is CRC32). 1 -- Can be read by RocksDB's versions since 3.0. Supports non-default checksum, like xxHash. It is written by RocksDB when BlockBasedTableOptions::checksum is something other than kCRC32c. (version 0 is silently upconverted) 2 -- Can be read by RocksDB's versions since 3.10. Changes the way we encode compressed blocks with LZ4, BZip2 and Zlib compression. If you don't plan to run RocksDB before version 3.10, you should probably use this. 3 -- Can be read by RocksDB's versions since 5.15. Changes the way we encode the keys in index blocks. If you don't plan to run RocksDB before version 5.15, you should probably use this. This option only affects newly written tables. When reading existing tables, the information about version is read from the footer. 4 -- Can be read by RocksDB's versions since 5.16. Changes the way we encode the values in index blocks. If you don't plan to run RocksDB before version 5.16 and you are using index_block_restart_interval > 1, you should probably use this as it would reduce the index size. This option only affects newly written tables. When reading existing tables, the information about version is read from the footer.

func (*BlockBasedTableOptions) SetHashIndexAllowCollision deprecated

func (opts *BlockBasedTableOptions) SetHashIndexAllowCollision(value bool)

SetHashIndexAllowCollision set allows hash-index collision.

Deprecated: no matter what value it is set to, it will behave as if hash_index_allow_collision=true.

func (*BlockBasedTableOptions) SetIndexBlockRestartInterval

func (opts *BlockBasedTableOptions) SetIndexBlockRestartInterval(value int)

SetIndexBlockRestartInterval same as block_restart_interval but used for the index block.

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) SetMetadataBlockSize

func (opts *BlockBasedTableOptions) SetMetadataBlockSize(value uint64)

SetMetadataBlockSize sets block size for partitioned metadata. Currently applied to indexes when kTwoLevelIndexSearch is used and to filters when partition_filters is used. Note: Since in the current implementation the filters and index partitions are aligned, an index/filter block is created when either index or filter block size reaches the specified limit. Note: this limit is currently applied to only index blocks; a filter partition is cut right after an index block is cut.

func (*BlockBasedTableOptions) SetNoBlockCache

func (opts *BlockBasedTableOptions) SetNoBlockCache(value bool)

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

func (*BlockBasedTableOptions) SetPartitionFilters

func (opts *BlockBasedTableOptions) SetPartitionFilters(value bool)

SetPartitionFilters use partitioned full filters for each SST file. This option is incompatible with block-based filters.

Note: currently this option requires kTwoLevelIndexSearch to be set as well.

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) SetPinTopLevelIndexAndFilter

func (opts *BlockBasedTableOptions) SetPinTopLevelIndexAndFilter(value bool)

SetPinTopLevelIndexAndFilter if cache_index_and_filter_blocks is true and the below is true, then the top-level index of partitioned 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. This is not limited to l0 in LSM tree.

Default: true.

func (*BlockBasedTableOptions) SetUseDeltaEncoding

func (opts *BlockBasedTableOptions) SetUseDeltaEncoding(value bool)

SetUseDeltaEncoding uses delta encoding to compress keys in blocks. ReadOptions::pin_data requires this option to be disabled.

Default: true

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 BottommostLevelCompaction

type BottommostLevelCompaction byte

BottommostLevelCompaction for level based compaction, we can configure if we want to skip/force bottommost level compaction.

const (
	// KSkip skip bottommost level compaction
	KSkip BottommostLevelCompaction = 0
	// KIfHaveCompactionFilter only compact bottommost level if there is a compaction filter
	// This is the default option
	KIfHaveCompactionFilter BottommostLevelCompaction = 1
	// KForce always compact bottommost level
	KForce BottommostLevelCompaction = 2
	// KForceOptimized always compact bottommost level but in bottommost level avoid
	// double-compacting files created in the same compaction
	KForceOptimized BottommostLevelCompaction = 3
)

type COWList

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

COWList implements a copy-on-write list. It is intended to be used by go callback registry for CGO, which is read-heavy with occasional writes. Reads do not block; Writes do not block reads (or vice versa), but only one write can occur at once;

func NewCOWList

func NewCOWList() *COWList

NewCOWList creates a new COWList.

func (*COWList) Append

func (c *COWList) Append(i interface{}) (index int)

Append appends an item to the COWList and returns the index for that item.

func (*COWList) Get

func (c *COWList) Get(index int) interface{}

Get gets the item at index.

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 uint64) *Cache

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

func NewLRUCacheWithOptions

func NewLRUCacheWithOptions(opt *LRUCacheOptions) *Cache

NewLRUCacheWithOptions creates a new LRU Cache from options.

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) DisownData

func (c *Cache) DisownData()

Disowndata call this on shutdown if you want to speed it up. Cache will disown any underlying data and will not free it on delete. This call will leak memory - call this only if you're shutting down the process. Any attempts of using cache after this call will fail terribly. Always delete the DB object before calling this method!

func (*Cache) GetCapacity

func (c *Cache) GetCapacity() uint64

GetCapacity returns capacity of the cache.

func (*Cache) GetPinnedUsage

func (c *Cache) GetPinnedUsage() uint64

GetPinnedUsage returns the Cache pinned memory usage.

func (*Cache) GetUsage

func (c *Cache) GetUsage() uint64

GetUsage returns the Cache memory usage.

func (*Cache) SetCapacity

func (c *Cache) SetCapacity(value uint64)

SetCapacity sets capacity of the cache.

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) (err 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 log_size_for_flush: 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.

type ColumnFamilyHandles

type ColumnFamilyHandles []*ColumnFamilyHandle

ColumnFamilyHandles represents collection of multiple column family handle.

type CompactRangeOptions

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

CompactRangeOptions represent all of the available options for compact range.

func NewCompactRangeOptions

func NewCompactRangeOptions() *CompactRangeOptions

NewCompactRangeOptions creates new compact range options.

func (*CompactRangeOptions) BottommostLevelCompaction

func (opts *CompactRangeOptions) BottommostLevelCompaction() BottommostLevelCompaction

BottommostLevelCompaction returns if bottommost level compaction feature is turned on.

func (*CompactRangeOptions) ChangeLevel

func (opts *CompactRangeOptions) ChangeLevel() bool

ChangeLevel if true, compacted files will be moved to the minimum level capable of holding the data or given level (specified non-negative target_level).

func (*CompactRangeOptions) Destroy

func (opts *CompactRangeOptions) Destroy()

Destroy deallocates the CompactionOptions object.

func (*CompactRangeOptions) GetExclusiveManualCompaction

func (opts *CompactRangeOptions) GetExclusiveManualCompaction() bool

GetExclusiveManualCompaction returns if exclusive manual compaction is turned on.

func (*CompactRangeOptions) SetBottommostLevelCompaction

func (opts *CompactRangeOptions) SetBottommostLevelCompaction(value BottommostLevelCompaction)

SetBottommostLevelCompaction sets bottommost level compaction.

Default: KIfHaveCompactionFilter

func (*CompactRangeOptions) SetChangeLevel

func (opts *CompactRangeOptions) SetChangeLevel(value bool)

SetChangeLevel if true, compacted files will be moved to the minimum level capable of holding the data or given level (specified non-negative target_level).

func (*CompactRangeOptions) SetExclusiveManualCompaction

func (opts *CompactRangeOptions) SetExclusiveManualCompaction(value bool)

SetExclusiveManualCompaction if more than one thread calls manual compaction, only one will actually schedule it while the other threads will simply wait for the scheduled manual compaction to complete. If exclusive_manual_compaction is set to true, the call will disable scheduling of automatic compaction jobs and wait for existing automatic compaction jobs to finish.

Default: true

func (*CompactRangeOptions) SetTargetLevel

func (opts *CompactRangeOptions) SetTargetLevel(value int32)

SetTargetLevel if change_level is true and target_level have non-negative value, compacted files will be moved to target_level.

Default: -1 - dynamically

func (*CompactRangeOptions) TargetLevel

func (opts *CompactRangeOptions) TargetLevel() int32

TargetLevel returns target level.

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

	// SetIgnoreSnapshots before release 6.0, if there is a snapshot taken later than
	// the key/value pair, RocksDB always try to prevent the key/value pair from being
	// filtered by compaction filter so that users can preserve the same view from a
	// snapshot, unless the compaction filter returns IgnoreSnapshots() = true. However,
	// this feature is deleted since 6.0, after realized that the feature has a bug which
	// can't be easily fixed. Since release 6.0, with compaction filter enabled, RocksDB
	// always invoke filtering for any key, even if it knows it will make a snapshot
	// not repeatable.
	SetIgnoreSnapshots(value bool)

	// Destroy underlying pointer/data.
	Destroy()
}

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

	// Return native comparator.
	Native() *C.rocksdb_comparator_t

	// Destroy comparator.
	Destroy()
}

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 CuckooTableOptions

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

CuckooTableOptions are options for cuckoo table.

func NewCuckooTableOptions

func NewCuckooTableOptions() *CuckooTableOptions

NewCuckooTableOptions returns new cuckoo table options.

func (*CuckooTableOptions) Destroy

func (opts *CuckooTableOptions) Destroy()

Destroy options.

func (*CuckooTableOptions) SetCuckooBlockSize

func (opts *CuckooTableOptions) SetCuckooBlockSize(value uint32)

SetCuckooBlockSize in case of collision while inserting, the builder attempts to insert in the next cuckoo_block_size locations before skipping over to the next Cuckoo hash function. This makes lookups more cache friendly in case of collisions.

Default: 5.

func (*CuckooTableOptions) SetHashRatio

func (opts *CuckooTableOptions) SetHashRatio(value float64)

SetHashRatio determines the utilization of hash tables. Smaller values result in larger hash tables with fewer collisions.

Default: 0.9.

func (*CuckooTableOptions) SetIdentityAsFirstHash

func (opts *CuckooTableOptions) SetIdentityAsFirstHash(value bool)

SetIdentityAsFirstHash if this option is enabled, user key is treated as uint64_t and its value is used as hash value directly. This option changes builder's behavior. Reader ignore this option and behave according to what specified in table property.

Default: false.

func (*CuckooTableOptions) SetMaxSearchDepth

func (opts *CuckooTableOptions) SetMaxSearchDepth(value uint32)

SetMaxSearchDepth property used by builder to determine the depth to go to to search for a path to displace elements in case of collision. See Builder.MakeSpaceForKey method. Higher values result in more efficient hash tables with fewer lookups but take more time to build.

Default: 100.

func (*CuckooTableOptions) SetUseModuleHash

func (opts *CuckooTableOptions) SetUseModuleHash(value bool)

SetUseModuleHash if this option is set to true, module is used during hash calculation. This often yields better space efficiency at the cost of performance. If this option is set to false, # of entries in table is constrained to be power of two, and bit and is used to calculate hash, which is faster in general.

Default: true

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 *DB, err error)

OpenDb opens a database with the specified options.

func OpenDbAsSecondary

func OpenDbAsSecondary(opts *Options, name, secondaryPath string) (db *DB, err error)

OpenDbAsSecondary creates a secondary instance that can dynamically tail the MANIFEST of a primary that must have already been created. User can call TryCatchUpWithPrimary to make the secondary instance catch up with primary (WAL tailing is NOT supported now) whenever the user feels necessary. Column families created by the primary after the secondary instance starts are currently ignored by the secondary instance. Column families opened by secondary and dropped by the primary will be dropped by secondary as well. However the user of the secondary instance can still access the data of such dropped column family as long as they do not destroy the corresponding column family handle. WAL tailing is not supported at present, but will arrive soon.

func OpenDbForReadOnly

func OpenDbForReadOnly(opts *Options, name string, errorIfWalFileExists bool) (db *DB, err error)

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

func OpenDbWithTTL

func OpenDbWithTTL(opts *Options, name string, ttl int) (db *DB, err error)

OpenDbWithTTL opens a database with TTL support with the specified options.

func (*DB) CancelAllBackgroundWork

func (db *DB) CancelAllBackgroundWork(wait bool)

CancelAllBackgroundWork requests stopping background work, if wait is true wait until it's done

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) CompactRangeCFOpt

func (db *DB) CompactRangeCFOpt(cf *ColumnFamilyHandle, r Range, opt *CompactRangeOptions)

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

func (*DB) CompactRangeOpt

func (db *DB) CompactRangeOpt(r Range, opt *CompactRangeOptions)

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

func (*DB) CreateColumnFamily

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

CreateColumnFamily create a new column family.

func (*DB) CreateColumnFamilyWithTTL

func (db *DB) CreateColumnFamilyWithTTL(opts *Options, name string, ttl int) (handle *ColumnFamilyHandle, err error)

CreateColumnFamilyWithTTL create a new column family along with its ttl.

BEHAVIOUR: TTL is accepted in seconds (int32_t)Timestamp(creation) is suffixed to values in Put internally Expired TTL values deleted in compaction only:(Timestamp+ttl<time_now) Get/Iterator may return expired entries(compaction not run on them yet) Different TTL may be used during different Opens Example: Open1 at t=0 with ttl=4 and insert k1,k2, close at t=2

Open2 at t=3 with ttl=5. Now k1,k2 should be deleted at t>=5

read_only=true opens in the usual read-only mode. Compactions will not be

triggered(neither manual nor automatic), so no expired entries removed

CONSTRAINTS: Not specifying/passing or non-positive TTL behaves like TTL = infinity

func (*DB) Delete

func (db *DB) Delete(opts *WriteOptions, key []byte) (err 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) (err 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) DeleteFileInRange

func (db *DB) DeleteFileInRange(r Range) (err error)

DeleteFileInRange deletes SST files that contain keys between the Range, [r.Start, r.Limit]

func (*DB) DeleteFileInRangeCF

func (db *DB) DeleteFileInRangeCF(cf *ColumnFamilyHandle, r Range) (err error)

DeleteFileInRangeCF deletes SST files that contain keys between the Range, [r.Start, r.Limit], and belong to a given column family

func (*DB) DeleteRangeCF

func (db *DB) DeleteRangeCF(opts *WriteOptions, cf *ColumnFamilyHandle, startKey []byte, endKey []byte) (err error)

DeleteRangeCF deletes keys that are between [startKey, endKey)

func (*DB) DisableFileDeletions

func (db *DB) DisableFileDeletions() (err error)

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

func (*DB) DropColumnFamily

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

DropColumnFamily drops a column family.

func (*DB) EnableFileDeletions

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

EnableFileDeletions enables file deletions for the database.

func (*DB) Flush

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

Flush triggers a manual flush for the database.

func (*DB) FlushCF

func (db *DB) FlushCF(cf *ColumnFamilyHandle, opts *FlushOptions) (err error)

FlushCF triggers a manual flush for the database on specific column family.

func (*DB) FlushWAL

func (db *DB) FlushWAL(sync bool) (err error)

FlushWAL flushes the WAL memory buffer to the file. If sync is true, it calls SyncWAL afterwards.

func (*DB) Get

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

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

func (*DB) GetApproximateSizes

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

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, error)

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) (data []byte, err 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) (slice *Slice, err error)

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

func (*DB) GetIntProperty

func (db *DB) GetIntProperty(propName string) (value uint64, success bool)

GetIntProperty similar to `GetProperty`, but only works for a subset of properties whose return value is an integer. Return the value by integer.

func (*DB) GetIntPropertyCF

func (db *DB) GetIntPropertyCF(propName string, cf *ColumnFamilyHandle) (value uint64, success bool)

GetIntPropertyCF similar to `GetProperty`, but only works for a subset of properties whose return value is an integer. Return the value by integer.

func (*DB) GetLatestSequenceNumber

func (db *DB) GetLatestSequenceNumber() uint64

GetLatestSequenceNumber returns sequence number of the most recent transaction.

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) GetPinned

func (db *DB) GetPinned(opts *ReadOptions, key []byte) (handle *PinnableSliceHandle, err error)

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

func (*DB) GetPinnedCF

func (db *DB) GetPinnedCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) (handle *PinnableSliceHandle, err error)

GetPinnedCF returns the data associated with the key from the database, specific column family.

func (*DB) GetProperty

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

GetProperty returns the value of a database property.

func (*DB) GetPropertyCF

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

GetPropertyCF returns the value of a database property.

func (*DB) GetUpdatesSince

func (db *DB) GetUpdatesSince(seqNumber uint64) (iter *WalIterator, err error)

GetUpdatesSince if the sequence number is non existent, it returns an iterator at the first available seq_no after the requested seq_no.

Must set WAL_ttl_seconds or WAL_size_limit_MB to large values to use this api, else the WAL files will get cleared aggressively and the iterator might keep getting invalid before an update is read.

Note: this API is not yet consistent with WritePrepared transactions. Sets iter to an iterator that is positioned at a write-batch containing seq_number.

func (*DB) IngestExternalFile

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

IngestExternalFile loads a list of external SST files.

func (*DB) IngestExternalFileCF

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

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

func (*DB) KeyMayExists

func (db *DB) KeyMayExists(opts *ReadOptions, key []byte, timestamp string) (slice *Slice)

KeyMayExists the value is only allocated (using malloc) and returned if it is found and value_found isn't NULL. In that case the user is responsible for freeing it.

func (*DB) KeyMayExistsCF

func (db *DB) KeyMayExistsCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte, timestamp string) (slice *Slice)

KeyMayExistsCF the value is only allocated (using malloc) and returned if it is found and value_found isn't NULL. In that case the user is responsible for freeing it.

func (*DB) Merge

func (db *DB) Merge(opts *WriteOptions, key []byte, value []byte) (err 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) (err error)

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

func (*DB) MultiGet

func (db *DB) MultiGet(opts *ReadOptions, keys ...[]byte) (Slices, error)

MultiGet returns the data associated with the passed keys from the database

func (*DB) MultiGetCF

func (db *DB) MultiGetCF(opts *ReadOptions, cf *ColumnFamilyHandle, keys ...[]byte) (Slices, error)

MultiGetCF returns the data associated with the passed keys from the column family

func (*DB) MultiGetCFMultiCF

func (db *DB) MultiGetCFMultiCF(opts *ReadOptions, cfs ColumnFamilyHandles, keys [][]byte) (Slices, error)

MultiGetCFMultiCF returns the data associated with the passed keys and column families.

func (*DB) Name

func (db *DB) Name() string

Name returns the name of the database.

func (*DB) NewCheckpoint

func (db *DB) NewCheckpoint() (cp *Checkpoint, err 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) NewIterators

func (db *DB) NewIterators(opts *ReadOptions, cfs []*ColumnFamilyHandle) (iters []*Iterator, err error)

NewIterators returns iterators from a consistent database state across multiple column families. Iterators are heap allocated and need to be deleted before the db is deleted

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) (err 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) (err 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) SetOptions

func (db *DB) SetOptions(keys, values []string) (err error)

SetOptions dynamically changes options through the SetOptions API.

func (*DB) SetOptionsCF

func (db *DB) SetOptionsCF(cf *ColumnFamilyHandle, keys, values []string) (err error)

SetOptionsCF dynamically changes options through the SetOptions API for specific Column Family.

func (*DB) TryCatchUpWithPrimary

func (db *DB) TryCatchUpWithPrimary() (err error)

TryCatchUpWithPrimary to make the secondary instance catch up with primary (WAL tailing is NOT supported now) whenever the user feels necessary. Column families created by the primary after the secondary instance starts are currently ignored by the secondary instance. Column families opened by secondary and dropped by the primary will be dropped by secondary as well. However the user of the secondary instance can still access the data of such dropped column family as long as they do not destroy the corresponding column family handle. WAL tailing is not supported at present, but will arrive soon.

func (*DB) Write

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

Write a batch to the database.

func (*DB) WriteWI

func (db *DB) WriteWI(opts *WriteOptions, batch *WriteBatchWI) (err error)

WriteWI writes a batch wi 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 *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 target_sizes.

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 DataBlockIndexType

type DataBlockIndexType uint

DataBlockIndexType specifies index type that will be used for the data block.

const (
	// KDataBlockIndexTypeBinarySearch is traditional block type
	KDataBlockIndexTypeBinarySearch DataBlockIndexType = 0
	// KDataBlockIndexTypeBinarySearchAndHash additional hash index
	KDataBlockIndexTypeBinarySearchAndHash DataBlockIndexType = 1
)

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 NewMemEnv

func NewMemEnv() *Env

NewMemEnv returns a new environment that stores its data in memory and delegates all non-file-storage tasks to base_env.

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) GetBackgroundThreads

func (env *Env) GetBackgroundThreads() int

GetBackgroundThreads sets the number of background worker threads of a specific thread pool for this environment. 'LOW' is the default pool.

func (*Env) GetBottomPriorityBackgroundThreads

func (env *Env) GetBottomPriorityBackgroundThreads() int

GetBottomPriorityBackgroundThreads gets the size of thread pool that can be used to prevent bottommost compactions from stalling memtable flushes.

func (*Env) GetHighPriorityBackgroundThreads

func (env *Env) GetHighPriorityBackgroundThreads() int

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

func (*Env) GetLowPriorityBackgroundThreads

func (env *Env) GetLowPriorityBackgroundThreads() int

GetLowPriorityBackgroundThreads gets the size of the low priority thread pool that can be used to prevent compactions from stalling memtable flushes.

func (*Env) JoinAllThreads

func (env *Env) JoinAllThreads()

JoinAllThreads wait for all threads started by StartThread to terminate.

func (*Env) LowerHighPriorityThreadPoolCPUPriority

func (env *Env) LowerHighPriorityThreadPoolCPUPriority()

LowerHighPriorityThreadPoolCPUPriority lower CPU priority for high priority thread pool.

func (*Env) LowerHighPriorityThreadPoolIOPriority

func (env *Env) LowerHighPriorityThreadPoolIOPriority()

LowerHighPriorityThreadPoolIOPriority lower IO priority for high priority thread pool.

func (*Env) LowerThreadPoolCPUPriority

func (env *Env) LowerThreadPoolCPUPriority()

LowerThreadPoolCPUPriority lower CPU priority for threads from the specified pool.

func (*Env) LowerThreadPoolIOPriority

func (env *Env) LowerThreadPoolIOPriority()

LowerThreadPoolIOPriority lower IO priority for threads from the specified pool.

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) SetBottomPriorityBackgroundThreads

func (env *Env) SetBottomPriorityBackgroundThreads(n int)

SetBottomPriorityBackgroundThreads sets the size of thread pool that can be used to prevent bottommost compactions from stalling memtable flushes.

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.

func (*Env) SetLowPriorityBackgroundThreads

func (env *Env) SetLowPriorityBackgroundThreads(n int)

SetLowPriorityBackgroundThreads sets the size of the low 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) GetMaxTableFilesSize

func (opts *FIFOCompactionOptions) GetMaxTableFilesSize() uint64

GetMaxTableFilesSize gets the max table file size. Once the total sum of table files reaches this, we will delete the oldest table file

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

	// Destroy filter policy object.
	Destroy()
}

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 float64) 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 NewBloomFilterFull

func NewBloomFilterFull(bitsPerKey float64) FilterPolicy

NewBloomFilterFull returns a new filter policy that uses a full 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.

func NewRibbonFilterPolicy

func NewRibbonFilterPolicy(bitsPerKey float64, bloomBeforeLevel int) FilterPolicy

NewRibbonFilterPolicy creates a new Bloom alternative that saves about 30% space compared to Bloom filters, with similar query times but roughly 3-4x CPU time and 3x temporary space usage during construction. For example, if you pass in 10 for bloom_equivalent_bits_per_key, you'll get the same 0.95% FP rate as Bloom filter but only using about 7 bits per key.

The space savings of Ribbon filters makes sense for lower (higher numbered; larger; longer-lived) levels of LSM, whereas the speed of Bloom filters make sense for highest levels of LSM. Setting bloom_before_level allows for this design with Level and Universal compaction styles. For example, bloom_before_level=1 means that Bloom filters will be used in level 0, including flushes, and Ribbon filters elsewhere, including FIFO compaction and external SST files. For this option, memtable flushes are considered level -1 (so that flushes can be distinguished from intra-L0 compaction). bloom_before_level=0 (default) -> Generate Bloom filters only for flushes under Level and Universal compaction styles. bloom_before_level=-1 -> Always generate Ribbon filters (except in some extreme or exceptional cases).

Ribbon filters are compatible with RocksDB >= 6.15.0. Earlier versions reading the data will behave as if no filter was used (degraded performance until compaction rebuilds filters). All built-in FilterPolicies (Bloom or Ribbon) are able to read other kinds of built-in filters.

Note: the current Ribbon filter schema uses some extra resources when constructing very large filters. For example, for 100 million keys in a single filter (one SST file without partitioned filters), 3GB of temporary, untracked memory is used, vs. 1GB for Bloom. However, the savings in filter space from just ~60 open SST files makes up for the additional temporary memory use.

Also consider using optimize_filters_for_memory to save filter memory.

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.

const (
	// KBinarySearchIndexType a space efficient index block that is optimized for
	// binary-search-based index.
	KBinarySearchIndexType IndexType = 0x00

	// KHashSearchIndexType the hash index, if enabled, will do the hash lookup when
	// `Options.prefix_extractor` is provided.
	KHashSearchIndexType IndexType = 0x01

	// KTwoLevelIndexSearchIndexType a two-level index implementation. Both levels are binary search indexes.
	KTwoLevelIndexSearchIndexType IndexType = 0x02

	// KBinarySearchWithFirstKey like KBinarySearchIndexType, but index also contains
	// first key of each block.
	//
	// This allows iterators to defer reading the block until it's actually
	// needed. May significantly reduce read amplification of short range scans.
	// Without it, iterator seek usually reads one block from each level-0 file
	// and from each level, which may be expensive.
	// Works best in combination with:
	//  - IndexShorteningMode::kNoShortening,
	//  - custom FlushBlockPolicy to cut blocks at some meaningful boundaries,
	//    e.g. when prefix changes.
	// Makes the index significantly bigger (2x or more), especially when keys
	// are long.
	//
	// IO errors are not handled correctly in this mode right now: if an error
	// happens when lazily reading a block in value(), value() returns empty
	// slice, and you need to call Valid()/status() afterwards.
	KBinarySearchWithFirstKey IndexType = 0x03
)

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) SetIngestionBehind

func (opts *IngestExternalFileOptions) SetIngestionBehind(flag bool)

SetIngestionBehind sets ingest_behind Set to true if you would like duplicate keys in the file being ingested to be skipped rather than overwriting existing data under that key. Usecase: back-fill of some historical data in the database without over-writing existing newer version of data. This option could only be used if the DB has been running with allow_ingest_behind=true since the dawn of time. All files will be ingested at the bottommost level with seqno=0.

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() (err error)

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

func (*Iterator) Key

func (iter *Iterator) Key() *Slice

Key returns the key 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) Prev

func (iter *Iterator) Prev()

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

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) 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) Value

func (iter *Iterator) Value() *Slice

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

type LRUCacheOptions

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

LRUCacheOptions are options for LRU Cache.

func NewLRUCacheOptions

func NewLRUCacheOptions() *LRUCacheOptions

NewLRUCacheOptions creates lru cache options.

func (*LRUCacheOptions) Destroy

func (l *LRUCacheOptions) Destroy()

Destroy lru cache options.

func (*LRUCacheOptions) SetCapacity

func (l *LRUCacheOptions) SetCapacity(s uint)

SetCapacity sets capacity for this lru cache.

func (*LRUCacheOptions) SetMemoryAllocator

func (l *LRUCacheOptions) SetMemoryAllocator(m *MemoryAllocator)

SetMemoryAllocator for this lru cache.

type LiveFileMetadata

type LiveFileMetadata struct {
	Name             string
	ColumnFamilyName string
	Level            int
	Size             int64
	SmallestKey      []byte
	LargestKey       []byte
	Entries          uint64 // number of entries
	Deletions        uint64 // number of deletions
}

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

type MemoryAllocator

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

MemoryAllocator wraps memory allocator for rocksdb.

func (*MemoryAllocator) Destroy

func (m *MemoryAllocator) Destroy()

Destroy this mem allocator.

type MemoryUsage

type MemoryUsage struct {
	// MemTableTotal estimates memory usage of all mem-tables
	MemTableTotal uint64
	// MemTableUnflushed estimates memory usage of unflushed mem-tables
	MemTableUnflushed uint64
	// MemTableReadersTotal memory usage of table readers (indexes and bloom filters)
	MemTableReadersTotal uint64
	// CacheTotal memory usage of cache
	CacheTotal uint64
}

MemoryUsage contains memory usage statistics provided by RocksDB

func GetApproximateMemoryUsageByType

func GetApproximateMemoryUsageByType(dbs []*DB, caches []*Cache) (result *MemoryUsage, err error)

GetApproximateMemoryUsageByType returns summary memory usage stats for given databases and caches.

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)

	// 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 MultiMerger

type MultiMerger interface {
	// PartialMerge performs merge on multiple operands
	// when all of 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,operand[0]), followed by db.Merge(key,operand[1]),
	// ... db.Merge(key, operand[n])).
	//
	// 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,operand[0]), followed by db.Merge(key,operand[1]),
	// ... db.Merge(key, operand[n])).
	//
	// If it is impossible or infeasible to combine the 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.
	PartialMergeMulti(key []byte, operands [][]byte) ([]byte, bool)

	// Destroy pointer/underlying data
	Destroy()
}

MultiMerger implements PartialMergeMulti(key []byte, operands [][]byte) ([]byte, err) When a MergeOperator implements this interface, PartialMergeMulti will be called in addition to FullMerge for compactions across levels

type OptimisticTransactionDB

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

OptimisticTransactionDB is a reusable handle to a RocksDB optimistic transactional database on disk.

func OpenOptimisticTransactionDb

func OpenOptimisticTransactionDb(
	opts *Options,
	name string,
) (tdb *OptimisticTransactionDB, err error)

OpenOptimisticTransactionDb opens a database with the specified options.

func (*OptimisticTransactionDB) Close

func (db *OptimisticTransactionDB) Close()

Close closes the database.

func (*OptimisticTransactionDB) CloseBaseDB

func (db *OptimisticTransactionDB) CloseBaseDB(base *DB)

CloseBaseDB closes base-database.

func (*OptimisticTransactionDB) GetBaseDB

func (db *OptimisticTransactionDB) GetBaseDB() *DB

GetBaseDB returns base-database.

func (*OptimisticTransactionDB) NewCheckpoint

func (db *OptimisticTransactionDB) NewCheckpoint() (cp *Checkpoint, err error)

NewCheckpoint creates a new Checkpoint for this db.

func (*OptimisticTransactionDB) TransactionBegin

func (db *OptimisticTransactionDB) TransactionBegin(
	opts *WriteOptions,
	transactionOpts *OptimisticTransactionOptions,
	oldTransaction *Transaction,
) *Transaction

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

func (*OptimisticTransactionDB) Write

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

Write batch.

type OptimisticTransactionOptions

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

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

func NewDefaultOptimisticTransactionOptions

func NewDefaultOptimisticTransactionOptions() *OptimisticTransactionOptions

NewDefaultOptimisticTransactionOptions creates a default TransactionOptions object.

func NewNativeOptimisticTransactionOptions

func NewNativeOptimisticTransactionOptions(c *C.rocksdb_optimistictransaction_options_t) *OptimisticTransactionOptions

NewNativeOptimisticTransactionOptions creates a OptimisticTransactionOptions object.

func (*OptimisticTransactionOptions) Destroy

func (opts *OptimisticTransactionOptions) Destroy()

Destroy deallocates the TransactionOptions object.

func (*OptimisticTransactionOptions) SetSetSnapshot

func (opts *OptimisticTransactionOptions) SetSetSnapshot(value bool)

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

type Options

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

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

func GetOptionsFromString

func GetOptionsFromString(base *Options, optStr string) (newOpt *Options, err error)

GetOptionsFromString creates a Options object from existing opt and string. If base is nil, a default opt create by NewDefaultOptions will be used as base opt.

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) AddCompactOnDeletionCollectorFactory

func (opts *Options) AddCompactOnDeletionCollectorFactory(windowSize, numDelsTrigger uint)

AddCompactOnDeletionCollectorFactory marks a SST file as need-compaction when it observe at least "D" deletion entries in any "N" consecutive entries or the ratio of tombstone entries in the whole file >= the specified deletion ratio.

func (*Options) AdviseRandomOnOpen

func (opts *Options) AdviseRandomOnOpen() bool

AdviseRandomOnOpen returns whether we will hint the underlying file system that the file access pattern is random, when a sst file is opened.

func (*Options) AllowConcurrentMemtableWrites

func (opts *Options) AllowConcurrentMemtableWrites() bool

AllowConcurrentMemtableWrites 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) AllowIngestBehind

func (opts *Options) AllowIngestBehind() bool

AllowIngestBehind checks if allow_ingest_behind is set

func (*Options) AllowMmapReads

func (opts *Options) AllowMmapReads() bool

AllowMmapReads returns setting for enable/disable mmap reads for sst tables.

func (*Options) AllowMmapWrites

func (opts *Options) AllowMmapWrites() bool

AllowMmapWrites returns setting for enable/disable mmap writes for sst tables.

func (*Options) Clone

func (opts *Options) Clone() *Options

Clone the options

func (*Options) CompactionReadaheadSize

func (opts *Options) CompactionReadaheadSize(value uint64)

CompactionReadaheadSize if non-zero, we perform bigger reads when doing compaction. If you're running RocksDB on spinning disks, you should set this to at least 2MB. That way RocksDB's compaction is doing sequential instead of random reads.

When non-zero, we also force new_table_reader_for_compaction_inputs to true.

Default: 0

Dynamically changeable through SetDBOptions() API.

func (*Options) CreateIfMissing

func (opts *Options) CreateIfMissing() bool

CreateIfMissing checks if create_if_mission option is set

func (*Options) CreateIfMissingColumnFamilies

func (opts *Options) CreateIfMissingColumnFamilies() bool

CreateIfMissingColumnFamilies checks if create_if_missing_cf option is set

func (*Options) Destroy

func (opts *Options) Destroy()

Destroy deallocates the Options object.

func (*Options) DisabledAutoCompactions

func (opts *Options) DisabledAutoCompactions() bool

DisabledAutoCompactions returns if automatic compactions is disabled.

func (*Options) EnableBlobFiles

func (opts *Options) EnableBlobFiles(value bool)

EnableBlobFiles when set, large values (blobs) are written to separate blob files, and only pointers to them are stored in SST files. This can reduce write amplification for large-value use cases at the cost of introducing a level of indirection for reads. See also the options min_blob_size, blob_file_size, blob_compression_type, enable_blob_garbage_collection, and blob_garbage_collection_age_cutoff below.

Default: false

Dynamically changeable through the API.

func (*Options) EnableBlobGC

func (opts *Options) EnableBlobGC(value bool)

EnableBlobGC toggles garbage collection of blobs. Blob GC is performed as part of compaction. Valid blobs residing in blob files older than a cutoff get relocated to new files as they are encountered during compaction, which makes it possible to clean up blob files once they contain nothing but obsolete/garbage blobs. See also blob_garbage_collection_age_cutoff below.

Default: false

Dynamically changeable through the API.

func (*Options) EnableStatistics

func (opts *Options) EnableStatistics()

EnableStatistics enable statistics.

func (*Options) EnabledPipelinedWrite

func (opts *Options) EnabledPipelinedWrite() bool

EnabledPipelinedWrite check if enable_pipelined_write is turned on.

func (*Options) EnabledWriteThreadAdaptiveYield

func (opts *Options) EnabledWriteThreadAdaptiveYield() bool

EnabledWriteThreadAdaptiveYield if true, threads synchronizing with the write batch group leader will wait for up to write_thread_max_yield_usec before blocking on a mutex. This can substantially improve throughput for concurrent workloads, regardless of whether allow_concurrent_memtable_write is enabled.

func (*Options) ErrorIfExists

func (opts *Options) ErrorIfExists() bool

ErrorIfExists checks if error_if_exist option is set

func (*Options) GetAccessHintOnCompactionStart

func (opts *Options) GetAccessHintOnCompactionStart() CompactionAccessPattern

GetAccessHintOnCompactionStart returns the file access pattern once a compaction is started.

func (*Options) GetArenaBlockSize

func (opts *Options) GetArenaBlockSize() uint64

GetArenaBlockSize returns the size of one block in arena memory allocation.

func (*Options) GetBaseBackgroundCompactions

func (opts *Options) GetBaseBackgroundCompactions() int

GetBaseBackgroundCompactions gets base background compactions setting.

func (*Options) GetBlobCompactionReadaheadSize

func (opts *Options) GetBlobCompactionReadaheadSize() uint64

GetBlobCompactionReadaheadSize returns compaction readahead size for blob files.

func (*Options) GetBlobCompressionType

func (opts *Options) GetBlobCompressionType() CompressionType

GetBlobCompressionType gets the compression algorithm to use for large values stored in blob files. Note that enable_blob_files has to be set in order for this option to have any effect.

func (*Options) GetBlobFileSize

func (opts *Options) GetBlobFileSize() uint64

GetBlobFileSize gets the size limit for blob files.

func (*Options) GetBlobGCAgeCutoff

func (opts *Options) GetBlobGCAgeCutoff() float64

GetBlobGCAgeCutoff returns the cutoff in terms of blob file age for garbage collection.

func (*Options) GetBlobGCForceThreshold

func (opts *Options) GetBlobGCForceThreshold() float64

GetBlobGCForceThreshold get the threshold for ratio of garbage in the oldest blob files. See also: `SetBlobGCForceThreshold`

Default: 1.0

func (*Options) GetBloomLocality

func (opts *Options) GetBloomLocality() uint32

GetBloomLocality returns 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.

func (*Options) GetBottommostCompression

func (opts *Options) GetBottommostCompression() CompressionType

GetBottommostCompression returns the compression algorithm for bottommost level.

func (*Options) GetBytesPerSync

func (opts *Options) GetBytesPerSync() uint64

GetBytesPerSync return setting for bytes (size) per sync.

func (*Options) GetCompactionReadaheadSize

func (opts *Options) GetCompactionReadaheadSize() uint64

GetCompactionReadaheadSize gets readahead size

func (*Options) GetCompactionStyle

func (opts *Options) GetCompactionStyle() CompactionStyle

GetCompactionStyle returns compaction style.

func (*Options) GetCompression

func (opts *Options) GetCompression() CompressionType

GetCompression returns the compression algorithm.

func (*Options) GetCompressionOptionsMaxDictBufferBytes

func (opts *Options) GetCompressionOptionsMaxDictBufferBytes() uint64

GetCompressionOptionsMaxDictBufferBytes returns the limit on data buffering when gathering samples to build a dictionary. Zero means no limit. When dictionary is disabled (`max_dict_bytes == 0`), enabling this limit (`max_dict_buffer_bytes != 0`) has no effect.

func (*Options) GetCompressionOptionsParallelThreads

func (opts *Options) GetCompressionOptionsParallelThreads() int

GetCompressionOptionsParallelThreads returns number of threads for parallel compression. Parallel compression is enabled only if threads > 1.

This option is valid only when BlockBasedTable is used. Default: 1.

Note: THE FEATURE IS STILL EXPERIMENTAL

func (*Options) GetCompressionOptionsZstdMaxTrainBytes

func (opts *Options) GetCompressionOptionsZstdMaxTrainBytes() int

GetCompressionOptionsZstdMaxTrainBytes gets maximum size of training data passed to zstd's dictionary trainer. Using zstd's dictionary trainer can achieve even better compression ratio improvements than using `max_dict_bytes` alone.

func (*Options) GetDbWriteBufferSize

func (opts *Options) GetDbWriteBufferSize() uint64

GetDbWriteBufferSize gets db_write_buffer_size which is set in options

func (*Options) GetDeleteObsoleteFilesPeriodMicros

func (opts *Options) GetDeleteObsoleteFilesPeriodMicros() uint64

GetDeleteObsoleteFilesPeriodMicros returns the periodicity when obsolete files get deleted.

func (*Options) GetHardPendingCompactionBytesLimit

func (opts *Options) GetHardPendingCompactionBytesLimit() uint64

GetHardPendingCompactionBytesLimit returns 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.

func (*Options) GetHardRateLimit

func (opts *Options) GetHardRateLimit() float64

GetHardRateLimit returns setting for hard rate limit.

func (*Options) GetInfoLogLevel

func (opts *Options) GetInfoLogLevel() InfoLogLevel

GetInfoLogLevel gets the info log level which options hold

func (*Options) GetInplaceUpdateNumLocks

func (opts *Options) GetInplaceUpdateNumLocks() uint

GetInplaceUpdateNumLocks returns number of locks used for inplace upddate.

func (*Options) GetKeepLogFileNum

func (opts *Options) GetKeepLogFileNum() uint

GetKeepLogFileNum return setting for maximum info log files to be kept.

func (*Options) GetLevel0FileNumCompactionTrigger

func (opts *Options) GetLevel0FileNumCompactionTrigger() int

GetLevel0FileNumCompactionTrigger gets the number of files to trigger level-0 compaction.

func (*Options) GetLevel0SlowdownWritesTrigger

func (opts *Options) GetLevel0SlowdownWritesTrigger() int

GetLevel0SlowdownWritesTrigger gets the soft limit on number of level-0 files. We start slowing down writes at this point.

func (*Options) GetLevel0StopWritesTrigger

func (opts *Options) GetLevel0StopWritesTrigger() int

GetLevel0StopWritesTrigger gets the maximum number of level-0 files. We stop writes at this point.

func (*Options) GetLevelCompactionDynamicLevelBytes

func (opts *Options) GetLevelCompactionDynamicLevelBytes() bool

GetLevelCompactionDynamicLevelBytes checks if level_compaction_dynamic_level_bytes option is set.

func (*Options) GetLogFileTimeToRoll

func (opts *Options) GetLogFileTimeToRoll() uint64

GetLogFileTimeToRoll returns the time for info log file to roll (in seconds).

func (*Options) GetManifestPreallocationSize

func (opts *Options) GetManifestPreallocationSize() uint64

GetManifestPreallocationSize returns the number of bytes to preallocate (via fallocate) the manifest files.

func (*Options) GetMaxBackgroundCompactions

func (opts *Options) GetMaxBackgroundCompactions() int

GetMaxBackgroundCompactions returns maximum number of concurrent background compaction jobs setting.

func (*Options) GetMaxBackgroundFlushes

func (opts *Options) GetMaxBackgroundFlushes() int

GetMaxBackgroundFlushes returns the maximum number of concurrent background memtable flush jobs setting.

func (*Options) GetMaxBackgroundJobs

func (opts *Options) GetMaxBackgroundJobs() int

GetMaxBackgroundJobs returns maximum number of concurrent background jobs setting.

func (*Options) GetMaxBytesForLevelBase

func (opts *Options) GetMaxBytesForLevelBase() uint64

GetMaxBytesForLevelBase gets the maximum total data size for a level.

func (*Options) GetMaxBytesForLevelMultiplier

func (opts *Options) GetMaxBytesForLevelMultiplier() float64

GetMaxBytesForLevelMultiplier gets the max bytes for level multiplier.

func (*Options) GetMaxCompactionBytes

func (opts *Options) GetMaxCompactionBytes() uint64

GetMaxCompactionBytes returns 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.

func (*Options) GetMaxFileOpeningThreads

func (opts *Options) GetMaxFileOpeningThreads() int

GetMaxFileOpeningThreads gets the maximum number of file opening threads.

func (*Options) GetMaxLogFileSize

func (opts *Options) GetMaxLogFileSize() uint64

GetMaxLogFileSize returns setting for maximum size of the info log file.

func (*Options) GetMaxManifestFileSize

func (opts *Options) GetMaxManifestFileSize() uint64

GetMaxManifestFileSize returns the maximum manifest file size until is rolled over. The older manifest file be deleted.

func (*Options) GetMaxOpenFiles

func (opts *Options) GetMaxOpenFiles() int

GetMaxOpenFiles gets the number of open files that can be used by the DB.

func (*Options) GetMaxSequentialSkipInIterations

func (opts *Options) GetMaxSequentialSkipInIterations() uint64

GetMaxSequentialSkipInIterations returns the number of keys (with the same userkey) that will be sequentially skipped before a reseek is issued.

func (*Options) GetMaxSubcompactions

func (opts *Options) GetMaxSubcompactions() uint32

GetMaxSubcompactions gets the maximum number of threads that will concurrently perform a compaction job by breaking it into multiple, smaller ones that are run simultaneously.

func (*Options) GetMaxSuccessiveMerges

func (opts *Options) GetMaxSuccessiveMerges() uint

GetMaxSuccessiveMerges returns 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.

func (*Options) GetMaxTotalWalSize

func (opts *Options) GetMaxTotalWalSize() uint64

GetMaxTotalWalSize gets the maximum total wal size (in bytes).

func (*Options) GetMaxWriteBufferNumber

func (opts *Options) GetMaxWriteBufferNumber() int

GetMaxWriteBufferNumber gets the maximum number of write buffers that are built up in memory.

func (*Options) GetMaxWriteBufferNumberToMaintain deprecated

func (opts *Options) GetMaxWriteBufferNumberToMaintain() int

GetMaxWriteBufferNumberToMaintain gets total maximum number of write buffers to maintain in memory including copies of buffers that have already been flushed. Unlike max_write_buffer_number, this parameter does not affect flushing. This controls the minimum amount of write history that will be available in memory for conflict checking when Transactions are used.

Deprecated: soon

func (*Options) GetMaxWriteBufferSizeToMaintain

func (opts *Options) GetMaxWriteBufferSizeToMaintain() int64

GetMaxWriteBufferSizeToMaintain gets the total maximum size(bytes) of write buffers to maintain in memory including copies of buffers that have already been flushed. This parameter only affects trimming of flushed buffers and does not affect flushing. This controls the maximum amount of write history that will be available in memory for conflict checking when Transactions are used. The actual size of write history (flushed Memtables) might be higher than this limit if further trimming will reduce write history total size below this limit. For example, if max_write_buffer_size_to_maintain is set to 64MB, and there are three flushed Memtables, with sizes of 32MB, 20MB, 20MB. Because trimming the next Memtable of size 20MB will reduce total memory usage to 52MB which is below the limit, RocksDB will stop trimming.

func (*Options) GetMemTablePrefixBloomSizeRatio

func (opts *Options) GetMemTablePrefixBloomSizeRatio() float64

GetMemTablePrefixBloomSizeRatio returns memtable_prefix_bloom_size_ratio.

func (*Options) GetMemtableHugePageSize

func (opts *Options) GetMemtableHugePageSize() uint64

GetMemtableHugePageSize returns the page size for huge page for arena used by the memtable.

func (*Options) GetMinBlobSize

func (opts *Options) GetMinBlobSize() uint64

GetMinBlobSize returns the size of the smallest value to be stored separately in a blob file.

func (*Options) GetMinWriteBufferNumberToMerge

func (opts *Options) GetMinWriteBufferNumberToMerge() int

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

func (*Options) GetNumLevels

func (opts *Options) GetNumLevels() int

GetNumLevels gets the number of levels.

func (*Options) GetRateLimitDelayMaxMilliseconds

func (opts *Options) GetRateLimitDelayMaxMilliseconds() uint

GetRateLimitDelayMaxMilliseconds sets the max time a put will be stalled when hard_rate_limit is enforced.

func (*Options) GetRecycleLogFileNum

func (opts *Options) GetRecycleLogFileNum() uint

GetRecycleLogFileNum returns setting for number of recycling log files.

func (*Options) GetSoftPendingCompactionBytesLimit

func (opts *Options) GetSoftPendingCompactionBytesLimit() uint64

GetSoftPendingCompactionBytesLimit returns 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.

func (*Options) GetSoftRateLimit

func (opts *Options) GetSoftRateLimit() float64

GetSoftRateLimit returns setting for soft rate limit.

func (*Options) GetStatisticsString

func (opts *Options) GetStatisticsString() (stats string)

GetStatisticsString returns the statistics as a string.

func (*Options) GetStatsDumpPeriodSec

func (opts *Options) GetStatsDumpPeriodSec() uint

GetStatsDumpPeriodSec returns the stats dump period in seconds.

func (*Options) GetStatsPersistPeriodSec

func (opts *Options) GetStatsPersistPeriodSec() uint

GetStatsPersistPeriodSec returns number of sec that RocksDB periodically dump stats.

func (*Options) GetTableCacheNumshardbits

func (opts *Options) GetTableCacheNumshardbits() int

GetTableCacheNumshardbits returns the number of shards used for table cache.

func (*Options) GetTargetFileSizeBase

func (opts *Options) GetTargetFileSizeBase() uint64

GetTargetFileSizeBase gets the target file size base for compaction.

func (*Options) GetTargetFileSizeMultiplier

func (opts *Options) GetTargetFileSizeMultiplier() int

GetTargetFileSizeMultiplier gets the target file size multiplier for compaction.

func (*Options) GetWALBytesPerSync

func (opts *Options) GetWALBytesPerSync() uint64

GetWALBytesPerSync same as bytes_per_sync, but applies to WAL files.

func (*Options) GetWALRecoveryMode

func (opts *Options) GetWALRecoveryMode() WALRecoveryMode

GetWALRecoveryMode returns the recovery mode.

func (*Options) GetWALTtlSeconds

func (opts *Options) GetWALTtlSeconds() uint64

GetWALTtlSeconds returns WAL ttl in seconds.

func (*Options) GetWalSizeLimitMb

func (opts *Options) GetWalSizeLimitMb() uint64

GetWalSizeLimitMb returns the WAL size limit in MB.

func (*Options) GetWritableFileMaxBufferSize

func (opts *Options) GetWritableFileMaxBufferSize() uint64

GetWritableFileMaxBufferSize returns the maximum buffer size that is used by WritableFileWriter. On Windows, we need to maintain an aligned buffer for writes. We allow the buffer to grow until it's size hits the limit in buffered IO and fix the buffer size when using direct IO to ensure alignment of write requests if the logical sector size is unusual

func (*Options) GetWriteBufferSize

func (opts *Options) GetWriteBufferSize() uint64

GetWriteBufferSize gets write_buffer_size which is set for options

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) InplaceUpdateSupport

func (opts *Options) InplaceUpdateSupport() bool

InplaceUpdateSupport returns setting for enable/disable thread-safe inplace updates.

func (*Options) IsAtomicFlush

func (opts *Options) IsAtomicFlush() bool

IsAtomicFlush returns setting for atomic flushing. If true, RocksDB supports flushing multiple column families and committing their results atomically to MANIFEST. Note that it is not necessary to set atomic_flush to true if WAL is always enabled since WAL allows the database to be restored to the last persistent state in WAL. This option is useful when there are column families with writes NOT protected by WAL. For manual flush, application has to specify which column families to flush atomically in DB::Flush. For auto-triggered flush, RocksDB atomically flushes ALL column families.

Currently, any WAL-enabled writes after atomic flush may be replayed independently if the process crashes later and tries to recover.

func (*Options) IsBlobFilesEnabled

func (opts *Options) IsBlobFilesEnabled() bool

IsBlobFilesEnabled returns if blob-file setting is enabled.

func (*Options) IsBlobGCEnabled

func (opts *Options) IsBlobGCEnabled() bool

IsBlobGCEnabled returns if blob garbage collection is enabled.

func (*Options) IsFdCloseOnExec

func (opts *Options) IsFdCloseOnExec() bool

IsFdCloseOnExec returns setting for enable/dsiable child process inherit open files.

func (*Options) IsManualWALFlush

func (opts *Options) IsManualWALFlush() bool

IsManualWALFlush returns true if WAL is not flushed automatically after each write.

func (*Options) OptimizeFiltersForHits

func (opts *Options) OptimizeFiltersForHits() bool

OptimizeFiltersForHits gets setting for optimize_filters_for_hits.

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) ParanoidChecks

func (opts *Options) ParanoidChecks() bool

ParanoidChecks checks if paranoid_check option is set

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) ReportBackgroundIOStats

func (opts *Options) ReportBackgroundIOStats() bool

ReportBackgroundIOStats returns if measureing IO stats in compactions and flushes is turned on.

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 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) SetAllowIngestBehind

func (opts *Options) SetAllowIngestBehind(value bool)

SetAllowIngestBehind sets allow_ingest_behind Set this option to true during creation of database if you want to be able to ingest behind (call IngestExternalFile() skipping keys that already exist, rather than overwriting matching keys). Setting this option to true will affect 2 things: 1) Disable some internal optimizations around SST file compression 2) Reserve bottom-most level for ingested files only. 3) Note that num_levels should be >= 3 if this option is turned on.

Default: false

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 uint64)

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) SetAtomicFlush

func (opts *Options) SetAtomicFlush(value bool)

SetAtomicFlush if true, RocksDB supports flushing multiple column families and committing their results atomically to MANIFEST. Note that it is not necessary to set atomic_flush to true if WAL is always enabled since WAL allows the database to be restored to the last persistent state in WAL. This option is useful when there are column families with writes NOT protected by WAL. For manual flush, application has to specify which column families to flush atomically in DB::Flush. For auto-triggered flush, RocksDB atomically flushes ALL column families.

Currently, any WAL-enabled writes after atomic flush may be replayed independently if the process crashes later and tries to recover.

func (*Options) SetBaseBackgroundCompactions deprecated

func (opts *Options) SetBaseBackgroundCompactions(value int)

SetBaseBackgroundCompactions set base background compactions.

Deprecated: RocksDB automatically decides this based on the value of max_background_jobs. This option is ignored.

func (*Options) SetBlobCompactionReadaheadSize

func (opts *Options) SetBlobCompactionReadaheadSize(val uint64)

SetBlobCompactionReadaheadSize sets compaction readahead for blob files.

Default: 0

Dynamically changeable through the SetOptions() API.

func (*Options) SetBlobCompressionType

func (opts *Options) SetBlobCompressionType(compressionType CompressionType)

SetBlobCompressionType sets the compression algorithm to use for large values stored in blob files. Note that enable_blob_files has to be set in order for this option to have any effect.

Default: no compression

Dynamically changeable through the API.

func (*Options) SetBlobFileSize

func (opts *Options) SetBlobFileSize(value uint64)

SetBlobFileSize sets the size limit for blob files. When writing blob files, a new file is opened once this limit is reached. Note that enable_blob_files has to be set in order for this option to have any effect.

Default: 256 MB

Dynamically changeable through the API.

func (*Options) SetBlobGCAgeCutoff

func (opts *Options) SetBlobGCAgeCutoff(value float64)

SetBlobGCAgeCutoff sets the cutoff in terms of blob file age for garbage collection. Blobs in the oldest N blob files will be relocated when encountered during compaction, where N = garbage_collection_cutoff * number_of_blob_files. Note that enable_blob_garbage_collection has to be set in order for this option to have any effect.

Default: 0.25

Dynamically changeable through the API.

func (*Options) SetBlobGCForceThreshold

func (opts *Options) SetBlobGCForceThreshold(val float64)

SetBlobGCForceThreshold if the ratio of garbage in the oldest blob files exceeds this threshold, targeted compactions are scheduled in order to force garbage collecting the blob files in question, assuming they are all eligible based on the value of blob_garbage_collection_age_cutoff above. This option is currently only supported with leveled compactions. Note that enable_blob_garbage_collection has to be set in order for this option to have any effect.

Default: 1.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) SetBottommostCompression

func (opts *Options) SetBottommostCompression(value CompressionType)

SetBottommostCompression sets the compression algorithm for bottommost level.

func (*Options) SetBottommostCompressionOptions

func (opts *Options) SetBottommostCompressionOptions(value CompressionOptions, enabled bool)

SetBottommostCompressionOptions sets different options for compression algorithms, for bottommost.

`enabled` true to use these compression options.

func (*Options) SetBottommostCompressionOptionsMaxDictBufferBytes

func (opts *Options) SetBottommostCompressionOptionsMaxDictBufferBytes(value uint64, enabled bool)

SetBottommostCompressionOptionsMaxDictBufferBytes limits on data buffering when gathering samples to build a dictionary, for bottom most level. Zero means no limit. When dictionary is disabled (`max_dict_bytes == 0`), enabling this limit (`max_dict_buffer_bytes != 0`) has no effect.

In compaction, the buffering is limited to the target file size (see `target_file_size_base` and `target_file_size_multiplier`) even if this setting permits more buffering. Since we cannot determine where the file should be cut until data blocks are compressed with dictionary, buffering more than the target file size could lead to selecting samples that belong to a later output SST.

Limiting too strictly may harm dictionary effectiveness since it forces RocksDB to pick samples from the initial portion of the output SST, which may not be representative of the whole file. Configuring this limit below `zstd_max_train_bytes` (when enabled) can restrict how many samples we can pass to the dictionary trainer. Configuring it below `max_dict_bytes` can restrict the size of the final dictionary.

Default: 0 (unlimited)

func (*Options) SetBottommostCompressionOptionsZstdMaxTrainBytes

func (opts *Options) SetBottommostCompressionOptionsZstdMaxTrainBytes(value int, enabled bool)

SetBottommostCompressionOptionsZstdMaxTrainBytes sets maximum size of training data passed to zstd's dictionary trainer for bottommost level. Using zstd's dictionary trainer can achieve even better compression ratio improvements than using `max_dict_bytes` alone.

`enabled` true to use these compression options.

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 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) 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.

func (*Options) SetCompressionOptionsMaxDictBufferBytes

func (opts *Options) SetCompressionOptionsMaxDictBufferBytes(value uint64)

SetCompressionOptionsMaxDictBufferBytes limits on data buffering when gathering samples to build a dictionary. Zero means no limit. When dictionary is disabled (`max_dict_bytes == 0`), enabling this limit (`max_dict_buffer_bytes != 0`) has no effect.

In compaction, the buffering is limited to the target file size (see `target_file_size_base` and `target_file_size_multiplier`) even if this setting permits more buffering. Since we cannot determine where the file should be cut until data blocks are compressed with dictionary, buffering more than the target file size could lead to selecting samples that belong to a later output SST.

Limiting too strictly may harm dictionary effectiveness since it forces RocksDB to pick samples from the initial portion of the output SST, which may not be representative of the whole file. Configuring this limit below `zstd_max_train_bytes` (when enabled) can restrict how many samples we can pass to the dictionary trainer. Configuring it below `max_dict_bytes` can restrict the size of the final dictionary.

Default: 0 (unlimited)

func (*Options) SetCompressionOptionsParallelThreads

func (opts *Options) SetCompressionOptionsParallelThreads(n int)

SetCompressionOptionsParallelThreads sets number of threads for parallel compression. Parallel compression is enabled only if threads > 1.

This option is valid only when BlockBasedTable is used.

When parallel compression is enabled, SST size file sizes might be more inflated compared to the target size, because more data of unknown compressed size is in flight when compression is parallelized. To be reasonably accurate, this inflation is also estimated by using historical compression ratio and current bytes inflight.

Default: 1.

Note: THE FEATURE IS STILL EXPERIMENTAL

func (*Options) SetCompressionOptionsZstdMaxTrainBytes

func (opts *Options) SetCompressionOptionsZstdMaxTrainBytes(value int)

SetCompressionOptionsZstdMaxTrainBytes sets maximum size of training data passed to zstd's dictionary trainer. Using zstd's dictionary trainer can achieve even better compression ratio improvements than using `max_dict_bytes` alone.

The training data will be used to generate a dictionary of max_dict_bytes.

Default: 0.

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) SetCuckooTableFactory

func (opts *Options) SetCuckooTableFactory(cuckooOpts *CuckooTableOptions)

SetCuckooTableFactory sets to use cuckoo table factory.

Note: move semantic. Don't use cuckoo options after calling this function.

Default: nil.

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 uint64)

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) SetDumpMallocStats

func (opts *Options) SetDumpMallocStats(value bool)

SetDumpMallocStats if true, then print malloc stats together with rocksdb.stats when printing to LOG.

func (*Options) SetEnablePipelinedWrite

func (opts *Options) SetEnablePipelinedWrite(value bool)

SetEnablePipelinedWrite enables pipelined write.

By default, a single write thread queue is maintained. The thread gets to the head of the queue becomes write batch group leader and responsible for writing to WAL and memtable for the batch group.

If enable_pipelined_write is true, separate write thread queue is maintained for WAL write and memtable write. A write thread first enter WAL writer queue and then memtable writer queue. Pending thread on the WAL writer queue thus only have to wait for previous writers to finish their WAL writing but not the memtable writing. Enabling the feature may improve write throughput and reduce latency of the prepare phase of two-phase commit.

Default: false

func (*Options) SetEnableWriteThreadAdaptiveYield

func (opts *Options) SetEnableWriteThreadAdaptiveYield(value bool)

SetEnableWriteThreadAdaptiveYield if true, threads synchronizing with the write batch group leader will wait for up to write_thread_max_yield_usec before blocking on a mutex. This can substantially improve throughput for concurrent workloads, regardless of whether allow_concurrent_memtable_write is enabled.

Default: true

func (*Options) SetEnv

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

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

Note: move semantic. Don't use env after calling this function

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.

Note: move semantic. Don't use fifo compaction options after calling this function

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 uint)

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 uint, 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 uint)

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 uint)

SetKeepLogFileNum sets the maximum 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: 2

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: 20

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: 36

func (*Options) SetLevelCompactionDynamicLevelBytes

func (opts *Options) SetLevelCompactionDynamicLevelBytes(value bool)

SetLevelCompactionDynamicLevelBytes specifies whether to pick target size of each level dynamically.

We will pick a base level b >= 1. L0 will be directly merged into level b, instead of always into level 1. Level 1 to b-1 need to be empty. We try to pick b and its target size so that

  1. target size is in the range of (max_bytes_for_level_base / max_bytes_for_level_multiplier, max_bytes_for_level_base]
  2. target size of the last level (level num_levels-1) equals to extra size of the level.

At the same time max_bytes_for_level_multiplier and max_bytes_for_level_multiplier_additional are still satisfied.

With this option on, from an empty DB, we make last level the base level, which means merging L0 data into the last level, until it exceeds max_bytes_for_level_base. And then we make the second last level to be base level, to start to merge L0 data to second last level, with its target size to be 1/max_bytes_for_level_multiplier of the last level's extra size. After the data accumulates more so that we need to move the base level to the third last one, and so on.

For example, assume max_bytes_for_level_multiplier=10, num_levels=6, and max_bytes_for_level_base=10MB. Target sizes of level 1 to 5 starts with: [- - - - 10MB] with base level is level. Target sizes of level 1 to 4 are not applicable because they will not be used. Until the size of Level 5 grows to more than 10MB, say 11MB, we make base target to level 4 and now the targets looks like: [- - - 1.1MB 11MB] While data are accumulated, size targets are tuned based on actual data of level 5. When level 5 has 50MB of data, the target is like: [- - - 5MB 50MB] Until level 5's actual size is more than 100MB, say 101MB. Now if we keep level 4 to be the base level, its target size needs to be 10.1MB, which doesn't satisfy the target size range. So now we make level 3 the target size and the target sizes of the levels look like: [- - 1.01MB 10.1MB 101MB] In the same way, while level 5 further grows, all levels' targets grow, like [- - 5MB 50MB 500MB] Until level 5 exceeds 1000MB and becomes 1001MB, we make level 2 the base level and make levels' target sizes like this: [- 1.001MB 10.01MB 100.1MB 1001MB] and go on...

By doing it, we give max_bytes_for_level_multiplier a priority against max_bytes_for_level_base, for a more predictable LSM tree shape. It is useful to limit worse case space amplification.

max_bytes_for_level_multiplier_additional is ignored with this flag on.

Turning this feature on or off for an existing DB can cause unexpected LSM tree structure so it's not recommended.

Default: false

func (*Options) SetLogFileTimeToRoll

func (opts *Options) SetLogFileTimeToRoll(value uint64)

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 uint64)

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).

func (*Options) SetManualWALFlush

func (opts *Options) SetManualWALFlush(v bool)

SetManualWALFlush if true WAL is not flushed automatically after each write. Instead it relies on manual invocation of db.FlushWAL to write the WAL buffer to its file.

Default: false

func (*Options) SetMaxBackgroundCompactions deprecated

func (opts *Options) SetMaxBackgroundCompactions(value int)

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

Deprecated: RocksDB automatically decides this based on the value of max_background_jobs. For backwards compatibility we will set `max_background_jobs = max_background_compactions + max_background_flushes` in the case where user sets at least one of `max_background_compactions` or `max_background_flushes` (we replace -1 by 1 in case one option is unset).

func (*Options) SetMaxBackgroundFlushes deprecated

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

Deprecated: RocksDB automatically decides this based on the value of max_background_jobs. For backwards compatibility we will set `max_background_jobs = max_background_compactions + max_background_flushes` in the case where user sets at least one of `max_background_compactions` or `max_background_flushes`.

func (*Options) SetMaxBackgroundJobs

func (opts *Options) SetMaxBackgroundJobs(value int)

SetMaxBackgroundJobs maximum number of concurrent background jobs (compactions and flushes).

Default: 2

Dynamically changeable through SetDBOptions() API.

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 uint64)

SetMaxLogFileSize sets the maximum 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 maximum 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: -1 - unlimited

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) SetMaxSubcompactions

func (opts *Options) SetMaxSubcompactions(value uint32)

SetMaxSubcompactions represents the maximum number of threads that will concurrently perform a compaction job by breaking it into multiple, smaller ones that are run simultaneously.

Default: 1 (i.e. no subcompactions)

func (*Options) SetMaxSuccessiveMerges

func (opts *Options) SetMaxSuccessiveMerges(value uint)

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) SetMaxWriteBufferNumberToMaintain deprecated

func (opts *Options) SetMaxWriteBufferNumberToMaintain(value int)

SetMaxWriteBufferNumberToMaintain sets total maximum number of write buffers to maintain in memory including copies of buffers that have already been flushed. Unlike max_write_buffer_number, this parameter does not affect flushing. This controls the minimum amount of write history that will be available in memory for conflict checking when Transactions are used.

When using an OptimisticTransactionDB: If this value is too low, some transactions may fail at commit time due to not being able to determine whether there were any write conflicts.

When using a TransactionDB: If Transaction::SetSnapshot is used, TransactionDB will read either in-memory write buffers or SST files to do write-conflict checking. Increasing this value can reduce the number of reads to SST files done for conflict detection.

Setting this value to 0 will cause write buffers to be freed immediately after they are flushed. If this value is set to -1, 'max_write_buffer_number' will be used.

Default: If using a TransactionDB/OptimisticTransactionDB, the default value will be set to the value of 'max_write_buffer_number' if it is not explicitly set by the user. Otherwise, the default is 0.

Deprecated: soon

func (*Options) SetMaxWriteBufferSizeToMaintain

func (opts *Options) SetMaxWriteBufferSizeToMaintain(value int64)

SetMaxWriteBufferSizeToMaintain is the total maximum size(bytes) of write buffers to maintain in memory including copies of buffers that have already been flushed. This parameter only affects trimming of flushed buffers and does not affect flushing. This controls the maximum amount of write history that will be available in memory for conflict checking when Transactions are used. The actual size of write history (flushed Memtables) might be higher than this limit if further trimming will reduce write history total size below this limit. For example, if max_write_buffer_size_to_maintain is set to 64MB, and there are three flushed Memtables, with sizes of 32MB, 20MB, 20MB. Because trimming the next Memtable of size 20MB will reduce total memory usage to 52MB which is below the limit, RocksDB will stop trimming.

When using an OptimisticTransactionDB: If this value is too low, some transactions may fail at commit time due to not being able to determine whether there were any write conflicts.

When using a TransactionDB: If Transaction::SetSnapshot is used, TransactionDB will read either in-memory write buffers or SST files to do write-conflict checking. Increasing this value can reduce the number of reads to SST files done for conflict detection.

Setting this value to 0 will cause write buffers to be freed immediately after they are flushed. If this value is set to -1, 'max_write_buffer_number * write_buffer_size' will be used.

Default: If using a TransactionDB/OptimisticTransactionDB, the default value will be set to the value of 'max_write_buffer_number * write_buffer_size' if it is not explicitly set by the user. Otherwise, the default is 0.

func (*Options) SetMemTablePrefixBloomSizeRatio

func (opts *Options) SetMemTablePrefixBloomSizeRatio(value float64)

SetMemTablePrefixBloomSizeRatio sets memtable_prefix_bloom_size_ratio if prefix_extractor is set and memtable_prefix_bloom_size_ratio is not 0, create prefix bloom for memtable with the size of write_buffer_size * memtable_prefix_bloom_size_ratio. If it is larger than 0.25, it is sanitized to 0.25.

Default: 0 (disable)

func (*Options) SetMemtableHugePageSize

func (opts *Options) SetMemtableHugePageSize(value uint64)

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) SetMemtableWholeKeyFiltering

func (opts *Options) SetMemtableWholeKeyFiltering(value bool)

SetMemtableWholeKeyFiltering enable whole key bloom filter in memtable. Note this will only take effect if memtable_prefix_bloom_size_ratio is not 0. Enabling whole key filtering can potentially reduce CPU usage for point-look-ups.

Default: false (disable)

Dynamically changeable through SetOptions() API

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) SetMinBlobSize

func (opts *Options) SetMinBlobSize(value uint64)

SetMinBlogSize sets the size of the smallest value to be stored separately in a blob file. Values which have an uncompressed size smaller than this threshold are stored alongside the keys in SST files in the usual fashion. A value of zero for this option means that all values are stored in blob files. Note that enable_blob_files has to be set in order for this option to have any effect.

Default: 0

Dynamically changeable through the API.

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) SetOptimizeFiltersForHits

func (opts *Options) SetOptimizeFiltersForHits(value bool)

SetOptimizeFiltersForHits sets optimize_filters_for_hits This flag specifies that the implementation should optimize the filters mainly for cases where keys are found rather than also optimize for keys missed. This would be used in cases where the application knows that there are very few misses or the performance in the case of misses is not important.

For now, this flag allows us to not store filters for the last level i.e the largest level which contains data of the LSM store. For keys which are hits, the filters in this level are not useful because we will search for the data anyway. NOTE: the filters in other levels are still useful even for key hit because they tell us whether to look in that level or go to the higher level.

Default: false

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 uint,
)

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().

Note: move semantic. Don't use slice transform after calling this function.

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.

Note: move semantic. Don't use rate limiter after calling this function

Default: nil

func (*Options) SetRecycleLogFileNum

func (opts *Options) SetRecycleLogFileNum(value uint)

SetRecycleLogFileNum if non-zero, we will reuse previously written log files for new logs, overwriting the old data. The value indicates how many such files we will keep around at any point in time for later use. This is more efficient because the blocks are already allocated and fdatasync does not need to update the inode after each write. Default: 0

func (*Options) SetReportBackgroundIOStats

func (opts *Options) SetReportBackgroundIOStats(value bool)

SetReportBackgroundIOStats measures IO stats in compactions and flushes, if true.

Default: false

Dynamically changeable through SetOptions() API

func (*Options) SetRowCache

func (opts *Options) SetRowCache(cache *Cache)

SetRowCache set global cache for table-level rows.

Default: nil (disabled) Not supported in ROCKSDB_LITE mode!

func (*Options) SetSkipCheckingSSTFileSizesOnDBOpen

func (opts *Options) SetSkipCheckingSSTFileSizesOnDBOpen(value bool)

SetSkipCheckingSSTFileSizesOnDBOpen skips checking sst file sizes on db openning

Default: false

func (*Options) SetSkipLogErrorOnRecovery deprecated

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

Deprecated: this options is no longer used.

func (*Options) SetSkipStatsUpdateOnDBOpen

func (opts *Options) SetSkipStatsUpdateOnDBOpen(value bool)

SetSkipStatsUpdateOnDBOpen if true, then DB::Open() will not update the statistics used to optimize compaction decision by loading table properties from many files. Turning off this feature will improve DBOpen time especially in disk environment.

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) SetStatsPersistPeriodSec

func (opts *Options) SetStatsPersistPeriodSec(value uint)

SetStatsPersistPeriodSec if not zero, dump rocksdb.stats to RocksDB every stats_persist_period_sec

Default: 600

func (*Options) SetTableCacheNumshardbits

func (opts *Options) SetTableCacheNumshardbits(value int)

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

func (*Options) SetTableCacheRemoveScanCountLimit deprecated

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

Deprecated: this options is no longer used.

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: 1MB

func (*Options) SetTargetFileSizeMultiplier

func (opts *Options) SetTargetFileSizeMultiplier(value int)

SetTargetFileSizeMultiplier sets the target file size multiplier for compaction.

Default: 1

func (*Options) SetUint64AddMergeOperator

func (opts *Options) SetUint64AddMergeOperator()

SetUint64AddMergeOperator set add/merge operator.

func (*Options) SetUniversalCompactionOptions

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

SetUniversalCompactionOptions sets the options needed to support Universal Style compactions.

Note: move semantic. Don't use universal compaction options after calling this function

Default: nil

func (*Options) SetUnorderedWrite

func (opts *Options) SetUnorderedWrite(value bool)

SetUnorderedWrite sets unordered_write to true trades higher write throughput with relaxing the immutability guarantee of snapshots. This violates the repeatability one expects from ::Get from a snapshot, as well as ::MultiGet and Iterator's consistent-point-in-time view property. If the application cannot tolerate the relaxed guarantees, it can implement its own mechanisms to work around that and yet benefit from the higher throughput. Using TransactionDB with WRITE_PREPARED write policy and two_write_queues=true is one way to achieve immutable snapshots despite unordered_write.

By default, i.e., when it is false, rocksdb does not advance the sequence number for new snapshots unless all the writes with lower sequence numbers are already finished. This provides the immutability that we except from snapshots. Moreover, since Iterator and MultiGet internally depend on snapshots, the snapshot immutability results into Iterator and MultiGet offering consistent-point-in-time view. If set to true, although Read-Your-Own-Write property is still provided, the snapshot immutability property is relaxed: the writes issued after the snapshot is obtained (with larger sequence numbers) will be still not visible to the reads from that snapshot, however, there still might be pending writes (with lower sequence number) that will change the state visible to the snapshot after they are landed to the memtable.

Default: false

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) SetWALBytesPerSync

func (opts *Options) SetWALBytesPerSync(value uint64)

SetWALBytesPerSync same as bytes_per_sync, but applies to WAL files.

Default: 0, turned off

Dynamically changeable through SetDBOptions() API.

func (*Options) SetWALRecoveryMode

func (opts *Options) SetWALRecoveryMode(mode WALRecoveryMode)

SetWALRecoveryMode sets the recovery mode. Recovery mode to control the consistency while replaying WAL.

Default: PointInTimeRecovery

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) SetWritableFileMaxBufferSize

func (opts *Options) SetWritableFileMaxBufferSize(value uint64)

SetWritableFileMaxBufferSize is the maximum buffer size that is used by WritableFileWriter. On Windows, we need to maintain an aligned buffer for writes. We allow the buffer to grow until it's size hits the limit in buffered IO and fix the buffer size when using direct IO to ensure alignment of write requests if the logical sector size is unusual

Default: 1024 * 1024 (1 MB)

Dynamically changeable through SetDBOptions() API.

func (*Options) SetWriteBufferSize

func (opts *Options) SetWriteBufferSize(value uint64)

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: 64MB

func (*Options) SkipCheckingSSTFileSizesOnDBOpen

func (opts *Options) SkipCheckingSSTFileSizesOnDBOpen() bool

SkipCheckingSSTFileSizesOnDBOpen checks if skips_checking_sst_file_sizes_on_db_openning is set.

func (*Options) SkipLogErrorOnRecovery

func (opts *Options) SkipLogErrorOnRecovery() bool

SkipLogErrorOnRecovery returns setting for enable/disable skipping of log corruption error on recovery (If client is ok with losing most recent changes).

func (*Options) SkipStatsUpdateOnDBOpen

func (opts *Options) SkipStatsUpdateOnDBOpen() bool

SkipStatsUpdateOnDBOpen checks if skip_stats_update_on_db_open is set.

func (*Options) UnorderedWrite

func (opts *Options) UnorderedWrite() bool

UnorderedWrite checks if unordered_write is turned on.

func (*Options) UseAdaptiveMutex

func (opts *Options) UseAdaptiveMutex() bool

UseAdaptiveMutex returns setting for enable/disable adaptive mutex, which spins in the user space before resorting to kernel.

func (*Options) UseDirectIOForFlushAndCompaction

func (opts *Options) UseDirectIOForFlushAndCompaction() bool

UseDirectIOForFlushAndCompaction returns setting for enable/disable direct I/O mode (O_DIRECT) for both reads and writes in background flush and compactions

func (*Options) UseDirectReads

func (opts *Options) UseDirectReads() bool

UseDirectReads returns setting for enable/disable direct I/O mode (O_DIRECT) for reads

func (*Options) UseFsync

func (opts *Options) UseFsync() bool

UseFsync returns fsync setting.

type PartialMerger

type PartialMerger interface {
	// 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)
}

PartialMerger implements PartialMerge(key, leftOperand, rightOperand []byte) ([]byte, err) When a MergeOperator implements this interface, PartialMerge will be called in addition to FullMerge for compactions across levels

type PerfContext

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

PerfContext a thread local context for gathering performance counter efficiently and transparently.

func NewPerfContext

func NewPerfContext() *PerfContext

NewPerfContext returns new perf context.

func (*PerfContext) Destroy

func (ctx *PerfContext) Destroy()

Destroy perf context object.

func (*PerfContext) Metric

func (ctx *PerfContext) Metric(id int) uint64

Metric returns value of a metric by its id.

Id is one of:

enum {
	rocksdb_user_key_comparison_count = 0,
	rocksdb_block_cache_hit_count,
	rocksdb_block_read_count,
	rocksdb_block_read_byte,
	rocksdb_block_read_time,
	rocksdb_block_checksum_time,
	rocksdb_block_decompress_time,
	rocksdb_get_read_bytes,
	rocksdb_multiget_read_bytes,
	rocksdb_iter_read_bytes,
	rocksdb_internal_key_skipped_count,
	rocksdb_internal_delete_skipped_count,
	rocksdb_internal_recent_skipped_count,
	rocksdb_internal_merge_count,
	rocksdb_get_snapshot_time,
	rocksdb_get_from_memtable_time,
	rocksdb_get_from_memtable_count,
	rocksdb_get_post_process_time,
	rocksdb_get_from_output_files_time,
	rocksdb_seek_on_memtable_time,
	rocksdb_seek_on_memtable_count,
	rocksdb_next_on_memtable_count,
	rocksdb_prev_on_memtable_count,
	rocksdb_seek_child_seek_time,
	rocksdb_seek_child_seek_count,
	rocksdb_seek_min_heap_time,
	rocksdb_seek_max_heap_time,
	rocksdb_seek_internal_seek_time,
	rocksdb_find_next_user_entry_time,
	rocksdb_write_wal_time,
	rocksdb_write_memtable_time,
	rocksdb_write_delay_time,
	rocksdb_write_pre_and_post_process_time,
	rocksdb_db_mutex_lock_nanos,
	rocksdb_db_condition_wait_nanos,
	rocksdb_merge_operator_time_nanos,
	rocksdb_read_index_block_nanos,
	rocksdb_read_filter_block_nanos,
	rocksdb_new_table_block_iter_nanos,
	rocksdb_new_table_iterator_nanos,
	rocksdb_block_seek_nanos,
	rocksdb_find_table_nanos,
	rocksdb_bloom_memtable_hit_count,
	rocksdb_bloom_memtable_miss_count,
	rocksdb_bloom_sst_hit_count,
	rocksdb_bloom_sst_miss_count,
	rocksdb_key_lock_wait_time,
	rocksdb_key_lock_wait_count,
	rocksdb_env_new_sequential_file_nanos,
	rocksdb_env_new_random_access_file_nanos,
	rocksdb_env_new_writable_file_nanos,
	rocksdb_env_reuse_writable_file_nanos,
	rocksdb_env_new_random_rw_file_nanos,
	rocksdb_env_new_directory_nanos,
	rocksdb_env_file_exists_nanos,
	rocksdb_env_get_children_nanos,
	rocksdb_env_get_children_file_attributes_nanos,
	rocksdb_env_delete_file_nanos,
	rocksdb_env_create_dir_nanos,
	rocksdb_env_create_dir_if_missing_nanos,
	rocksdb_env_delete_dir_nanos,
	rocksdb_env_get_file_size_nanos,
	rocksdb_env_get_file_modification_time_nanos,
	rocksdb_env_rename_file_nanos,
	rocksdb_env_link_file_nanos,
	rocksdb_env_lock_file_nanos,
	rocksdb_env_unlock_file_nanos,
	rocksdb_env_new_logger_nanos,
	rocksdb_total_metric_count = 68
};

func (*PerfContext) Report

func (ctx *PerfContext) Report(excludeZeroCounters bool) (value string)

Report with exclusion of zero counter.

func (*PerfContext) Reset

func (ctx *PerfContext) Reset()

Reset context.

type PerfLevel

type PerfLevel int

PerfLevel indicates how much perf stats to collect. Affects perf_context and iostats_context.

const (
	// KUninitialized indicates unknown setting
	KUninitialized PerfLevel = 0
	// KDisable disables perf stats
	KDisable PerfLevel = 1
	// KEnableCount enables only count stats
	KEnableCount PerfLevel = 2
	// KEnableTimeExceptForMutex other than count stats,
	// also enable time stats except for mutexes
	KEnableTimeExceptForMutex PerfLevel = 3
	// KEnableTimeAndCPUTimeExceptForMutex other than time,
	// also measure CPU time counters. Still don't measure
	// time (neither wall time nor CPU time) for mutexes.
	KEnableTimeAndCPUTimeExceptForMutex PerfLevel = 4
	// KEnableTime enables count and time stats
	KEnableTime PerfLevel = 5
	// KOutOfBounds N.B. Must always be the last value!
	KOutOfBounds PerfLevel = 6
)

type PinnableSliceHandle

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

PinnableSliceHandle represents a handle to a PinnableSlice.

func NewNativePinnableSliceHandle

func NewNativePinnableSliceHandle(c *C.rocksdb_pinnableslice_t) *PinnableSliceHandle

NewNativePinnableSliceHandle creates a PinnableSliceHandle object.

func (*PinnableSliceHandle) Data

func (h *PinnableSliceHandle) Data() []byte

Data returns the data of the slice.

func (*PinnableSliceHandle) Destroy

func (h *PinnableSliceHandle) Destroy()

Destroy calls the destructor of the underlying pinnable slice handle.

func (*PinnableSliceHandle) Exists

func (h *PinnableSliceHandle) Exists() bool

Exists returns if underlying data exists.

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, refillPeriodMicros int64, fairness int32) *RateLimiter

NewRateLimiter creates a default RateLimiter object.

func (*RateLimiter) Destroy

func (r *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 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) FillCache

func (opts *ReadOptions) FillCache() bool

FillCache returns 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.

func (*ReadOptions) GetBackgroundPurgeOnIteratorCleanup

func (opts *ReadOptions) GetBackgroundPurgeOnIteratorCleanup() bool

GetBackgroundPurgeOnIteratorCleanup returns if background purge on iterator cleanup is turned on.

func (*ReadOptions) GetDeadline

func (opts *ReadOptions) GetDeadline() uint64

GetDeadline for completing an API call (Get/MultiGet/Seek/Next for now) in microseconds.

func (*ReadOptions) GetIOTimeout

func (opts *ReadOptions) GetIOTimeout() uint64

GetIOTimeout gets timeout in microseconds to be passed to the underlying FileSystem for reads. As opposed to deadline, this determines the timeout for each individual file read request. If a MultiGet/Get/Seek/Next etc call results in multiple reads, each read can last upto io_timeout us.

func (*ReadOptions) GetMaxSkippableInternalKeys

func (opts *ReadOptions) GetMaxSkippableInternalKeys() uint64

GetMaxSkippableInternalKeys returns the threshold for the number of keys that can be skipped before failing an iterator seek as incomplete. The default value of 0 should be used to never fail a request as incomplete, even on skipping too many keys.

func (*ReadOptions) GetReadTier

func (opts *ReadOptions) GetReadTier() ReadTier

GetReadTier returns read tier that the request should process data.

func (*ReadOptions) GetReadaheadSize

func (opts *ReadOptions) GetReadaheadSize() uint64

GetReadaheadSize returns the value of "readahead_size".

func (*ReadOptions) GetTotalOrderSeek

func (opts *ReadOptions) GetTotalOrderSeek() bool

GetTotalOrderSeek returns if total order seek is enabled.

func (*ReadOptions) IgnoreRangeDeletions

func (opts *ReadOptions) IgnoreRangeDeletions() bool

IgnoreRangeDeletions returns if ignore range deletion is turned on.

func (*ReadOptions) PinData

func (opts *ReadOptions) PinData() bool

PinData returns 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.

func (*ReadOptions) PrefixSameAsStart

func (opts *ReadOptions) PrefixSameAsStart() bool

PrefixSameAsStart returns if the iterator will iterate over the same prefix as the seek.

func (*ReadOptions) SetBackgroundPurgeOnIteratorCleanup

func (opts *ReadOptions) SetBackgroundPurgeOnIteratorCleanup(value bool)

SetBackgroundPurgeOnIteratorCleanup if true, when PurgeObsoleteFile is called in CleanupIteratorState, we schedule a background job in the flush job queue and delete obsolete files in background.

Default: false

func (*ReadOptions) SetDeadline

func (opts *ReadOptions) SetDeadline(microseconds uint64)

SetDeadline for completing an API call (Get/MultiGet/Seek/Next for now) in microseconds.

It should be set to microseconds since epoch, i.e, gettimeofday or equivalent plus allowed duration in microseconds. The best way is to use env->NowMicros() + some timeout.

This is best efforts. The call may exceed the deadline if there is IO involved and the file system doesn't support deadlines, or due to checking for deadline periodically rather than for every key if processing a batch

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) SetIOTimeout

func (opts *ReadOptions) SetIOTimeout(microseconds uint64)

SetIOTimeout sets a timeout in microseconds to be passed to the underlying FileSystem for reads. As opposed to deadline, this determines the timeout for each individual file read request. If a MultiGet/Get/Seek/Next etc call results in multiple reads, each read can last upto io_timeout us.

func (*ReadOptions) SetIgnoreRangeDeletions

func (opts *ReadOptions) SetIgnoreRangeDeletions(value bool)

SetIgnoreRangeDeletions if true, keys deleted using the DeleteRange() API will be visible to readers until they are naturally deleted during compaction. This improves read performance in DBs with many range deletions.

Default: false

func (*ReadOptions) SetIterateLowerBound

func (opts *ReadOptions) SetIterateLowerBound(key []byte)

SetIterateLowerBound specifies `iterate_lower_bound` defines the smallest key at which the backward iterator can return an entry. Once the bound is passed, Valid() will be false. `iterate_lower_bound` is inclusive ie the bound value is a valid entry. If prefix_extractor is not null, the Seek target and `iterate_lower_bound` need to have the same prefix. This is because ordering is not guaranteed outside of prefix domain. Default: nullptr

func (*ReadOptions) SetIterateUpperBound

func (opts *ReadOptions) SetIterateUpperBound(key []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

func (*ReadOptions) SetMaxSkippableInternalKeys

func (opts *ReadOptions) SetMaxSkippableInternalKeys(value uint64)

SetMaxSkippableInternalKeys sets a threshold for the number of keys that can be skipped before failing an iterator seek as incomplete. The default value of 0 should be used to never fail a request as incomplete, even on skipping too many keys.

Default: 0

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) SetPrefixSameAsStart

func (opts *ReadOptions) SetPrefixSameAsStart(value bool)

SetPrefixSameAsStart forces the iterator iterate over the same prefix as the seek.

This option is effective only for prefix seeks, i.e. prefix_extractor is non-null for the column family and total_order_seek is false. Unlike iterate_upper_bound, prefix_same_as_start only works within a prefix but in both directions.

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(value uint64)

SetReadaheadSize specifies the value of "readahead_size". 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 we are creating 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 enable 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.

Default: false

func (*ReadOptions) SetVerifyChecksums

func (opts *ReadOptions) SetVerifyChecksums(value bool)

SetVerifyChecksums specify if all data read from underlying storage will be verified against corresponding checksums.

Default: false

func (*ReadOptions) Tailing

func (opts *ReadOptions) Tailing() bool

Tailing returns if creating a tailing iterator.

func (*ReadOptions) VerifyChecksums

func (opts *ReadOptions) VerifyChecksums() bool

VerifyChecksums returns if all data read from underlying storage will be verified against corresponding checksums.

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 NewSSTFileWriterWithComparator

func NewSSTFileWriterWithComparator(opts *EnvOptions, dbOpts *Options, cmp Comparator) *SSTFileWriter

NewSSTFileWriterWithComparator creates an SSTFileWriter object with comparator.

func (*SSTFileWriter) Add

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

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

func (*SSTFileWriter) Delete

func (w *SSTFileWriter) Delete(key []byte) (err error)

Delete key from currently opened file.

func (*SSTFileWriter) Destroy

func (w *SSTFileWriter) Destroy()

Destroy destroys the SSTFileWriter object.

func (*SSTFileWriter) FileSize

func (w *SSTFileWriter) FileSize() (size uint64)

FileSize returns size of currently opened file.

func (*SSTFileWriter) Finish

func (w *SSTFileWriter) Finish() (err error)

Finish finishes writing to sst file and close file.

func (*SSTFileWriter) Merge

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

Merge key, value to currently opened file.

func (*SSTFileWriter) Open

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

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

func (*SSTFileWriter) Put

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

Put key, value to currently opened file.

type ShareFilesNaming

type ShareFilesNaming uint32

ShareFilesNaming describes possible naming schemes for backup table file names when the table files are stored in the shared_checksum directory (i.e., both share_table_files and share_files_with_checksum are true).

const (
	// LegacyCrc32cAndFileSize indicates backup SST filenames are <file_number>_<crc32c>_<file_size>.sst
	// where <crc32c> is an unsigned decimal integer. This is the
	// original/legacy naming scheme for share_files_with_checksum,
	// with two problems:
	// * At massive scale, collisions on this triple with different file
	//   contents is plausible.
	// * Determining the name to use requires computing the checksum,
	//   so generally requires reading the whole file even if the file
	//   is already backed up.
	// ** ONLY RECOMMENDED FOR PRESERVING OLD BEHAVIOR **
	LegacyCrc32cAndFileSize ShareFilesNaming = 1

	// UseDBSessionID indicates backup SST filenames are <file_number>_s<db_session_id>.sst. This
	// pair of values should be very strongly unique for a given SST file
	// and easily determined before computing a checksum. The 's' indicates
	// the value is a DB session id, not a checksum.
	//
	// Exceptions:
	// * For old SST files without a DB session id, kLegacyCrc32cAndFileSize
	//   will be used instead, matching the names assigned by RocksDB versions
	//   not supporting the newer naming scheme.
	// * See also flags below.
	UseDBSessionID ShareFilesNaming = 2

	MaskNoNamingFlags ShareFilesNaming = 0xffff

	// FlagIncludeFileSize if not already part of the naming scheme, insert
	//   _<file_size>
	// before .sst in the name. In case of user code actually parsing the
	// last _<whatever> before the .sst as the file size, this preserves that
	// feature of kLegacyCrc32cAndFileSize. In other words, this option makes
	// official that unofficial feature of the backup metadata.
	//
	// We do not consider SST file sizes to have sufficient entropy to
	// contribute significantly to naming uniqueness.
	FlagIncludeFileSize ShareFilesNaming = 1 << 31

	// FlagMatchInterimNaming indicates when encountering an SST file from a Facebook-internal early
	// release of 6.12, use the default naming scheme in effect for
	// when the SST file was generated (assuming full file checksum
	// was not set to GetFileChecksumGenCrc32cFactory()). That naming is
	// <file_number>_<db_session_id>.sst
	// and ignores kFlagIncludeFileSize setting.
	// NOTE: This flag is intended to be temporary and should be removed
	// in a later release.
	FlagMatchInterimNaming ShareFilesNaming = 1 << 30

	MaskNamingFlags ShareFilesNaming = ^MaskNoNamingFlags
)

type Slice

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

Slice is used as a wrapper for non-copy values

func NewSlice

func NewSlice(data *C.char, size C.size_t) *Slice

NewSlice returns a slice with the given data.

func (*Slice) Data

func (s *Slice) Data() []byte

Data returns the data of the slice. If the key doesn't exist this will be a nil slice.

func (*Slice) Exists

func (s *Slice) Exists() bool

Exists returns if underlying data exists.

func (*Slice) Free

func (s *Slice) Free()

Free frees the slice data.

func (*Slice) Size

func (s *Slice) Size() int

Size returns the size of the data.

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

	// Destroy underlying pointer/data
	Destroy()
}

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.

func NewNoopPrefixTransform

func NewNoopPrefixTransform() SliceTransform

NewNoopPrefixTransform creates a new no-op prefix transform.

type Slices

type Slices []*Slice

Slices is collection of Slice.

func (Slices) Destroy

func (slices Slices) Destroy()

Destroy free slices.

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.

func (*Snapshot) Destroy

func (snapshot *Snapshot) Destroy()

Destroy deallocates the 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() (err error)

Commit commits the transaction to the database.

func (*Transaction) Delete

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

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

func (*Transaction) DeleteCF

func (transaction *Transaction) DeleteCF(cf *ColumnFamilyHandle, key []byte) (err error)

DeleteCF removes the data associated with the key (belongs to specific column family) 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) (slice *Slice, err error)

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

func (*Transaction) GetForUpdate

func (transaction *Transaction) GetForUpdate(opts *ReadOptions, key []byte) (slice *Slice, err error)

GetForUpdate queries the data associated with the key and puts an exclusive lock on the key from the database given this transaction.

func (*Transaction) GetForUpdateWithCF

func (transaction *Transaction) GetForUpdateWithCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) (slice *Slice, err error)

GetForUpdateWithCF queries the data associated with the key and puts an exclusive lock on the key from the database, with column family, given this transaction.

func (*Transaction) GetSnapshot

func (transaction *Transaction) GetSnapshot() *Snapshot

GetSnapshot returns the Snapshot created by the last call to SetSnapshot().

func (*Transaction) GetWithCF

func (transaction *Transaction) GetWithCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) (slice *Slice, err error)

GetWithCF returns the data associated with the key from the database, with column family, given this transaction.

func (*Transaction) Merge

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

Merge key, value to the transaction.

func (*Transaction) MergeCF

func (transaction *Transaction) MergeCF(cf *ColumnFamilyHandle, key, value []byte) (err error)

MergeCF key, value to the transaction on specific column family.

func (*Transaction) NewIterator

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

NewIterator returns an iterator that will iterate on all keys in the default column family including both keys in the DB and uncommitted keys in this transaction.

Setting read_options.snapshot will affect what is read from the DB but will NOT change which keys are read from this transaction (the keys in this transaction do not yet belong to any snapshot and will be fetched regardless).

Caller is responsible for deleting the returned Iterator.

func (*Transaction) NewIteratorCF

func (transaction *Transaction) NewIteratorCF(opts *ReadOptions, cf *ColumnFamilyHandle) *Iterator

NewIteratorCF returns an iterator that will iterate on all keys in the specific column family including both keys in the DB and uncommitted keys in this transaction.

Setting read_options.snapshot will affect what is read from the DB but will NOT change which keys are read from this transaction (the keys in this transaction do not yet belong to any snapshot and will be fetched regardless).

Caller is responsible for deleting the returned Iterator.

func (*Transaction) Put

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

Put writes data associated with a key to the transaction.

func (*Transaction) PutCF

func (transaction *Transaction) PutCF(cf *ColumnFamilyHandle, key, value []byte) (err error)

PutCF writes data associated with a key to the transaction. Key belongs to column family.

func (*Transaction) Rollback

func (transaction *Transaction) Rollback() (err error)

Rollback performs a rollback on the transaction.

func (*Transaction) RollbackToSavePoint

func (transaction *Transaction) RollbackToSavePoint() (err error)

RollbackToSavePoint undo all operations in this transaction (Put, Merge, Delete, PutLogData) since the most recent call to SetSavePoint() and removes the most recent SetSavePoint().

func (*Transaction) SetSavePoint

func (transaction *Transaction) SetSavePoint()

SetSavePoint records the state of the transaction for future calls to RollbackToSavePoint(). May be called multiple times to set multiple save points.

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,
) (tdb *TransactionDB, err error)

OpenTransactionDb opens a database with the specified options.

func (*TransactionDB) Close

func (db *TransactionDB) Close()

Close closes the database.

func (*TransactionDB) CreateColumnFamily

func (db *TransactionDB) CreateColumnFamily(opts *Options, name string) (handle *ColumnFamilyHandle, err error)

CreateColumnFamily create a new column family.

func (*TransactionDB) Delete

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

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

func (*TransactionDB) DeleteCF

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

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

func (*TransactionDB) Get

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

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

func (*TransactionDB) GetCF

func (db *TransactionDB) GetCF(opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) (slice *Slice, err error)

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

func (*TransactionDB) Merge

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

Merge writes data associated with a key to the database.

func (*TransactionDB) MergeCF

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

MergeCF writes data associated with a key to the database on specific column family.

func (*TransactionDB) NewCheckpoint

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

NewCheckpoint creates a new Checkpoint for this db.

func (*TransactionDB) NewIterator

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

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

func (*TransactionDB) NewIteratorCF

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

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

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) (err error)

Put writes data associated with a key to the database.

func (*TransactionDB) PutCF

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

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

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.

func (*TransactionDB) Write

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

Write writes a WriteBatch to the database.

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 from native 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) GetCompressionSizePercent

func (opts *UniversalCompactionOptions) GetCompressionSizePercent() int

GetCompressionSizePercent gets 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

func (*UniversalCompactionOptions) GetMaxMergeWidth

func (opts *UniversalCompactionOptions) GetMaxMergeWidth() int

GetMaxMergeWidth gets the maximum number of files in a single compaction run.

func (*UniversalCompactionOptions) GetMaxSizeAmplificationPercent

func (opts *UniversalCompactionOptions) GetMaxSizeAmplificationPercent() int

GetMaxSizeAmplificationPercent gets 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.

func (*UniversalCompactionOptions) GetMinMergeWidth

func (opts *UniversalCompactionOptions) GetMinMergeWidth() int

GetMinMergeWidth gets the minimum number of files in a single compaction run.

func (*UniversalCompactionOptions) GetSizeRatio

func (opts *UniversalCompactionOptions) GetSizeRatio() int

GetSizeRatio gets 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.

func (*UniversalCompactionOptions) GetStopStyle

GetStopStyle gets the algorithm used to stop picking files into a single compaction run.

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 int)

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 int)

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

Default: 2

func (*UniversalCompactionOptions) SetSizeRatio

func (opts *UniversalCompactionOptions) SetSizeRatio(value int)

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 WALRecoveryMode

type WALRecoveryMode int

WALRecoveryMode mode of WAL Recovery.

type WalIterator

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

WalIterator is iterator for WAL Files.

func NewNativeWalIterator

func NewNativeWalIterator(c unsafe.Pointer) *WalIterator

NewNativeWalIterator returns new WalIterator.

func (*WalIterator) Destroy

func (iter *WalIterator) Destroy()

Destroy free iterator.

func (*WalIterator) Err

func (iter *WalIterator) Err() (err error)

Err returns error happened during iteration.

func (*WalIterator) GetBatch

func (iter *WalIterator) GetBatch() (*WriteBatch, uint64)

GetBatch returns the current write_batch and the sequence number of the earliest transaction contained in the batch.

func (*WalIterator) Next

func (iter *WalIterator) Next()

Next moves next.

func (*WalIterator) Valid

func (iter *WalIterator) Valid() bool

Valid check if current WAL is valid.

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) DeleteRange

func (wb *WriteBatch) DeleteRange(startKey []byte, endKey []byte)

DeleteRange deletes keys that are between [startKey, endKey)

func (*WriteBatch) DeleteRangeCF

func (wb *WriteBatch) DeleteRangeCF(cf *ColumnFamilyHandle, startKey []byte, endKey []byte)

DeleteRangeCF deletes keys that are between [startKey, endKey) and belong to a given column family

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) PopSavePoint

func (wb *WriteBatch) PopSavePoint() (err error)

PopSavePoint pops the most recent save point. If there is no previous call to SetSavePoint(), Status::NotFound() will be returned.

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) PutLogData

func (wb *WriteBatch) PutLogData(blob []byte)

PutLogData appends a blob of arbitrary size to the records in this batch.

func (*WriteBatch) RollbackToSavePoint

func (wb *WriteBatch) RollbackToSavePoint() (err error)

RollbackToSavePoint removes all entries in this batch (Put, Merge, Delete, PutLogData) since the most recent call to SetSavePoint() and removes the most recent save point.

func (*WriteBatch) SetSavePoint

func (wb *WriteBatch) SetSavePoint()

SetSavePoint records the state of the batch for future calls to RollbackToSavePoint(). May be called multiple times to set multiple save points.

func (*WriteBatch) SingleDelete

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

SingleDelete removes the database entry for "key". Requires that the key exists and was not overwritten. Returns OK on success, and a non-OK status on error. It is not an error if "key" did not exist in the database.

If a key is overwritten (by calling Put() multiple times), then the result of calling SingleDelete() on this key is undefined. SingleDelete() only behaves correctly if there has been only one Put() for this key since the previous call to SingleDelete() for this key.

This feature is currently an experimental performance optimization for a very specific workload. It is up to the caller to ensure that SingleDelete is only used for a key that is not deleted using Delete() or written using Merge(). Mixing SingleDelete operations with Deletes and Merges can result in undefined behavior.

Note: consider setting options.sync = true.

func (*WriteBatch) SingleDeleteCF

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

SingleDeleteCF same as SingleDelete but specific 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 {
	CF    int
	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 (
	WriteBatchDeletionRecord                 WriteBatchRecordType = 0x0
	WriteBatchValueRecord                    WriteBatchRecordType = 0x1
	WriteBatchMergeRecord                    WriteBatchRecordType = 0x2
	WriteBatchLogDataRecord                  WriteBatchRecordType = 0x3
	WriteBatchCFDeletionRecord               WriteBatchRecordType = 0x4
	WriteBatchCFValueRecord                  WriteBatchRecordType = 0x5
	WriteBatchCFMergeRecord                  WriteBatchRecordType = 0x6
	WriteBatchSingleDeletionRecord           WriteBatchRecordType = 0x7
	WriteBatchCFSingleDeletionRecord         WriteBatchRecordType = 0x8
	WriteBatchBeginPrepareXIDRecord          WriteBatchRecordType = 0x9
	WriteBatchEndPrepareXIDRecord            WriteBatchRecordType = 0xA
	WriteBatchCommitXIDRecord                WriteBatchRecordType = 0xB
	WriteBatchRollbackXIDRecord              WriteBatchRecordType = 0xC
	WriteBatchNoopRecord                     WriteBatchRecordType = 0xD
	WriteBatchRangeDeletion                  WriteBatchRecordType = 0xF
	WriteBatchCFRangeDeletion                WriteBatchRecordType = 0xE
	WriteBatchCFBlobIndex                    WriteBatchRecordType = 0x10
	WriteBatchBlobIndex                      WriteBatchRecordType = 0x11
	WriteBatchBeginPersistedPrepareXIDRecord WriteBatchRecordType = 0x12
	WriteBatchNotUsedRecord                  WriteBatchRecordType = 0x7F
)

Types of batch records.

type WriteBatchWI

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

WriteBatchWI is a batching with index of Puts, Merges and Deletes to implement read-your-own-write. See also: https://rocksdb.org/blog/2015/02/27/write-batch-with-index.html

func NewNativeWriteBatchWI

func NewNativeWriteBatchWI(c *C.rocksdb_writebatch_wi_t) *WriteBatchWI

NewNativeWriteBatchWI create a WriteBatchWI object.

func NewWriteBatchWI

func NewWriteBatchWI(reservedBytes uint, overwriteKeys bool) *WriteBatchWI

NewWriteBatchWI create a WriteBatchWI object.

  • reserved_bytes: reserved bytes in underlying WriteBatch
  • overwrite_key: if true, overwrite the key in the index when inserting the same key as previously, so iterator will never show two entries with the same key.

func (*WriteBatchWI) Clear

func (wb *WriteBatchWI) Clear()

Clear removes all the enqueued Put and Deletes.

func (*WriteBatchWI) Count

func (wb *WriteBatchWI) Count() int

Count returns the number of updates in the batch.

func (*WriteBatchWI) Data

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

Data returns the serialized version of this batch.

func (*WriteBatchWI) Delete

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

Delete queues a deletion of the data at key.

func (*WriteBatchWI) DeleteCF

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

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

func (*WriteBatchWI) DeleteRange

func (wb *WriteBatchWI) DeleteRange(startKey []byte, endKey []byte)

DeleteRange deletes keys that are between [startKey, endKey)

func (*WriteBatchWI) DeleteRangeCF

func (wb *WriteBatchWI) DeleteRangeCF(cf *ColumnFamilyHandle, startKey []byte, endKey []byte)

DeleteRangeCF deletes keys that are between [startKey, endKey) and belong to a given column family

func (*WriteBatchWI) Destroy

func (wb *WriteBatchWI) Destroy()

Destroy deallocates the WriteBatch object.

func (*WriteBatchWI) Get

func (wb *WriteBatchWI) Get(opts *Options, key []byte) (slice *Slice, err error)

Get returns the data associated with the key from batch.

func (*WriteBatchWI) GetFromDB

func (wb *WriteBatchWI) GetFromDB(db *DB, opts *ReadOptions, key []byte) (slice *Slice, err error)

GetFromDB returns the data associated with the key from the database and write batch.

func (*WriteBatchWI) GetFromDBWithCF

func (wb *WriteBatchWI) GetFromDBWithCF(db *DB, opts *ReadOptions, cf *ColumnFamilyHandle, key []byte) (slice *Slice, err error)

GetFromDBWithCF returns the data associated with the key from the database and write batch. Key belongs to specific column family.

func (*WriteBatchWI) GetWithCF

func (wb *WriteBatchWI) GetWithCF(opts *Options, cf *ColumnFamilyHandle, key []byte) (slice *Slice, err error)

GetWithCF returns the data associated with the key from batch. Key belongs to specific column family.

func (*WriteBatchWI) Merge

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

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

func (*WriteBatchWI) MergeCF

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

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

func (*WriteBatchWI) NewIterator

func (wb *WriteBatchWI) NewIterator() *WriteBatchIterator

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

func (*WriteBatchWI) Put

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

Put queues a key-value pair.

func (*WriteBatchWI) PutCF

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

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

func (*WriteBatchWI) PutLogData

func (wb *WriteBatchWI) PutLogData(blob []byte)

PutLogData appends a blob of arbitrary size to the records in this batch.

func (*WriteBatchWI) RollbackToSavePoint

func (wb *WriteBatchWI) RollbackToSavePoint() (err error)

RollbackToSavePoint removes all entries in this batch (Put, Merge, Delete, PutLogData) since the most recent call to SetSavePoint() and removes the most recent save point.

func (*WriteBatchWI) SetSavePoint

func (wb *WriteBatchWI) SetSavePoint()

SetSavePoint records the state of the batch for future calls to RollbackToSavePoint(). May be called multiple times to set multiple save points.

func (*WriteBatchWI) SingleDelete

func (wb *WriteBatchWI) SingleDelete(key []byte)

SingleDelete removes the database entry for "key". Requires that the key exists and was not overwritten. Returns OK on success, and a non-OK status on error. It is not an error if "key" did not exist in the database.

If a key is overwritten (by calling Put() multiple times), then the result of calling SingleDelete() on this key is undefined. SingleDelete() only behaves correctly if there has been only one Put() for this key since the previous call to SingleDelete() for this key.

This feature is currently an experimental performance optimization for a very specific workload. It is up to the caller to ensure that SingleDelete is only used for a key that is not deleted using Delete() or written using Merge(). Mixing SingleDelete operations with Deletes and Merges can result in undefined behavior.

Note: consider setting options.sync = true.

func (*WriteBatchWI) SingleDeleteCF

func (wb *WriteBatchWI) SingleDeleteCF(cf *ColumnFamilyHandle, key []byte)

SingleDeleteCF same as SingleDelete but specific column family

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) IgnoreMissingColumnFamilies

func (opts *WriteOptions) IgnoreMissingColumnFamilies() bool

IgnoreMissingColumnFamilies returns the setting for ignoring missing column famlies.

If true and if user is trying to write to column families that don't exist (they were dropped), ignore the write (don't return an error). If there are multiple writes in a WriteBatch, other writes will succeed.

func (*WriteOptions) IsDisableWAL

func (opts *WriteOptions) IsDisableWAL() bool

IsDisableWAL returns if we turned on DisableWAL flag for writing.

func (*WriteOptions) IsLowPri

func (opts *WriteOptions) IsLowPri() bool

IsLowPri returns if the write request is of lower priority if compaction is behind.

func (*WriteOptions) IsNoSlowdown

func (opts *WriteOptions) IsNoSlowdown() bool

IsNoSlowdown returns no_slow_down setting.

func (*WriteOptions) IsSync

func (opts *WriteOptions) IsSync() bool

IsSync returns if sync mode is turned on.

func (*WriteOptions) MemtableInsertHintPerBatch

func (opts *WriteOptions) MemtableInsertHintPerBatch() bool

MemtableInsertHintPerBatch returns if this writebatch will maintain the last insert positions of each memtable as hints in concurrent write.

func (*WriteOptions) SetIgnoreMissingColumnFamilies

func (opts *WriteOptions) SetIgnoreMissingColumnFamilies(value bool)

SetIgnoreMissingColumnFamilies if true and if user is trying to write to column families that don't exist (they were dropped), ignore the write (don't return an error). If there are multiple writes in a WriteBatch, other writes will succeed.

Default: false

func (*WriteOptions) SetLowPri

func (opts *WriteOptions) SetLowPri(value bool)

SetLowPri if true, this write request is of lower priority if compaction is behind. In this case, no_slowdown = true, the request will be cancelled immediately with Status::Incomplete() returned. Otherwise, it will be slowed down. The slowdown value is determined by RocksDB to guarantee it introduces minimum impacts to high priority writes.

Default: false

func (*WriteOptions) SetMemtableInsertHintPerBatch

func (opts *WriteOptions) SetMemtableInsertHintPerBatch(value bool)

SetMemtableInsertHintPerBatch if true, this writebatch will maintain the last insert positions of each memtable as hints in concurrent write. It can improve write performance in concurrent writes if keys in one writebatch are sequential. In non-concurrent writes (when concurrent_memtable_writes is false) this option will be ignored.

Default: false

func (*WriteOptions) SetNoSlowdown

func (opts *WriteOptions) SetNoSlowdown(value bool)

SetNoSlowdown if true and we need to wait or sleep for the write request, fails immediately with Status::Incomplete().

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

Jump to

Keyboard shortcuts

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