Package tkrzw
Go Binding of Tkrzw
DBM (Database Manager) is a concept to store an associative array on a permanent storage. In other words, DBM allows an application program to store key-value pairs in a file and reuse them later. Each of keys and values is a string or a sequence of bytes. A key must be unique within the database and a value is associated to it. You can retrieve a stored record with its key very quickly. Thanks to simple structure of DBM, its performance can be extremely high.
Tkrzw is a library implementing DBM with various algorithms. It features high degrees of performance, concurrency, scalability and durability. The following data structures are provided.
HashDBM : File datatabase manager implementation based on hash table.
TreeDBM : File datatabase manager implementation based on B+ tree.
SkipDBM : File datatabase manager implementation based on skip list.
TinyDBM : On-memory datatabase manager implementation based on hash table.
BabyDBM : On-memory datatabase manager implementation based on B+ tree.
CacheDBM : On-memory datatabase manager implementation with LRU deletion.
StdHashDBM : On-memory DBM implementations using std::unordered_map.
StdTreeDBM : On-memory DBM implementations using std::map.
Whereas Tkrzw is C++ library, this package provides its Go interface. All above data structures are available via one adapter struct "DBM". Read the homepage (http://dbmx.net/tkrzw/) for details.
DBM stores key-value pairs of strings. Each string is represented as a byte array in Go. Although you can also use methods with string arguments and return values, their internal representations are byte arrays. Other types such as intergers can also be taken as parameters and they are converted into byte arrays implicitly.
All identifiers are defined under the package "tkrzw", which can be imported in source files of application programs as "github.com/estraier/tkrzw-go".
import "github.com/estraier/tkrzw-go"
The following types are mainly used.
tkrzw.Future : Future containing a status object and extra data
An instance of the struct "DBM" is used in order to handle a database. You can store, delete, and retrieve records with the instance. The result status of each operation is represented by an object of the struct "Status". Iterator to access each record is implemented by the struct "Iterator".
The key and the value of the records are stored as byte arrays. However, you can specify strings and other types which imlements the Stringer interface whereby the object is converted into a byte array.
Install the latest version of Tkrzw beforehand. If you write the above import directive and prepare the "go.mod" file, the Go module for Tkrzw is installed implicitly when you run "go get". Go 1.14 or later is required to use this package.
The following code is a simple example to use a database, without checking errors. Many methods accept both byte arrays and strings. If strings are given, they are converted implicitly into byte arrays.
package main
import (
"fmt"
"github.com/estraier/tkrzw-go"
)
func main() {
// Prepares the database.
dbm := tkrzw.NewDBM()
dbm.Open("casket.tkh", true,
tkrzw.ParseParams("truncate=true,num_buckets=100"))
// Sets records.
// Keys and values are implicitly converted into bytes.
dbm.Set("first", "hop", true)
dbm.Set("second", "step", true)
dbm.Set("third", "jump", true)
// Retrieves record values as strings.
fmt.Println(dbm.GetStrSimple("first", "*"))
fmt.Println(dbm.GetStrSimple("second", "*"))
fmt.Println(dbm.GetStrSimple("third", "*"))
// Checks and deletes a record.
if dbm.Check("first") {
dbm.Remove("first")
}
// Traverses records with a range over a channel.
for record := range dbm.EachStr() {
fmt.Println(record.Key, record.Value)
}
// Closes the database.
dbm.Close()
}
The following code is an advanced example where a so-called long transaction is done by the compare-and-exchange (aka compare-and-swap) idiom. The example also shows how to use the iterator to access each record.
package main
import (
"fmt"
"github.com/estraier/tkrzw-go"
)
func main() {
// Prepares the database.
// The method OrDie causes panic if the status is not success.
// You should write your own error handling in large scale programs.
dbm := tkrzw.NewDBM()
dbm.Open("casket.tkt", true,
tkrzw.ParseParams("truncate=true,num_buckets=100")).OrDie()
// Closes the database for sure and checks the error too.
defer func() { dbm.Close().OrDie() }()
// Two bank accounts for Bob and Alice.
// Numeric values are converted into strings implicitly.
dbm.Set("Bob", 1000, false).OrDie()
dbm.Set("Alice", 3000, false).OrDie()
// Function to do a money transfer atomically.
transfer := func(src_key string, dest_key string, amount int64) *tkrzw.Status {
// Gets the old values as numbers.
old_src_value := tkrzw.ToInt(dbm.GetStrSimple(src_key, "0"))
old_dest_value := tkrzw.ToInt(dbm.GetStrSimple(dest_key, "0"))
// Calculates the new values.
new_src_value := old_src_value - amount
new_dest_value := old_dest_value + amount
if new_src_value < 0 {
return tkrzw.NewStatus(tkrzw.StatusApplicationError, "insufficient value")
}
// Prepares the pre-condition and the post-condition of the transaction.
old_records := []tkrzw.KeyValueStrPair{
{src_key, tkrzw.ToString(old_src_value)},
{dest_key, tkrzw.ToString(old_dest_value)},
}
new_records := []tkrzw.KeyValueStrPair{
{src_key, tkrzw.ToString(new_src_value)},
{dest_key, tkrzw.ToString(new_dest_value)},
}
// Performs the transaction atomically.
// This fails safely if other concurrent transactions break the pre-condition.
return dbm.CompareExchangeMultiStr(old_records, new_records)
}
// Tries a transaction until it succeeds
var status *tkrzw.Status
for num_tries := 0; num_tries < 100; num_tries++ {
status = transfer("Alice", "Bob", 500)
if !status.Equals(tkrzw.StatusInfeasibleError) {
break
}
}
status.OrDie()
// Traverses records in a primitive way.
iter := dbm.MakeIterator()
defer iter.Destruct()
iter.First()
for {
key, value, status := iter.GetStr()
if !status.IsOK() {
break
}
fmt.Println(key, value)
iter.Next()
}
}
The following code is examples to use a tree database which handles numeric keys with various key comparators. For integers, there are two ways: 1) to use the default comparator and serialize integer keys into byte sequences, or 2) to use the decimal integer comparator and represent keys as decimal integers like "123". For real numbers, there are also two ways: 1) to use the decimal real number comparator and represents keys as decimal real numbers like "123.45", or 2) to use the big-endian floating-point numbers comparator and serialize floating-point numbers into byte sequences.
package main
import (
"fmt"
"github.com/estraier/tkrzw-go"
)
func main() {
// Opens a new database with the default key comparator (LexicalKeyComparator).
dbm := tkrzw.NewDBM()
dbm.Open("casket.tkt", true, tkrzw.ParseParams("truncate=true")).OrDie()
// Sets records with the key being a big-endian binary of an integer.
// e.g: "\x00\x00\x00\x00\x00\x00\x00\x31" -> "hop"
dbm.Set(tkrzw.SerializeInt(1), "hop", true).OrDie()
dbm.Set(tkrzw.SerializeInt(256), "step", true).OrDie()
dbm.Set(tkrzw.SerializeInt(32), "jump", true).OrDie()
// Gets records with the key being a decimal string of an integer.
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeInt(1), ""))
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeInt(256), ""))
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeInt(32), ""))
// Lists up all records, restoring keys into integers.
iter := dbm.MakeIterator()
iter.First()
for {
key, value, status := iter.Get()
if !status.IsOK() {
break
}
fmt.Printf("%d: %s\n", tkrzw.DeserializeInt(key), value)
iter.Next()
}
iter.Destruct()
// Closes the database.
dbm.Close().OrDie()
// Opens a new database with the decimal integer comparator.
dbm = tkrzw.NewDBM()
dbm.Open("casket.tkt", true, tkrzw.ParseParams(
"truncate=true,key_comparator=Decimal")).OrDie()
// Sets records with the key being a decimal string of an integer.
// e.g: "1" -> "hop"
dbm.Set("1", "hop", true).OrDie()
dbm.Set("256", "step", true).OrDie()
dbm.Set("32", "jump", true).OrDie()
// Gets records with the key being a decimal string of an integer.
fmt.Println(dbm.GetStrSimple("1", ""))
fmt.Println(dbm.GetStrSimple("256", ""))
fmt.Println(dbm.GetStrSimple("32", ""))
// Lists up all records, restoring keys into integers.
iter = dbm.MakeIterator()
iter.First()
for {
key, value, status := iter.Get()
if !status.IsOK() {
break
}
fmt.Printf("%d: %s\n", tkrzw.ToInt(key), value)
iter.Next()
}
iter.Destruct()
// Closes the database.
dbm.Close().OrDie()
// Opens a new database with the decimal real number comparator.
dbm = tkrzw.NewDBM()
dbm.Open("casket.tkt", true, tkrzw.ParseParams(
"truncate=true,key_comparator=RealNumber")).OrDie()
// Sets records with the key being a decimal string of a real number.
// e.g: "1.5" -> "hop"
dbm.Set("1.5", "hop", true).OrDie()
dbm.Set("256.5", "step", true).OrDie()
dbm.Set("32.5", "jump", true).OrDie()
// Gets records with the key being a decimal string of a real number.
fmt.Println(dbm.GetStrSimple("1.5", ""))
fmt.Println(dbm.GetStrSimple("256.5", ""))
fmt.Println(dbm.GetStrSimple("32.5", ""))
// Lists up all records, restoring keys into floating-point numbers.
iter = dbm.MakeIterator()
iter.First()
for {
key, value, status := iter.Get()
if !status.IsOK() {
break
}
fmt.Printf("%.3f: %s\n", tkrzw.ToFloat(key), value)
iter.Next()
}
iter.Destruct()
// Closes the database.
dbm.Close().OrDie()
// Opens a new database with the big-endian signed integers comparator.
dbm = tkrzw.NewDBM()
dbm.Open("casket.tkt", true, tkrzw.ParseParams(
"truncate=true,key_comparator=SignedBigEndian")).OrDie()
// Sets records with the key being a big-endian binary of a signed integer.
// e.g: "\x00\x00\x00\x00\x00\x00\x00\x31" -> "hop"
dbm.Set(tkrzw.SerializeInt(-1), "hop", true).OrDie()
dbm.Set(tkrzw.SerializeInt(-256), "step", true).OrDie()
dbm.Set(tkrzw.SerializeInt(-32), "jump", true).OrDie()
// Gets records with the key being a big-endian binary of a signed integer.
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeInt(-1), ""))
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeInt(-256), ""))
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeInt(-32), ""))
// Lists up all records, restoring keys into signed integers.
iter = dbm.MakeIterator()
iter.First()
for {
key, value, status := iter.Get()
if !status.IsOK() {
break
}
fmt.Printf("%d: %s\n", tkrzw.DeserializeInt(key), value)
iter.Next()
}
iter.Destruct()
// Closes the database.
dbm.Close().OrDie()
// Opens a new database with the big-endian floating-point numbers comparator.
dbm = tkrzw.NewDBM()
dbm.Open("casket.tkt", true, tkrzw.ParseParams(
"truncate=true,key_comparator=FloatBigEndian")).OrDie()
// Sets records with the key being a big-endian binary of a floating-point number.
// e.g: "\x3F\xF8\x00\x00\x00\x00\x00\x00" -> "hop"
dbm.Set(tkrzw.SerializeFloat(1.5), "hop", true).OrDie()
dbm.Set(tkrzw.SerializeFloat(256.5), "step", true).OrDie()
dbm.Set(tkrzw.SerializeFloat(32.5), "jump", true).OrDie()
// Gets records with the key being a big-endian binary of a floating-point number.
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeFloat(1.5), ""))
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeFloat(256.5), ""))
fmt.Println(dbm.GetStrSimple(tkrzw.SerializeFloat(32.5), ""))
// Lists up all records, restoring keys into floating-point numbers.
iter = dbm.MakeIterator()
iter.First()
for {
key, value, status := iter.Get()
if !status.IsOK() {
break
}
fmt.Printf("%.3f: %s\n", tkrzw.DeserializeFloat(key), value)
iter.Next()
}
iter.Destruct()
// Closes the database.
dbm.Close().OrDie()
}
The following code is a typical example of the asynchronous API. The AsyncDBM class manages a thread pool and handles database operations in the background in parallel. Each Method of AsyncDBM returns a Future object to monitor the result.
package main
import (
"fmt"
"github.com/estraier/tkrzw-go"
)
func main() {
// Prepares the database.
dbm := tkrzw.NewDBM()
dbm.Open("casket.tkt", true,
tkrzw.ParseParams("truncate=true,num_buckets=100"))
defer dbm.Close()
// Prepares the asynchronous adapter with 4 worker threads.
async := tkrzw.NewAsyncDBM(dbm, 4)
defer async.Destruct()
// Executes the Set method asynchronously.
future := async.Set("hello", "world", true)
// Does something in the foreground.
fmt.Println("Setting a record")
// Checks the result after awaiting the set operation.
// The Get method releases the resource of the future.
status := future.Get()
if !status.IsOK() {
fmt.Println("ERROR: " + status.String())
}
// Executes the get method asynchronously.
future = async.Get("hello")
// Does something in the foreground.
fmt.Println("Getting a record")
// Checks the result after awaiting the get operation.
// The GetStr method releases the resource of the future.
value, status := future.GetStr()
if status.IsOK() {
fmt.Println("VALUE: " + value)
}
}
The following code uses Process, ProcessMulti, and ProcessEach methods which take callback functions to process the record efficiently. Process is useful to update a record atomically according to the current value. ProcessEach is useful to access every record in the most efficient way.
package main
import (
"fmt"
"github.com/estraier/tkrzw-go"
"regexp"
"strings"
)
func main() {
// Opens the database.
dbm := tkrzw.NewDBM()
dbm.Open("casket.tkh", true,
tkrzw.ParseParams("truncate=true,num_buckets=100"))
defer dbm.Close()
// Sets records with lambda functions.
dbm.Process("doc-1", func(k []byte, v []byte) interface{} {
return "Tokyo is the capital city of Japan."
}, true)
dbm.Process("doc-2", func(k []byte, v []byte) interface{} {
return "Is she living in Tokyo, Japan?"
}, true)
dbm.Process("doc-3", func(k []byte, v []byte) interface{} {
return "She must leave Tokyo!"
}, true)
// Lowers record values.
lower := func(k []byte, v []byte) interface{} {
// If no matching record, nil is given as the value.
if v == nil {
return nil
}
// Sets the new value.
// Note that the key and the value are a "bytes" object.
return strings.ToLower(string(v))
}
dbm.Process("doc-1", lower, true)
dbm.Process("doc-2", lower, true)
dbm.Process("doc-3", lower, true)
dbm.Process("non-existent", lower, true)
// Adds multiple records at once.
ops := []tkrzw.KeyProcPair{
{"doc-4", func(k []byte, v []byte) interface{} { return "Tokyo Go!" }},
{"doc-5", func(k []byte, v []byte) interface{} { return "Japan Go!" }},
}
dbm.ProcessMulti(ops, true)
// Modifies multiple records at once.
dbm.ProcessMulti([]tkrzw.KeyProcPair{{"doc-4", lower}, {"doc-5", lower}}, true)
// Checks the whole content.
// This uses an external iterator and is relavively slow.
for record := range dbm.EachStr() {
fmt.Println(record.Key, record.Value)
}
// Function for word counting.
wordCounts := make(map[string]int)
wordSplitter := regexp.MustCompile("\\W")
wordCounter := func(key []byte, value []byte) interface{} {
if key == nil {
return nil
}
words := wordSplitter.Split(string(value), -1)
for _, word := range words {
if len(word) == 0 {
continue
}
wordCounts[word] += 1
}
return nil
}
// The second parameter should be false if the value is not updated.
dbm.ProcessEach(wordCounter, false)
for word, count := range wordCounts {
fmt.Printf("%s = %d\n", word, count)
}
// Returning RemoveBytes by the callbacks removes the record.
dbm.Process("doc-1", func(k []byte, v []byte) interface{} {
return tkrzw.RemoveBytes
}, true)
println(dbm.CountSimple())
dbm.ProcessMulti([]tkrzw.KeyProcPair{
{"doc-4", func(k []byte, v []byte) interface{} { return tkrzw.RemoveBytes }},
{"doc-5", func(k []byte, v []byte) interface{} { return tkrzw.RemoveBytes }},
}, true)
println(dbm.CountSimple())
dbm.ProcessEach(func(k []byte, v []byte) interface{} {
return tkrzw.RemoveBytes
}, true)
println(dbm.CountSimple())
}
The following code is an example to use a secondary index, which is useful to organize records by non-primary keys.
package main
import (
"fmt"
"github.com/estraier/tkrzw-go"
)
func main() {
// Opens the index.
index := tkrzw.NewIndex()
index.Open("casket.tkt", true,
tkrzw.ParseParams("truncate=true,num_buckets=100")).OrDie()
defer func() { index.Close().OrDie() }()
// Adds records to the index.
// The key is a division name and the value is person name.
index.Add("general", "anne").OrDie()
index.Add("general", "matthew").OrDie()
index.Add("general", "marilla").OrDie()
index.Add("sales", "gilbert").OrDie()
// Anne moves to the sales division.
index.Remove("general", "anne").OrDie()
index.Add("sales", "anne").OrDie()
// Prints all members for each division.
divisions := [] string{"general", "sales"}
for _, division := range divisions {
fmt.Printf("%s\n", division)
members := index.GetValuesStr(division, 0)
for _, member := range members {
fmt.Printf(" -- %s\n", member)
}
}
// Prints every record by iterator.
iter := index.MakeIterator()
defer iter.Destruct()
iter.First()
for {
key, value, ok := iter.GetStr()
if !ok {
break
}
fmt.Printf("%s: %s\n", key, value)
iter.Next()
}
}
- Constants
- Variables
- func DeserializeFloat(data []byte) float64
- func DeserializeInt(data []byte) int64
- func EditDistanceLev(a string, b string, utf bool) int
- func GetMemoryCapacity() int64
- func GetMemoryUsage() int64
- func IsAnyBytes(data []byte) bool
- func IsAnyData(data interface{}) bool
- func IsAnyString(data string) bool
- func IsNilData(data interface{}) bool
- func IsNilString(data string) bool
- func IsRemoveBytes(data []byte) bool
- func IsRemoveData(data interface{}) bool
- func IsRemoveString(data string) bool
- func ParseParams(expr string) map[string]string
- func PrimaryHash(data []byte, num_buckets uint64) uint64
- func SecondaryHash(data []byte, num_shards uint64) uint64
- func SerializeFloat(num float64) []byte
- func SerializeInt(num int64) []byte
- func StatusCodeName(code StatusCode) string
- func ToByteArray(x interface{}) []byte
- func ToFloat(value interface{}) float64
- func ToInt(value interface{}) int64
- func ToString(x interface{}) string
- type AsyncDBM
- func NewAsyncDBM(dbm *DBM, num_worker_threads int) *AsyncDBM
- func (self *AsyncDBM) Append(key interface{}, value interface{}, delim interface{}) *Future
- func (self *AsyncDBM) AppendMulti(records map[string][]byte, delim interface{}) *Future
- func (self *AsyncDBM) AppendMultiStr(records map[string]string, delim interface{}) *Future
- func (self *AsyncDBM) Clear() *Future
- func (self *AsyncDBM) CompareExchange(key interface{}, expected interface{}, desired interface{}) *Future
- func (self *AsyncDBM) CompareExchangeMulti(expected []KeyValuePair, desired []KeyValuePair) *Future
- func (self *AsyncDBM) CompareExchangeMultiStr(expected []KeyValueStrPair, desired []KeyValueStrPair) *Future
- func (self *AsyncDBM) CopyFileData(destPath string, syncHard bool) *Future
- func (self *AsyncDBM) Destruct()
- func (self *AsyncDBM) Export(destDBM *DBM) *Future
- func (self *AsyncDBM) ExportToFlatRecords(destFile *File) *Future
- func (self *AsyncDBM) Get(key interface{}) *Future
- func (self *AsyncDBM) GetMulti(keys []string) *Future
- func (self *AsyncDBM) ImportFromFlatRecords(srcFile *File) *Future
- func (self *AsyncDBM) Increment(key interface{}, inc interface{}, init interface{}) *Future
- func (self *AsyncDBM) PopFirst() *Future
- func (self *AsyncDBM) PushLast(value interface{}, wtime float64) *Future
- func (self *AsyncDBM) Rebuild(params map[string]string) *Future
- func (self *AsyncDBM) Rekey(old_key interface{}, new_key interface{}, overwrite bool, copying bool) *Future
- func (self *AsyncDBM) Remove(key interface{}) *Future
- func (self *AsyncDBM) RemoveMulti(keys []string) *Future
- func (self *AsyncDBM) Search(mode string, pattern string, capacity int) *Future
- func (self *AsyncDBM) Set(key interface{}, value interface{}, overwrite bool) *Future
- func (self *AsyncDBM) SetMulti(records map[string][]byte, overwrite bool) *Future
- func (self *AsyncDBM) SetMultiStr(records map[string]string, overwrite bool) *Future
- func (self *AsyncDBM) String() string
- func (self *AsyncDBM) Synchronize(hard bool, params map[string]string) *Future
- type DBM
- func NewDBM() *DBM
- func (self *DBM) Append(key interface{}, value interface{}, delim interface{}) *Status
- func (self *DBM) AppendMulti(records map[string][]byte, delim interface{}) *Status
- func (self *DBM) AppendMultiStr(records map[string]string, delim interface{}) *Status
- func (self *DBM) Check(key interface{}) bool
- func (self *DBM) Clear() *Status
- func (self *DBM) Close() *Status
- func (self *DBM) CompareExchange(key interface{}, expected interface{}, desired interface{}) *Status
- func (self *DBM) CompareExchangeAndGet(key interface{}, expected interface{}, desired interface{}) ([]byte, *Status)
- func (self *DBM) CompareExchangeAndGetStr(key interface{}, expected interface{}, desired interface{}) (string, *Status)
- func (self *DBM) CompareExchangeMulti(expected []KeyValuePair, desired []KeyValuePair) *Status
- func (self *DBM) CompareExchangeMultiStr(expected []KeyValueStrPair, desired []KeyValueStrPair) *Status
- func (self *DBM) CopyFileData(destPath string, syncHard bool) *Status
- func (self *DBM) Count() (int64, *Status)
- func (self *DBM) CountSimple() int64
- func (self *DBM) Destruct()
- func (self *DBM) Each() <-chan KeyValuePair
- func (self *DBM) EachStr() <-chan KeyValueStrPair
- func (self *DBM) Export(destDBM *DBM) *Status
- func (self *DBM) ExportKeysAsLines(destFile *File) *Status
- func (self *DBM) ExportToFlatRecords(destFile *File) *Status
- func (self *DBM) Get(key interface{}) ([]byte, *Status)
- func (self *DBM) GetFilePath() (string, *Status)
- func (self *DBM) GetFilePathSimple() string
- func (self *DBM) GetFileSize() (int64, *Status)
- func (self *DBM) GetFileSizeSimple() int64
- func (self *DBM) GetMulti(keys []string) map[string][]byte
- func (self *DBM) GetMultiStr(keys []string) map[string]string
- func (self *DBM) GetSimple(key interface{}, defaultValue interface{}) []byte
- func (self *DBM) GetStr(key interface{}) (string, *Status)
- func (self *DBM) GetStrSimple(key interface{}, defaultValue interface{}) string
- func (self *DBM) GetTimestamp() (float64, *Status)
- func (self *DBM) GetTimestampSimple() float64
- func (self *DBM) ImportFromFlatRecords(srcFile *File) *Status
- func (self *DBM) Increment(key interface{}, inc interface{}, init interface{}) (int64, *Status)
- func (self *DBM) Inspect() map[string]string
- func (self *DBM) IsHealthy() bool
- func (self *DBM) IsOpen() bool
- func (self *DBM) IsOrdered() bool
- func (self *DBM) IsWritable() bool
- func (self *DBM) MakeIterator() *Iterator
- func (self *DBM) Open(path string, writable bool, params map[string]string) *Status
- func (self *DBM) PopFirst() ([]byte, []byte, *Status)
- func (self *DBM) PopFirstStr() (string, string, *Status)
- func (self *DBM) Process(key interface{}, proc RecordProcessor, writable bool) *Status
- func (self *DBM) ProcessEach(proc RecordProcessor, writable bool) *Status
- func (self *DBM) ProcessMulti(keyProcPairs []KeyProcPair, writable bool) *Status
- func (self *DBM) PushLast(value interface{}, wtime float64) *Status
- func (self *DBM) Rebuild(params map[string]string) *Status
- func (self *DBM) Rekey(oldKey interface{}, newKey interface{}, overwrite bool, copying bool) *Status
- func (self *DBM) Remove(key interface{}) *Status
- func (self *DBM) RemoveAndGet(key interface{}) ([]byte, *Status)
- func (self *DBM) RemoveAndGetStr(key interface{}) (*string, *Status)
- func (self *DBM) RemoveMulti(keys []string) *Status
- func (self *DBM) Search(mode string, pattern string, capacity int) []string
- func (self *DBM) Set(key interface{}, value interface{}, overwrite bool) *Status
- func (self *DBM) SetAndGet(key interface{}, value interface{}, overwrite bool) ([]byte, *Status)
- func (self *DBM) SetAndGetStr(key interface{}, value interface{}, overwrite bool) (*string, *Status)
- func (self *DBM) SetMulti(records map[string][]byte, overwrite bool) *Status
- func (self *DBM) SetMultiStr(records map[string]string, overwrite bool) *Status
- func (self *DBM) ShouldBeRebuilt() (bool, *Status)
- func (self *DBM) ShouldBeRebuiltSimple() bool
- func (self *DBM) String() string
- func (self *DBM) Synchronize(hard bool, params map[string]string) *Status
- type File
- func NewFile() *File
- func (self *File) Append(data interface{}) (int64, *Status)
- func (self *File) Close() *Status
- func (self *File) Destruct()
- func (self *File) GetPath() (string, *Status)
- func (self *File) GetSize() (int64, *Status)
- func (self *File) Open(path string, writable bool, params map[string]string) *Status
- func (self *File) Read(off int64, size int64) ([]byte, *Status)
- func (self *File) ReadStr(off int64, size int64) (string, *Status)
- func (self *File) Search(mode string, pattern string, capacity int) []string
- func (self *File) String() string
- func (self *File) Synchronize(hard bool, off int64, size int64) *Status
- func (self *File) Truncate(size int64) *Status
- func (self *File) Write(off int64, data interface{}) *Status
- type Future
- func (self *Future) Destruct()
- func (self *Future) Get() *Status
- func (self *Future) GetArray() ([][]byte, *Status)
- func (self *Future) GetArrayStr() ([]string, *Status)
- func (self *Future) GetBytes() ([]byte, *Status)
- func (self *Future) GetInt() (int64, *Status)
- func (self *Future) GetMap() (map[string][]byte, *Status)
- func (self *Future) GetMapStr() (map[string]string, *Status)
- func (self *Future) GetPair() ([]byte, []byte, *Status)
- func (self *Future) GetPairStr() (string, string, *Status)
- func (self *Future) GetStr() (string, *Status)
- func (self *Future) String() string
- func (self *Future) Wait(timeout float64) bool
- type Index
- func NewIndex() *Index
- func (self *Index) Add(key interface{}, value interface{}) *Status
- func (self *Index) Check(key interface{}, value interface{}) bool
- func (self *Index) Clear() *Status
- func (self *Index) Close() *Status
- func (self *Index) Count() int64
- func (self *Index) Destruct()
- func (self *Index) GetFilePath() string
- func (self *Index) GetValues(key interface{}, max int) [][]byte
- func (self *Index) GetValuesStr(key interface{}, max int) []string
- func (self *Index) IsOpen() bool
- func (self *Index) IsWritable() bool
- func (self *Index) MakeIterator() *IndexIterator
- func (self *Index) Open(path string, writable bool, params map[string]string) *Status
- func (self *Index) Rebuild() *Status
- func (self *Index) Remove(key interface{}, value interface{}) *Status
- func (self *Index) String() string
- func (self *Index) Synchronize(hard bool) *Status
- type IndexIterator
- func (self *IndexIterator) Destruct()
- func (self *IndexIterator) First()
- func (self *IndexIterator) Get() ([]byte, []byte, bool)
- func (self *IndexIterator) GetStr() (string, string, bool)
- func (self *IndexIterator) Jump(key interface{}, value interface{})
- func (self *IndexIterator) Last()
- func (self *IndexIterator) Next()
- func (self *IndexIterator) Previous()
- func (self *IndexIterator) String() string
- type Iterator
- func (self *Iterator) Destruct()
- func (self *Iterator) First() *Status
- func (self *Iterator) Get() ([]byte, []byte, *Status)
- func (self *Iterator) GetKey() ([]byte, *Status)
- func (self *Iterator) GetKeyStr() (string, *Status)
- func (self *Iterator) GetStr() (string, string, *Status)
- func (self *Iterator) GetValue() ([]byte, *Status)
- func (self *Iterator) GetValueStr() (string, *Status)
- func (self *Iterator) Jump(key interface{}) *Status
- func (self *Iterator) JumpLower(key interface{}, inclusive bool) *Status
- func (self *Iterator) JumpUpper(key interface{}, inclusive bool) *Status
- func (self *Iterator) Last() *Status
- func (self *Iterator) Next() *Status
- func (self *Iterator) Previous() *Status
- func (self *Iterator) Remove() *Status
- func (self *Iterator) Set(value interface{}) *Status
- func (self *Iterator) Step() ([]byte, []byte, *Status)
- func (self *Iterator) StepStr() (string, string, *Status)
- func (self *Iterator) String() string
- type KeyBytesProcPair
- type KeyProcPair
- type KeyValuePair
- type KeyValueStrPair
- type RecordProcessor
- type RecordProcessorPool
- type Status
- func NewStatus(args ...interface{}) *Status
- func NewStatus1(code StatusCode) *Status
- func NewStatus2(code StatusCode, message string) *Status
- func RestoreDatabase(oldFilePath string, newFilePath string, className string, endOffset int64, cipherKey string) *Status
- func (self *Status) Equals(rhs interface{}) bool
- func (self *Status) Error() string
- func (self *Status) GetCode() StatusCode
- func (self *Status) GetMessage() string
- func (self *Status) IsOK() bool
- func (self *Status) Join(rhs *Status)
- func (self *Status) OrDie()
- func (self *Status) Set(args ...interface{})
- func (self *Status) String() string
- type StatusCode
Package files
asyncdbm.go
dbm.go
doc.go
file.go
future.go
index.go
index_iterator.go
iterator.go
native.go
status.go
util.go
Constants
Enumeration of status codes.
const (
StatusSuccess = StatusCode(0)
StatusUnknownError = StatusCode(1)
StatusSystemError = StatusCode(2)
StatusNotImplementedError = StatusCode(3)
StatusPreconditionError = StatusCode(4)
StatusInvalidArgumentError = StatusCode(5)
StatusCanceledError = StatusCode(6)
StatusNotFoundError = StatusCode(7)
StatusPermissionError = StatusCode(8)
StatusInfeasibleError = StatusCode(9)
StatusDuplicationError = StatusCode(10)
StatusBrokenDataError = StatusCode(11)
StatusNetworkError = StatusCode(12)
StatusApplicationError = StatusCode(13)
)
Variables
The special bytes value for no-operation or any data.
var AnyBytes = []byte("\x00[ANY]\x00")
The special string value for no-operation or any data.
var AnyString = string([]byte("\x00[ANY]\x00"))
The minimum value of int64. */
var Int64Max int64
The minimum value of int64. */
var Int64Min int64
The special string value for non-existing data.
var NilString = string([]byte("\x00[NIL]\x00"))
The recognized OS name.
var OSName string
The recognized OS name.
var PageSize int
The special bytes value to remove a record.
var RemoveBytes = []byte("\x00[REMOVE]\x00")
The special string value to remove a record.
var RemoveString = string([]byte("\x00[REMOVE]\x00"))
The package version numbers.
var Version string
func DeserializeFloat(data []byte) float64
Deserializes a big-endian binary sequence into a floating-point number.
@param data a binary sequence.
@return The result floating-point number.
func DeserializeInt(data []byte) int64
Deserializes a big-endian binary sequence into an integer.
@param data a binary sequence.
@return The result integer.
func EditDistanceLev(a string, b string, utf bool) int
Gets the Levenshtein edit distance of two Unicode strings.
@param a A string.
@param b The other string.
@param utf If true, text is treated as UTF-8. If false, it is treated as raw bytes.
@return The Levenshtein edit distance of the two strings.
func GetMemoryCapacity() int64
Gets the memory capacity of the platform.
@return The memory capacity of the platform in bytes, or -1 on failure.
func GetMemoryUsage() int64
Gets the current memory usage of the process.
@return The current memory usage of the process in bytes, or -1 on failure.
func IsAnyBytes(data []byte) bool
Checks whether the given bytes are the any bytes.
@param data The data to check.
@return True if the data are the any bytes.
func IsAnyData(data interface{}) bool
Checks whether the given data is a unique value of any data.
@param data The data to check.
@return True if the data is any data or false if not.
func IsAnyString(data string) bool
Checks whether the given string is the any string.
@param data The data to check.
@return True if the data is the any string, or false if not.
func IsNilData(data interface{}) bool
Checks whether the given data is a nil-equivalent value.
@param data The data to check.
@return True if the data is a nil-equivalent value, or false if not.
func IsNilString(data string) bool
Checks whether the given string is the nil string.
@param data The data to check.
@return True if the data is the nil string, or false if not.
func IsRemoveBytes(data []byte) bool
Checks whether the given bytes are the removing bytes.
@param data The data to check.
@return True if the data are the removing bytes.
func IsRemoveData(data interface{}) bool
Checks whether the given data is a unique value of removing data.
@param data The data to check.
@return True if the data is removing data or false if not.
func IsRemoveString(data string) bool
Checks whether the given string is the removing string.
@param data The data to check.
@return True if the data is the removing string, or false if not.
func ParseParams(expr string) map[string]string
Parses a parameter string to make a parameter string map.
@param expr A parameter string in "name=value,name=value,..." format.
@return The string map of the parameters.
func PrimaryHash(data []byte, num_buckets uint64) uint64
Primary hash function for the hash database.
@param data The data to calculate the hash value for.
@param num_buckets: The number of buckets of the hash table.
func SecondaryHash(data []byte, num_shards uint64) uint64
Secondary hash function for sharding.
@param data The data to calculate the hash value for.
@aram num_shards The number of shards.
@return The hash value.
func SerializeFloat(num float64) []byte
Serializes a floating-point number into a big-endian binary sequence.
@param num a floating-point number.
@return The result binary sequence.
func SerializeInt(num int64) []byte
Serializes an integer into a big-endian binary sequence.
@param num an integer.
@return The result binary sequence.
func StatusCodeName(code StatusCode) string
Gets the name of a status code.
@param code The status code.
@return The name of the status code.
func ToByteArray(x interface{}) []byte
Converts any object into a byte array.
@param x The object to convert.
@return The result byte array.
func ToFloat(value interface{}) float64
Converts any object into a real number.
@param x The object to convert.
@return The result real number.
func ToInt(value interface{}) int64
Converts any object into an integer.
@param x The object to convert.
@return The result integer.
func ToString(x interface{}) string
Converts any object into a string.
@param x The object to convert.
@return The result string.
Asynchronous database manager adapter.
This class is a wrapper of DBM for asynchronous operations. A task queue with a thread pool is used inside. Every method except for the constructor and the destructor is run by a thread in the thread pool and the result is set in the future oject of the return value. The caller can ignore the future object if it is not necessary. The destruct method waits for all tasks to be done. Therefore, the destructor should be called before the database is closed.
type AsyncDBM struct {
}
func NewAsyncDBM(dbm *DBM, num_worker_threads int) *AsyncDBM
Makes a new AsyncDBM object.
@param dbm A database object which has been opened.
@param num_worker_threads The number of threads in the internal thread pool.
@return The pointer to the created database object.
func (*AsyncDBM) Append
¶
func (self *AsyncDBM) Append(key interface{}, value interface{}, delim interface{}) *Future
Appends data at the end of a record of a key.
@param key The key of the record.
@param value The value to append.
@param delim The delimiter to put after the existing record.
@return The future for the result status.
If there's no existing record, the value is set without the delimiter. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) AppendMulti(records map[string][]byte, delim interface{}) *Future
Appends data to multiple records.
@param records Records to append.
@param delim The delimiter to put after the existing record.
@return The future for the result status. The result should be gotten by the Get method of the future.
If there's no existing record, the value is set without the delimiter.
func (self *AsyncDBM) AppendMultiStr(records map[string]string, delim interface{}) *Future
Appends data to multiple records, with string data.
@param records Records to append.
@param delim The delimiter to put after the existing record.
@return The future for the result status. The result should be gotten by the Get method of the future.
If there's no existing record, the value is set without the delimiter.
func (*AsyncDBM) Clear
¶
func (self *AsyncDBM) Clear() *Future
Removes all records.
@return The future for the result status. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) CompareExchange(
key interface{}, expected interface{}, desired interface{}) *Future
Compares the value of a record and exchanges if the condition meets.
@param key The key of the record.
@param expected The expected value. If it is nil or NilString, no existing record is expected. If it is AnyBytes or AnyString, an existing record with any value is expacted.
@param desired The desired value. If it is nil or NilString, the record is to be removed. If it is AnyBytes or AnyString, no update is done.
@return The future for the result status. If the condition doesn't meet, StatusInfeasibleError is set. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) CompareExchangeMulti(
expected []KeyValuePair, desired []KeyValuePair) *Future
Compares the values of records and exchanges if the condition meets.
@param expected A sequence of pairs of the record keys and their expected values. If the value is nil, no existing record is expected. If the value is AnyBytes, an existing record with any value is expacted.
@param desired A sequence of pairs of the record keys and their desired values. If the value is nil, the record is to be removed.
@return The future for the result status. If the condition doesn't meet, StatusInfeasibleError is set. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) CompareExchangeMultiStr(
expected []KeyValueStrPair, desired []KeyValueStrPair) *Future
Compares the values of records and exchanges if the condition meets, using string data.
@param expected A sequence of pairs of the record keys and their expected values. If the value is NilString, no existing record is expected. If the value is AnyString, an existing record with any value is expacted.
@param desired A sequence of pairs of the record keys and their desired values. If the value is NilString, the record is to be removed.
@return The future for The result status. If the condition doesn't meet, StatusInfeasibleError is set. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) CopyFileData(destPath string, syncHard bool) *Future
Copies the content of the database file to another file.
@param destPath A path to the destination file.
@param syncHard True to do physical synchronization with the hardware.
@return The future for the result status. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) Destruct()
Destructs the object and releases resources.
This method waits for all tasks to be done.
func (*AsyncDBM) Export
¶
func (self *AsyncDBM) Export(destDBM *DBM) *Future
Exports all records to another database.
@param destDBM The destination database. The lefetime of the database object must last until the task finishes.
@return The future for the result status. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) ExportToFlatRecords(destFile *File) *Future
Exports all records of a database to a flat record file.
@param file: The file object to write records in. The lefetime of the file object must last until the task finishes.
@return The future for the result status. The result should be gotten by the Get method of the future.
A flat record file contains a sequence of binary records without any high level structure so it is useful as a intermediate file for data migration.
func (*AsyncDBM) Get
¶
func (self *AsyncDBM) Get(key interface{}) *Future
Gets the value of a record of a key.
@param key The key of the record.
@return The future for the record value and the result status. If there's no matching record, StatusNotFoundError is set. The result should be gotten by the GetBytes or GetStr method of the future.
func (self *AsyncDBM) GetMulti(keys []string) *Future
Gets the values of multiple records of keys.
@param keys The keys of records to retrieve.
@return The future for a map of retrieved records and the result status. Keys which don't match existing records are ignored. The result should be gotten by the GetMap or GetMapStr method of the future.
func (self *AsyncDBM) ImportFromFlatRecords(srcFile *File) *Future
Imports records to a database from a flat record file.
@param file The file object to read records from. The lefetime of the file object must last until the task finishes.
@return The future for the result status. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) Increment(key interface{}, inc interface{}, init interface{}) *Future
Increments the numeric value of a record.
@param key The key of the record.
@param inc The incremental value. If it is Int64Min, the current value is not changed and a new record is not created.
@param init The initial value.
@return The future for the result status.and the current value. The result should be gotten by the GetInt method of the future.
func (self *AsyncDBM) PopFirst() *Future
Gets the first record and removes it.
@return A tuple of the result status, the key and the value of the first record. The result should be gotten by the GetPair or GetPairStr method of the future.
func (self *AsyncDBM) PushLast(value interface{}, wtime float64) *Future
Adds a record with a key of the current timestamp.
@param value The value of the record.
@param wtime The current wall time used to generate the key. If it is None, the system clock is used.
@return The future for the result status.
The key is generated as an 8-bite big-endian binary string of the timestamp. If there is an existing record matching the generated key, the key is regenerated and the attempt is repeated until it succeeds.
func (*AsyncDBM) Rebuild
¶
func (self *AsyncDBM) Rebuild(params map[string]string) *Future
Rebuilds the entire database.
@param params Optional parameters. If it is nil, it is ignored.
@return The future for the result status. The result should be gotten by the Get method of the future.
The parameters work in the same way as with DBM::Rebuild.
func (*AsyncDBM) Rekey
¶
func (self *AsyncDBM) Rekey(old_key interface{}, new_key interface{},
overwrite bool, copying bool) *Future
Changes the key of a record.
@param old_key The old key of the record.
@param new_key The new key of the record.
@param overwrite Whether to overwrite the existing record of the new key.
@param copying Whether to retain the record of the old key.
@return The future for the result status. If there's no matching record to the old key, NOT_FOUND_ERROR is set. If the overwrite flag is false and there is an existing record of the new key, DUPLICATION ERROR is set. The result should be gotten by the Get method of the future.
This method is done atomically by ProcessMulti. The other threads observe that the record has either the old key or the new key. No intermediate states are observed.
func (*AsyncDBM) Remove
¶
func (self *AsyncDBM) Remove(key interface{}) *Future
Removes a record of a key.
@param key The key of the record.
@return The future for the result status. If there's no matching record, StatusNotFoundError is set. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) RemoveMulti(keys []string) *Future
Removes records of keys.
@param key The keys of the records.
@return The future for the result status. If there are missing records, StatusNotFoundError is set. The result should be gotten by the Get method of the future.
func (*AsyncDBM) Search
¶
func (self *AsyncDBM) Search(mode string, pattern string, capacity int) *Future
Searches the database and get keys which match a pattern.
@param mode The search mode. "contain" extracts keys containing the pattern. "begin" extracts keys beginning with the pattern. "end" extracts keys ending with the pattern. "regex" extracts keys partially matches the pattern of a regular expression. "edit" extracts keys whose edit distance to the UTF-8 pattern is the least. "editbin" extracts keys whose edit distance to the binary pattern is the least.
@param pattern The pattern for matching.
@param capacity The maximum records to obtain. 0 means unlimited.
@return The future for a list of keys matching the condition and the result status. The result should be gotten by the GetArray or GetArrayStr method of the future.
func (*AsyncDBM) Set
¶
func (self *AsyncDBM) Set(key interface{}, value interface{}, overwrite bool) *Future
Sets a record of a key and a value.
@param key The key of the record.
@param value The value of the record.
@param overwrite Whether to overwrite the existing value.
@return The future for the result status. If overwriting is abandoned, StatusDuplicationError is set. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) SetMulti(records map[string][]byte, overwrite bool) *Future
Sets multiple records.
@param records Records to store.
@param overwrite Whether to overwrite the existing value if there's a record with the same key. If true, the existing value is overwritten by the new value. If false, the operation is given up and an error status is returned.
@return The future for the result status. If there are records avoiding overwriting, StatusDuplicationError is set. The result should be gotten by the Get method of the future.
func (self *AsyncDBM) SetMultiStr(records map[string]string, overwrite bool) *Future
Sets multiple records, with string data.
@param records Records to store.
@param overwrite Whether to overwrite the existing value if there's a record with the same key. If true, the existing value is overwritten by the new value. If false, the operation is given up and an error status is returned.
@return The future for the result status. If there are records avoiding overwriting, StatusDuplicationError is set. The result should be gotten by the Get method of the future.
func (*AsyncDBM) String
¶
func (self *AsyncDBM) String() string
Makes a string representing the adapter.
@return The string representing the adapter.
func (self *AsyncDBM) Synchronize(hard bool, params map[string]string) *Future
Synchronizes the content of the database to the file system.
@param hard True to do physical synchronization with the hardware or false to do only logical synchronization with the file system.
@param params Optional parameters. If it is nil, it is ignored.
@return The future for the result status. The result should be gotten by the Get method of the future.
The parameters work in the same way as with DBM::Synchronize.
Polymorphic database manager.
All operations except for "Open" and "Close" are thread-safe; Multiple threads can access the same database concurrently. You can specify a data structure when you call the "Open" method. Every opened database must be closed explicitly by the "Close" method to avoid data corruption.
type DBM struct {
}
func NewDBM() *DBM
Makes a new DBM object.
@return The pointer to the created database object.
func (self *DBM) Append(key interface{}, value interface{}, delim interface{}) *Status
Appends data at the end of a record of a key.
@param key The key of the record.
@param value The value to append.
@param delim The delimiter to put after the existing record.
@return The result status.
If there's no existing record, the value is set without the delimiter.
func (self *DBM) AppendMulti(records map[string][]byte, delim interface{}) *Status
Appends data to multiple records.
@param records Records to append.
@param delim The delimiter to put after the existing record.
@return The result status.
If there's no existing record, the value is set without the delimiter.
func (self *DBM) AppendMultiStr(records map[string]string, delim interface{}) *Status
Appends data to multiple records, with string data.
@param records Records to append.
@param delim The delimiter to put after the existing record.
@return The result status.
If there's no existing record, the value is set without the delimiter.
func (*DBM) Check
¶
func (self *DBM) Check(key interface{}) bool
Checks if a record exists or not.
@param key The key of the record.
@return True if the record exists, or false if not.
func (*DBM) Clear
¶
func (self *DBM) Clear() *Status
Removes all records.
@return The result status.
func (*DBM) Close
¶
func (self *DBM) Close() *Status
Closes the database file.
@return The result status.
func (self *DBM) CompareExchange(
key interface{}, expected interface{}, desired interface{}) *Status
Compares the value of a record and exchanges if the condition meets.
@param key The key of the record.
@param expected The expected value. If it is nil or NilString, no existing record is expected. If it is AnyBytes or AnyString, an existing record with any value is expacted.
@param desired The desired value. If it is nil or NilString, the record is to be removed. If it is AnyBytes or AnyString, no update is done.
@return The result status. If the condition doesn't meet, StatusInfeasibleError is returned.
func (self *DBM) CompareExchangeAndGet(
key interface{}, expected interface{}, desired interface{}) ([]byte, *Status)
Does compare-and-exchange and/or gets the old value of the record.
@param key The key of the record.
@param expected The expected value. If it is nil or NilString, no existing record is expected. If it is AnyBytes or AnyString, an existing record with any value is expacted.
@param desired The desired value. If it is nil or NilString, the record is to be removed. If it is AnyBytes or AnyString, no update is done.
@return The old value and the result status. If the condition doesn't meet, the state is INFEASIBLE_ERROR. If there's no existing record, the value is nil.
func (self *DBM) CompareExchangeAndGetStr(
key interface{}, expected interface{}, desired interface{}) (string, *Status)
Does compare-and-exchange and/or gets the old value of the record, as a string.
@param key The key of the record.
@param expected The expected value. If it is nil or NilString, no existing record is expected. If it is AnyBytes or AnyString, an existing record with any value is expacted.
@param desired The desired value. If it is nil or NilString, the record is to be removed. If it is AnyBytes or AnyString, no update is done.
@return The old value and the result status. If the condition doesn't meet, the state is INFEASIBLE_ERROR. If there's no existing record, the value is NilString.
func (self *DBM) CompareExchangeMulti(expected []KeyValuePair, desired []KeyValuePair) *Status
Compares the values of records and exchanges if the condition meets.
@param expected A sequence of pairs of the record keys and their expected values. If the value is nil, no existing record is expected. If the value is AnyBytes, an existing record with any value is expacted.
@param desired A sequence of pairs of the record keys and their desired values. If the value is nil, the record is to be removed.
@return The result status. If the condition doesn't meet, StatusInfeasibleError is returned.
func (self *DBM) CompareExchangeMultiStr(
expected []KeyValueStrPair, desired []KeyValueStrPair) *Status
Compares the values of records and exchanges if the condition meets, using string data.
@param expected A sequence of pairs of the record keys and their expected values. If the value is NilString, no existing record is expected. If the value is AnyString, an existing record with any value is expacted.
@param desired A sequence of pairs of the record keys and their desired values. If the value is NilString, the record is to be removed.
@return The result status. If the condition doesn't meet, StatusInfeasibleError is returned.
func (self *DBM) CopyFileData(destPath string, syncHard bool) *Status
Copies the content of the database file to another file.
@param destPath A path to the destination file.
@param syncHard True to do physical synchronization with the hardware.
@return The result status.
func (*DBM) Count
¶
func (self *DBM) Count() (int64, *Status)
Gets the number of records.
@return The number of records and the result status.
func (self *DBM) CountSimple() int64
Gets the number of records, in a simple way.
@return The number of records or -1 on failure.
func (self *DBM) Destruct()
Releases the resource explicitly.
The database is closed implicitly if it has not been closed. As long as you close the database explicitly, you don't have to call this method.
func (*DBM) Each
¶
func (self *DBM) Each() <-chan KeyValuePair
Makes a channel to read each records.
@return the channel to read each records. All values should be read from the channel to avoid resource leak.
func (self *DBM) EachStr() <-chan KeyValueStrPair
Makes a channel to read each records, as strings.
@return the channel to read each records. All values should be read from the channel to avoid resource leak.
func (self *DBM) Export(destDBM *DBM) *Status
Exports all records to another database.
@param destDBM The destination database.
@return The result status.
func (self *DBM) ExportKeysAsLines(destFile *File) *Status
Exports the keys of all records as lines to a text file.
@param file The file object to write keys in.
@return The result status.
As the exported text file is smaller than the database file, scanning the text file by the search method is often faster than scanning the whole database.
func (self *DBM) ExportToFlatRecords(destFile *File) *Status
Exports all records of a database to a flat record file.
@param file: The file object to write records in.
@return The result status.
A flat record file contains a sequence of binary records without any high level structure so it is useful as a intermediate file for data migration.
func (*DBM) Get
¶
func (self *DBM) Get(key interface{}) ([]byte, *Status)
Gets the value of a record of a key.
@param key The key of the record.
@return The bytes value of the matching record and the result status. If there's no matching record, the status is StatusNotFoundError.
func (self *DBM) GetFilePath() (string, *Status)
Gets the path of the database file.
@return The path of the database file and the result status.
func (self *DBM) GetFilePathSimple() string
Gets the path of the database file, in a simple way.
@return The path of the database file, or an empty string on failure.
func (self *DBM) GetFileSize() (int64, *Status)
Gets the current file size of the database.
@return The current file size of the database and the result status.
func (self *DBM) GetFileSizeSimple() int64
Gets the current file size of the database, in a simple way.
@return The current file size of the database, or -1 on failure.
func (self *DBM) GetMulti(keys []string) map[string][]byte
Gets the values of multiple records of keys.
@param keys The keys of records to retrieve.
@return A map of retrieved records. Keys which don't match existing records are ignored.
func (self *DBM) GetMultiStr(keys []string) map[string]string
Gets the values of multiple records of keys, as strings.
@param keys The keys of records to retrieve.
@eturn A map of retrieved records. Keys which don't match existing records are ignored.
func (self *DBM) GetSimple(key interface{}, defaultValue interface{}) []byte
Gets the value of a record of a key, in a simple way.
@param key The key of the record.
@param defaultValue The value to be returned on failure.
@return The value of the matching record on success, or the default value on failure.
func (self *DBM) GetStr(key interface{}) (string, *Status)
Gets the value of a record of a key, as a string.
@param key The key of the record.
@return The string value of the matching record and the result status. If there's no matching record, the status is StatusNotFoundError.
func (self *DBM) GetStrSimple(key interface{}, defaultValue interface{}) string
Gets the value of a record of a key, in a simple way, as a string.
@param key The key of the record.
@param defaultValue The value to be returned on failure.
@return The value of the matching record on success, or the default value on failure.
func (self *DBM) GetTimestamp() (float64, *Status)
Gets the timestamp in seconds of the last modified time.
@return The timestamp in seconds of the last modified time and the result status.
func (self *DBM) GetTimestampSimple() float64
Gets the timestamp in seconds of the last modified time, in a simple way.
@return The timestamp in seconds of the last modified, or -1 on failure.
func (self *DBM) ImportFromFlatRecords(srcFile *File) *Status
Imports records to a database from a flat record file.
@param file The file object to read records from.
@return The result status.
func (self *DBM) Increment(key interface{}, inc interface{}, init interface{}) (int64, *Status)
Increments the numeric value of a record.
@param key The key of the record.
@param inc The incremental value. If it is Int64Min, the current value is not changed and a new record is not created.
@param init The initial value.
@return The current value and the result status.
func (self *DBM) Inspect() map[string]string
Inspects the database.
return A map of property names and their values.
func (self *DBM) IsHealthy() bool
Checks whether the database condition is healthy.
@return True if the database condition is healthy, or false if not.
func (self *DBM) IsOpen() bool
Checks whether the database is open.
@return True if the database is open, or false if not.
func (self *DBM) IsOrdered() bool
Checks whether ordered operations are supported.
@return True if ordered operations are supported, or false if not.
func (self *DBM) IsWritable() bool
Checks whether the database is writable.
@return True if the database is writable, or false if not.
func (self *DBM) MakeIterator() *Iterator
Makes an iterator for each record.
@return The iterator for each record.
Every iterator should be destructed explicitly by the "Destruct" method.
func (*DBM) Open
¶
func (self *DBM) Open(path string, writable bool, params map[string]string) *Status
Opens a database file.
@param path A path of the file.
@param writable If true, the file is writable. If false, it is read-only.
@param params Optional parameters. If it is nil, it is ignored.
@return The result status.
The extension of the path indicates the type of the database.
.tkh : File hash database (HashDBM)
.tkt : File tree database (TreeDBM)
.tks : File skip database (SkipDBM)
.tkmt : On-memory hash database (TinyDBM)
.tkmb : On-memory tree database (BabyDBM)
.tkmc : On-memory cache database (CacheDBM)
.tksh : On-memory STL hash database (StdHashDBM)
.tkst : On-memory STL tree database (StdTreeDBM)
The optional parameters can include options for the file opening operation.
truncate (bool): True to truncate the file.
no_create (bool): True to omit file creation.
no_wait (bool): True to fail if the file is locked by another process.
no_lock (bool): True to omit file locking.
sync_hard (bool): True to do physical synchronization when closing.
The optional parameter "dbm" supercedes the decision of the database type by the extension. The value is the type name: "HashDBM", "TreeDBM", "SkipDBM", "TinyDBM", "BabyDBM", "CacheDBM", "StdHashDBM", "StdTreeDBM".
The optional parameter "file" specifies the internal file implementation class. The default file class is "MemoryMapAtomicFile". The other supported classes are "StdFile", "MemoryMapAtomicFile", "PositionalParallelFile", and "PositionalAtomicFile".
For HashDBM, these optional parameters are supported.
update_mode (string): How to update the database file: "UPDATE_IN_PLACE" for the in-palce or "UPDATE_APPENDING" for the appending mode.
record_crc_mode (string): How to add the CRC data to the record: "RECORD_CRC_NONE" to add no CRC to each record, "RECORD_CRC_8" to add CRC-8 to each record, "RECORD_CRC_16" to add CRC-16 to each record, or "RECORD_CRC_32" to add CRC-32 to each record.
record_comp_mode (string): How to compress the record data: "RECORD_COMP_NONE" to do no compression, "RECORD_COMP_ZLIB" to compress with ZLib, "RECORD_COMP_ZSTD" to compress with ZStd, "RECORD_COMP_LZ4" to compress with LZ4, "RECORD_COMP_LZMA" to compress with LZMA, "RECORD_COMP_RC4" to cipher with RC4, "RECORD_COMP_AES" to cipher with AES.
offset_width (int): The width to represent the offset of records.
align_pow (int): The power to align records.
num_buckets (int): The number of buckets for hashing.
restore_mode (string): How to restore the database file: "RESTORE_SYNC" to restore to the last synchronized state, "RESTORE_READ_ONLY" to make the database read-only, or "RESTORE_NOOP" to do nothing. By default, as many records as possible are restored.
fbp_capacity (int): The capacity of the free block pool.
min_read_size (int): The minimum reading size to read a record.
cache_buckets (bool): True to cache the hash buckets on memory.
cipher_key (string): The encryption key for cipher compressors.
For TreeDBM, all optional parameters for HashDBM are available. In addition, these optional parameters are supported.
max_page_size (int): The maximum size of a page.
max_branches (int): The maximum number of branches each inner node can have.
max_cached_pages (int): The maximum number of cached pages.
page_update_mode (string): What to do when each page is updated: "PAGE_UPDATE_NONE" is to do no operation or "PAGE_UPDATE_WRITE" is to write immediately.
key_comparator (string): The comparator of record keys: "LexicalKeyComparator" for the lexical order, "LexicalCaseKeyComparator" for the lexical order ignoring case, "DecimalKeyComparator" for the order of decimal integer numeric expressions, "HexadecimalKeyComparator" for the order of hexadecimal integer numeric expressions, "RealNumberKeyComparator" for the order of decimal real number expressions, "SignedBigEndianKeyComparator" for the order of binary signed integer expressions, and "FloatBigEndianKeyComparator" for the order of binary float-number expressions.
For SkipDBM, these optional parameters are supported.
offset_width (int): The width to represent the offset of records.
step_unit (int): The step unit of the skip list.
max_level (int): The maximum level of the skip list.
restore_mode (string): How to restore the database file: "RESTORE_SYNC" to restore to the last synchronized state or "RESTORE_NOOP" to do nothing make the database read-only. By default, as many records as possible are restored.
sort_mem_size (int): The memory size used for sorting to build the database in the at-random mode.
insert_in_order (bool): If true, records are assumed to be inserted in ascending order of the key.
max_cached_records (int): The maximum number of cached records.
For TinyDBM, these optional parameters are supported.
num_buckets (int): The number of buckets for hashing.
For BabyDBM, these optional parameters are supported.
key_comparator (string): The comparator of record keys. The same ones as TreeDBM.
For CacheDBM, these optional parameters are supported.
cap_rec_num (int): The maximum number of records.
cap_mem_size (int): The total memory size to use.
All databases support taking update logs into files. It is enabled by setting the prefix of update log files.
ulog_prefix (str): The prefix of the update log files.
ulog_max_file_size (num): The maximum file size of each update log file. By default, it is 1GiB.
ulog_server_id (num): The server ID attached to each log. By default, it is 0.
ulog_dbm_index (num): The DBM index attached to each log. By default, it is 0.
For the file "PositionalParallelFile" and "PositionalAtomicFile", these optional parameters are supported.
block_size (int): The block size to which all blocks should be aligned.
access_options (str): Values separated by colon. "direct" for direct I/O. "sync" for synchrnizing I/O, "padding" for file size alignment by padding, "pagecache" for the mini page cache in the process.
If the optional parameter "num_shards" is set, the database is sharded into multiple shard files. Each file has a suffix like "-00003-of-00015". If the value is 0, the number of shards is set by patterns of the existing files, or 1 if they doesn't exist.
func (self *DBM) PopFirst() ([]byte, []byte, *Status)
Gets the first record and removes it.
@return The key and the value of the first record, and the result status.
func (self *DBM) PopFirstStr() (string, string, *Status)
Gets the first record as strings and removes it.
@return The key and the value of the first record, and the result status.
func (self *DBM) Process(key interface{}, proc RecordProcessor, writable bool) *Status
Processes a record with an arbitrary function.
@param key The key of the record.
@param proc The function to process a record. The first parameter is the key bytes of the record. The second parameter is the value bytes of the existing record, or nil if it the record doesn't exist. The return value is bytes or a string to update the record value. If the return value is nil or NilString, the record is not modified. If the return value is RemoveBytes or RemoveString, the record is removed.
@param writable True if the processor can edit the record.
@return The result status.
func (self *DBM) ProcessEach(proc RecordProcessor, writable bool) *Status
Processes each and every record in the database with an arbitrary function.
@param proc The function to process a record. The first parameter is the key bytes of the record. The second parameter is the value bytes of the existing record, or nil if it the record doesn't exist. The return value is bytes or a string to update the record value. If the return value is nil or NilString, the record is not modified. If the return value is RemoveBytes or RemoveString, the record is removed.
@param writable True if the processor can edit the record.
@return The result status.
The given function is called repeatedly for each record. It is also called once before the iteration and once after the iteration with both the key and the value being nil.
func (self *DBM) ProcessMulti(keyProcPairs []KeyProcPair, writable bool) *Status
Processes multiple records with arbitrary functions.
@param keyProcPairs A list of pairs of keys and their functions. The first parameter is the key bytes of the record. The second parameter is the value bytes of the existing record, or nil if it the record doesn't exist. The return value is bytes or a string to update the record value. If the return value is nil or NilString, the record is not modified. If the return value is RemoveBytes or RemoveString, the record is removed.
@param writable True if the processor can edit the record.
@return The result status.
func (self *DBM) PushLast(value interface{}, wtime float64) *Status
Adds a record with a key of the current timestamp.
@param value The value of the record.
@param wtime The current wall time used to generate the key. If it is None, the system clock is used.
@return The result status.
The key is generated as an 8-bite big-endian binary string of the timestamp. If there is an existing record matching the generated key, the key is regenerated and the attempt is repeated until it succeeds.
func (self *DBM) Rebuild(params map[string]string) *Status
Rebuilds the entire database.
@param params Optional parameters. If it is nil, it is ignored.
@return The result status.
The optional parameters are the same as the Open method. Omitted tuning parameters are kept the same or implicitly optimized.
In addition, HashDBM, TreeDBM, and SkipDBM supports the following parameters.
skip_broken_records (bool): If true, the operation continues even if there are broken records which can be skipped.
sync_hard (bool): If true, physical synchronization with the hardware is done before finishing the rebuilt file.
func (*DBM) Rekey
¶
func (self *DBM) Rekey(oldKey interface{}, newKey interface{},
overwrite bool, copying bool) *Status
Changes the key of a record.
@param old_key The old key of the record.
@param new_key The new key of the record.
@param overwrite Whether to overwrite the existing record of the new key.
@param copying Whether to retain the record of the old key.
@return The result status. If there's no matching record to the old key, NOT_FOUND_ERROR is returned. If the overwrite flag is false and there is an existing record of the new key, DUPLICATION ERROR is returned.
This method is done atomically by ProcessMulti. The other threads observe that the record has either the old key or the new key. No intermediate states are observed.
func (self *DBM) Remove(key interface{}) *Status
Removes a record of a key.
@param key The key of the record.
@return The result status. If there's no matching record, StatusNotFoundError is returned.
func (self *DBM) RemoveAndGet(key interface{}) ([]byte, *Status)
Removes a record and get the value.
@param key The key of the record.
@return The old value and the result status.
func (self *DBM) RemoveAndGetStr(key interface{}) (*string, *Status)
Removes a record and get the value, as a string.
@param key The key of the record.
@return The old value and the result status.
func (self *DBM) RemoveMulti(keys []string) *Status
Removes records of keys.
@param key The keys of the records.
@return The result status. If there are missing records, StatusNotFoundError is returned.
func (self *DBM) Search(mode string, pattern string, capacity int) []string
Searches the database and get keys which match a pattern.
@param mode The search mode. "contain" extracts keys containing the pattern. "begin" extracts keys beginning with the pattern. "end" extracts keys ending with the pattern. "regex" extracts keys partially matches the pattern of a regular expression. "edit" extracts keys whose edit distance to the UTF-8 pattern is the least. "editbin" extracts keys whose edit distance to the binary pattern is the least. "containcase", "containword", and "containcaseword" extract keys considering case and word boundary. Ordered databases support "upper" and "lower" which extract keys whose positions are upper/lower than the pattern. "upperinc" and "lowerinc" are their inclusive versions.
@param pattern The pattern for matching.
@param capacity The maximum records to obtain. 0 means unlimited.
@return A list of keys matching the condition.
func (*DBM) Set
¶
func (self *DBM) Set(key interface{}, value interface{}, overwrite bool) *Status
Sets a record of a key and a value.
@param key The key of the record.
@param value The value of the record.
@param overwrite Whether to overwrite the existing value.
@return The result status. If overwriting is abandoned, StatusDuplicationError is returned.
func (self *DBM) SetAndGet(key interface{}, value interface{}, overwrite bool) ([]byte, *Status)
Sets a record and get the old value.
@param key: The key of the record.
@param value The value of the record.
@param overwrite Whether to overwrite the existing value.
@return The old value and the result status.
func (self *DBM) SetAndGetStr(key interface{}, value interface{},
overwrite bool) (*string, *Status)
Sets a record and get the old value, as a string.
@param key: The key of the record.
@param value The value of the record.
@param overwrite Whether to overwrite the existing value.
@return The old value and the result status.
func (self *DBM) SetMulti(records map[string][]byte, overwrite bool) *Status
Sets multiple records.
@param records Records to store.
@param overwrite Whether to overwrite the existing value if there's a record with the same key. If true, the existing value is overwritten by the new value. If false, the operation is given up and an error status is returned.
@return The result status. If there are records avoiding overwriting, StatusDuplicationError is returned.
func (self *DBM) SetMultiStr(records map[string]string, overwrite bool) *Status
Sets multiple records, with string data.
@param records Records to store.
@param overwrite Whether to overwrite the existing value if there's a record with the same key. If true, the existing value is overwritten by the new value. If false, the operation is given up and an error status is returned.
@return The result status. If there are records avoiding overwriting, StatusDuplicationError is set.
func (self *DBM) ShouldBeRebuilt() (bool, *Status)
Checks whether the database should be rebuilt.
@return The result decision and the result status. The decision is true to be optimized or false with no necessity.
func (self *DBM) ShouldBeRebuiltSimple() bool
Checks whether the database should be rebuilt, in a simple way.
@return True to be optimized or false with no necessity.
func (self *DBM) String() string
Makes a string representing the database.
@return The string representing the database.
func (self *DBM) Synchronize(hard bool, params map[string]string) *Status
Synchronizes the content of the database to the file system.
@param hard True to do physical synchronization with the hardware or false to do only logical synchronization with the file system.
@param params Optional parameters. If it is nil, it is ignored.
@return The result status.
Only SkipDBM uses the optional parameters. The "merge" parameter specifies paths of databases to merge, separated by colon. The "reducer" parameter specifies the reducer to apply to records of the same key. "ReduceToFirst", "ReduceToSecond", "ReduceToLast", etc are supported.
Generic file implementation.
All operations except for "Open" and "Close" are thread-safe; Multiple threads can access the same file concurrently. You can specify a concrete class when you call the "Open" method. Every opened file must be closed explicitly by the "Close" method to avoid data corruption.
type File struct {
}
func NewFile() *File
Makes a new file object.
@return The pointer to the created file object.
func (self *File) Append(data interface{}) (int64, *Status)
Appends data at the end of the file.
@param data The data to write.
@return The offset at which the data has been put, and the result status.
func (*File) Close
¶
func (self *File) Close() *Status
Closes the file.
@return The result status.
func (self *File) Destruct()
Releases the resource explicitly.
The file is closed implicitly if it has not been closed. As long as you close the file explicitly, you don't have to call this method.
func (self *File) GetPath() (string, *Status)
Gets the path of the file.
@return The path of the file and the result status.
func (self *File) GetSize() (int64, *Status)
Gets the size of the file.
@return The size of the file and the result status.
func (*File) Open
¶
func (self *File) Open(path string, writable bool, params map[string]string) *Status
Opens a file.
@param path A path of the file.
@param writable If true, the file is writable. If false, it is read-only.
@param params Optional parameters. If it is nil, it is ignored.
@return The result status.
The optional parameters can include options for the file opening operation.
truncate (bool): True to truncate the file.
no_create (bool): True to omit file creation.
no_wait (bool): True to fail if the file is locked by another process.
no_lock (bool): True to omit file locking.
sync_hard (bool): True to do physical synchronization when closing.
The optional parameter "file" specifies the internal file implementation class. The default file class is "MemoryMapAtomicFile". The other supported classes are "StdFile", "MemoryMapAtomicFile", "PositionalParallelFile", and "PositionalAtomicFile".
For the file "PositionalParallelFile" and "PositionalAtomicFile", these optional parameters are supported.
block_size (int): The block size to which all blocks should be aligned.
access_options (str): Values separated by colon. "direct" for direct I/O. "sync" for synchrnizing I/O, "padding" for file size alignment by padding, "pagecache" for the mini page cache in the process.
func (*File) Read
¶
func (self *File) Read(off int64, size int64) ([]byte, *Status)
Reads data.
@param off The offset of a source region.
@param size The size to be read.
@return The bytes value of the read data and the result status.
func (self *File) ReadStr(off int64, size int64) (string, *Status)
Reads data as a string.
@param off The offset of a source region.
@param size The size to be read.
@return The string value of the read data and the result status.
func (self *File) Search(mode string, pattern string, capacity int) []string
Searches the file and get lines which match a pattern.
@param mode The search mode. "contain" extracts lines containing the pattern. "begin" extracts lines beginning with the pattern. "end" extracts lines ending with the pattern. "regex" extracts lines partially matches the pattern of a regular expression. "edit" extracts lines whose edit distance to the UTF-8 pattern is the least. "editbin" extracts lines whose edit distance to the binary pattern is the least. "containcase", "containword", and "containcaseword" extract keys considering case and word boundary. Ordered databases support "upper" and "lower" which extract keys whose positions are upper/lower than the pattern. "upperinc" and "lowerinc" are their inclusive versions.
@param pattern The pattern for matching.
@param capacity The maximum records to obtain. 0 means unlimited.
@return A list of lines matching the condition.
func (self *File) String() string
Makes a string representing the file.
@return The string representing the file.
func (self *File) Synchronize(hard bool, off int64, size int64) *Status
Synchronizes the content of the file to the file system.
@param hard True to do physical synchronization with the hardware or false to do only logical synchronization with the file system.
@param off The offset of the region to be synchronized.
@param size The size of the region to be synchronized. If it is zero, the length to the end of file is specified.
@return The result status.
The pysical file size can be larger than the logical size in order to improve performance by reducing frequency of allocation. Thus, you should call this function before accessing the file with external tools.
func (self *File) Truncate(size int64) *Status
Truncates the file.
@param size The new size of the file.
@return The result status.
If the file is shrunk, data after the new file end is discarded. If the file is expanded, null codes are filled after the old file end.
func (*File) Write
¶
func (self *File) Write(off int64, data interface{}) *Status
Writes data.
@param off The offset of the destination region.
@param data The data to write.
@return The result status.
Future containing a status object and extra data.
Future objects are made by methods of AsyncDBM. Every future object should be destroyed by the "Destruct" method or the "Get" method family to free resources.
type Future struct {
}
func (self *Future) Destruct()
Destructs the object and releases resources.
func (*Future) Get
¶
func (self *Future) Get() *Status
Gets the status of the operation.
@return The result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (self *Future) GetArray() ([][]byte, *Status)
Gets the extra array of byte arrays and the status of the operation.
@return An array of byte arrays and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (self *Future) GetArrayStr() ([]string, *Status)
Gets the extra array of strings and the status of the operation.
@return An array of strings and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (self *Future) GetBytes() ([]byte, *Status)
Gets the extra byte array data and the status of the operation.
@return The bytes value of the matching record and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (*Future) GetInt
¶
func (self *Future) GetInt() (int64, *Status)
Gets the extra integer data and the status of the operation.
@return The integer value and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (*Future) GetMap
¶
func (self *Future) GetMap() (map[string][]byte, *Status)
Gets the extra byte array map and the status of the operation.
@return A byte array map and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (self *Future) GetMapStr() (map[string]string, *Status)
Gets the extra string map and the status of the operation.
@return A string map and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (self *Future) GetPair() ([]byte, []byte, *Status)
Gets the extra bytes pair and the status of the operation.
@return The bytes pair and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (self *Future) GetPairStr() (string, string, *Status)
Gets the extra string pair and the status of the operation.
@return The string pair and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (*Future) GetStr
¶
func (self *Future) GetStr() (string, *Status)
Gets the extra string data and the status of the operation.
@return The string value and the result status.
The internal resource is released by this method. "Wait" and "Get" faminly cannot be called after calling this method.
func (*Future) String
¶
func (self *Future) String() string
Makes a string representing the future.
@return The string representing the future.
func (*Future) Wait
¶
func (self *Future) Wait(timeout float64) bool
Waits for the operation to be done.
@param timeout The waiting time in seconds. If it is negative, no timeout is set.
@return True if the operation has done. False if timeout occurs.
Secondary index.
All operations except for "Open" and "Close" are thread-safe; Multiple threads can access the same index concurrently. You can specify a data structure when you call the "Open" method. Every opened index must be closed explicitly by the "Close" method to avoid data corruption.
type Index struct {
}
func NewIndex() *Index
Makes a new Index object.
@return The pointer to the created index object.
func (*Index) Add
¶
func (self *Index) Add(key interface{}, value interface{}) *Status
Adds a record.
@param key The key of the record. This can be an arbitrary expression to search the index.
@param value The value of the record. This should be a primary value of another database.
@return The result status.
func (*Index) Check
¶
func (self *Index) Check(key interface{}, value interface{}) bool
Checks whether a record exists in the index.
@param key The key of the record.
@param value The value of the record.
@return True if the record exists, or false if not.
func (*Index) Clear
¶
func (self *Index) Clear() *Status
Removes all records.
@return The result status.
func (*Index) Close
¶
func (self *Index) Close() *Status
Closes the index file.
@return The result status.
func (*Index) Count
¶
func (self *Index) Count() int64
Gets the number of records.
@return The number of records, or -1 on failure.
func (self *Index) Destruct()
Releases the resource explicitly.
The index is closed implicitly if it has not been closed. As long as you close the index explicitly, you don't have to call this method.
func (self *Index) GetFilePath() string
Gets the path of the index file.
@return The path of the index file, or an empty string on failure.
func (self *Index) GetValues(key interface{}, max int) [][]byte
Gets all values of records of a key.
@param key The key of the record.
@param max The maximum number of values to get. 0 means unlimited.
func (self *Index) GetValuesStr(key interface{}, max int) []string
Gets all values of records of a key, as strings.
@param key The key of the record.
@param max The maximum number of values to get. 0 means unlimited.
func (*Index) IsOpen
¶
func (self *Index) IsOpen() bool
Checks whether the index is open.
@return True if the index is open, or false if not.
func (self *Index) IsWritable() bool
Checks whether the index is writable.
@return True if the index is writable, or false if not.
func (self *Index) MakeIterator() *IndexIterator
Makes an iterator for each record.
@return The iterator for each record.
Every iterator should be destructed explicitly by the "Destruct" method.
func (*Index) Open
¶
func (self *Index) Open(path string, writable bool, params map[string]string) *Status
Opens an index file.
@param path A path of the file.
@param writable If true, the file is writable. If false, it is read-only.
@param params Optional parameters. If it is nil, it is ignored.
@return The result status.
If the path is empty, BabyDBM is used internally, which is equivalent to using the MemIndex class. If the path ends with ".tkt", TreeDBM is used internally, which is equivalent to using the FileIndex class. If the key comparator of the tuning parameter is not set, PairLexicalKeyComparator is set implicitly. Other compatible key comparators are PairLexicalCaseKeyComparator, PairDecimalKeyComparator, PairHexadecimalKeyComparator, PairRealNumberKeyComparator, PairSignedBigEndianKeyComparator, and PairFloatBigEndianKeyComparator. Other options can be specified as with DBM::Open.
func (self *Index) Rebuild() *Status
Rebuilds the entire index.
@return The result status.
func (*Index) Remove
¶
func (self *Index) Remove(key interface{}, value interface{}) *Status
Removes a record.
@param key The key of the record. This can be an arbitrary expression to search the index.
@param value The value of the record. This should be a primary value of another database.
@return The result status.
func (*Index) String
¶
func (self *Index) String() string
Makes a string representing the index.
@return The string representing the index.
func (self *Index) Synchronize(hard bool) *Status
Synchronizes the content of the index to the file system.
@param hard True to do physical synchronization with the hardware or false to do only logical synchronization with the file system.
@return The result status.
Iterator for each record of the secondary index.
An iterator is made by the "MakeIerator" method of Index. Every unused iterator object should be destructed explicitly by the "Destruct" method to free resources.
type IndexIterator struct {
}
func (*IndexIterator) Destruct
¶
func (self *IndexIterator) Destruct()
Releases the resource explicitly.
func (*IndexIterator) First
¶
func (self *IndexIterator) First()
Initializes the iterator to indicate the first record.
func (*IndexIterator) Get
¶
func (self *IndexIterator) Get() ([]byte, []byte, bool)
Gets the key and the value of the current record of the iterator.
@return The key and the value of the current record, and a boolean status.
func (*IndexIterator) GetStr
¶
func (self *IndexIterator) GetStr() (string, string, bool)
Gets the key and the value of the current record of the iterator, as strings.
@return The key and the value of the current record, and a boolean status.
func (*IndexIterator) Jump
¶
func (self *IndexIterator) Jump(key interface{}, value interface{})
Initializes the iterator to indicate a specific range.
@param key The key of the lower bound.
@param value The value of the lower bound.
func (*IndexIterator) Last
¶
func (self *IndexIterator) Last()
Initializes the iterator to indicate the last record.
func (*IndexIterator) Next
¶
func (self *IndexIterator) Next()
Moves the iterator to the next record.
func (*IndexIterator) Previous
¶
func (self *IndexIterator) Previous()
Moves the iterator to the previous record.
func (*IndexIterator) String
¶
func (self *IndexIterator) String() string
Makes a string representing the iterator.
@return The string representing the iterator.
Iterator for each record.
An iterator is made by the "MakeIerator" method of DBM. Every unused iterator object should be destructed explicitly by the "Destruct" method to free resources.
type Iterator struct {
}
func (self *Iterator) Destruct()
Releases the resource explicitly.
func (*Iterator) First
¶
func (self *Iterator) First() *Status
Initializes the iterator to indicate the first record.
@return The result status.
Even if there's no record, the operation doesn't fail.
func (*Iterator) Get
¶
func (self *Iterator) Get() ([]byte, []byte, *Status)
Gets the key and the value of the current record of the iterator.
@return The key and the value of the current record, and the result status.
func (*Iterator) GetKey
¶
func (self *Iterator) GetKey() ([]byte, *Status)
Gets the key of the current record.
@return The key of the current record and the result status.
func (self *Iterator) GetKeyStr() (string, *Status)
Gets the key of the current record, as a string.
@return The key of the current record and the result status.
func (*Iterator) GetStr
¶
func (self *Iterator) GetStr() (string, string, *Status)
Gets the key and the value of the current record of the iterator, as strings.
@return The key and the value of the current record, and the result status.
func (self *Iterator) GetValue() ([]byte, *Status)
Gets the value of the current record.
@return The value of the current record and the result status.
func (self *Iterator) GetValueStr() (string, *Status)
Gets the value of the current record, as a string.
@return The value of the current record and the result status.
func (*Iterator) Jump
¶
func (self *Iterator) Jump(key interface{}) *Status
Initializes the iterator to indicate a specific record.
@param key The key of the record to look for.
@return The result status.
Ordered databases can support "lower bound" jump; If there's no record with the same key, the iterator refers to the first record whose key is greater than the given key. The operation fails with unordered databases if there's no record with the same key.
func (self *Iterator) JumpLower(key interface{}, inclusive bool) *Status
Initializes the iterator to indicate the last record whose key is lower than a given key.
@param key The key to compare with.
@param inclusive If true, the considtion is inclusive: equal to or lower than the key.
@return The result status.
Even if there's no matching record, the operation doesn't fail. This method is suppoerted only by ordered databases.
func (self *Iterator) JumpUpper(key interface{}, inclusive bool) *Status
Initializes the iterator to indicate the first record whose key is upper than a given key.
@param key The key to compare with.
@param inclusive If true, the considtion is inclusive: equal to or upper than the key.
@return The result status.
Even if there's no matching record, the operation doesn't fail. This method is suppoerted only by ordered databases.
func (*Iterator) Last
¶
func (self *Iterator) Last() *Status
Initializes the iterator to indicate the last record.
@return The result status.
Even if there's no record, the operation doesn't fail. This method is suppoerted only by ordered databases.
func (*Iterator) Next
¶
func (self *Iterator) Next() *Status
Moves the iterator to the next record.
@return The result status.
If the current record is missing, the operation fails. Even if there's no next record, the operation doesn't fail.
func (self *Iterator) Previous() *Status
Moves the iterator to the previous record.
@return The result status.
If the current record is missing, the operation fails. Even if there's no previous record, the operation doesn't fail. This method is suppoerted only by ordered databases.
func (*Iterator) Remove
¶
func (self *Iterator) Remove() *Status
Removes the current record.
@return The result status.
func (*Iterator) Set
¶
func (self *Iterator) Set(value interface{}) *Status
Sets the value of the current record.
@param value The value of the record.
@return The result status.
func (*Iterator) Step
¶
func (self *Iterator) Step() ([]byte, []byte, *Status)
Gets the current record and moves the iterator to the next record.
@return The key and the value of the current record, and the result status.
func (*Iterator) StepStr
¶
func (self *Iterator) StepStr() (string, string, *Status)
Gets the current record and moves the iterator to the next record, as strings.
@return The key and the value of the current record, and the result status.
func (*Iterator) String
¶
func (self *Iterator) String() string
Makes a string representing the iterator.
@return The string representing the iterator.
A pair of the key bytes and the record processor function.
type KeyBytesProcPair struct {
Key []byte
Proc RecordProcessor
}
A pair of the key and the record processor function.
type KeyProcPair struct {
Key interface{}
Proc RecordProcessor
}
A pair of the key and the value of a record.
type KeyValuePair struct {
Key []byte
Value []byte
}
A string pair of the key and the value of a record.
type KeyValueStrPair struct {
Key string
Value string
}
Function to process a record.
type RecordProcessor func(key []byte, value []byte) interface{}
Storage to make RecordProcessor accessible to the C code.
type RecordProcessorPool struct {
}
Status of operations.
type Status struct {
}
func NewStatus(args ...interface{}) *Status
Makes a new status, with variable length arguments.
@param args If the first parameter is given, it is treated as the status code. If the second parameter is given, it is treated as the status message.
@return The pointer to the created status object.
func NewStatus1(code StatusCode) *Status
Makes a new status, with a code.
@param code The status code.
@return The pointer to the created status object.
func NewStatus2(code StatusCode, message string) *Status
Makes a new status, with a code and a message.
@param code The status code.
@param code The status message.
@return The pointer to the created status object.
func RestoreDatabase(
oldFilePath string, newFilePath string, className string,
endOffset int64, cipherKey string) *Status
Restores a broken database as a new healthy database.
@param old_file_path The path of the broken database.
@param new_file_path The path of the new database to be created.
@param class_name The name of the database class. If it is nil or empty, the class is guessed from the file extension.
@param end_offset The exclusive end offset of records to read. Negative means unlimited. 0 means the size when the database is synched or closed properly. Using a positive value is not meaningful if the number of shards is more than one.
@param cipherKey The encryption key for cipher compressors.
@return The result status.
func (*Status) Equals
¶
func (self *Status) Equals(rhs interface{}) bool
Checks whether the status equal to another status.
@param rhs a status object or a status code.
@param true for the both operands are equal, or false if not.
func (*Status) Error
¶
func (self *Status) Error() string
Makes a string representing the status, to be an error.
@return The string representing the code. As the string contains only the code, comparison
of the result strings is not affected by difference of the status messages.
the additiona
func (self *Status) GetCode() StatusCode
Gets the status code.
@return The status code.
func (self *Status) GetMessage() string
Gets the status message.
@return The status message.
func (*Status) IsOK
¶
func (self *Status) IsOK() bool
Returns true if the status is success.
@return true if the status is success, or false if not.
func (*Status) Join
¶
func (self *Status) Join(rhs *Status)
Assigns the internal state from another status object only if the current state is success.
@param rhs The status object.
func (*Status) OrDie
¶
func (self *Status) OrDie()
Causes a panic if the status is not success.
func (*Status) Set
¶
func (self *Status) Set(args ...interface{})
Sets the code and the message.
@param code The status code.
@param message An arbitrary status message. If it is omitted, no message is set.
func (*Status) String
¶
func (self *Status) String() string
Makes a string representing the status.
@return The string representing the status.
Type alias for the enumeration of status codes.
type StatusCode int32
Subdirectories