Go language bindings for FoundationDB, a distributed key-value store with ACID transactions
—
The fdb package provides comprehensive Go bindings for FoundationDB, a distributed key-value store with strong ACID guarantees. This package enables Go applications to interact with FoundationDB clusters through a high-level, idiomatic Go API.
Package Path: github.com/apple/foundationdb/bindings/go/src/fdb
Supported API Versions: 200-730
Requirements:
{ .api }
func APIVersion(version int) errorSets the runtime behavior of the fdb package. Must be called before any other fdb functions. This function is thread-safe.
Parameters:
version: API version to use (200-730)Returns: Error if version is not supported
Example:
if err := fdb.APIVersion(730); err != nil {
log.Fatal(err)
}func MustAPIVersion(version int)Like APIVersion but panics on error. Convenient for initialization.
Example:
fdb.MustAPIVersion(730)func GetAPIVersion() (int, error)Returns the selected API version, or error if not yet set.
Returns:
func MustGetAPIVersion() intLike GetAPIVersion but panics if API version has not been set.
func IsAPIVersionSelected() boolChecks if API version has been selected.
Returns: true if APIVersion or MustAPIVersion has been called
{ .api }
const DefaultClusterFile string = ""Empty string constant that allows platform-appropriate default cluster file selection.
{ .api }
func OpenDefault() (Database, error)Opens database using the platform's default cluster file.
Returns:
Example:
db, err := fdb.OpenDefault()
if err != nil {
log.Fatal(err)
}
defer db.Close()func MustOpenDefault() DatabaseLike OpenDefault but panics on error.
func OpenDatabase(clusterFile string) (Database, error)Opens database with specified cluster file path.
Parameters:
clusterFile: Path to cluster file, or empty string for defaultReturns:
Note: Multiple calls with the same clusterFile return a cached database instance. Call Close() to release resources.
func MustOpenDatabase(clusterFile string) DatabaseLike OpenDatabase but panics on error.
func OpenWithConnectionString(connectionString string) (Database, error)Opens database using a connection string instead of a cluster file. Useful for short-lived connections or testing different connection strings.
Parameters:
connectionString: Non-empty connection stringReturns:
Note: Caller must call Close() to release resources.
{ .api }
type Database struct {
// contains filtered or unexported fields
}Database is a handle to a FoundationDB database. Database is lightweight, efficiently copied, and safe for concurrent use by multiple goroutines.
{ .api }
func (d Database) CreateTransaction() (Transaction, error)Creates a new transaction. Generally preferable to use Transact method which handles retries automatically.
Returns:
func (d Database) Transact(f func(Transaction) (interface{}, error)) (interface{}, error)Runs a function inside a retry loop with automatic commit. Handles retryable errors automatically.
Parameters:
f: Transactional function that receives a TransactionReturns:
fExample:
result, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
tr.Set(fdb.Key("key"), []byte("value"))
return tr.Get(fdb.Key("key")).MustGet(), nil
})Important Notes:
func (d Database) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)Runs a read-only function inside a retry loop. Transactions are not committed and are destroyed automatically.
Parameters:
f: Read-only transactional functionReturns:
fExample:
result, err := db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
return rtr.Get(fdb.Key("key")).Get()
})func (d Database) Options() DatabaseOptionsReturns a DatabaseOptions instance for setting database-specific options.
func (d Database) Close()Closes the database and cleans up resources. Must be called exactly once for each created database. Do not reuse database after closing.
func (d Database) CreateTenant(name KeyConvertible) errorCreates a new tenant in the cluster. Tenant name cannot start with \xff byte.
Parameters:
name: Tenant nameReturns: Error if tenant exists or name is invalid
func (d Database) DeleteTenant(name KeyConvertible) errorDeletes an existing tenant.
Parameters:
name: Tenant nameReturns: Error if tenant doesn't exist
func (d Database) OpenTenant(name KeyConvertible) (Tenant, error)Opens a handle to an existing tenant.
Parameters:
name: Tenant nameReturns:
func (d Database) ListTenants() ([]Key, error)Lists all existing tenants in the cluster.
Returns:
func (d Database) LocalityGetBoundaryKeys(er ExactRange, limit int, readVersion int64) ([]Key, error)Returns keys at the start of contiguous ranges stored on a single server.
Parameters:
er: Range to querylimit: Maximum keys to return (0 = unlimited)readVersion: Read version to use (0 = latest)Returns:
func (d Database) GetClientStatus() ([]byte, error)Returns JSON-formatted client status information including multi-version client details and connection status.
Returns:
func (d Database) RebootWorker(address string, checkFile bool, suspendDuration int) errorReboots a worker process at the specified address.
Parameters:
address: Process address as "IP:Port"checkFile: Whether to check data directory writabilitysuspendDuration: Suspension duration in seconds (0 = no suspension)Returns: Error if reboot request fails
{ .api }
type DatabaseOptions struct {
// contains filtered or unexported fields
}DatabaseOptions is a handle for setting options that affect a Database object.
{ .api }
func (o DatabaseOptions) SetLocationCacheSize(param int64) errorSets the size of the location cache. Default: 100000.
func (o DatabaseOptions) SetMaxWatches(param int64) errorSets the maximum number of outstanding watches. Default: 10000, Maximum: 1000000.
func (o DatabaseOptions) SetMachineId(param string) errorSets machine ID for location-aware load balancing.
func (o DatabaseOptions) SetDatacenterId(param string) errorSets datacenter ID for location-aware load balancing.
func (o DatabaseOptions) SetSnapshotRywEnable() errorEnables snapshot read-your-writes. This is the default behavior.
func (o DatabaseOptions) SetSnapshotRywDisable() errorDisables snapshot read-your-writes.
func (o DatabaseOptions) SetTransactionTimeout(param int64) errorSets transaction timeout in milliseconds for all transactions on this database.
func (o DatabaseOptions) SetTransactionRetryLimit(param int64) errorSets maximum retry count for all transactions.
func (o DatabaseOptions) SetTransactionMaxRetryDelay(param int64) errorSets maximum backoff delay in milliseconds for retries.
func (o DatabaseOptions) SetTransactionSizeLimit(param int64) errorSets transaction size limit in bytes.
func (o DatabaseOptions) SetTransactionCausalReadRisky() errorSets causal read risky mode for all transactions.
func (o DatabaseOptions) SetTransactionIncludePortInAddress() errorDeprecated: Enabled by default in API version 630+.
func (o DatabaseOptions) SetTransactionAutomaticIdempotency() errorSets random idempotency ID for all transactions on this database.
func (o DatabaseOptions) SetTransactionBypassUnreadable() errorAllows get operations on unreadable keyspace for all transactions.
func (o DatabaseOptions) SetTransactionUsedDuringCommitProtectionDisable() errorDisables operation-during-commit protection for all transactions.
func (o DatabaseOptions) SetTransactionLoggingMaxFieldLength(param int64) errorSets maximum field length for transaction logging.
func (o DatabaseOptions) SetTransactionReportConflictingKeys() errorEnables conflicting key reporting for all transactions.
func (o DatabaseOptions) SetTestCausalReadRisky(param int64) errorEnables causal read risky verification for testing.
func (o DatabaseOptions) SetUseConfigDatabase() errorUses configuration database instead of cluster file.
{ .api }
type Transaction struct {
// contains filtered or unexported fields
}Transaction is a handle to a FoundationDB transaction. It is lightweight, efficiently copied, and safe for concurrent use by multiple goroutines.
Transactions provide ACID properties: atomicity, isolation, durability, and consistency. All read and write operations see a consistent snapshot of the database. Changes only persist if the transaction commits successfully.
{ .api }
func (t Transaction) Get(key KeyConvertible) FutureByteSliceReads the value associated with a key asynchronously.
Parameters:
key: Key to readReturns: FutureByteSlice that will contain the value (or nil if key doesn't exist)
Example:
future := tr.Get(fdb.Key("mykey"))
value, err := future.Get()
if err != nil {
return err
}
if value != nil {
fmt.Printf("Value: %s\n", value)
}func (t Transaction) GetKey(sel Selectable) FutureKeyResolves a key selector to an actual key asynchronously.
Parameters:
sel: Key selector (FirstGreaterOrEqual, LastLessThan, etc.)Returns: FutureKey containing the resolved key
func (t Transaction) GetRange(r Range, options RangeOptions) RangeResultReads a range of key-value pairs asynchronously.
Parameters:
r: Range specifying begin and endoptions: Range options (limit, mode, reverse)Returns: RangeResult for iterating over key-value pairs
Example:
kr := fdb.KeyRange{Begin: fdb.Key("a"), End: fdb.Key("z")}
rangeResult := tr.GetRange(kr, fdb.RangeOptions{Limit: 100})
kvs, err := rangeResult.GetSliceWithError()
if err != nil {
return err
}
for _, kv := range kvs {
fmt.Printf("%s = %s\n", kv.Key, kv.Value)
}func (t Transaction) GetReadVersion() FutureInt64Returns the transaction's read version asynchronously.
Returns: FutureInt64 containing read version
func (t Transaction) GetVersionstamp() FutureKeyReturns the versionstamp for this transaction. Only ready after successful commit.
Returns: FutureKey containing 10-byte versionstamp
func (t Transaction) GetApproximateSize() FutureInt64Returns approximate transaction size (mutations + conflict ranges) in bytes.
Returns: FutureInt64 containing size estimate
func (t Transaction) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64Estimates the number of bytes stored in a range. More accurate for ranges larger than 3MB.
Parameters:
r: Exact range to estimateReturns: FutureInt64 containing size estimate
func (t Transaction) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArrayReturns keys that split a range into roughly equal chunks.
Parameters:
r: Range to splitchunkSize: Target chunk size in bytesReturns: FutureKeyArray containing split point keys (includes begin and end keys)
func (t Transaction) GetDatabase() DatabaseReturns the database handle associated with this transaction.
func (t Transaction) Snapshot() SnapshotReturns a Snapshot view of the transaction for snapshot reads with relaxed isolation.
Returns: Snapshot handle
Example:
snapshot := tr.Snapshot()
value := snapshot.Get(fdb.Key("key")).MustGet()func (t Transaction) GetCommittedVersion() (int64, error)Returns the version at which the transaction was committed. Must be called after successful commit.
Returns:
{ .api }
func (t Transaction) Set(key KeyConvertible, value []byte)Sets a key to a value, overwriting any previous value.
Parameters:
key: Key to setvalue: Value to storeExample:
tr.Set(fdb.Key("mykey"), []byte("myvalue"))func (t Transaction) Clear(key KeyConvertible)Removes a key and its associated value.
Parameters:
key: Key to removefunc (t Transaction) ClearRange(r ExactRange)Removes all keys in a range [begin, end). Efficient for large ranges - only begin and end keys count toward transaction size.
Parameters:
r: Range to clearExample:
kr := fdb.KeyRange{Begin: fdb.Key("a"), End: fdb.Key("z")}
tr.ClearRange(kr){ .api }
Atomic operations perform read-modify-write operations in a single command, without conflict.
func (t Transaction) Add(key KeyConvertible, param []byte)Performs atomic addition of little-endian integers. If key doesn't exist or is shorter than param, it's extended with zero bytes. If param is shorter, value is truncated.
Parameters:
key: Key to modifyparam: Little-endian integer to addExample:
// Increment counter by 1
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, 1)
tr.Add(fdb.Key("counter"), buf)func (t Transaction) BitAnd(key KeyConvertible, param []byte)Performs bitwise AND operation. If key doesn't exist, param is stored.
func (t Transaction) BitOr(key KeyConvertible, param []byte)Performs bitwise OR operation.
func (t Transaction) BitXor(key KeyConvertible, param []byte)Performs bitwise XOR operation.
func (t Transaction) Max(key KeyConvertible, param []byte)Performs little-endian comparison and stores the larger value.
func (t Transaction) Min(key KeyConvertible, param []byte)Performs little-endian comparison and stores the smaller value.
func (t Transaction) ByteMax(key KeyConvertible, param []byte)Performs lexicographic comparison and stores the larger value.
func (t Transaction) ByteMin(key KeyConvertible, param []byte)Performs lexicographic comparison and stores the smaller value.
func (t Transaction) CompareAndClear(key KeyConvertible, param []byte)Clears the key if its value equals param.
Parameters:
key: Key to conditionally clearparam: Value to compare againstfunc (t Transaction) SetVersionstampedKey(key KeyConvertible, param []byte)Transforms key using a versionstamp and sets it to param. The last 4 bytes of key specify the position where the 10-byte versionstamp will be placed.
func (t Transaction) SetVersionstampedValue(key KeyConvertible, param []byte)Sets key to a versionstamped value. The last 4 bytes of param specify the position where the 10-byte versionstamp will be placed.
func (t Transaction) AppendIfFits(key KeyConvertible, param []byte)Appends param to existing value if final size is within limits. No error is returned if value is too large - mutation silently fails.
{ .api }
func (t Transaction) Commit() FutureNilAttempts to commit the transaction. Blocks until commit completes or fails.
Returns: FutureNil that resolves to nil on success or error on failure
Example:
err := tr.Commit().Get()
if err != nil {
// Handle commit error
}func (t Transaction) OnError(e Error) FutureNilDetermines if an error is retryable. Blocks for appropriate delay if retryable, returns same error if fatal.
Parameters:
e: FDB error to checkReturns: FutureNil that resolves to nil for retryable errors or error for fatal errors
Note: Typically used by Transact method - direct use is rare.
func (t Transaction) Reset()Resets transaction to initial state. Equivalent to destroying and creating a new transaction.
func (t Transaction) Cancel()Cancels the transaction. All pending operations will fail. Transaction can be reused after Reset.
Warning: Racing Cancel with Commit has unpredictable behavior.
func (t Transaction) SetReadVersion(version int64)Sets the read version for the transaction. Cannot guarantee causal consistency.
Parameters:
version: Database version to read fromfunc (t Transaction) Transact(f func(Transaction) (interface{}, error)) (interface{}, error)Executes a function with this transaction. Does not retry or commit automatically. Allows transaction composition.
Parameters:
f: Function to executeReturns:
func (t Transaction) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)Executes a read-only function with this transaction. Does not retry.
func (t Transaction) Options() TransactionOptionsReturns TransactionOptions for setting transaction-specific options.
{ .api }
func (t Transaction) Watch(key KeyConvertible) FutureNilCreates a watch that triggers when the key's value changes. Watch is relative to this transaction's view.
Parameters:
key: Key to watchReturns: FutureNil that completes when key changes
Important Notes:
Example:
watch := tr.Watch(fdb.Key("key"))
err := tr.Commit().Get()
if err != nil {
return err
}
// Wait for key to change
err = watch.Get(){ .api }
func (t Transaction) AddReadConflictRange(er ExactRange) errorAdds a range to the transaction's read conflict ranges. Other transactions writing to this range will cause conflict.
Parameters:
er: Exact range to addReturns: Error if operation fails
func (t Transaction) AddReadConflictKey(key KeyConvertible) errorAdds a single key to read conflict ranges.
Parameters:
key: Key to addReturns: Error if operation fails
func (t Transaction) AddWriteConflictRange(er ExactRange) errorAdds a range to write conflict ranges. Other transactions reading this range will cause conflict.
func (t Transaction) AddWriteConflictKey(key KeyConvertible) errorAdds a single key to write conflict ranges.
{ .api }
func (t Transaction) LocalityGetAddressesForKey(key KeyConvertible) FutureStringSliceReturns public network addresses of storage servers responsible for a key.
Parameters:
key: Key to queryReturns: FutureStringSlice containing server addresses
{ .api }
type TransactionOptions struct {
// contains filtered or unexported fields
}TransactionOptions provides methods to set options that affect a Transaction.
{ .api }
func (o TransactionOptions) SetCausalWriteRisky() errorEnables causal write risky mode.
func (o TransactionOptions) SetCausalReadRisky() errorEnables causal read risky mode.
func (o TransactionOptions) SetCausalReadDisable() errorDisables causal read guarantees.
func (o TransactionOptions) SetReadYourWritesDisable() errorDisables read-your-writes behavior.
func (o TransactionOptions) SetReadAheadDisable() errorDisables read-ahead optimization.
func (o TransactionOptions) SetAccessSystemKeys() errorAllows reading and writing system keys (keys starting with \xff).
func (o TransactionOptions) SetReadSystemKeys() errorAllows reading system keys.
func (o TransactionOptions) SetPrioritySystemImmediate() errorSets transaction priority to system immediate (highest).
func (o TransactionOptions) SetPriorityBatch() errorSets transaction priority to batch (lowest).
func (o TransactionOptions) SetInitializeNewDatabase() errorAllows transaction to initialize a new database.
func (o TransactionOptions) SetTimeout(param int64) errorSets transaction timeout in milliseconds.
func (o TransactionOptions) SetRetryLimit(param int64) errorSets maximum number of retries.
func (o TransactionOptions) SetMaxRetryDelay(param int64) errorSets maximum backoff delay in milliseconds.
func (o TransactionOptions) SetSizeLimit(param int64) errorSets transaction size limit in bytes.
func (o TransactionOptions) SetLockAware() errorAllows transaction to read and write in locked keyspace.
func (o TransactionOptions) SetReadLockAware() errorAllows transaction to read from locked keyspace.
func (o TransactionOptions) SetDebugTransactionIdentifier(param string) errorSets debug identifier for transaction logging.
func (o TransactionOptions) SetLogTransaction() errorEnables transaction logging for debugging.
func (o TransactionOptions) SetTransactionLoggingMaxFieldLength(param int64) errorSets maximum field length for transaction logs.
func (o TransactionOptions) SetServerRequestTracing() errorEnables server-side request tracing.
func (o TransactionOptions) SetUsedDuringCommitProtectionDisable() errorDisables protection against operations during commit.
func (o TransactionOptions) SetReportConflictingKeys() errorEnables conflicting key reporting on transaction conflict.
func (o TransactionOptions) SetExpensiveClearCostEstimationEnable() errorEnables expensive clear cost estimation.
func (o TransactionOptions) SetBypassUnreadable() errorAllows get operations on unreadable keyspace.
func (o TransactionOptions) SetFirstInBatch() errorMarks transaction as first in batch.
func (o TransactionOptions) SetIdempotencyId(param [16]byte) errorSets idempotency ID for transaction deduplication.
func (o TransactionOptions) SetAutomaticIdempotency() errorEnables automatic idempotency ID generation.
func (o TransactionOptions) SetSpecialKeySpaceEnableWrites() errorEnables writes to special keyspace (required for tenant operations).
func (o TransactionOptions) SetAuthorizationToken(param string) errorSets authorization token for authentication.
{ .api }
type ReadTransaction interface {
Get(key KeyConvertible) FutureByteSlice
GetKey(sel Selectable) FutureKey
GetRange(r Range, options RangeOptions) RangeResult
GetReadVersion() FutureInt64
GetDatabase() Database
Snapshot() Snapshot
GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
Options() TransactionOptions
Cancel()
ReadTransactor
}ReadTransaction defines read-only operations available on transactions and snapshots. Both Transaction and Snapshot implement this interface.
{ .api }
type Transactor interface {
Transact(func(Transaction) (interface{}, error)) (interface{}, error)
ReadTransactor
}Transactor is implemented by Database, Transaction, and Tenant. Allows transactional functions to accept any of these types.
Example:
func updateCounter(t fdb.Transactor, key fdb.Key) error {
_, err := t.Transact(func(tr fdb.Transaction) (interface{}, error) {
val := tr.Get(key).MustGet()
count := binary.LittleEndian.Uint64(val)
count++
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, count)
tr.Set(key, buf)
return nil, nil
})
return err
}
// Can be called with Database, Transaction, or Tenant
updateCounter(db, fdb.Key("counter")){ .api }
type ReadTransactor interface {
ReadTransact(func(ReadTransaction) (interface{}, error)) (interface{}, error)
}ReadTransactor is implemented by Database, Transaction, Snapshot, and Tenant. Allows read-only transactional functions.
Example:
func getKey(rt fdb.ReadTransactor, key fdb.Key) ([]byte, error) {
result, err := rt.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
return rtr.Get(key).Get()
})
if err != nil {
return nil, err
}
return result.([]byte), nil
}{ .api }
type Tenant struct {
// contains filtered or unexported fields
}Tenant is a handle to a FoundationDB tenant. All transactions created by a tenant operate on the tenant's isolated keyspace. Tenant is lightweight, efficiently copied, and safe for concurrent use.
{ .api }
func (t Tenant) CreateTransaction() (Transaction, error)Creates a transaction in the tenant's keyspace.
Returns:
func (t Tenant) Transact(f func(Transaction) (interface{}, error)) (interface{}, error)Runs a function in a retry loop with automatic commit in tenant keyspace.
Example:
tenant, _ := db.OpenTenant(fdb.Key("my-tenant"))
result, err := tenant.Transact(func(tr fdb.Transaction) (interface{}, error) {
tr.Set(fdb.Key("key"), []byte("value"))
return nil, nil
})func (t Tenant) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)Runs a read-only function in tenant keyspace.
{ .api }
type Snapshot struct {
// contains filtered or unexported fields
}Snapshot provides snapshot reads with relaxed isolation. Snapshot reads see a consistent view of the database but don't create read conflicts, reducing transaction conflicts.
{ .api }
All read methods from ReadTransaction are available:
func (s Snapshot) Get(key KeyConvertible) FutureByteSlicePerforms snapshot read of a key.
func (s Snapshot) GetKey(sel Selectable) FutureKeyResolves key selector as snapshot read.
func (s Snapshot) GetRange(r Range, options RangeOptions) RangeResultPerforms snapshot range read.
func (s Snapshot) GetReadVersion() FutureInt64Gets read version for snapshot.
func (s Snapshot) GetDatabase() DatabaseReturns associated database handle.
func (s Snapshot) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64Estimates range size as snapshot read.
func (s Snapshot) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArrayGets split points as snapshot read.
func (s Snapshot) Snapshot() SnapshotReturns self.
func (s Snapshot) Options() TransactionOptionsReturns transaction options.
func (s Snapshot) Cancel()Cancels the underlying transaction.
func (s Snapshot) ReadTransact(f func(ReadTransaction) (interface{}, error)) (interface{}, error)Executes read-only function without retry.
Futures represent asynchronous operations. All futures provide BlockUntilReady, IsReady, and Cancel methods.
{ .api }
type Future interface {
BlockUntilReady()
IsReady() bool
Cancel()
}func (f Future) BlockUntilReady()Blocks until the future is ready (has value or error).
func (f Future) IsReady() boolReturns true if future is ready, false otherwise (non-blocking).
func (f Future) Cancel()Cancels the asynchronous operation. No effect if already ready.
{ .api }
type FutureByteSlice interface {
Get() ([]byte, error)
MustGet() []byte
Future
}Result of Get operations. Returns byte slice or nil if key doesn't exist.
func (f FutureByteSlice) Get() ([]byte, error)Blocks and returns value or error.
func (f FutureByteSlice) MustGet() []byteBlocks and returns value, panics on error.
{ .api }
type FutureKey interface {
Get() (Key, error)
MustGet() Key
Future
}Result of GetKey operations.
func (f FutureKey) Get() (Key, error)Blocks and returns key or error.
func (f FutureKey) MustGet() KeyBlocks and returns key, panics on error.
{ .api }
type FutureNil interface {
Get() error
MustGet()
Future
}Result of operations with no return value (Commit, Watch, OnError).
func (f FutureNil) Get() errorBlocks and returns error or nil on success.
func (f FutureNil) MustGet()Blocks and panics on error.
{ .api }
type FutureInt64 interface {
Get() (int64, error)
MustGet() int64
Future
}Result of operations returning int64 (GetReadVersion, GetApproximateSize, etc.).
func (f FutureInt64) Get() (int64, error)Blocks and returns int64 or error.
func (f FutureInt64) MustGet() int64Blocks and returns int64, panics on error.
{ .api }
type FutureKeyArray interface {
Get() ([]Key, error)
MustGet() []Key
Future
}Result of operations returning key arrays (GetRangeSplitPoints).
func (f FutureKeyArray) Get() ([]Key, error)Blocks and returns key array or error.
func (f FutureKeyArray) MustGet() []KeyBlocks and returns key array, panics on error.
{ .api }
type FutureStringSlice interface {
Get() ([]string, error)
MustGet() []string
Future
}Result of locality operations returning string arrays.
{ .api }
type Key []byteKey is a lexicographically-ordered byte sequence. Implements KeyConvertible.
func (k Key) FDBKey() KeyReturns self, implementing KeyConvertible.
func (k Key) String() stringReturns human-readable representation using Printable.
{ .api }
type KeyConvertible interface {
FDBKey() Key
}Types implementing KeyConvertible can be used as keys. Includes Key, tuple.Tuple, and subspace.Subspace.
{ .api }
type KeySelector struct {
Key KeyConvertible
OrEqual bool
Offset int
}KeySelector describes a key relative to another key. Used for range queries and key resolution.
func (ks KeySelector) FDBKeySelector() KeySelectorReturns self, implementing Selectable.
{ .api }
func FirstGreaterOrEqual(key KeyConvertible) KeySelectorReturns selector for the first key >= given key.
func FirstGreaterThan(key KeyConvertible) KeySelectorReturns selector for the first key > given key.
func LastLessOrEqual(key KeyConvertible) KeySelectorReturns selector for the last key <= given key.
func LastLessThan(key KeyConvertible) KeySelectorReturns selector for the last key < given key.
Example:
// Get all keys from "a" (inclusive) to "z" (exclusive)
begin := fdb.FirstGreaterOrEqual(fdb.Key("a"))
end := fdb.FirstGreaterOrEqual(fdb.Key("z"))
rangeResult := tr.GetRange(fdb.SelectorRange{begin, end}, fdb.RangeOptions{}){ .api }
type Selectable interface {
FDBKeySelector() KeySelector
}Types that can be converted to KeySelector. Implemented by KeySelector and Key (which converts to FirstGreaterOrEqual).
{ .api }
type Range interface {
FDBRangeKeySelectors() (begin, end Selectable)
}Describes a range using key selectors.
{ .api }
type ExactRange interface {
FDBRangeKeys() (begin, end KeyConvertible)
Range
}Describes a range using exact keys. All ExactRanges are also Ranges.
{ .api }
type KeyRange struct {
Begin KeyConvertible // Inclusive
End KeyConvertible // Exclusive
}Exact range specified by begin and end keys.
func (kr KeyRange) FDBRangeKeys() (KeyConvertible, KeyConvertible)Returns begin and end keys.
func (kr KeyRange) FDBRangeKeySelectors() (Selectable, Selectable)Returns FirstGreaterOrEqual selectors for begin and end.
Example:
kr := fdb.KeyRange{
Begin: fdb.Key("user/"),
End: fdb.Key("user0"),
}
kvs, _ := tr.GetRange(kr, fdb.RangeOptions{}).GetSliceWithError(){ .api }
type SelectorRange struct {
Begin Selectable
End Selectable
}Range specified by key selectors.
func (sr SelectorRange) FDBRangeKeySelectors() (Selectable, Selectable)Returns begin and end selectors.
{ .api }
func PrefixRange(prefix []byte) (KeyRange, error)Returns a KeyRange for all keys with the given prefix.
Parameters:
prefix: Key prefixReturns:
Example:
pr, _ := fdb.PrefixRange([]byte("user/"))
// Returns range ["user/", "user0"){ .api }
type RangeResult struct {
// contains filtered or unexported fields
}RangeResult is a handle to an asynchronous range read. Safe for concurrent use.
{ .api }
func (rr RangeResult) GetSliceWithError() ([]KeyValue, error)Returns all key-value pairs in the range. Blocks until all reads complete.
Returns:
func (rr RangeResult) GetSliceOrPanic() []KeyValueReturns all key-value pairs, panics on error.
func (rr RangeResult) Iterator() *RangeIteratorReturns an iterator for lazy evaluation.
Example:
ri := rangeResult.Iterator()
for ri.Advance() {
kv, err := ri.Get()
if err != nil {
return err
}
fmt.Printf("%s = %s\n", kv.Key, kv.Value)
}{ .api }
type RangeIterator struct {
// contains filtered or unexported fields
}RangeIterator iterates over key-value pairs from a range read. Should not be copied or used concurrently, but multiple iterators can be created from one RangeResult.
{ .api }
func (ri *RangeIterator) Advance() boolAdvances to next key-value pair. Must be called before each Get/MustGet.
Returns: true if more pairs exist, false if exhausted
func (ri *RangeIterator) Get() (KeyValue, error)Returns current key-value pair. Advance must have returned true.
Returns:
func (ri *RangeIterator) MustGet() KeyValueReturns current key-value pair, panics on error.
{ .api }
type RangeOptions struct {
Limit int
Mode StreamingMode
Reverse bool
}RangeOptions specifies how a range read is performed.
Fields:
Limit: Maximum key-value pairs to return (0 = unlimited)Mode: Streaming mode (default: StreamingModeIterator)Reverse: If true, iterate in reverse orderExample:
opts := fdb.RangeOptions{
Limit: 100,
Mode: fdb.StreamingModeWantAll,
Reverse: false,
}{ .api }
type StreamingMode intStreamingMode controls how range data is transferred from server to client.
{ .api }
const (
StreamingModeWantAll StreamingMode = -1 // Transfer entire range immediately
StreamingModeIterator StreamingMode = 0 // Default: balance performance
StreamingModeExact StreamingMode = 1 // Transfer exact row limit
StreamingModeSmall StreamingMode = 2 // Small batches
StreamingModeMedium StreamingMode = 3 // Medium batches
StreamingModeLarge StreamingMode = 4 // Large batches
StreamingModeSerial StreamingMode = 5 // Maximum bandwidth batches
)StreamingModeWantAll: Client intends to consume entire range. Transfers all data as early as possible.
StreamingModeIterator (default): Balances concerns. Starts with small batches, increases batch size as iteration continues.
StreamingModeExact: Requires specific row limit. Delivers exactly that many rows in one batch.
StreamingModeSmall: Small batches to minimize cost if iteration stops early.
StreamingModeMedium: Between small and large batches.
StreamingModeLarge: Large batches for high concurrency efficiency.
StreamingModeSerial: Maximum throughput batches for single client bandwidth.
{ .api }
type KeyValue struct {
Key Key
Value []byte
}KeyValue represents a single key-value pair.
{ .api }
type Error struct {
Code int
}Error represents a FoundationDB error with error code.
{ .api }
func (e Error) Error() stringReturns formatted error message with code and description.
Example:
if err != nil {
var fdbErr fdb.Error
if errors.As(err, &fdbErr) {
fmt.Printf("FDB error code: %d\n", fdbErr.Code)
}
}{ .api }
var (
ErrNetworkAlreadyStopped = errors.New("network has already been stopped")
ErrNetworkIsStopped = errors.New("network is stopped")
ErrNetworkNotStarted = errors.New("network has not been started")
ErrMultiVersionClientUnavailable = errors.New("multi-version client API is unavailable")
){ .api }
type ErrorPredicate intErrorPredicate constants for checking error properties.
{ .api }
const (
ErrorPredicateRetryable ErrorPredicate = 50000
ErrorPredicateMaybeCommitted ErrorPredicate = 50001
ErrorPredicateRetryableNotCommitted ErrorPredicate = 50002
)ErrorPredicateRetryable: Error is retryable due to transient issue.
ErrorPredicateMaybeCommitted: Transaction may have succeeded but system cannot verify.
ErrorPredicateRetryableNotCommitted: Transaction not committed but is retryable.
{ .api }
func Printable(d []byte) stringReturns human-readable representation of byte array. ASCII printable characters [32-127) pass through, others shown as \xHH.
Example:
key := []byte{0x01, 'h', 'e', 'l', 'l', 'o', 0xff}
fmt.Println(fdb.Printable(key)) // Output: \x01hello\xfffunc Strinc(prefix []byte) ([]byte, error)Returns first key outside the prefixed range. Useful for range queries.
Parameters:
prefix: Byte prefixReturns:
Example:
end, _ := fdb.Strinc([]byte("user/"))
// Returns "user0" (last byte incremented)
kr := fdb.KeyRange{
Begin: fdb.Key("user/"),
End: fdb.Key(end),
}{ .api }
func StartNetwork() errorDeprecated: Network starts automatically when database is opened. Does nothing but ensures API version is set.
func StopNetwork() errorSignals network event loop to terminate and waits for completion. Thread-safe.
Returns: Error if network not started or already stopped
Example:
// At application shutdown
if err := fdb.StopNetwork(); err != nil {
log.Printf("Error stopping network: %v", err)
}func Options() NetworkOptionsReturns a NetworkOptions instance for setting network-level options. These options must be set before opening any databases.
Returns: NetworkOptions handle for configuring the network
Example:
// Configure network options before opening database
fdb.MustAPIVersion(730)
// Enable trace logging
if err := fdb.Options().SetTraceEnable("/var/log/fdb-traces"); err != nil {
log.Fatal(err)
}
// Set trace format to JSON
if err := fdb.Options().SetTraceFormat("json"); err != nil {
log.Fatal(err)
}
// Configure TLS
if err := fdb.Options().SetTLSCertPath("/path/to/cert.pem"); err != nil {
log.Fatal(err)
}
if err := fdb.Options().SetTLSKeyPath("/path/to/key.pem"); err != nil {
log.Fatal(err)
}
// Now open database
db := fdb.MustOpenDefault()
defer db.Close()Important: Network options must be set before calling any database opening functions (OpenDefault, OpenDatabase, etc.).
{ .api }
type Cluster struct {
// contains filtered or unexported fields
}Deprecated: Use OpenDatabase or OpenDefault to obtain database handles directly.
func CreateCluster(clusterFile string) (Cluster, error)Returns cluster handle. Use OpenDatabase instead.
func (c Cluster) OpenDatabase(dbName []byte) (Database, error)Opens database from cluster. Database name must be []byte("DB"). Use fdb.OpenDatabase instead.
{ .api }
type NetworkOptions struct {
// contains filtered or unexported fields
}NetworkOptions is a handle for setting options that affect the entire FoundationDB client network. These options must be set before opening any databases.
{ .api }
func (o NetworkOptions) SetTraceEnable(param string) errorEnables trace output to a file in a directory of the client's choosing.
Parameters:
param: Path to output directory (or empty string for current working directory)func (o NetworkOptions) SetTraceRollSize(param int64) errorSets the maximum size in bytes of a single trace output file. Range: [0, INT64_MAX]. Default: 10,485,760 bytes.
func (o NetworkOptions) SetTraceMaxLogsSize(param int64) errorSets the maximum size of all trace output files combined. Range: [0, INT64_MAX]. Default: 104,857,600 bytes.
func (o NetworkOptions) SetTraceLogGroup(param string) errorSets the 'LogGroup' attribute for all events in trace output. Default: "default".
func (o NetworkOptions) SetTraceFormat(param string) errorSelects the format of log files. Supported: "xml" (default), "json".
func (o NetworkOptions) SetTraceClockSource(param string) errorSelects clock source for trace files. Supported: "now" (default), "realtime".
func (o NetworkOptions) SetTraceFileIdentifier(param string) errorString used to replace the port/PID in log file names.
func (o NetworkOptions) SetTraceShareAmongClientThreads() errorUses the same base trace file name for all client threads (pre-7.2 behavior).
func (o NetworkOptions) SetTraceInitializeOnSetup() errorInitializes trace files on network setup. Otherwise tracing starts when opening first database.
func (o NetworkOptions) SetTracePartialFileSuffix(param string) errorSets file suffix for partially written log files. Include separator if adding extension (e.g., ".tmp").
func (o NetworkOptions) SetTLSCertBytes(param []byte) errorSets the certificate chain from bytes.
func (o NetworkOptions) SetTLSCertPath(param string) errorSets the file path from which to load the certificate chain.
func (o NetworkOptions) SetTLSKeyBytes(param []byte) errorSets the private key corresponding to your certificate from bytes.
func (o NetworkOptions) SetTLSKeyPath(param string) errorSets the file path from which to load the private key.
func (o NetworkOptions) SetTLSVerifyPeers(param []byte) errorSets the peer certificate field verification criteria.
func (o NetworkOptions) SetTLSCaBytes(param []byte) errorSets the CA bundle from bytes.
func (o NetworkOptions) SetTLSCaPath(param string) errorSets the file path from which to load the CA bundle.
func (o NetworkOptions) SetTLSPassword(param string) errorSets the password for encrypted private key.
func (o NetworkOptions) SetKnob(param string) errorSets internal tuning or debugging knobs. Format: "knob_name=knob_value".
func (o NetworkOptions) SetDisableMultiVersionClientApi() errorDisables the multi-version client API and only uses the current version.
func (o NetworkOptions) SetCallbacksOnExternalThreads() errorAllows network callbacks to be called on external threads.
func (o NetworkOptions) SetExternalClientLibrary(param string) errorAdds an external client library for multi-version support.
Parameters:
param: Path to client library or linker-resolved namefunc (o NetworkOptions) SetExternalClientDirectory(param string) errorSearches for client libraries in the specified directory for multi-version support.
func (o NetworkOptions) SetDisableLocalClient() errorPrevents connections through the local client.
func (o NetworkOptions) SetClientThreadsPerVersion(param int64) errorSets the number of client threads per version.
func (o NetworkOptions) SetFutureVersionClientLibrary(param string) errorAdds a future version client library for testing.
func (o NetworkOptions) SetRetainClientLibraryCopies() errorPrevents cleanup of client library copies loaded by the multi-version client.
func (o NetworkOptions) SetIgnoreExternalClientFailures() errorIgnores failures to load external client libraries.
func (o NetworkOptions) SetFailIncompatibleClient() errorFails when encountering an incompatible client library.
func (o NetworkOptions) SetDisableClientStatisticsLogging() errorDisables logging of client statistics.
func (o NetworkOptions) SetEnableRunLoopProfiling() errorEnables run loop profiling for performance analysis.
func (o NetworkOptions) SetDisableClientBypass() errorDisables client-side bypass optimization.
func (o NetworkOptions) SetDistributedClientTracer(param string) errorSets the tracer type for distributed tracing.
func (o NetworkOptions) SetClientTmpDir(param string) errorSets the temporary directory for client use.
func (o NetworkOptions) SetBuggifyEnable() errorEnables buggify for testing. Not yet fully implemented.
func (o NetworkOptions) SetBuggifyDisable() errorDisables buggify. Not yet fully implemented.
func (o NetworkOptions) SetBuggifySectionActivatedProbability(param int64) errorSets probability (0-100) of a BUGGIFY section being active.
func (o NetworkOptions) SetBuggifySectionFiredProbability(param int64) errorSets probability (0-100) of an active BUGGIFY section being fired.
func (o NetworkOptions) SetClientBuggifyEnable() errorEnables client-side buggify for testing.
func (o NetworkOptions) SetClientBuggifyDisable() errorDisables client-side buggify.
func (o NetworkOptions) SetClientBuggifySectionActivatedProbability(param int64) errorSets probability (0-100) for client buggify section activation.
func (o NetworkOptions) SetClientBuggifySectionFiredProbability(param int64) errorSets probability (0-100) for client buggify section firing.
func (o NetworkOptions) SetLocalAddress(param string) errorDeprecated. Sets local address in "IP:PORT" format.
func (o NetworkOptions) SetClusterFile(param string) errorDeprecated. Sets path to cluster file.
func (o NetworkOptions) SetTLSPlugin(param string) errorDeprecated. Sets TLS plugin file path or linker-resolved name.
func (o NetworkOptions) SetEnableSlowTaskProfiling() errorDeprecated. Enables slow task profiling.
fdb.MustAPIVersion(730)
db := fdb.MustOpenDefault()
defer db.Close()
// Write and read
_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
tr.Set(fdb.Key("hello"), []byte("world"))
value := tr.Get(fdb.Key("hello")).MustGet()
fmt.Printf("Value: %s\n", value)
return nil, nil
})
if err != nil {
log.Fatal(err)
}_, err := db.ReadTransact(func(rtr fdb.ReadTransaction) (interface{}, error) {
kr := fdb.KeyRange{
Begin: fdb.Key("user/"),
End: fdb.Key("user0"),
}
ri := rtr.GetRange(kr, fdb.RangeOptions{Limit: 100}).Iterator()
for ri.Advance() {
kv := ri.MustGet()
fmt.Printf("%s = %s\n", kv.Key, kv.Value)
}
return nil, nil
})import "encoding/binary"
func incrementCounter(db fdb.Database, key fdb.Key) error {
_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
// Atomic increment by 1
buf := make([]byte, 8)
binary.LittleEndian.PutUint64(buf, 1)
tr.Add(key, buf)
return nil, nil
})
return err
}_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
watch := tr.Watch(fdb.Key("config"))
// Commit must succeed for watch to be active
if err := tr.Commit().Get(); err != nil {
return nil, err
}
// Wait for change (in separate goroutine in real code)
go func() {
err := watch.Get()
if err != nil {
log.Printf("Watch failed: %v", err)
} else {
log.Println("Config changed!")
}
}()
return nil, nil
})// Create tenant
if err := db.CreateTenant(fdb.Key("tenant-1")); err != nil {
log.Fatal(err)
}
// Open tenant
tenant, err := db.OpenTenant(fdb.Key("tenant-1"))
if err != nil {
log.Fatal(err)
}
// Use tenant (isolated keyspace)
_, err = tenant.Transact(func(tr fdb.Transaction) (interface{}, error) {
tr.Set(fdb.Key("data"), []byte("tenant data"))
return nil, nil
})_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
// Regular read - creates read conflict
value1 := tr.Get(fdb.Key("key1")).MustGet()
// Snapshot read - no read conflict
snapshot := tr.Snapshot()
value2 := snapshot.Get(fdb.Key("key2")).MustGet()
// Write based on both values
tr.Set(fdb.Key("result"), append(value1, value2...))
return nil, nil
})_, err := db.Transact(func(tr fdb.Transaction) (interface{}, error) {
// Add explicit read conflict
kr := fdb.KeyRange{
Begin: fdb.Key("protected/"),
End: fdb.Key("protected0"),
}
if err := tr.AddReadConflictRange(kr); err != nil {
return nil, err
}
// Other transactions writing to protected/ will cause conflict
tr.Set(fdb.Key("data"), []byte("value"))
return nil, nil
})errors.As() for FDB errorsInstall with Tessl CLI
npx tessl i tessl/golang-github-com-apple-foundationdb-bindings-go