Documentation
¶
Overview ¶
Package fdb provides a pure-Go client for FoundationDB.
This package is API-compatible with the official Apple FDB Go binding (fdb.dev/pkg/fdbgo/fdb) but requires no C library (libfdb_c). It uses a native Go wire protocol implementation.
Basic usage:
fdb.MustAPIVersion(730)
db := fdb.MustOpenDefault()
defer db.Close()
ret, err := db.Transact(func(tr fdb.WritableTransaction) (interface{}, error) {
tr.Set(fdb.Key("hello"), []byte("world"))
return tr.Get(fdb.Key("foo")).MustGet(), nil
})
Known behavioral differences from the Apple C binding:
- Error messages: Error.Error() returns "FoundationDB error: <code>" rather than the human-readable description from libfdb_c. Use Error.Code for programmatic matching.
- Future.Cancel() is a no-op — the underlying operation runs to completion.
- No per-transaction context.Context: matching the Apple binding, methods like Get/GetRange do not accept a context parameter. Use SetTimeout for deadlines, or call Cancel() from another goroutine for cancellation. context.Background() is used internally for all operations.
- No internal max-retry / connection timeout. Unlike libfdb_c (which bounds connection attempts with its own timeouts), this client retries cluster connection and transaction onError indefinitely until the caller's context.Context is cancelled. A bare Transact / OpenDatabase against a down or unreachable cluster therefore BLOCKS until ctx cancels — and the no-context Transact uses context.Background() (never cancels). Migrators MUST bound it: pass a deadline ctx to TransactCtx / OpenDatabaseFromConfig, and/or set a transaction SetTimeout. This is the single biggest behavioral difference for an operator (RFC-110/RFC-111 P1.5).
Index ¶
- func APIVersion(version int) error
- func GetAPIVersion() (int, error)
- func IsAPIVersionSelected() bool
- func IsOnErrorRetryable(code int) bool
- func IsRetryable(code int) bool
- func MustAPIVersion(version int)
- func MustGetAPIVersion() int
- func Printable(b []byte) string
- func StartNetwork() error
- func StopNetwork() error
- func Strinc(prefix []byte) ([]byte, error)
- type BackendDatabase
- type CtxReadTransactor
- type CtxTransactor
- type Database
- func MustOpen(clusterFile string, _ []byte) Database
- func MustOpenDatabase(clusterFile string) Database
- func MustOpenDefault() Database
- func Open(clusterFile string, _ []byte) (Database, error)
- func OpenDatabase(clusterFile string, opts ...Option) (Database, error)
- func OpenDatabaseFromConfig(ctx context.Context, cf *client.ClusterFile, opts ...Option) (Database, error)
- func OpenDefault() (Database, error)
- func OpenWithConnectionString(connStr string, opts ...Option) (Database, error)
- func WrapDatabase(db *client.Database) Database
- func (db Database) Close()
- func (db Database) CreateTenant(name KeyConvertible) error
- func (db Database) CreateTransaction() (Transaction, error)
- func (db Database) CreateWritableTransaction() (WritableTransaction, error)
- func (db Database) DeleteTenant(name KeyConvertible) error
- func (db Database) GetClientStatus() ([]byte, error)
- func (db Database) HedgeEnabled() bool
- func (db Database) InvalidateGRVCache()
- func (db Database) IsValid() bool
- func (db Database) ListTenants() ([]Key, error)
- func (db Database) LocalityGetBoundaryKeys(r ExactRange, limit int, readVersion int64) ([]Key, error)
- func (db Database) OpenTenant(name KeyConvertible) (Tenant, error)
- func (db Database) OpenTenantById(id int64) Tenant
- func (db Database) Options() DatabaseOptions
- func (db Database) ReadTransact(f func(ReadTransaction) (any, error)) (any, error)
- func (db Database) ReadTransactCtx(ctx context.Context, f func(ReadTransaction) (any, error)) (any, error)
- func (db Database) RebootWorker(_ string, _ bool, _ int) error
- func (db Database) SetHedgeEnabled(enabled bool)
- func (db Database) Transact(f func(WritableTransaction) (any, error)) (any, error)
- func (db Database) TransactCtx(ctx context.Context, f func(WritableTransaction) (any, error)) (any, error)
- type DatabaseOptions
- func (o DatabaseOptions) SetDatacenterId(_ string) error
- func (o DatabaseOptions) SetLocationCacheSize(_ int64) error
- func (o DatabaseOptions) SetMachineId(_ string) error
- func (o DatabaseOptions) SetMaxWatches(n int64) error
- func (o DatabaseOptions) SetReadSystemKeys() error
- func (o DatabaseOptions) SetSnapshotRywDisable() error
- func (o DatabaseOptions) SetSnapshotRywEnable() error
- func (o DatabaseOptions) SetTestCausalReadRisky(_ int64) error
- func (o DatabaseOptions) SetTransactionAutomaticIdempotency() error
- func (o DatabaseOptions) SetTransactionBypassUnreadable() error
- func (o DatabaseOptions) SetTransactionCausalReadRisky() error
- func (o DatabaseOptions) SetTransactionIncludePortInAddress() error
- func (o DatabaseOptions) SetTransactionLoggingMaxFieldLength(_ int64) error
- func (o DatabaseOptions) SetTransactionMaxRetryDelay(ms int64) error
- func (o DatabaseOptions) SetTransactionReportConflictingKeys() error
- func (o DatabaseOptions) SetTransactionRetryLimit(retries int64) error
- func (o DatabaseOptions) SetTransactionSizeLimit(bytes int64) error
- func (o DatabaseOptions) SetTransactionTimeout(ms int64) error
- func (o DatabaseOptions) SetTransactionUsedDuringCommitProtectionDisable() error
- func (o DatabaseOptions) SetUseConfigDatabase() error
- type Error
- type ExactRange
- type Future
- type FutureByteSlice
- type FutureInt64
- type FutureKey
- type FutureKeyArray
- type FutureNil
- type FutureStringSlice
- type Key
- type KeyConvertible
- type KeyRange
- type KeySelector
- type KeyValue
- type Option
- type Range
- type RangeIterator
- type RangeOptions
- type RangeResult
- type ReadTransaction
- type ReadTransactor
- type Selectable
- type SelectorRange
- type Snapshot
- func (sn Snapshot) Cancel()
- func (sn Snapshot) Get(key KeyConvertible) FutureByteSlice
- func (sn Snapshot) GetDatabase() Database
- func (sn Snapshot) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
- func (sn Snapshot) GetKey(sel Selectable) FutureKey
- func (sn Snapshot) GetRange(r Range, options RangeOptions) RangeResult
- func (sn Snapshot) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
- func (sn Snapshot) GetReadVersion() FutureInt64
- func (sn Snapshot) Options() TransactionOptions
- func (sn Snapshot) ReadTransact(f func(ReadTransaction) (any, error)) (any, error)
- func (sn Snapshot) Snapshot() ReadTransaction
- type StreamingMode
- type Tenant
- func (t Tenant) CreateTransaction() (Transaction, error)
- func (t Tenant) ID() int64
- func (t Tenant) ReadTransact(f func(ReadTransaction) (any, error)) (any, error)
- func (t Tenant) ReadTransactCtx(ctx context.Context, f func(ReadTransaction) (any, error)) (any, error)
- func (t Tenant) Transact(f func(WritableTransaction) (any, error)) (any, error)
- func (t Tenant) TransactCtx(ctx context.Context, f func(WritableTransaction) (any, error)) (any, error)
- type TenantOptionError
- type Transaction
- func (tr Transaction) Add(key KeyConvertible, param []byte)
- func (tr Transaction) AddBytes(key, param []byte)
- func (tr Transaction) AddReadConflictKey(key KeyConvertible) error
- func (tr Transaction) AddReadConflictRange(er ExactRange) error
- func (tr Transaction) AddWriteConflictKey(key KeyConvertible) error
- func (tr Transaction) AddWriteConflictRange(er ExactRange) error
- func (tr Transaction) And(key KeyConvertible, param []byte)
- func (tr Transaction) AppendIfFits(key KeyConvertible, param []byte)
- func (tr Transaction) BitAnd(key KeyConvertible, param []byte)
- func (tr Transaction) BitOr(key KeyConvertible, param []byte)
- func (tr Transaction) BitXor(key KeyConvertible, param []byte)
- func (tr Transaction) ByteMax(key KeyConvertible, param []byte)
- func (tr Transaction) ByteMin(key KeyConvertible, param []byte)
- func (tr Transaction) Cancel()
- func (tr Transaction) Clear(key KeyConvertible)
- func (tr Transaction) ClearBytes(key []byte)
- func (tr Transaction) ClearRange(er ExactRange)
- func (tr Transaction) Commit() FutureNil
- func (tr Transaction) CompareAndClear(key KeyConvertible, param []byte)
- func (tr Transaction) CompareAndClearBytes(key, param []byte)
- func (tr Transaction) CreateTenant(name KeyConvertible) error
- func (tr Transaction) DeleteTenant(name KeyConvertible) error
- func (tr Transaction) Get(key KeyConvertible) FutureByteSlice
- func (tr Transaction) GetApproximateSize() FutureInt64
- func (tr Transaction) GetCommittedVersion() (int64, error)
- func (tr Transaction) GetDatabase() Database
- func (tr Transaction) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
- func (tr Transaction) GetKey(sel Selectable) FutureKey
- func (tr Transaction) GetRange(r Range, options RangeOptions) RangeResult
- func (tr Transaction) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
- func (tr Transaction) GetReadVersion() FutureInt64
- func (tr Transaction) GetVersionstamp() FutureKey
- func (tr Transaction) ListTenants() ([]Key, error)
- func (tr Transaction) LocalityGetAddressesForKey(key KeyConvertible) FutureStringSlice
- func (tr Transaction) Max(key KeyConvertible, param []byte)
- func (tr Transaction) MaxBytes(key, param []byte)
- func (tr Transaction) Min(key KeyConvertible, param []byte)
- func (tr Transaction) MinBytes(key, param []byte)
- func (tr Transaction) OnError(e Error) FutureNil
- func (tr Transaction) Options() TransactionOptions
- func (tr Transaction) Or(key KeyConvertible, param []byte)
- func (tr Transaction) ReadTransact(f func(ReadTransaction) (any, error)) (r any, e error)
- func (tr Transaction) Reset()
- func (tr Transaction) Set(key KeyConvertible, value []byte)
- func (tr Transaction) SetBytes(key, value []byte)
- func (tr Transaction) SetReadVersion(version int64)
- func (tr Transaction) SetVersionstampedKey(key KeyConvertible, param []byte)
- func (tr Transaction) SetVersionstampedValue(key KeyConvertible, param []byte)
- func (tr Transaction) Snapshot() ReadTransaction
- func (tr Transaction) Transact(f func(WritableTransaction) (any, error)) (r any, e error)
- func (tr Transaction) Watch(key KeyConvertible) FutureNil
- func (tr Transaction) Xor(key KeyConvertible, param []byte)
- type TransactionOptions
- type Transactor
- type UnsupportedOptionError
- type WritableTransaction
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIVersion ¶
APIVersion must be called before any other fdb function. It selects the FDB API version to use. The pure Go client supports a broad range of API versions but does not enforce version-specific behavior differences.
func GetAPIVersion ¶
GetAPIVersion returns the API version that has been selected, or 0 if none has been selected.
func IsAPIVersionSelected ¶
func IsAPIVersionSelected() bool
IsAPIVersionSelected reports whether an API version has been selected. Mirrors the Apple binding's fdb.IsAPIVersionSelected so callers can branch on it without catching the api_version_unset error.
func IsOnErrorRetryable ¶
IsOnErrorRetryable reports whether fdb_transaction_on_error retries `code` (i.e. resets the transaction and backs off, rather than re-raising it terminal). This is a DIFFERENT, larger set than IsRetryable (the fdb_error_predicate RETRYABLE set): OnError additionally retries blob_granule_request_failed (1079) — retried by C++ Transaction::onError (NativeAPI.actor.cpp:7743-7768) but absent from the error-predicate set — plus the Go extensions the pure-Go client documents (cluster_version_changed 1039 via the MVC layer, the Go-internal 1200, and 7.4+ 1235/1242).
MUST stay in sync with the pure-Go client's onErrorRetryable (client/commitpath.go:231), which is the same set; both trace to C++ Transaction::onError + the documented MVC/Go extensions. The duplication is forced: the cgo backend can't import client (fdb imports client, so client can't import fdb), and this is the predicate that decides whether a libfdb_c OnError has a backoff worth ctx-bounding. Verified by TestIsOnErrorRetryable.
func IsRetryable ¶
IsRetryable reports whether the given FDB error code is retryable per FDB's `fdb_error_predicate(FDB_ERROR_PREDICATE_RETRYABLE, code)`.
RETRYABLE = MAYBE_COMMITTED ∪ RETRYABLE_NOT_COMMITTED.
Source of truth: bindings/c/fdb_c.cpp (function fdb_error_predicate). The set is intentionally small — most 1xxx codes are NOT retryable, despite the surrounding range being "Normal failures". Anything 2xxx+ (client error, API misuse, tenant/cluster errors, tuple/directory errors, backup errors, auth errors, internal bugs) is non-retryable.
NOTE: transaction_timed_out (1031) is explicitly NOT retryable (matches C++ Transaction::onError, where a timed-out transaction propagates the error without resetting / retrying).
func MustAPIVersion ¶
func MustAPIVersion(version int)
MustAPIVersion is a convenience function equivalent to APIVersion that panics on error. Matches Apple's fdb.MustAPIVersion.
func MustGetAPIVersion ¶
func MustGetAPIVersion() int
MustGetAPIVersion returns the selected API version, panicking if none has been selected. Mirrors the Apple binding's fdb.MustGetAPIVersion.
func Printable ¶
Printable returns a human-readable representation of a byte slice, replacing non-printable characters with \x## escapes.
func StartNetwork ¶
func StartNetwork() error
StartNetwork is a no-op (see the package note above). Returns nil.
func StopNetwork ¶
func StopNetwork() error
StopNetwork is a no-op (see the package note above). Returns nil.
Types ¶
type BackendDatabase ¶
type BackendDatabase interface {
Transactor
// CreateWritableTransaction creates a standalone, non-retry transaction. The
// caller owns its lifecycle (commit / cancel); the underlying handle is
// GC-finalized on both backends.
CreateWritableTransaction() (WritableTransaction, error)
// LocalityGetBoundaryKeys returns the shard boundary keys within r (a read of
// the \xff/keyServers system range). readVersion 0 = use the latest.
LocalityGetBoundaryKeys(r ExactRange, limit int, readVersion int64) ([]Key, error)
Close()
}
BackendDatabase is the minimal database surface the record layer needs to drive its Run / RunRead path on any backend: the Transactor interface (which already takes the WritableTransaction / ReadTransaction interfaces, not the concrete pure-Go types) plus Close. The pure-Go Database satisfies it; the libfdb_c backend (pkg/fdbgo/libfdbc) provides an alternative implementation over cgofdb.
Which implementation a binary carries is a BUILD-time choice (a build tag), not a runtime one — see pkg/internal/fdbclient. That mirrors the physical reality: libfdb_c's network thread is initialized once per process and is unrecoverable, so there is no live switch between backends anyway.
It also exposes CreateWritableTransaction, which returns a standalone (non-retry) transaction as the WritableTransaction INTERFACE — the backend-agnostic analog of the pure-Go Database.CreateTransaction (which returns the concrete pure-Go type). The record layer needs a long-lived transaction handle for database/sql explicit transactions (BeginTx / COMMIT), which span multiple driver calls and so cannot use the closure-based Transactor gold path. libfdb_c can create transactions just as well as the pure-Go client (it does so internally for its own Transact loop) — exposing it here is what makes BeginTx work on either backend, rather than the SQL engine being silently pure-Go-only. (CGo-allocated transactions are GC-finalized by Apple's binding, exactly like the pure-Go ones, so the caller manages no extra lifecycle.)
It also exposes LocalityGetBoundaryKeys (FDB shard boundaries), which the online MUTUAL indexer uses to partition the keyspace into fragments for concurrent building. Like a transaction creation, libfdb_c can do this — it's a read of the \xff/keyServers system range, identical bytes on either client — so exposing it here makes mutual indexing parallel on libfdb_c instead of degrading to a single fragment.
It deliberately still does NOT include tenant ops: those return concrete pure-Go handles a cgo backend cannot build and remain pure-Go-only in v1.
type CtxReadTransactor ¶
type CtxReadTransactor interface {
ReadTransactCtx(ctx context.Context, f func(ReadTransaction) (any, error)) (any, error)
}
CtxReadTransactor is the read-side analog of CtxTransactor (bounds the read-retry loop + backoff by the caller context).
type CtxTransactor ¶
type CtxTransactor interface {
TransactCtx(ctx context.Context, f func(WritableTransaction) (any, error)) (any, error)
}
CtxTransactor is an OPTIONAL capability: a Transactor whose retry loop, backoff, and reads are bounded by a caller context. Database and Tenant implement it; recordlayer.Run type-asserts for it and falls back to Transact otherwise (so the Transactor interface stays unwidened and Transaction — which has no retry loop — needs no meaningless TransactCtx). Per RFC-090 the dispatched commit and its commit_unknown_result barrier deliberately run on a DETACHED context, so the caller's ctx never cancels an in-flight commit (which is already bounded by the per-RPC timeout).
type Database ¶
type Database struct {
// contains filtered or unexported fields
}
Database is a handle to a FoundationDB database. Database is safe for concurrent use by multiple goroutines.
func MustOpenDatabase ¶
MustOpenDatabase opens a database or panics.
func MustOpenDefault ¶
func MustOpenDefault() Database
MustOpenDefault opens the default database or panics.
func OpenDatabase ¶
OpenDatabase opens a connection using the specified cluster file path. APIVersion must have been called first. See WithTLSConfig / WithDialFunc.
Bootstrap is bounded by an internal default timeout (bootstrapContext). There is NO internal max-retry beyond that for the live database: unlike libfdb_c, once open the client retries cluster reconnection indefinitely until the caller's context cancels. Against a permanently down cluster a subsequent bare Transact (which uses context.Background()) blocks forever — bound it with TransactCtx or a transaction SetTimeout (RFC-111 P1.5; see the package doc). Use OpenDatabaseFromConfig to pass a context for bootstrap itself.
func OpenDatabaseFromConfig ¶
func OpenDatabaseFromConfig(ctx context.Context, cf *client.ClusterFile, opts ...Option) (Database, error)
OpenDatabaseFromConfig creates a Database from a client.ClusterFile. The provided ctx is used only for the initial bootstrap (coordinator connection); if it has no deadline, bootstrap is bounded by defaultBootstrapTimeout so an unreachable cluster fails fast instead of hanging forever. The Database uses context.Background() for ongoing operations.
func OpenDefault ¶
OpenDefault opens the database at the default cluster file (/etc/foundationdb/fdb.cluster).
func OpenWithConnectionString ¶
OpenWithConnectionString opens a connection using a cluster connection string (e.g., "description:id@host1:port1,host2:port2").
func WrapDatabase ¶
WrapDatabase wraps an existing client.Database as an fdb.Database. This is useful when code already has a client.Database handle and needs to use the fdb facade layer (e.g., for the directory layer).
func (Database) CreateTenant ¶
func (db Database) CreateTenant(name KeyConvertible) error
CreateTenant creates a new tenant. Writes to system keys (\xff/tenant/*) matching C++ TenantAPI::createTenantTransaction.
func (Database) CreateTransaction ¶
func (db Database) CreateTransaction() (Transaction, error)
CreateTransaction creates a new Transaction. Database-level option defaults set via Options() (SetTransactionTimeout / SetTransactionRetryLimit / …) are applied to it — matching libfdb_c, where the database transaction defaults are copied into every transaction the database creates. The transaction is bound to context.Background() (no Go-context cancellation — Apple-binding parity); drive its retries with OnError and override an inherited default per-transaction via SetTimeout / SetRetryLimit. For Go-context cancellation, prefer TransactCtx / ReadTransactCtx over a manual CreateTransaction loop.
func (Database) CreateWritableTransaction ¶
func (db Database) CreateWritableTransaction() (WritableTransaction, error)
CreateWritableTransaction satisfies fdb.BackendDatabase: the standalone- transaction creator returning the WritableTransaction interface. On the pure-Go client it is exactly CreateTransaction (the concrete Transaction already implements WritableTransaction); it exists so the record layer can create a standalone transaction on ANY backend (the libfdb_c backend implements the same method over cgofdb).
func (Database) DeleteTenant ¶
func (db Database) DeleteTenant(name KeyConvertible) error
DeleteTenant deletes a tenant. Writes to system keys (\xff/tenant/*).
func (Database) GetClientStatus ¶
GetClientStatus returns a JSON blob with client connection status. Provides basic connectivity info — not the full FDB status JSON.
func (Database) HedgeEnabled ¶
HedgeEnabled returns whether speculative second requests are active.
func (Database) InvalidateGRVCache ¶
func (db Database) InvalidateGRVCache()
InvalidateGRVCache forces the next transaction to fetch a fresh read version from the GRV proxy instead of using the cached version. Use after external writes (e.g., from a Java conformance server) to ensure Go reads see them.
func (Database) IsValid ¶
IsValid reports whether the Database is a live handle (non-zero). A zero Database{} is what an FDBDatabase constructed on a non-pure-Go backend carries in its concrete-db slot; the record layer checks this before using the pure-Go-only CreateTransaction / Locality paths.
func (Database) ListTenants ¶
ListTenants lists all tenants by scanning the name index.
func (Database) LocalityGetBoundaryKeys ¶
func (db Database) LocalityGetBoundaryKeys(r ExactRange, limit int, readVersion int64) ([]Key, error)
LocalityGetBoundaryKeys returns shard boundary keys within the given range.
It honors readVersion (RFC-111 P1.6): boundary keys live in the \xFF/keyServers/<key> system range, and reading that range AT the supplied read version yields MVCC-consistent boundaries — pinning the result to a snapshot rather than returning whatever the location cache holds now. readVersion == 0 means "use a fresh read version" (a normal GRV). This is a 1:1 port of the Apple binding's LocalityGetBoundaryKeys.
func (Database) OpenTenant ¶
func (db Database) OpenTenant(name KeyConvertible) (Tenant, error)
OpenTenant opens a tenant by name. Reads the tenant ID from the system key name index (\xff/tenant/nameIndex/<name>).
func (Database) OpenTenantById ¶
OpenTenantById opens a tenant by its numeric ID. All operations on the returned Tenant are scoped to the tenant's key space. The caller is responsible for ensuring the tenant ID is valid.
func (Database) Options ¶
func (db Database) Options() DatabaseOptions
Options returns a DatabaseOptions handle for setting database-level defaults.
func (Database) ReadTransact ¶
ReadTransact runs a read-only transactional function with automatic retry. Like Transact, this is the Apple-binding-compatible no-ctx form: no Go-context cancellation, retries bounded only by SetTransactionTimeout / SetTransactionRetryLimit (default unbounded, matching libfdb_c). Use ReadTransactCtx for Go-context cancellation/deadline (RFC-090).
func (Database) ReadTransactCtx ¶
func (db Database) ReadTransactCtx(ctx context.Context, f func(ReadTransaction) (any, error)) (any, error)
ReadTransactCtx is ReadTransact bounded by ctx (RFC-090 / fdb.CtxReadTransactor): ctx bounds the read-retry loop and backoff.
func (Database) RebootWorker ¶
RebootWorker is not yet implemented.
func (Database) SetHedgeEnabled ¶
SetHedgeEnabled controls speculative second requests (hedge) for read RPCs. When enabled (default), slow reads are rescued by sending a backup request to a second server after max(10ms, 2×latency).
func (Database) Transact ¶
Transact runs a transactional function with automatic retry. This no-ctx form is drop-in compatible with the Apple Go binding: it has no Go-context cancellation and, by default, retries indefinitely on retryable errors. Bound it with DatabaseOptions.SetTransactionTimeout / SetTransactionRetryLimit (an overall budget honored across retries), or use TransactCtx for Go-context cancellation and deadlines.
func (Database) TransactCtx ¶
func (db Database) TransactCtx(ctx context.Context, f func(WritableTransaction) (any, error)) (any, error)
TransactCtx is Transact bounded by ctx (RFC-090 / fdb.CtxTransactor): ctx bounds the retry loop, backoff, and reads. The dispatched commit and its commit_unknown_result idempotency barrier run on a detached context (in client.Database.Transact), so the caller's ctx never cancels an in-flight commit — which is already bounded by the per-RPC timeout.
type DatabaseOptions ¶
type DatabaseOptions struct {
// contains filtered or unexported fields
}
DatabaseOptions is a handle for setting options that affect a Database.
func (DatabaseOptions) SetDatacenterId ¶
func (o DatabaseOptions) SetDatacenterId(_ string) error
func (DatabaseOptions) SetLocationCacheSize ¶
func (o DatabaseOptions) SetLocationCacheSize(_ int64) error
func (DatabaseOptions) SetMachineId ¶
func (o DatabaseOptions) SetMachineId(_ string) error
func (DatabaseOptions) SetMaxWatches ¶
func (o DatabaseOptions) SetMaxWatches(n int64) error
SetMaxWatches caps the number of concurrently-outstanding watches for this Database; a new watch over the cap fails with too_many_watches (1032). Matches FDB_DB_OPTION_MAX_WATCHES (default 10000). An out-of-range value (< 0 or > ABSOLUTE_MAX_WATCHES=1e6) is rejected with invalid_option_value (2006), leaving the cap unchanged — C++ extractIntOption throws on out-of-range, not clamps.
func (DatabaseOptions) SetReadSystemKeys ¶
func (o DatabaseOptions) SetReadSystemKeys() error
func (DatabaseOptions) SetSnapshotRywDisable ¶
func (o DatabaseOptions) SetSnapshotRywDisable() error
SetSnapshotRywDisable is an honored DB default: libfdb_c disables snapshot read-your-writes on every new transaction, changing snapshot reads after a local write — a read-semantics change, not a hint. Propagate it via txDefaults rather than silently dropping it.
func (DatabaseOptions) SetSnapshotRywEnable ¶
func (o DatabaseOptions) SetSnapshotRywEnable() error
func (DatabaseOptions) SetTestCausalReadRisky ¶
func (o DatabaseOptions) SetTestCausalReadRisky(_ int64) error
func (DatabaseOptions) SetTransactionAutomaticIdempotency ¶
func (o DatabaseOptions) SetTransactionAutomaticIdempotency() error
func (DatabaseOptions) SetTransactionBypassUnreadable ¶
func (o DatabaseOptions) SetTransactionBypassUnreadable() error
SetTransactionBypassUnreadable is an honored DB default: libfdb_c sets bypass_unreadable on every new transaction, turning accessed_unreadable failures into reads — observable behaviour, not a hint. Propagate it via txDefaults.
func (DatabaseOptions) SetTransactionCausalReadRisky ¶
func (o DatabaseOptions) SetTransactionCausalReadRisky() error
SetTransactionCausalReadRisky is an honored DB default (FDB C++ dev review, #331): it sets the GRV causal-read-risky flag on every new transaction, relaxing the read version (a read-version / staleness change). The per-tx SetCausalReadRisky IS honored, so the DB default must propagate too rather than be silently dropped (unlike causal_write_risky, whose per-tx form is a fail-safe no-op).
func (DatabaseOptions) SetTransactionIncludePortInAddress ¶
func (o DatabaseOptions) SetTransactionIncludePortInAddress() error
func (DatabaseOptions) SetTransactionLoggingMaxFieldLength ¶
func (o DatabaseOptions) SetTransactionLoggingMaxFieldLength(_ int64) error
func (DatabaseOptions) SetTransactionMaxRetryDelay ¶
func (o DatabaseOptions) SetTransactionMaxRetryDelay(ms int64) error
func (DatabaseOptions) SetTransactionReportConflictingKeys ¶
func (o DatabaseOptions) SetTransactionReportConflictingKeys() error
DB-level defaults for the options the per-transaction setters reject (RFC-111 P1.3): keep the fail-loud taxonomy consistent across both surfaces — a DB default that silently swallows report_conflicting_keys / automatic_idempotency would re-open the same migration trap the per-tx SetReportConflictingKeys/SetAutomaticIdempotency now guard against.
func (DatabaseOptions) SetTransactionRetryLimit ¶
func (o DatabaseOptions) SetTransactionRetryLimit(retries int64) error
func (DatabaseOptions) SetTransactionSizeLimit ¶
func (o DatabaseOptions) SetTransactionSizeLimit(bytes int64) error
func (DatabaseOptions) SetTransactionTimeout ¶
func (o DatabaseOptions) SetTransactionTimeout(ms int64) error
func (DatabaseOptions) SetTransactionUsedDuringCommitProtectionDisable ¶
func (o DatabaseOptions) SetTransactionUsedDuringCommitProtectionDisable() error
func (DatabaseOptions) SetUseConfigDatabase ¶
func (o DatabaseOptions) SetUseConfigDatabase() error
type Error ¶
type Error struct {
Code int
}
Error represents a low-level error returned by FoundationDB. Compare the Code field against FDB error codes, pass to Transaction.OnError to determine if the error is retryable, or call IsRetryable(code) directly for the canonical FDB_ERROR_PREDICATE_RETRYABLE classification.
type ExactRange ¶
type ExactRange interface {
FDBRangeKeys() (begin, end KeyConvertible)
Range
}
ExactRange describes all keys between a begin (inclusive) and end (exclusive) key. Any ExactRange also implements Range.
type Future ¶
type Future interface {
BlockUntilReady()
IsReady() bool
Cancel()
}
Future represents a value (or error) available at some later time.
type FutureByteSlice ¶
FutureByteSlice represents the asynchronous result of a function that returns a byte slice.
type FutureInt64 ¶
FutureInt64 represents the asynchronous result of a function that returns an int64.
type FutureKeyArray ¶
FutureKeyArray represents the asynchronous result of a function that returns an array of keys.
type FutureNil ¶
FutureNil represents the asynchronous result of a function that has no return value.
type FutureStringSlice ¶
FutureStringSlice represents the asynchronous result of a function that returns a slice of strings.
type Key ¶
type Key []byte
Key represents a FoundationDB key, a lexicographically-ordered sequence of bytes. Key implements the KeyConvertible interface.
type KeyConvertible ¶
type KeyConvertible interface {
FDBKey() Key
}
KeyConvertible can be converted to a FoundationDB Key. All functions that address a specific key accept a KeyConvertible.
type KeyRange ¶
type KeyRange struct {
Begin KeyConvertible
End KeyConvertible
}
KeyRange is an ExactRange constructed from a pair of KeyConvertibles.
func PrefixRange ¶
PrefixRange returns a KeyRange covering all keys with the given prefix.
func (KeyRange) FDBRangeKeySelectors ¶
func (kr KeyRange) FDBRangeKeySelectors() (Selectable, Selectable)
FDBRangeKeySelectors returns selectors for the begin and end of this range.
func (KeyRange) FDBRangeKeys ¶
func (kr KeyRange) FDBRangeKeys() (KeyConvertible, KeyConvertible)
FDBRangeKeys returns the begin and end keys.
type KeySelector ¶
type KeySelector struct {
Key KeyConvertible
OrEqual bool
Offset int
}
KeySelector represents a description of a key in a FoundationDB database. A KeySelector may be resolved to a specific key with Transaction.GetKey, or used as endpoints of a range for GetRange.
func FirstGreaterOrEqual ¶
func FirstGreaterOrEqual(key KeyConvertible) KeySelector
FirstGreaterOrEqual returns a KeySelector specifying the lexicographically least key greater than or equal to the given key. Matches Apple Go binding: KeySelectorRef(key, false, 1).
func FirstGreaterThan ¶
func FirstGreaterThan(key KeyConvertible) KeySelector
FirstGreaterThan returns a KeySelector specifying the lexicographically least key strictly greater than the given key. Matches Apple Go binding: KeySelectorRef(key, true, 1).
func LastLessOrEqual ¶
func LastLessOrEqual(key KeyConvertible) KeySelector
LastLessOrEqual returns a KeySelector specifying the lexicographically greatest key less than or equal to the given key.
func LastLessThan ¶
func LastLessThan(key KeyConvertible) KeySelector
LastLessThan returns a KeySelector specifying the lexicographically greatest key strictly less than the given key.
func (KeySelector) FDBKeySelector ¶
func (ks KeySelector) FDBKeySelector() KeySelector
FDBKeySelector returns the selector itself. Satisfies Selectable.
type Option ¶
Option configures a database opened via OpenDatabase / OpenDatabaseFromConfig (e.g. WithTLSConfig, WithDialFunc). It is an alias for client.Option so the two packages share one option type.
func WithDialFunc ¶
WithDialFunc overrides the dialer used for every connection (advanced / tests).
func WithRangeByteCeiling ¶
WithRangeByteCeiling bounds how many bytes a single GetRange may materialize before it fails with a *client.RangeMaterializationLimitError, instead of OOM-ing on a runaway unbounded scan. n ≤ 0 (the default) is UNLIMITED, matching libfdb_c. An opt-in OOM safety valve; for large result sets prefer the bounded Iterator() (which honors StreamingMode). RFC-115 §2.
func WithTLSConfig ¶
WithTLSConfig connects to the cluster over TLS using a standard *crypto/tls.Config (in-memory certs, GetClientCertificate rotation, custom VerifyPeerCertificate, cipher/version policy). It takes precedence over the FDB_TLS_* environment / cluster-file ":tls" resolution and enables TLS even when the cluster string lacks ":tls".
func WithTracer ¶
WithTracer sets the OpenTelemetry tracer that EXPORTS client-side trace spans (a "Transaction" span + per-operation child spans), seeded with the same traceID the client puts on the wire. Pass any go.opentelemetry.io/otel/trace.Tracer; nil (the default) is a no-op (zero telemetry, no OTEL SDK pulled in). RFC-115 §4 Layer 2.
func WithTracingSampleRate ¶
WithTracingSampleRate sets the fraction (0.0–1.0) of transactions whose trace span is flagged sampled. Default 0.0 matches C++ TRACING_SAMPLE_RATE — every transaction still carries a real (randomly-generated, wire-faithful) SpanContext, flagged unsampled. RFC-115 §4.
type Range ¶
type Range interface {
FDBRangeKeySelectors() (begin, end Selectable)
}
Range describes all keys between a begin (inclusive) and end (exclusive) key selector.
type RangeIterator ¶
type RangeIterator interface {
Advance() bool
Get() (KeyValue, error)
MustGet() KeyValue
SetTraceLog(fn func(iteration, requested, returned int, more bool, err error))
}
RangeIterator streams key-value pairs from a range read. Call Advance() before each Get(); Get() is idempotent (returns the current element without advancing). Interface for the same backend-substitution reason as RangeResult (RFC-109).
type RangeOptions ¶
type RangeOptions struct {
// Limit restricts the number of key-value pairs returned. 0 = no limit.
Limit int
// Mode sets the streaming mode of the range read.
//
// Honored by Iterator(): Advance() sizes each batch from Mode (Iterator
// doubles, Exact/WantAll fetch in one go, Small/Medium/Large/Serial use fixed
// sizes) — the right tool for large or unbounded result sets. Ignored ONLY by
// GetSliceWithError, which always fetches the whole range in exact mode and
// materializes it into one slice regardless of Mode; for an unexpectedly large
// range prefer Iterator() (or set WithRangeByteCeiling as an OOM backstop).
Mode StreamingMode
// Reverse indicates that the read should be performed in reverse
// lexicographic order.
Reverse bool
}
RangeOptions specify how a database range read operation is carried out.
type RangeResult ¶
type RangeResult interface {
// GetSliceWithError materializes the whole range into a slice.
GetSliceWithError() ([]KeyValue, error)
// GetSliceOrPanic is GetSliceWithError, panicking on error.
GetSliceOrPanic() []KeyValue
// Iterator streams the range in batches per the StreamingMode.
Iterator() RangeIterator
}
RangeResult is the asynchronous result of a range read. It is an INTERFACE (RFC-109) so a non-pure-Go backend (libfdb_c) can return its own implementation; the pure-Go client returns goRangeResult.
type ReadTransaction ¶
type ReadTransaction interface {
Get(key KeyConvertible) FutureByteSlice
GetKey(sel Selectable) FutureKey
GetRange(r Range, options RangeOptions) RangeResult
GetReadVersion() FutureInt64
Snapshot() ReadTransaction
GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
Options() TransactionOptions
ReadTransactor
}
ReadTransaction can asynchronously read from a FoundationDB database. Transaction and Snapshot both satisfy ReadTransaction.
GetDatabase() is intentionally OFF this interface (RFC-109): it returns the concrete pure-Go fdb.Database (a ~40-method handle a cgo backend cannot build), and nothing in the record layer calls it through the interface — same rationale as Watch/Locality/tenant methods staying concrete-only. It remains a concrete method on Transaction/Snapshot for direct-typed callers.
type ReadTransactor ¶
type ReadTransactor interface {
ReadTransact(func(ReadTransaction) (any, error)) (any, error)
}
ReadTransactor can execute a function that requires a ReadTransaction. Database, Transaction, and Snapshot implement ReadTransactor.
type Selectable ¶
type Selectable interface {
FDBKeySelector() KeySelector
}
Selectable can be converted to a FoundationDB KeySelector.
type SelectorRange ¶
type SelectorRange struct {
Begin Selectable
End Selectable
}
SelectorRange is a Range constructed from a pair of Selectables.
func (SelectorRange) FDBRangeKeySelectors ¶
func (sr SelectorRange) FDBRangeKeySelectors() (Selectable, Selectable)
FDBRangeKeySelectors returns the begin and end selectors.
type Snapshot ¶
type Snapshot struct {
// contains filtered or unexported fields
}
Snapshot is a handle to a FoundationDB transaction snapshot. Snapshot reads do not add read conflict ranges.
func (Snapshot) Get ¶
func (sn Snapshot) Get(key KeyConvertible) FutureByteSlice
func (Snapshot) GetDatabase ¶
func (Snapshot) GetEstimatedRangeSizeBytes ¶
func (sn Snapshot) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
func (Snapshot) GetKey ¶
func (sn Snapshot) GetKey(sel Selectable) FutureKey
func (Snapshot) GetRange ¶
func (sn Snapshot) GetRange(r Range, options RangeOptions) RangeResult
func (Snapshot) GetRangeSplitPoints ¶
func (sn Snapshot) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
func (Snapshot) GetReadVersion ¶
func (sn Snapshot) GetReadVersion() FutureInt64
func (Snapshot) Options ¶
func (sn Snapshot) Options() TransactionOptions
func (Snapshot) ReadTransact ¶
func (Snapshot) Snapshot ¶
func (sn Snapshot) Snapshot() ReadTransaction
type StreamingMode ¶
type StreamingMode int
StreamingMode controls how range reads transfer data from the database.
const ( // StreamingModeWantAll transfers all data in as few server requests as // possible. Recommended for small reads within a transaction. // Values match Apple binding: fdb_c_options.g.go. StreamingModeWantAll StreamingMode = -1 // StreamingModeIterator provides a good balance for typical iteration. // This is the default (zero value). StreamingModeIterator StreamingMode = 0 // StreamingModeExact transfers data in one batch, sized to the exact // Limit specified. A Limit must be specified. StreamingModeExact StreamingMode = 1 // StreamingModeSmall hints that only a few key-value pairs are expected. StreamingModeSmall StreamingMode = 2 // StreamingModeMedium hints that a moderate number of key-value pairs // are expected. StreamingModeMedium StreamingMode = 3 // StreamingModeLarge hints that a large number of key-value pairs are // expected. StreamingModeLarge StreamingMode = 4 // StreamingModeSerial transfers data in large batches, useful when the // client is processing each result before requesting more. StreamingModeSerial StreamingMode = 5 )
type Tenant ¶
type Tenant struct {
// contains filtered or unexported fields
}
Tenant is a handle to a FoundationDB tenant. Operations on a Tenant are scoped to the tenant's key space.
func (Tenant) CreateTransaction ¶
func (t Tenant) CreateTransaction() (Transaction, error)
CreateTransaction creates a new Transaction scoped to this tenant's key space. Like Database.CreateTransaction, it inherits database-level option defaults set via Options() (SetTransactionTimeout / SetTransactionRetryLimit / …) — matching libfdb_c, where DB transaction defaults are copied into every transaction.
func (Tenant) ReadTransact ¶
ReadTransact runs a read-only transactional function with automatic retry, scoped to this tenant's key space.
func (Tenant) ReadTransactCtx ¶
func (t Tenant) ReadTransactCtx(ctx context.Context, f func(ReadTransaction) (any, error)) (any, error)
ReadTransactCtx is ReadTransact bounded by ctx (RFC-090 / fdb.CtxReadTransactor).
func (Tenant) Transact ¶
Transact runs a transactional function with automatic retry, scoped to this tenant's key space. Matches Database.Transact but sets the tenant ID on the underlying transaction.
func (Tenant) TransactCtx ¶
func (t Tenant) TransactCtx(ctx context.Context, f func(WritableTransaction) (any, error)) (any, error)
TransactCtx is Transact bounded by ctx (RFC-090 / fdb.CtxTransactor). The dispatched commit + commit_unknown barrier run detached (in client.Database.Transact); ctx never cancels an in-flight commit.
type TenantOptionError ¶
type TenantOptionError struct{ Option string }
TenantOptionError is returned when a system-key-access option (READ_SYSTEM_KEYS / ACCESS_SYSTEM_KEYS) is set on a tenant transaction. C++ setOption throws invalid_option (2007) here — "System key access implies raw access", which is incompatible with tenant scoping (NativeAPI.actor.cpp:7159-7171). Unlike UnsupportedOptionError, the option IS supported by the pure-Go client; it is just invalid in this context.
func (*TenantOptionError) Error ¶
func (e *TenantOptionError) Error() string
func (*TenantOptionError) FDBCode ¶
func (e *TenantOptionError) FDBCode() int
FDBCode reports invalid_option (2007), matching libfdb_c's throw.
type Transaction ¶
type Transaction struct {
// contains filtered or unexported fields
}
Transaction is a handle to a FoundationDB transaction.
Data operations — Get, GetRange, GetKey, Set, Clear, ClearRange, Atomic, Commit, GetApproximateSize, and the conflict-range adders — are safe for concurrent use by multiple goroutines (the shared mutation/conflict buffers are guarded internally). Read-your-writes ordering across concurrent read-modify-write on the SAME key is still racy (lost update), matching the C binding; serialize such sequences yourself.
Option setters (the Set* configuration methods, e.g. SetPriority, SetWriteConflictsDisabled, SetTag, SetReadVersion) and Reset() are NOT concurrent-safe with operations or each other — configure the transaction BEFORE issuing concurrent operations, and drain all pending futures before calling Reset (in-flight goroutines hold references to the internal handle). This mirrors the FDB C API, where fdb_transaction_set_option is not meant to race the transaction's data calls.
In the Apple binding, Transaction is a concrete struct with value receiver methods. We match this by making Transaction a struct that wraps a pointer to the internal state.
func WrapTransaction ¶
func WrapTransaction(tx *client.Transaction, db Database) Transaction
WrapTransaction wraps an existing client.Transaction as an fdb.Transaction. This is useful when you need to pass a client.Transaction to code that expects the fdb facade types (e.g., the directory layer).
func (Transaction) Add ¶
func (tr Transaction) Add(key KeyConvertible, param []byte)
func (Transaction) AddBytes ¶
func (tr Transaction) AddBytes(key, param []byte)
AddBytes performs an atomic Add using raw byte slices. Avoids KeyConvertible interface boxing in the hot path.
func (Transaction) AddReadConflictKey ¶
func (tr Transaction) AddReadConflictKey(key KeyConvertible) error
AddReadConflictKey adds a read conflict on a single key.
func (Transaction) AddReadConflictRange ¶
func (tr Transaction) AddReadConflictRange(er ExactRange) error
AddReadConflictRange adds a read conflict range.
func (Transaction) AddWriteConflictKey ¶
func (tr Transaction) AddWriteConflictKey(key KeyConvertible) error
AddWriteConflictKey adds a write conflict on a single key.
func (Transaction) AddWriteConflictRange ¶
func (tr Transaction) AddWriteConflictRange(er ExactRange) error
AddWriteConflictRange adds a write conflict range.
func (Transaction) And ¶
func (tr Transaction) And(key KeyConvertible, param []byte)
func (Transaction) AppendIfFits ¶
func (tr Transaction) AppendIfFits(key KeyConvertible, param []byte)
func (Transaction) BitAnd ¶
func (tr Transaction) BitAnd(key KeyConvertible, param []byte)
func (Transaction) BitOr ¶
func (tr Transaction) BitOr(key KeyConvertible, param []byte)
func (Transaction) BitXor ¶
func (tr Transaction) BitXor(key KeyConvertible, param []byte)
func (Transaction) ByteMax ¶
func (tr Transaction) ByteMax(key KeyConvertible, param []byte)
func (Transaction) ByteMin ¶
func (tr Transaction) ByteMin(key KeyConvertible, param []byte)
func (Transaction) Cancel ¶
func (tr Transaction) Cancel()
Cancel cancels the transaction. Also unblocks any pending GetVersionstamp() futures.
func (Transaction) Clear ¶
func (tr Transaction) Clear(key KeyConvertible)
Clear removes a key from the database.
func (Transaction) ClearBytes ¶
func (tr Transaction) ClearBytes(key []byte)
ClearBytes deletes a key using raw bytes. Avoids KeyConvertible boxing.
func (Transaction) ClearRange ¶
func (tr Transaction) ClearRange(er ExactRange)
ClearRange removes all keys k such that begin <= k < end. The Apple binding's ClearRange is void because mutations are buffered locally with no I/O. Our pure Go client validates begin <= end and returns inverted_range (2005) on violation. We suppress all errors to match the Apple void API contract. Today the only possible error is inverted_range; if the client adds new error paths, this should be revisited (see client.Transaction.ClearRange).
func (Transaction) Commit ¶
func (tr Transaction) Commit() FutureNil
Commit commits the transaction. The returned FutureNil becomes ready when the commit has been acknowledged by the cluster. Also unblocks any pending GetVersionstamp() futures.
func (Transaction) CompareAndClear ¶
func (tr Transaction) CompareAndClear(key KeyConvertible, param []byte)
func (Transaction) CompareAndClearBytes ¶
func (tr Transaction) CompareAndClearBytes(key, param []byte)
func (Transaction) CreateTenant ¶
func (tr Transaction) CreateTenant(name KeyConvertible) error
CreateTenant creates a tenant within this transaction. Convenience method matching Apple binding — delegates to Database.CreateTenant.
func (Transaction) DeleteTenant ¶
func (tr Transaction) DeleteTenant(name KeyConvertible) error
DeleteTenant deletes a tenant within this transaction. Convenience method matching Apple binding — delegates to Database.DeleteTenant.
func (Transaction) Get ¶
func (tr Transaction) Get(key KeyConvertible) FutureByteSlice
Get returns the value associated with the specified key, or nil if the key does not exist. The read is performed asynchronously.
func (Transaction) GetApproximateSize ¶
func (tr Transaction) GetApproximateSize() FutureInt64
GetApproximateSize returns the approximate transaction size so far.
func (Transaction) GetCommittedVersion ¶
func (tr Transaction) GetCommittedVersion() (int64, error)
GetCommittedVersion returns the version at which this transaction committed. Must be called after a successful Commit.
func (Transaction) GetDatabase ¶
func (tr Transaction) GetDatabase() Database
GetDatabase returns the Database this transaction is operating on.
func (Transaction) GetEstimatedRangeSizeBytes ¶
func (tr Transaction) GetEstimatedRangeSizeBytes(r ExactRange) FutureInt64
GetEstimatedRangeSizeBytes returns an estimate of the byte size of the key range.
func (Transaction) GetKey ¶
func (tr Transaction) GetKey(sel Selectable) FutureKey
GetKey returns the key referenced by the given key selector.
func (Transaction) GetRange ¶
func (tr Transaction) GetRange(r Range, options RangeOptions) RangeResult
GetRange performs a range read. The range is specified by a Range and options. Returns a RangeResult that can be iterated or fetched as a slice.
func (Transaction) GetRangeSplitPoints ¶
func (tr Transaction) GetRangeSplitPoints(r ExactRange, chunkSize int64) FutureKeyArray
GetRangeSplitPoints suggests split points for the given key range.
func (Transaction) GetReadVersion ¶
func (tr Transaction) GetReadVersion() FutureInt64
GetReadVersion returns the read version used by this transaction.
func (Transaction) GetVersionstamp ¶
func (tr Transaction) GetVersionstamp() FutureKey
GetVersionstamp returns the versionstamp which was used by any versionstamp operations in this transaction.
Can be called before or after Commit(). If called before, the returned future blocks until commit completes — matching the Apple binding's deferred versionstamp pattern.
Only supported on transactions created via CreateTransaction() with explicit Commit(). Transactions from Transact()/ReadTransact() return error 2015 (used_during_commit) because commit is managed internally.
func (Transaction) ListTenants ¶
func (tr Transaction) ListTenants() ([]Key, error)
ListTenants lists all tenants. Convenience method matching Apple binding — delegates to Database.ListTenants.
func (Transaction) LocalityGetAddressesForKey ¶
func (tr Transaction) LocalityGetAddressesForKey(key KeyConvertible) FutureStringSlice
LocalityGetAddressesForKey returns the addresses of storage servers that hold the given key. Uses the location cache, querying the cluster on miss.
func (Transaction) Max ¶
func (tr Transaction) Max(key KeyConvertible, param []byte)
func (Transaction) MaxBytes ¶
func (tr Transaction) MaxBytes(key, param []byte)
func (Transaction) Min ¶
func (tr Transaction) Min(key KeyConvertible, param []byte)
func (Transaction) MinBytes ¶
func (tr Transaction) MinBytes(key, param []byte)
func (Transaction) OnError ¶
func (tr Transaction) OnError(e Error) FutureNil
OnError determines whether an error is retryable. The returned FutureNil includes the retry delay — the delay runs when Get() is called, not when OnError() is called. This matches Apple binding semantics.
func (Transaction) Options ¶
func (tr Transaction) Options() TransactionOptions
Options returns a TransactionOptions handle.
func (Transaction) Or ¶
func (tr Transaction) Or(key KeyConvertible, param []byte)
func (Transaction) ReadTransact ¶
func (tr Transaction) ReadTransact(f func(ReadTransaction) (any, error)) (r any, e error)
ReadTransact implements ReadTransactor for composability.
func (Transaction) Reset ¶
func (tr Transaction) Reset()
Reset resets the transaction to its initial state. NOT safe to call concurrently with other Transaction methods. Callers must drain all pending futures before calling Reset — in-flight goroutines from Get/GetRange/Commit access tr.t.inner and will race with Reset. This matches Apple binding semantics where Reset must not be called while the transaction is in use.
func (Transaction) Set ¶
func (tr Transaction) Set(key KeyConvertible, value []byte)
Set sets a key-value pair in the database.
func (Transaction) SetBytes ¶
func (tr Transaction) SetBytes(key, value []byte)
SetBytes sets a key-value pair using raw byte slices. Avoids the KeyConvertible interface boxing allocation in the hot path.
func (Transaction) SetReadVersion ¶
func (tr Transaction) SetReadVersion(version int64)
SetReadVersion sets the read version for this transaction.
func (Transaction) SetVersionstampedKey ¶
func (tr Transaction) SetVersionstampedKey(key KeyConvertible, param []byte)
SetVersionstampedKey sets a key with an embedded incomplete versionstamp.
func (Transaction) SetVersionstampedValue ¶
func (tr Transaction) SetVersionstampedValue(key KeyConvertible, param []byte)
SetVersionstampedValue sets a value with an embedded incomplete versionstamp.
func (Transaction) Snapshot ¶
func (tr Transaction) Snapshot() ReadTransaction
Snapshot returns a Snapshot view of this transaction.
func (Transaction) Transact ¶
func (tr Transaction) Transact(f func(WritableTransaction) (any, error)) (r any, e error)
Transact implements Transactor for composability. Catches Error panics from MustGet() and returns them as errors, matching the Apple binding's panicToError recovery.
func (Transaction) Watch ¶
func (tr Transaction) Watch(key KeyConvertible) FutureNil
Watch returns a future that becomes ready when the value associated with the given key changes. The watch is a long-poll to the storage server.
func (Transaction) Xor ¶
func (tr Transaction) Xor(key KeyConvertible, param []byte)
type TransactionOptions ¶
type TransactionOptions interface {
SetTimeout(milliseconds int64) error
SetRetryLimit(retries int64) error
SetPriorityBatch() error
SetPrioritySystemImmediate() error
SetDebugTransactionIdentifier(id string) error
SetNextWriteNoWriteConflictRange() error
SetCausalReadRisky() error
SetReadYourWritesDisable() error
EnsureMutationCapacity(n int)
SetWriteConflictsDisabled()
SetAccessSystemKeys() error
SetReadSystemKeys() error
SetLockAware() error
SetReadLockAware() error
SetLogTransaction() error
SetTransactionLoggingEnable(id string) error
SetSizeLimit(limit int64) error
SetMaxRetryDelay(ms int64) error
SetSnapshotRywEnable() error
SetSnapshotRywDisable() error
SetUseGrvCache() error
SetSkipGrvCache() error
SetAutoThrottleTag(tag string) error
SetTag(tag string) error
SetReportConflictingKeys() error
SetSpecialKeySpaceRelaxed() error
SetSpecialKeySpaceEnableWrites() error
SetRawAccess() error
SetBypassUnreadable() error
SetAutomaticIdempotency() error
SetDebugRetryLogging(loggerName string) error
SetIncludePortInAddress() error
SetCausalReadDisable() error
SetCausalWriteRisky() error
SetDurabilityRisky() error
SetDurabilityDatacenter() error
SetDurabilityDevNullIsWebScale() error
SetTransactionLoggingMaxFieldLength(maxFieldLength int64) error
SetServerRequestTracing() error
SetUsedDuringCommitProtectionDisable() error
SetReadAheadDisable() error
SetReadPriorityHigh() error
SetReadPriorityLow() error
SetReadPriorityNormal() error
SetReadServerSideCacheEnable() error
SetReadServerSideCacheDisable() error
SetUseProvisionalProxies() error
SetBypassStorageQuota() error
SetInitializeNewDatabase() error
SetAuthorizationToken(token string) error
SetSpanParent(parent []byte) error
SetExpensiveClearCostEstimationEnable() error
}
TransactionOptions sets options that affect a Transaction, obtained via ReadTransaction.Options(). It is an interface so a non-pure-Go backend can provide its own implementation (RFC-109): the pure-Go goTransactionOptions delegates to the client transaction — no-op'ing options the pure-Go client does not model — while the libfdb_c backend forwards each call by raw integer opcode (RFC-109 §"Options by raw integer"). Every option is on the interface precisely so the cgo backend can faithfully forward even those the pure-Go client ignores (e.g. SetServerRequestTracing, SetReadAheadDisable).
type Transactor ¶
type Transactor interface {
Transact(func(WritableTransaction) (any, error)) (any, error)
ReadTransactor
}
Transactor can execute a function that requires a Transaction. Both Database and Transaction implement Transactor.
type UnsupportedOptionError ¶
type UnsupportedOptionError struct{ Option string }
UnsupportedOptionError is returned by the pure-Go backend for a transaction option that alters security / access / idempotency semantics but that the pure-Go client does not model. These fail LOUD instead of the old silent no-op: silently ignoring such an option is a migration trap — e.g. an ignored authorization token means the request is sent unauthenticated (auth bypass), and an ignored raw-access flag means a tenant-scoped read instead of the raw keyspace. The libfdb_c backend forwards these options normally; pure-Go callers that need them must use that backend. Options that fail SAFE when ignored (the causal/durability knobs — ignoring keeps the STRONGER guarantee) remain accepted-but-ignored and are documented option-by-option in OPTIONS.md. Resolves to FDB invalid_option (2007).
func (*UnsupportedOptionError) Error ¶
func (e *UnsupportedOptionError) Error() string
func (*UnsupportedOptionError) FDBCode ¶
func (e *UnsupportedOptionError) FDBCode() int
FDBCode reports the FDB error code (invalid_option, 2007) so callers that map on the numeric code treat it like libfdb_c rejecting an option.
type WritableTransaction ¶
type WritableTransaction interface {
ReadTransaction
// Mutations
Set(key KeyConvertible, value []byte)
Clear(key KeyConvertible)
ClearRange(er ExactRange)
// Atomic mutations
Add(key KeyConvertible, param []byte)
And(key KeyConvertible, param []byte)
BitAnd(key KeyConvertible, param []byte)
Or(key KeyConvertible, param []byte)
BitOr(key KeyConvertible, param []byte)
Xor(key KeyConvertible, param []byte)
BitXor(key KeyConvertible, param []byte)
Max(key KeyConvertible, param []byte)
Min(key KeyConvertible, param []byte)
ByteMax(key KeyConvertible, param []byte)
ByteMin(key KeyConvertible, param []byte)
AppendIfFits(key KeyConvertible, param []byte)
CompareAndClear(key KeyConvertible, param []byte)
SetVersionstampedKey(key KeyConvertible, param []byte)
SetVersionstampedValue(key KeyConvertible, param []byte)
// []byte fast-path overloads — avoid KeyConvertible boxing on the hot index-
// maintenance path (RFC-109: callers invoke these through the interface, so they
// must be on it; both backends implement them).
SetBytes(key, value []byte)
ClearBytes(key []byte)
AddBytes(key, param []byte)
MaxBytes(key, param []byte)
MinBytes(key, param []byte)
CompareAndClearBytes(key, param []byte)
// Conflict ranges
AddReadConflictRange(er ExactRange) error
AddReadConflictKey(key KeyConvertible) error
AddWriteConflictRange(er ExactRange) error
AddWriteConflictKey(key KeyConvertible) error
// Transaction lifecycle
Commit() FutureNil
Cancel()
Reset()
OnError(e Error) FutureNil
SetReadVersion(version int64)
// Post-commit
GetCommittedVersion() (int64, error)
GetVersionstamp() FutureKey
GetApproximateSize() FutureInt64
}
WritableTransaction extends ReadTransaction with write operations. Only Transaction satisfies this (not Snapshot).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package directory provides a tool for managing related subspaces.
|
Package directory provides a tool for managing related subspaces. |
|
Package subspace provides a convenient way to use FoundationDB tuples to define namespaces for different categories of data.
|
Package subspace provides a convenient way to use FoundationDB tuples to define namespaces for different categories of data. |
|
Package tuple provides a layer for encoding and decoding multi-element tuples into keys usable by FoundationDB.
|
Package tuple provides a layer for encoding and decoding multi-element tuples into keys usable by FoundationDB. |