vastdb

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2022 License: MIT Imports: 14 Imported by: 0

README ΒΆ

vastDB

Embedded high-performance Key-Value store with custom indexing written in Go.

πŸͺ§ Description

vastDB is a generic and performance focused ACID key-Value Store with custom indexing. It's basically a modified Version of buntdb with support for generic types and faster field indexing.

The goal of this Project is to provide a generic key-value store, that does not only perform well on reads, but also on writes and especially for writes with indexing on struct properties. This can be achieved by using the struct directly in the indexing process. This is not possible with buntdb, because it only supports indexing on string values or on json fields (reduces performance significant). It's not meant to be a replacement for a full-blown database, but rather a tool to store and lookup data in a fast and easy way.

πŸŽ‰ Features

  • In-memory database for fast reads and writes
  • Embeddable with a simple API
  • Index fields of the struct for fast queries
  • Type safety by generics
  • ACID transactions, supporting rollbacks
  • Support for multi value indexes
  • Iterating data ascending, descending or in range by keys or indexes
  • TTL support
  • Persisting with Append-Only-File (AOF) and Snapshotting (Always, every x seconds, never)
  • Thread safe

πŸ“š Table of contents

πŸ“₯ Installation

add to your project with

go get github.com/kesimo/vastdb

import with

import "github.com/kesimo/vastdb"

πŸ“œ Usage

Open a database

package main

import "github.com/kesimo/vastdb"

// create a custom struct to store in the database
type customItem struct {
	ID       string
	Num       int
}

// create a new database instance by passing in the path to the database file,
// or ":memory:" to create a database that exists only in memory
// add an empty (or filled) object of the custom struct to the database
// interfaces are not supported as well as double-pointers
db, err := Open(":memory:", customItem{}) //OR Open[customItem]("path/to/db")
if err != nil {
    // handle error
}
defer db.Close()

Configuring the database

// [...]
// create configuration and use same data struct as before for generic type
config := &vastdb.Config[customItem]{
        // set the sync type: Never,EverySecond,Always  (default is Always)
        SyncPolicy SyncPolicy 
	// AutoShrinkPercentage is used by the background process to trigger
	// a shrink of the aof file when the size of the file is larger than the
	// percentage of the result of the previous shrunk file.
	AutoShrinkPercentage int

	// AutoShrinkMinSize defines the minimum size of the aof file before
	AutoShrinkMinSize int

	// AutoShrinkDisabled turns off automatic background shrinking
	AutoShrinkDisabled bool

	// OnExpired is a function to custom handle actions on expired keys.
	OnExpired func(keys []string)

	// OnExpiredSync will be called inside the same transaction that is
	// performing the deletion of expired items. If OnExpired is present then
	// this callback will not be called. If this callback is present, then the
	// deletion of the timed-out item is the explicit responsibility of this
	// callback.
	OnExpiredSync func(key string, value T, tx *Tx[T]) error
}

//Apply the configuration to the database
db.SetConfig(config)

Inserting data

Insert Data into the database by passing in a key and a value of the custom struct. If the key already exists, the value will be overwritten and the old value will be returned.

WARNING: If you use persistent storage, only the exported fields will be stored.

// [...]
// insert a new item into the database
prev, err := db.Set("keyA", mockExt{
    ID:        "id1",
    Num:        1,
})
// insert a new item into the database with a TTL
prev, err := db.SetWithTTL("keyA", mockExt{
    ID:        "id1",
    Num:        1,
}, &vastdb.SetOptions{TTL: time.Second, Expires: true})

Reading data

Read data from the database by passing in a key. The value will be returned as a pointer to the custom struct. If the key does not exist, the returned pointer will be nil. if the value is expired nothing will be returned.

WARNING: Do not modify the returned value, as it will be modified in the database as well. If you want to modify the value, you have to copy it first. In case you want to modify the value in database, you should use a transaction.

package main

import "github.com/kesimo/vastdb"
// [...]
// read an item from the database
item, err := db.Get("keyA")
if err != nil {
    // handle error
}
// do something with the item
if item.ID != "id1" {
    //...
}

Deleting data

Delete data from the database by passing in a key. The deleted value will be returned as a pointer to the custom struct.

// [...]
// delete an item from the database
prev, err = db.Del("key1")
if err != nil {
t.Errorf("error deleting item: %v", err)
}

Transactions

transactions can be used to group multiple operations into a single atomic operation. like updating multiple objects or deleting multiple objects. there can be multiple transactions running at the same time, but only one transaction can be writing to the database at a time.

to open a read-only transaction, use the db.View method.

to open a read-write transaction, use the db.Update method.

For example - update one field in an item:

// [...]
// update an item in the database
err := db.Update(func(tx *vastdb.Tx[customItem]) error {
    val, err := tx.Get("keyA")
    if err != nil {
        return err
    }
    // update the item
    val.Num = 321
    // insert the updated item into the database
    _, _, err = tx.Set("keyA", *val, nil)
	if err != nil {
		return err
	}
    return nil
})

if an error is returned from the transaction, then the transaction is rolled back.

Indexes

They can be used to query the database for specific values and speed up get actions by using the index instead of the key. For every index a Btree will be created, which will be used to store the values in specific order defined by the comparator function. They can be created on any field of the struct and applied to specific keys by pattern. Indexes are created by passing a function to the CreateIndex method.

// [...]
// create an index on the Num field of our customItem struct
// the first argument is the name of the index that will be used to interact with
// the index will be applied to all keys that start with "key:"
err := db.CreateIndex("num", "key:*",func(a, b *customItem) bool {
    return a.Num < b.Num
})

Iterating data

For iterating over the database, you can use the Ascend and Descend methods.

for Pivots, you have tu use an object of type *vastdb.PivotKV[T] its a struct that contains the key and the value of the item and used for fallback in case the index is empty -> using the k property

*vastdb.PivotKV[customItem]{K: "keyA", V: customItem{Num: 1}}

Example usage of AscendLessThan:

// [...]
// iterate over all items in the database that have a Num field less than 10
err := db.View(func(tx *Tx[mock]) error {
    err := tx.AscendLessThan("num", *vastdb.PivotKV[customItem]{V: customItem{Num: 10}}, 
	func(key string, val mock) bool {
		//should always be true
		if val.Num < 10 { 
			// ...
		}
		// break the iteration if false is returned
		return true
	})
    if err != nil {
    // handle error
    }
    return nil
})

Available methods are:

Method Usage
AscendKeys(pattern, iterator) Iterate through all Elements that matches the key pattern (e.g. "user:*")
Ascend(index, iterator) Iterate through all Elements in specified index
AscendGreaterOrEqual(index, gte pivotKV, iterator) Iterate through all Elements that are greater or equal the specified pivot in index
AscendLessThan(index, lt PivotKV, iterator) Iterate through all Elements that are less than the specified pivot in index
AscendRange(index, gte PivotKV, lt PivotKV, iterator) Iterates through Elements in specified Range in index
AscendEqual(index, eq PivotKV, iterator) Iterates through Elements with equal value to specified one
DescendKeys(pattern, iterator) Equal to "AscendKeys", but in descend order
Descend(index, iterator) Equal to "Ascend", but in descend order
DescendLessOrEqual(index, lte PivotKV, iterator) Iterates through all Elements that are less or equal the specified pivot in descend order
DescendGreaterThan(index, gt PivotKV, iterator) Iterates through all Elements that are greater than the specified pivot in descend order
DescendRange(index, lte PivotKV, gt PivotKV, iterator) Equal to "AscendRange", but in descend order
DescendEqual(index, eq PivotKV, iterator) Equal to "AscendEqual", but in descend order

⏱ Performance

The performance of the database is heavily dependent on the performance of the comparator function and the usage of indexes.

for benchmarking we used the following struct:

type mockB struct {
    Key       string
    Workspace string
    Num       int
    Boolean   bool
}

Benchmark results of set and get operations:

cpu: Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz

Benchmark_Set-8                  1105269          1048 ns/op
Benchmark_Set_1_index-8           721592          1789 ns/op
Benchmark_Set_2_index-8           502111          2583 ns/op
Benchmark_Set_3_index-8           333624          3848 ns/op
Benchmark_Set_Persist-8           120302          10947 ns/op
BenchmarkTx_Get-8                3921300          301.0 ns/op
BenchmarkTx_Get_Random-8         1347905          876.1 ns/op
BenchmarkTx_Get_Parallel-8      13910053          85.15 ns/op

License


MIT License

for more information see the LICENSE file

Documentation ΒΆ

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	// ErrTxNotWritable is returned when performing a write operation on a
	// read-only transaction.
	ErrTxNotWritable = errors.New("tx not writable")

	// ErrTxClosed is returned when committing or rolling back a transaction
	// that has already been committed or rolled back.
	ErrTxClosed = errors.New("tx closed")

	// ErrNotFound is returned when an item or index is not in the database.
	ErrNotFound = errors.New("not found")

	// ErrIndexNotFound is returned when an index is not in the database.
	ErrIndexNotFound = errors.New("index not found")

	// ErrInvalid is returned when the database file is an invalid format.
	ErrInvalid = errors.New("invalid database")

	// ErrDatabaseClosed is returned when the database is closed.
	ErrDatabaseClosed = errors.New("database closed")

	// ErrIndexExists is returned when an index already exists in the database.
	ErrIndexExists = errors.New("index exists")

	// ErrInvalidOperation is returned when an operation cannot be completed.
	ErrInvalidOperation = errors.New("invalid operation")

	// ErrInvalidSyncPolicy is returned for an invalid SyncPolicy value.
	ErrInvalidSyncPolicy = errors.New("invalid sync policy")

	// ErrShrinkInProcess is returned when a shrink operation is in-process.
	ErrShrinkInProcess = errors.New("shrink is in-process")

	// ErrPersistenceActive is returned when post-loading data from an only on-memory database
	ErrPersistenceActive = errors.New("persistence active")

	// ErrTxIterating is returned when Set or Delete are called while iterating.
	ErrTxIterating = errors.New("tx is iterating")

	// ErrEmptyKey is returned when an empty key is provided.
	ErrEmptyKey = errors.New("empty key")
)
View Source
var (
	// ErrSyncFile is returned when the file cannot be synced.
	ErrSyncFile = errors.New("file cannot be synced")
)

Functions ΒΆ

This section is empty.

Types ΒΆ

type Config ΒΆ

type Config[T any] struct {
	// SyncPolicy adjusts how often the data is synced to disk.
	// This value can be Never, EverySecond, or Always.
	// The default is EverySecond.
	SyncPolicy SyncPolicy

	// AutoShrinkPercentage is used by the background process to trigger
	// a shrink of the aof file when the size of the file is larger than the
	// percentage of the result of the previous shrunk file.
	// For example, if this value is 100, and the last shrink process
	// resulted in a 100mb file, then the new aof file must be 200mb before
	// a shrink is triggered.
	AutoShrinkPercentage int

	// AutoShrinkMinSize defines the minimum size of the aof file before
	// an automatic shrink can occur.
	AutoShrinkMinSize int

	// AutoShrinkDisabled turns off automatic background shrinking
	AutoShrinkDisabled bool

	// OnExpired is used to custom handle the deletion option when a Key
	// has been expired.
	OnExpired func(keys []string)

	// OnExpiredSync will be called inside the same transaction that is
	// performing the deletion of expired items. If OnExpired is present then
	// this callback will not be called. If this callback is present, then the
	// deletion of the timed-out item is the explicit responsibility of this
	// callback.
	// WARNING: This callback is called multiple times on each expired key if not deleted inside function within
	// the same tick of the background process.
	OnExpiredSync func(key string, value T, tx *Tx[T]) error
}

Config represents database configuration options. These options are used to change various behaviors of the database.

type DB ΒΆ

type DB[T any] struct {
	// contains filtered or unexported fields
}

DB represents a collection of Key-value pairs that persist on disk. Transactions are used for all forms of data access to the DB.

func Open ΒΆ

func Open[T any](path string, typeObject ...T) (*DB[T], error)

Open opens a database at the provided path and optionally an object whose struct should be used for the values. If the file does not exist then it will be created automatically. If the file exists then the database will be loaded from the file (do not open a database on the same file twice). the returned DB object can be used for future operations

func (*DB[T]) Close ΒΆ

func (db *DB[T]) Close() error

Close releases all database resources. All transactions must be closed before closing the database.

func (*DB[T]) CreateIndex ΒΆ

func (db *DB[T]) CreateIndex(name, pattern string,
	comparator ...func(a, b T) bool) error

CreateIndex builds a new index and populates it with items. The items are ordered in a b-tree and can be retrieved using the Ascend* and Descend* methods. An error will occur if an index with the same name already exists.

When a pattern is provided, the index will be populated with keys that match the specified pattern. This is a very simple pattern match where '*' matches on any number characters and '?' matches on any one character. The comparator function compares if object 'a' is less than object 'b'. It allows for indexes to create custom ordering

func (*DB[T]) Del ΒΆ

func (db *DB[T]) Del(key string) (prev *T, err error)

Del removes the value for a given key. It's a wrapper around Update with a single Delete Write-transaction call. Return previous value if any.

func (*DB[T]) DropIndex ΒΆ

func (db *DB[T]) DropIndex(name string) error

DropIndex removes an index.

func (*DB[T]) Get ΒΆ

func (db *DB[T]) Get(key string) (*T, error)

Get returns the value for a given key. If the key does not exist then nil, It's a wrapper around View with a single Get Read-transaction call. ErrNotFound is returned if the key does not exist.

func (*DB[T]) Indexes ΒΆ

func (db *DB[T]) Indexes() ([]string, error)

Indexes returns a list of index names.

func (*DB[T]) Len ΒΆ

func (db *DB[T]) Len() (int, error)

Len returns the number of items in the database

func (*DB[T]) Load ΒΆ

func (db *DB[T]) Load(rd io.Reader) error

Load loads commands from reader. This operation blocks all reads and writes. Note that this can only work for fully in-memory databases

func (*DB[T]) ReadConfig ΒΆ

func (db *DB[T]) ReadConfig(config *Config[T]) error

ReadConfig returns the database configuration.

func (*DB[T]) ReplaceIndex ΒΆ

func (db *DB[T]) ReplaceIndex(name, pattern string,
	comparator ...func(a, b T) bool) error

ReplaceIndex builds a new index and populates it with items. The items are ordered in a b-tree and can be retrieved using the Ascend* and Descend* methods. If a previous index with the same name exists, that index will be deleted.

func (*DB[T]) Set ΒΆ

func (db *DB[T]) Set(key string, val T, options ...*SetOptions) (prev *T, err error)

Set sets the value for a given key. It's a wrapper around Update with a single Set Write-transaction call. Return previous value if any.

func (*DB[T]) SetConfig ΒΆ

func (db *DB[T]) SetConfig(config Config[T]) error

SetConfig updates the database configuration.

func (*DB[T]) Shrink ΒΆ

func (db *DB[T]) Shrink() error

Shrink will make the database file smaller by removing redundant log entries. This operation does not block the database.

func (*DB[T]) Snapshot ΒΆ

func (db *DB[T]) Snapshot(wr io.Writer) error

Snapshot writes a snapshot of the database to a writer. This operation blocks all writes, but not reads. This can be used for snapshots and backups for pure in-memory databases. For persistent databases, the database file can be copied

func (*DB[T]) Update ΒΆ

func (db *DB[T]) Update(fn func(tx *Tx[T]) error) error

Update executes a function within a managed read/write transaction. The transaction has been committed when no error is returned. In the event that an error is returned, the transaction will be rolled back. When a non-nil error is returned from the function, the transaction will be rolled back and the that error will be return to the caller of Update().

Executing a manual commit or rollback from inside the function will result in a panic.

func (*DB[T]) View ΒΆ

func (db *DB[T]) View(fn func(tx *Tx[T]) error) error

View executes a function within a managed read-only transaction. When a non-nil error is returned from the function that error will be return to the caller of View().

Executing a manual commit or rollback from inside the function will result in a panic.

type IndexOptions ΒΆ

type IndexOptions struct {
	// CaseInsensitiveKeyMatching allow for case-insensitive
	// matching on keys when setting Key/values.
	CaseInsensitiveKeyMatching bool
}

IndexOptions provides an index with additional features or alternate functionality.

type PivotKV ΒΆ

type PivotKV[T any] struct {
	K string
	V T
}

PivotKV is a Key/value pair that is used to pivot a range of items. The Key is used to find the item in the database by key and as fallback if no value is given The Value is used to find the item in the database by value if an index is present

type SetOptions ΒΆ

type SetOptions struct {
	// Expires indicates that the Set() Key-value will expire
	Expires bool
	// TTL is how much time the Key-value will exist in the database
	// before being evicted. The Expires field must also be set to true.
	// TTL stands for Time-To-Live.
	TTL time.Duration
}

SetOptions represents options that may be included with the Set() command.

type SyncPolicy ΒΆ

type SyncPolicy int

SyncPolicy represents how often data is synced to disk.

const (
	// Never is used to disable syncing data to disk.
	// The faster and less safe method.
	Never SyncPolicy = 0
	// EverySecond is used to sync data to disk every second.
	// It's pretty fast, and you can lose 1 second of data if there
	// is a disaster.
	// This is the recommended setting.
	EverySecond SyncPolicy = 1
	// Always is used to sync data after every write to disk.
	// Slow. Very safe.
	Always SyncPolicy = 2
)

type Tx ΒΆ

type Tx[T any] struct {
	// contains filtered or unexported fields
}

Tx represents a transaction on the database. This transaction can either be read-only or read/write. Read-only transactions can be used for retrieving values for keys and iterating through keys and values. Read/write transactions can set and delete keys.

All transactions must be committed or rolled-back when done.

func (*Tx[T]) Ascend ΒΆ

func (tx *Tx[T]) Ascend(index string,
	iterator func(key string, value T) bool) error

Ascend calls the iterator for every item in the database within the range until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) AscendEqual ΒΆ

func (tx *Tx[T]) AscendEqual(index string, pivot PivotKV[T],
	iterator func(key string, value T) bool) error

AscendEqual calls the iterator for every item in the database that equals pivot, until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) AscendGreaterOrEqual ΒΆ

func (tx *Tx[T]) AscendGreaterOrEqual(index string, pivot PivotKV[T],
	iterator func(key string, value T) bool) error

AscendGreaterOrEqual calls the iterator for every item in the database within the range [pivot, last], until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) AscendKeys ΒΆ

func (tx *Tx[T]) AscendKeys(pattern string,
	iterator func(key string, value T) bool) error

AscendKeys allows for iterating through keys based on the specified pattern.

func (*Tx[T]) AscendLessThan ΒΆ

func (tx *Tx[T]) AscendLessThan(index string, lessThan PivotKV[T],
	iterator func(key string, value T) bool) error

AscendLessThan calls the iterator for every item in the database within the range [first, pivot), until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error. excluding the pivot

func (*Tx[T]) AscendRange ΒΆ

func (tx *Tx[T]) AscendRange(index string, greaterOrEqual, lessThan PivotKV[T],
	iterator func(key string, value T) bool) error

AscendRange calls the iterator for every item in the database within the range [greaterOrEqual, lessThan), until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error. including greaterOrEqual, excluding lessThan

func (*Tx[T]) Commit ΒΆ

func (tx *Tx[T]) Commit() error

Commit writes all changes to disk. An error is returned when a write error occurs, or when a Commit() is called from a read-only transaction.

func (*Tx[T]) CreateIndex ΒΆ

func (tx *Tx[T]) CreateIndex(name, pattern string,
	less ...func(a, b T) bool) error

CreateIndex builds a new index and populates it with items. The items are ordered in a b-tree and can be retrieved using the Ascend* and Descend* methods. An error will occur if an index with the same name already exists.

When a pattern is provided, the index will be populated with keys that match the specified pattern. This is a very simple pattern match where '*' matches on any number characters and '?' matches on any one character. The less function compares if string 'a' is less than string 'b'. It allows for indexes to create custom ordering. It's possible that the strings may be textual or binary. It's up to the provided less function to handle the content format and comparison. There are some default less function that can be used such as IndexString, IndexBinary, etc.

func (*Tx[T]) CreateIndexOptions ΒΆ

func (tx *Tx[T]) CreateIndexOptions(name, pattern string,
	opts *IndexOptions,
	less ...func(a, b T) bool) error

CreateIndexOptions is the same as CreateIndex except that it allows for additional options.

func (*Tx[T]) Delete ΒΆ

func (tx *Tx[T]) Delete(key string) (val *T, err error)

Delete removes an item from the database based on the item's Key. If the item does not exist or if the item has expired then ErrNotFound is returned.

Only a writable transaction can be used for this operation. This operation is not allowed during iterations such as Ascend* & Descend*.

func (*Tx[T]) DeleteAll ΒΆ

func (tx *Tx[T]) DeleteAll() error

DeleteAll deletes all items from the database.

func (*Tx[T]) Descend ΒΆ

func (tx *Tx[T]) Descend(index string,
	iterator func(key string, value T) bool) error

Descend calls the iterator for every item in the database within the range [last, first], until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) DescendEqual ΒΆ

func (tx *Tx[T]) DescendEqual(index string, pivot PivotKV[T],
	iterator func(key string, value T) bool) error

DescendEqual calls the iterator for every item in the database that equals pivot, until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) DescendGreaterThan ΒΆ

func (tx *Tx[T]) DescendGreaterThan(index string, pivot PivotKV[T],
	iterator func(key string, value T) bool) error

DescendGreaterThan calls the iterator for every item in the database within the range [last, pivot), until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) DescendKeys ΒΆ

func (tx *Tx[T]) DescendKeys(pattern string,
	iterator func(key string, value T) bool) error

DescendKeys allows for iterating through keys based on the specified pattern.

func (*Tx[T]) DescendLessOrEqual ΒΆ

func (tx *Tx[T]) DescendLessOrEqual(index string, pivot PivotKV[T],
	iterator func(key string, value T) bool) error

DescendLessOrEqual calls the iterator for every item in the database within the range [pivot, first], until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) DescendRange ΒΆ

func (tx *Tx[T]) DescendRange(index string, lessOrEqual, greaterThan PivotKV[T],
	iterator func(key string, value T) bool) error

DescendRange calls the iterator for every item in the database within the range [lessOrEqual, greaterThan), until iterator returns false. When an index is provided, the results will be ordered by the item values as specified by the comparator function of the defined index. When an index is not provided, the results will be ordered by the item Key. An invalid index will return an error.

func (*Tx[T]) DropIndex ΒΆ

func (tx *Tx[T]) DropIndex(name string) error

DropIndex removes an index.

func (*Tx[T]) Get ΒΆ

func (tx *Tx[T]) Get(key string, ignoreExpired ...bool) (val *T, err error)

Get returns a value for a Key. If the item does not exist or if the item has expired then ErrNotFound is returned. If ignoreExpired is true, then the found value will be returned even if it is expired.

func (*Tx[T]) GetLess ΒΆ

func (tx *Tx[T]) GetLess(index string) (func(a, b T) bool, error)

GetLess returns the comparator function for an index. This is handy for doing ad-hoc compares inside a transaction. Returns ErrNotFound if the index is not found or there is no comparator function bound to the index

func (*Tx[T]) IndexLen ΒΆ added in v0.2.0

func (tx *Tx[T]) IndexLen(index string) (int, error)

IndexLen returns the number of items in the index if index identifier is empty the total Len of the DB will be returned

func (*Tx[T]) Indexes ΒΆ

func (tx *Tx[T]) Indexes() ([]string, error)

Indexes returns a list of index names.

func (*Tx[T]) Len ΒΆ

func (tx *Tx[T]) Len() (int, error)

Len returns the number of items in the database

func (*Tx[T]) Rollback ΒΆ

func (tx *Tx[T]) Rollback() error

Rollback closes the transaction and reverts all mutable operations that were performed on the transaction such as Set() and Delete().

Read-only transactions can only be rolled back, not committed.

func (*Tx[T]) Set ΒΆ

func (tx *Tx[T]) Set(key string, value T, opts *SetOptions) (previous *T,
	replaced bool, err error)

Set inserts or replaces an item in the database based on the Key. The opts param may be used for additional functionality such as forcing the item to be evicted at a specified time. When the return value for err is nil the operation succeeded. When the return value of replaced is true, then the operation replaced an existing item whose value will be returned through the previousValue variable. The results of this operation will not be available to other transactions until the current transaction has successfully committed.

Only a writable transaction can be used with this operation. This operation is not allowed during iterations such as Ascend* & Descend*.

func (*Tx[_]) TTL ΒΆ

func (tx *Tx[_]) TTL(key string) (time.Duration, error)

TTL returns the remaining time-to-live for an item. A negative duration will be returned for items that do not have an expiration.

Directories ΒΆ

Path Synopsis
internal

Jump to

Keyboard shortcuts

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