client

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2023 License: Apache-2.0 Imports: 42 Imported by: 45

Documentation

Overview

This package contains the official implementation of the go client for the immudb database.

Please refer to documentation at https://docs.immudb.io for more details on how to use this SDK.

Index

Constants

View Source
const AdminTokenFileSuffix = "_admin"

AdminTokenFileSuffix is the suffix used for the token file name

View Source
const DefaultDB = "defaultdb"
View Source
const SQLPrefix byte = 2

Variables

View Source
var (

	// ErrIllegalArguments indicates illegal arguments provided to a method
	ErrIllegalArguments = errors.New("illegal arguments")

	// ErrAlreadyConnected is used when trying to establish a new connection with a client that is already connected
	ErrAlreadyConnected = errors.New("already connected")

	// ErrNotConnected is used when the operation can not be done because the client connection is closed
	ErrNotConnected = errors.New("not connected")

	// ErrHealthCheckFailed is used to indicate that health check has failed
	ErrHealthCheckFailed = errors.New("health check failed")

	// ErrServerStateIsOlder is used to inform that the client has newer state than the server.
	// This could happen if the client connects to an asynchronous replica that did not yet
	// replicate all transactions from the primary database.
	ErrServerStateIsOlder = errors.New("server state is older than the client one")

	// ErrSessionAlreadyOpen is used when trying to create a new session but there's a valid session already set up.
	ErrSessionAlreadyOpen = errors.New("session already opened")
)

Errors related to Client connection and health check

View Source
var (
	ErrSrvIllegalArguments   = status.Error(codes.InvalidArgument, "illegal arguments")
	ErrSrvIllegalState       = status.Error(codes.InvalidArgument, "illegal state")
	ErrSrvEmptyAdminPassword = status.Error(codes.InvalidArgument, "Admin password cannot be empty")
	ErrWriteOnlyTXNotAllowed = status.Error(codes.InvalidArgument, "write only transaction not allowed")
)

Server errors mapping

Functions

func NewClient added in v1.2.0

func NewClient() *immuClient

NewClient creates a new instance if immudb client object.

The returned object implements the ImmuClient interface.

Returned instance is not connected to the database, use OpenSession to establish the connection.

func NewHeartBeater added in v1.5.0

func NewHeartBeater(sessionID string, sc schema.ImmuServiceClient, keepAliveInterval time.Duration, errhandler ErrorHandler) *heartBeater

func NewImmuClient deprecated

func NewImmuClient(options *Options) (*immuClient, error)

NewImmuClient creates a new immudb client object instance and connects to a server.

Deprecated: use NewClient instead.

Types

type ErrorHandler added in v1.5.0

type ErrorHandler func(sessionID string, err error)

type GetOption added in v1.3.0

type GetOption func(req *schema.KeyRequest) error

GetOption is used to set additional options when reading a value with a Get call

func AtRevision added in v1.3.0

func AtRevision(rev int64) GetOption

AtRevision request specific revision for given key.

Key revision is an integer value that starts at 1 when the key is created and then increased by 1 on every update made to that key.

The way rev is interpreted depends on the value:

  • if rev = 0, returns current value
  • if rev > 0, returns nth revision value, e.g. 1 is the first value, 2 is the second and so on
  • if rev < 0, returns nth revision value from the end, e.g. -1 is the previous value, -2 is the one before and so on

func AtTx added in v1.3.0

func AtTx(tx uint64) GetOption

AtTx option is used to specify that the value read must be the one set at transaction with id given in the tx parameter.

If the key was not modified at given transaction, the request will return key not found result even if the key was changed before that transaction.

Using AtTx also allows reading entries set with disabled indexing.

func NoWait added in v1.3.0

func NoWait(nowait bool) GetOption

NoWait option set to true means that the server should not wait for the indexer to be up-to-date with the most recent transaction.

In practice this means that the user will get the result instantly without the risk of the server wait for the indexer that may happen in case of a large spike of new transactions.

The disadvantage of using this option is that the server can reply with an older value for the same key or with a key not found result even though already committed transactions contain newer updates to that key.

func SinceTx added in v1.3.0

func SinceTx(tx uint64) GetOption

SinceTx option can be used to avoid waiting for the indexer to be up-to-date with the most recent transaction. The client requires though that at least the transaction with id given in the tx parameter must be indexed.

This option can be used to avoid additional latency while the server waits for the indexer to finish indexing but still guarantees that specific portion of the database history has already been indexed.

type HeartBeater added in v1.5.0

type HeartBeater interface {
	KeepAlive(ctx context.Context)
	Stop()
}

type ImmuClient

type ImmuClient interface {

	// Disconnect closes the current connection to the server.
	//
	// Deprecated: use NewClient and CloseSession instead.
	Disconnect() error

	// IsConnected checks whether the client is connected to the server.
	IsConnected() bool

	// WaitForHealthCheck waits for up to Options.HealthCheckRetries seconds to
	// get a successful HealthCheck response from the server.
	//
	// Deprecated: grpc retry mechanism can be implemented with WithConnectParams dialOption.
	WaitForHealthCheck(ctx context.Context) error

	// Get server health information.
	//
	// Deprecated: use ServerInfo.
	HealthCheck(ctx context.Context) error

	// Connect establishes new connection to the server.
	//
	// Deprecated: use NewClient and OpenSession instead.
	Connect(ctx context.Context) (clientConn *grpc.ClientConn, err error)

	// Login authenticates the user in an established connection.
	//
	// Deprecated: use NewClient and OpenSession instead.
	Login(ctx context.Context, user []byte, pass []byte) (*schema.LoginResponse, error)

	// Logout logs out the user.
	//
	// Deprecated: use CloseSession.
	Logout(ctx context.Context) error

	// OpenSession establishes a new session with the server, this method also opens new
	// connection to the server.
	//
	// Note: it is important to call CloseSession() once the session is no longer needed.
	OpenSession(ctx context.Context, user []byte, pass []byte, database string) (err error)

	// CloseSession closes the current session and the connection to the server,
	// this call also allows the server to free up all resources allocated for a session
	// (without explicit call, the server will only free resources after session inactivity timeout).
	CloseSession(ctx context.Context) error

	// CreateUser creates new user with given credentials and permission.
	//
	// Required user permission is SysAdmin or database Admin.
	//
	// SysAdmin user can create users with access to any database.
	//
	// Admin user can only create users with access to databases where
	// the user has admin permissions.
	//
	// The permission argument is the permission level and can be one of those values:
	//   - 1 (auth.PermissionR) - read-only access
	//   - 2 (auth.PermissionRW) - read-write access
	//   - 254 (auth.PermissionAdmin) - read-write with admin rights
	CreateUser(ctx context.Context, user []byte, pass []byte, permission uint32, databasename string) error

	// ListUser returns a list of database users.
	//
	// This call requires Admin or SysAdmin permission level.
	//
	// When called as a SysAdmin user, all users in the database are returned.
	// When called as an Admin user, users for currently selected database are returned.
	ListUsers(ctx context.Context) (*schema.UserList, error)

	// ChangePassword changes password for existing user.
	//
	// This call requires Admin or SysAdmin permission level.
	//
	// The oldPass argument is only necessary when changing SysAdmin user's password.
	ChangePassword(ctx context.Context, user []byte, oldPass []byte, newPass []byte) error

	// ChangePermission grants or revokes permission to one database for given user.
	//
	// This call requires SysAdmin or admin permission to the database where we grant permissions.
	//
	// The permission argument is used when granting permission and can be one of those values:
	//   - 1 (auth.PermissionR) - read-only access
	//   - 2 (auth.PermissionRW) - read-write access
	//   - 254 (auth.PermissionAdmin) - read-write with admin rights
	//
	// The following restrictions are applied:
	//  - the user can not change permission for himself
	//  - can not change permissions of the SysAdmin user
	//  - the user must be active
	//  - when the user already had permission to the database, it is overwritten
	//    by the new permission (even if the user had higher permission before)
	ChangePermission(ctx context.Context, action schema.PermissionAction, username string, database string, permissions uint32) error

	// UpdateAuthConfig is no longer supported.
	//
	// Deprecated: will be removed in future versions.
	UpdateAuthConfig(ctx context.Context, kind auth.Kind) error

	// UpdateMTLSConfig is no longer supported.
	//
	// Deprecated: will be removed in future versions.
	UpdateMTLSConfig(ctx context.Context, enabled bool) error

	// WithOptions sets up client options for the instance.
	WithOptions(options *Options) *immuClient

	// WithLogger sets up custom client logger.
	WithLogger(logger logger.Logger) *immuClient

	// WithStateService sets up the StateService object.
	WithStateService(rs state.StateService) *immuClient

	// Deprecated: will be removed in future versions.
	WithClientConn(clientConn *grpc.ClientConn) *immuClient

	// Deprecated: will be removed in future versions.
	WithServiceClient(serviceClient schema.ImmuServiceClient) *immuClient

	// Deprecated: will be removed in future versions.
	WithTokenService(tokenService tokenservice.TokenService) *immuClient

	// WithServerSigningPubKey sets up public key for server's state validation.
	WithServerSigningPubKey(serverSigningPubKey *ecdsa.PublicKey) *immuClient

	// WithStreamServiceFactory sets up stream factory for the client.
	WithStreamServiceFactory(ssf stream.ServiceFactory) *immuClient

	// GetServiceClient returns low-level GRPC service client.
	GetServiceClient() schema.ImmuServiceClient

	// GetOptions returns current client options.
	GetOptions() *Options

	// SetupDialOptions extracts grpc dial options from provided client options.
	SetupDialOptions(options *Options) []grpc.DialOption

	// Return list of databases the user has access to.
	//
	// Deprecated: Use DatabaseListV2.
	DatabaseList(ctx context.Context) (*schema.DatabaseListResponse, error)

	// DatabaseListV2 returns a list of databases the user has access to.
	DatabaseListV2(ctx context.Context) (*schema.DatabaseListResponseV2, error)

	// CreateDatabase creates new database.
	// This call requires SysAdmin permission level.
	//
	// Deprecated: Use CreateDatabaseV2.
	CreateDatabase(ctx context.Context, d *schema.DatabaseSettings) error

	// CreateDatabaseV2 creates a new database.
	// This call requires SysAdmin permission level.
	CreateDatabaseV2(ctx context.Context, database string, settings *schema.DatabaseNullableSettings) (*schema.CreateDatabaseResponse, error)

	// LoadDatabase loads database on the server. A database is not loaded
	// if it has AutoLoad setting set to false or if it failed to load during
	// immudb startup.
	//
	// This call requires SysAdmin permission level or admin permission to the database.
	LoadDatabase(ctx context.Context, r *schema.LoadDatabaseRequest) (*schema.LoadDatabaseResponse, error)

	// UnloadDatabase unloads database on the server. Such database becomes inaccessible
	// by the client and server frees internal resources allocated for that database.
	//
	// This call requires SysAdmin permission level or admin permission to the database.
	UnloadDatabase(ctx context.Context, r *schema.UnloadDatabaseRequest) (*schema.UnloadDatabaseResponse, error)

	// DeleteDatabase removes an unloaded database.
	// This also removes locally stored files used by the database.
	//
	// This call requires SysAdmin permission level or admin permission to the database.
	DeleteDatabase(ctx context.Context, r *schema.DeleteDatabaseRequest) (*schema.DeleteDatabaseResponse, error)

	// UseDatabase changes the currently selected database.
	//
	// This call requires at least read permission level for the target database.
	UseDatabase(ctx context.Context, d *schema.Database) (*schema.UseDatabaseReply, error)

	// UpdateDatabase updates database settings.
	//
	// Deprecated: Use UpdateDatabaseV2.
	UpdateDatabase(ctx context.Context, settings *schema.DatabaseSettings) error

	// UpdateDatabaseV2 updates database settings.
	//
	// Settings can be set selectively - values not set in the settings object
	// will not be updated.
	//
	// The returned value is the list of settings after the update.
	//
	// Settings other than those related to replication will only be applied after
	// immudb restart or unload/load cycle of the database.
	UpdateDatabaseV2(ctx context.Context, database string, settings *schema.DatabaseNullableSettings) (*schema.UpdateDatabaseResponse, error)

	// Deprecated: Use GetDatabaseSettingsV2.
	GetDatabaseSettings(ctx context.Context) (*schema.DatabaseSettings, error)

	// GetDatabaseSettingsV2 retrieves current persisted database settings.
	GetDatabaseSettingsV2(ctx context.Context) (*schema.DatabaseSettingsResponse, error)

	// SetActiveUser activates or deactivates a user.
	SetActiveUser(ctx context.Context, u *schema.SetActiveUserRequest) error

	// FlushIndex requests a flush operation from the database.
	// This call requires SysAdmin or Admin permission to given database.
	//
	// The cleanupPercentage value is the amount of index nodes data in percent
	// that will be scanned in order to free up unused disk space.
	FlushIndex(ctx context.Context, cleanupPercentage float32, synced bool) (*schema.FlushIndexResponse, error)

	// CompactIndex perform full database compaction.
	// This call requires SysAdmin or Admin permission to given database.
	//
	// Note: Full compaction will greatly affect the performance of the database.
	// It should also be called only when there's a minimal database activity,
	// if full compaction collides with a read or write operation, it will be aborted
	// and may require retry of the whole operation. For that reason it is preferred
	// to periodically call FlushIndex with a small value of cleanupPercentage or set the
	// cleanupPercentage database option.
	CompactIndex(ctx context.Context, req *empty.Empty) error

	// ServerInfo returns information about the server instance.
	ServerInfo(ctx context.Context, req *schema.ServerInfoRequest) (*schema.ServerInfoResponse, error)

	// Health returns Health information about the current database.
	//
	// Requires read access to the database.
	Health(ctx context.Context) (*schema.DatabaseHealthResponse, error)

	// CurrentState returns the current state value from the server for the current database.
	CurrentState(ctx context.Context) (*schema.ImmutableState, error)

	// Set commits a change of a value for a single key.
	Set(ctx context.Context, key []byte, value []byte) (*schema.TxHeader, error)

	// VerifiedSet commits a change of a value for a single key.
	//
	// This function also requests a server-generated proof, verifies the entry in the transaction
	// using the proof and verifies the signature of the signed state.
	// If verification does not succeed the store.ErrCorruptedData error is returned.
	VerifiedSet(ctx context.Context, key []byte, value []byte) (*schema.TxHeader, error)

	// ExpirableSet commits a change of a value for a single key and sets up the expiration
	// time for that value after which the value will no longer be retrievable.
	ExpirableSet(ctx context.Context, key []byte, value []byte, expiresAt time.Time) (*schema.TxHeader, error)

	// Get reads a single value for given key.
	Get(ctx context.Context, key []byte, opts ...GetOption) (*schema.Entry, error)

	// GetSince reads a single value for given key assuming that at least transaction `tx` was indexed.
	// For more information about getting value with sinceTx constraint see the SinceTx get option.
	GetSince(ctx context.Context, key []byte, tx uint64) (*schema.Entry, error)

	// GetAt reads a single value that was modified at a specific transaction.
	// For more information about getting value from specific revision see the AtTx get option.
	GetAt(ctx context.Context, key []byte, tx uint64) (*schema.Entry, error)

	// GetAtRevision reads value for given key by its revision.
	// For more information about the revisions see the AtRevision get option.
	GetAtRevision(ctx context.Context, key []byte, rev int64) (*schema.Entry, error)

	// Gets reads a single value for given key with additional server-provided proof validation.
	VerifiedGet(ctx context.Context, key []byte, opts ...GetOption) (*schema.Entry, error)

	// VerifiedGetSince reads a single value for given key assuming that at least transaction `tx` was indexed.
	// For more information about getting value with sinceTx constraint see the SinceTx get option.
	//
	// This function also requests a server-generated proof, verifies the entry in the transaction
	// using the proof and verifies the signature of the signed state.
	// If verification does not succeed the store.ErrCorruptedData error is returned.
	VerifiedGetSince(ctx context.Context, key []byte, tx uint64) (*schema.Entry, error)

	// VerifiedGetAt reads a single value that was modified at a specific transaction.
	// For more information about getting value from specific revision see the AtTx get option.
	//
	// This function also requests a server-generated proof, verifies the entry in the transaction
	// using the proof and verifies the signature of the signed state.
	// If verification does not succeed the store.ErrCorruptedData error is returned.
	VerifiedGetAt(ctx context.Context, key []byte, tx uint64) (*schema.Entry, error)

	// VerifiedGetAtRevision reads value for given key by its revision.
	// For more information about the revisions see the AtRevision get option.
	//
	// This function also requests a server-generated proof, verifies the entry in the transaction
	// using the proof and verifies the signature of the signed state.
	// If verification does not succeed the store.ErrCorruptedData error is returned.
	VerifiedGetAtRevision(ctx context.Context, key []byte, rev int64) (*schema.Entry, error)

	// History returns history for a single key.
	History(ctx context.Context, req *schema.HistoryRequest) (*schema.Entries, error)

	// ZAdd adds a new entry to sorted set.
	// New entry is a reference to some other key's value with additional score used for ordering set members.
	ZAdd(ctx context.Context, set []byte, score float64, key []byte) (*schema.TxHeader, error)

	// VerifiedZAdd adds a new entry to sorted set.
	// New entry is a reference to some other key's value
	// with additional score used for ordering set members.
	//
	// This function also requests a server-generated proof, verifies the entry in the transaction
	// using the proof and verifies the signature of the signed state.
	// If verification does not succeed the store.ErrCorruptedData error is returned.
	VerifiedZAdd(ctx context.Context, set []byte, score float64, key []byte) (*schema.TxHeader, error)

	// ZAddAt adds a new entry to sorted set.
	// New entry is a reference to some other key's value at a specific transaction
	// with additional score used for ordering set members.
	ZAddAt(ctx context.Context, set []byte, score float64, key []byte, atTx uint64) (*schema.TxHeader, error)

	// VerifiedZAddAt adds a new entry to sorted set.
	// New entry is a reference to some other key's value at a specific transaction
	// with additional score used for ordering set members.
	//
	// This function also requests a server-generated proof, verifies the entry in the transaction
	// using the proof and verifies the signature of the signed state.
	// If verification does not succeed the store.ErrCorruptedData error is returned.
	VerifiedZAddAt(ctx context.Context, set []byte, score float64, key []byte, atTx uint64) (*schema.TxHeader, error)

	// Scan iterates over the set of keys in a topological order.
	Scan(ctx context.Context, req *schema.ScanRequest) (*schema.Entries, error)

	// ZScan iterates over the elements of sorted set ordered by their score.
	ZScan(ctx context.Context, req *schema.ZScanRequest) (*schema.ZEntries, error)

	// TxByID retrieves all entries (in a raw, unprocessed form) for given transaction.
	//
	// Note: In order to read keys and values, it is necessary to parse returned entries
	// TxByIDWithSpec can be used to read already-parsed values
	TxByID(ctx context.Context, tx uint64) (*schema.Tx, error)

	// TxByID retrieves all entries (in a raw, unprocessed form) for given transaction
	// and performs verification of the server-provided proof for the whole transaction.
	VerifiedTxByID(ctx context.Context, tx uint64) (*schema.Tx, error)

	// TxByIDWithSpec retrieves entries from given transaction according to given spec.
	TxByIDWithSpec(ctx context.Context, req *schema.TxRequest) (*schema.Tx, error)

	// TxScan returns raw entries for a range of transactions.
	TxScan(ctx context.Context, req *schema.TxScanRequest) (*schema.TxList, error)

	// Count returns count of key-value entries with given prefix.
	//
	// Note: This feature is not implemented yet.
	Count(ctx context.Context, prefix []byte) (*schema.EntryCount, error)

	// Count returns count of all key-value entries.
	//
	// Note: This feature is not implemented yet.
	CountAll(ctx context.Context) (*schema.EntryCount, error)

	// SetAll sets multiple entries in a single transaction.
	SetAll(ctx context.Context, kvList *schema.SetRequest) (*schema.TxHeader, error)

	// GetAll retrieves multiple entries in a single call.
	GetAll(ctx context.Context, keys [][]byte) (*schema.Entries, error)

	// Delete performs a logical deletion for a list of keys marking them as deleted.
	Delete(ctx context.Context, req *schema.DeleteKeysRequest) (*schema.TxHeader, error)

	// ExecAll performs multiple write operations (values, references, sorted set entries)
	// in a single transaction.
	ExecAll(ctx context.Context, in *schema.ExecAllRequest) (*schema.TxHeader, error)

	// SetReference creates a reference to another key's value.
	//
	// Note: references can only be created to non-reference keys.
	SetReference(ctx context.Context, key []byte, referencedKey []byte) (*schema.TxHeader, error)

	// VerifiedSetReference creates a reference to another key's value and verifies server-provided
	// proof for the write.
	//
	// Note: references can only be created to non-reference keys.
	VerifiedSetReference(ctx context.Context, key []byte, referencedKey []byte) (*schema.TxHeader, error)

	// SetReference creates a reference to another key's value at a specific transaction.
	//
	// Note: references can only be created to non-reference keys.
	SetReferenceAt(ctx context.Context, key []byte, referencedKey []byte, atTx uint64) (*schema.TxHeader, error)

	// SetReference creates a reference to another key's value at a specific transaction and verifies server-provided
	// proof for the write.
	//
	// Note: references can only be created to non-reference keys.
	VerifiedSetReferenceAt(ctx context.Context, key []byte, referencedKey []byte, atTx uint64) (*schema.TxHeader, error)

	// Dump is currently not implemented.
	Dump(ctx context.Context, writer io.WriteSeeker) (int64, error)

	// StreamSet performs a write operation of a value for a single key retrieving key and value form io.Reader streams.
	StreamSet(ctx context.Context, kv []*stream.KeyValue) (*schema.TxHeader, error)

	// StreamGet retrieves a single entry for a key read from an io.Reader stream.
	StreamGet(ctx context.Context, k *schema.KeyRequest) (*schema.Entry, error)

	// StreamVerifiedSet performs a write operation of a value for a single key retrieving key and value form io.Reader streams
	// with additional verification of server-provided write proof.
	StreamVerifiedSet(ctx context.Context, kv []*stream.KeyValue) (*schema.TxHeader, error)

	// StreamVerifiedGet retrieves a single entry for a key read from an io.Reader stream
	// with additional verification of server-provided value proof.
	StreamVerifiedGet(ctx context.Context, k *schema.VerifiableGetRequest) (*schema.Entry, error)

	// StreamScan scans for keys with given prefix, using stream API to overcome limits of large keys and values.
	StreamScan(ctx context.Context, req *schema.ScanRequest) (*schema.Entries, error)

	// StreamZScan scans entries from given sorted set, using stream API to overcome limits of large keys and values.
	StreamZScan(ctx context.Context, req *schema.ZScanRequest) (*schema.ZEntries, error)

	// StreamHistory returns a history of given key, using stream API to overcome limits of large keys and values.
	StreamHistory(ctx context.Context, req *schema.HistoryRequest) (*schema.Entries, error)

	// StreamExecAll performs an ExecAll operation (write operation for multiple data types in a single transaction)
	// using stream API to overcome limits of large keys and values.
	StreamExecAll(ctx context.Context, req *stream.ExecAllRequest) (*schema.TxHeader, error)

	// ExportTx retrieves serialized transaction object.
	ExportTx(ctx context.Context, req *schema.ExportTxRequest) (schema.ImmuService_ExportTxClient, error)

	// ReplicateTx sends a previously serialized transaction object replicating it on another database.
	ReplicateTx(ctx context.Context) (schema.ImmuService_ReplicateTxClient, error)

	// StreamExportTx provides a bidirectional endpoint for retrieving serialized transactions
	StreamExportTx(ctx context.Context, opts ...grpc.CallOption) (schema.ImmuService_StreamExportTxClient, error)

	// SQLExec performs a modifying SQL query within the transaction.
	// Such query does not return SQL result.
	SQLExec(ctx context.Context, sql string, params map[string]interface{}) (*schema.SQLExecResult, error)

	// SQLQuery performs a query (read-only) operation.
	//
	// The renewSnapshot parameter is deprecated and  is ignored by the server.
	SQLQuery(ctx context.Context, sql string, params map[string]interface{}, renewSnapshot bool) (*schema.SQLQueryResult, error)

	// ListTables returns a list of SQL tables.
	ListTables(ctx context.Context) (*schema.SQLQueryResult, error)

	// Describe table returns a description of a table structure.
	DescribeTable(ctx context.Context, tableName string) (*schema.SQLQueryResult, error)

	// VerifyRow reads a single row from the database with additional validation of server-provided proof.
	//
	// The row parameter should contain row from a single table, either returned from
	// query or manually assembled. The table parameter contains the name of the table
	// where the row comes from. The pkVals argument is an array containing values for
	// the primary key of the row. The row parameter does not have to contain all
	// columns of the table. Once the row itself is verified, only those columns that
	// are in the row will be compared against the verified row retrieved from the database.
	VerifyRow(ctx context.Context, row *schema.Row, table string, pkVals []*schema.SQLValue) error

	// NewTx starts a new transaction.
	//
	// Note: Currently such transaction can only be used for SQL operations.
	NewTx(ctx context.Context, opts ...TxOption) (Tx, error)

	// TruncateDatabase truncates a database.
	// This truncates the locally stored value log files used by the database.
	//
	// This call requires SysAdmin permission level or admin permission to the database.
	TruncateDatabase(ctx context.Context, db string, retentionPeriod time.Duration) error
}

ImmuClient is an interface that represents immudb client. Instances returned from NewClient or NewImmuClient methods implement this interface.

type MTLsOptions

type MTLsOptions struct {
	Servername  string
	Pkey        string
	Certificate string
	ClientCAs   string
}

MTLsOptions mTLS options

func DefaultMTLsOptions

func DefaultMTLsOptions() MTLsOptions

DefaultMTLsOptions returns the default mTLS options

func (MTLsOptions) WithCertificate

func (o MTLsOptions) WithCertificate(certificate string) MTLsOptions

WithCertificate sets the client certificate

func (MTLsOptions) WithClientCAs

func (o MTLsOptions) WithClientCAs(clientCAs string) MTLsOptions

WithClientCAs sets a list of CA certificates

func (MTLsOptions) WithPkey

func (o MTLsOptions) WithPkey(pkey string) MTLsOptions

WithPkey sets the client private key

func (MTLsOptions) WithServername

func (o MTLsOptions) WithServername(servername string) MTLsOptions

WithServername sets the server name

type Options

type Options struct {
	Dir                string
	Address            string            // Database hostname / ip address
	Port               int               // Database port number
	HealthCheckRetries int               // Deprecated: no longer used
	MTLs               bool              // If set to true, client should use MTLS for authentication
	MTLsOptions        MTLsOptions       // MTLS settings if used
	Auth               bool              // Set to false if client does not use authentication
	MaxRecvMsgSize     int               // Maximum size of received GRPC message
	DialOptions        []grpc.DialOption // Additional GRPC dial options
	Config             string            // Filename with additional configuration in toml format
	TokenFileName      string            // Deprecated: not used for session-based authentication, name of the file with client token
	CurrentDatabase    string            // Name of the current database

	//--> used by immuclient CLI and sql stdlib package
	PasswordReader c.PasswordReader // Password reader used by the immuclient CLI (TODO: Do not store in immuclient options)
	Username       string           // Currently used username, used by immuclient CLI and go SQL stdlib (TODO: Do not store in immuclient options)
	Password       string           // Currently used password, used by immuclient CLI and go SQL stdlib (TODO: Do not store in immuclient options)
	Database       string           // Currently used database name, used by immuclient CLI and go SQL stdlib (TODO: Do not store in immuclient options)

	Metrics             bool   // Set to true if we should expose metrics, used by immuclient in auditor mode (TODO: Do not store in immuclient options)
	PidPath             string // Path of the PID file, used by immuclient in auditor mode (TODO: Do not store in immuclient options)
	LogFileName         string // Name of the log file to use, used by immuclient in auditor mode (TODO: Do not store in immuclient options)
	ServerSigningPubKey string // Name of the file containing public key for server signature validations
	StreamChunkSize     int    // Maximum size of a data chunk in bytes for streaming operations (directly affects maximum GRPC packet size)

	HeartBeatFrequency time.Duration // Duration between two consecutive heartbeat calls to the server for session heartbeats

	DisableIdentityCheck bool // Do not validate server's identity
}

Options client options

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions ...

func (*Options) Bind

func (o *Options) Bind() string

Bind concatenates address and port

func (*Options) ServerIdentity added in v1.4.1

func (o *Options) ServerIdentity() string

Identity returns server's identity

func (*Options) String

func (o *Options) String() string

String converts options object to a json string

func (*Options) WithAddress

func (o *Options) WithAddress(address string) *Options

WithAddress sets address

func (*Options) WithAuth

func (o *Options) WithAuth(authEnabled bool) *Options

WithAuth activate/deactivate auth

func (*Options) WithConfig

func (o *Options) WithConfig(config string) *Options

WithConfig sets config file name

func (*Options) WithDatabase added in v0.9.2

func (o *Options) WithDatabase(database string) *Options

WithDatabase sets the database for the client

func (*Options) WithDialOptions

func (o *Options) WithDialOptions(dialOptions []grpc.DialOption) *Options

WithDialOptions sets dialOptions

func (*Options) WithDir

func (o *Options) WithDir(dir string) *Options

WithDir sets program file folder

func (*Options) WithDisableIdentityCheck added in v1.4.1

func (o *Options) WithDisableIdentityCheck(disableIdentityCheck bool) *Options

WithDisableIdentityCheck disables or enables server identity check.

Each server identifies itself with a unique UUID which along with the database name is used to identify a particular immudb database instance. This UUID+database name tuple is then used to select appropriate state value stored on the client side to do proof verifications.

Identity check is responsible for ensuring that the server with given identity (which is currently the "host:port" string) must always present with the same UUID.

Disabling this check means that the server can present different UUID.

func (*Options) WithHealthCheckRetries

func (o *Options) WithHealthCheckRetries(retries int) *Options

WithHealthCheckRetries sets health check retries

func (*Options) WithHeartBeatFrequency added in v1.2.0

func (o *Options) WithHeartBeatFrequency(heartBeatFrequency time.Duration) *Options

WithHeartBeatFrequency set the keep alive message frequency

func (*Options) WithLogFileName added in v0.7.0

func (o *Options) WithLogFileName(filename string) *Options

WithLogFileName set log file name

func (*Options) WithMTLs

func (o *Options) WithMTLs(MTLs bool) *Options

WithMTLs activate/deactivate MTLs

func (*Options) WithMTLsOptions

func (o *Options) WithMTLsOptions(MTLsOptions MTLsOptions) *Options

WithMTLsOptions sets MTLsOptions

func (*Options) WithMaxRecvMsgSize added in v0.8.1

func (o *Options) WithMaxRecvMsgSize(maxRecvMsgSize int) *Options

MaxRecvMsgSize max recv msg size in bytes

func (*Options) WithMetrics added in v0.7.0

func (o *Options) WithMetrics(start bool) *Options

WithMetrics set if metrics should start

func (*Options) WithPassword added in v0.9.2

func (o *Options) WithPassword(password string) *Options

WithPassword sets the password for the client

func (*Options) WithPasswordReader added in v0.7.0

func (o *Options) WithPasswordReader(pr c.PasswordReader) *Options

WithPasswordReader sets the password reader for the client

func (*Options) WithPidPath added in v0.7.0

func (o *Options) WithPidPath(path string) *Options

WithPidPath set pid file path

func (*Options) WithPort

func (o *Options) WithPort(port int) *Options

WithPort sets port

func (*Options) WithServerSigningPubKey added in v0.9.0

func (o *Options) WithServerSigningPubKey(serverSigningPubKey string) *Options

WithServerSigningPubKey sets the public key. If presents server state signature verification is enabled

func (*Options) WithStreamChunkSize added in v0.9.2

func (o *Options) WithStreamChunkSize(streamChunkSize int) *Options

WithStreamChunkSize set the chunk size

func (*Options) WithTokenFileName

func (o *Options) WithTokenFileName(tokenFileName string) *Options

WithTokenFileName sets token file name

func (*Options) WithUsername added in v0.9.2

func (o *Options) WithUsername(username string) *Options

WithUsername sets the username for the client

type TimestampService

type TimestampService interface {
	GetTime() time.Time
}

TimestampService is a simple service returning the current time.

func NewTimestampService

func NewTimestampService(ts timestamp.TsGenerator) TimestampService

NewTimestampService creates new timestamp service returning current system time.

type Tx added in v1.2.0

type Tx interface {

	// Commit commits a transaction.
	Commit(ctx context.Context) (*schema.CommittedSQLTx, error)

	// Rollback rollbacks a transaction.
	Rollback(ctx context.Context) error

	// SQLExec performs a modifying SQL query within the transaction.
	// Such query does not return SQL result.
	SQLExec(ctx context.Context, sql string, params map[string]interface{}) error

	// SQLQuery performs a query (read-only) operation.
	SQLQuery(ctx context.Context, sql string, params map[string]interface{}) (*schema.SQLQueryResult, error)
}

Tx represents an open transaction

Note: Currently this object only supports SQL transactions

type TxOption added in v1.5.0

type TxOption func(req *schema.NewTxRequest) error

TxOption is used to set additional options when creating a transaction with a NewTx call

func SnapshotMustIncludeTxID added in v1.5.0

func SnapshotMustIncludeTxID(txID uint64) TxOption

An existing snapshot may be reused as long as it includes the specified transaction

func SnapshotRenewalPeriod added in v1.5.0

func SnapshotRenewalPeriod(renewalPeriod time.Duration) TxOption

An existing snapshot may be reused as long as it is not older than the specified timeframe

func UnsafeMVCC added in v1.5.0

func UnsafeMVCC() TxOption

UnsafeMVCC option means the server is not forced to wait for the indexer to be up-to-date with the most recent transaction during conflict detection.

In practice this means that the user will get the result faster with the risk of inconsistencies if another transaction invalidated the data read by this transaction.

This option may be useful when it's guaranteed that related data is not concurrently written.

Directories

Path Synopsis
Package clienttest ...
Package clienttest ...

Jump to

Keyboard shortcuts

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