v3 – github.com/ydb-platform/ydb-go-sdk/v3 Index | Examples | Files | Directories

package ydb

import "github.com/ydb-platform/ydb-go-sdk/v3"

Package ydb-go-sdk - native Go's driver for YDB.

Supports table, discovery, coordination, ratelimiter, scheme and scripting clients for YDB. YDB is an open-source Distributed SQL Database that combines high availability and scalability with strict consistency and ACID transactions.

Example (TableBulkUpsert)

Code:

{
	ctx := context.Background()
	db, err := ydb.New(ctx,
		ydb.WithConnectionString("grpcs://localhost:2135/?database=/local"),
		ydb.WithAnonymousCredentials(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		_ = db.Close(ctx)
	}()
	type logMessage struct {
		App       string
		Host      string
		Timestamp time.Time
		HTTPCode  uint32
		Message   string
	}
	// prepare native go data
	const batchSize = 10000
	logs := make([]logMessage, 0, batchSize)
	for i := 0; i < batchSize; i++ {
		message := logMessage{
			App:       fmt.Sprintf("App_%d", i/256),
			Host:      fmt.Sprintf("192.168.0.%d", i%256),
			Timestamp: time.Now().Add(time.Millisecond * time.Duration(i%1000)),
			HTTPCode:  200,
		}
		if i%2 == 0 {
			message.Message = "GET / HTTP/1.1"
		} else {
			message.Message = "GET /images/logo.png HTTP/1.1"
		}
		logs = append(logs, message)
	}
	// execute bulk upsert with native ydb data
	err = db.Table().Do( // Do retry operation on errors with best effort
		ctx, // context manage exiting from Do
		func(ctx context.Context, s table.Session) (err error) { // retry operation
			rows := make([]types.Value, 0, len(logs))
			for _, msg := range logs {
				rows = append(rows, types.StructValue(
					types.StructFieldValue("App", types.UTF8Value(msg.App)),
					types.StructFieldValue("Host", types.UTF8Value(msg.Host)),
					types.StructFieldValue("Timestamp", types.TimestampValueFromTime(msg.Timestamp)),
					types.StructFieldValue("HTTPCode", types.Uint32Value(msg.HTTPCode)),
					types.StructFieldValue("Message", types.UTF8Value(msg.Message)),
				))
			}
			return s.BulkUpsert(ctx, "/local/bulk_upsert_example", types.ListValue(rows...))
		},
	)
	if err != nil {
		log.Printf("unexpected error: %v", err)
	}
}
Example (TableCreateTable)

Code:

{
	ctx := context.Background()
	db, err := ydb.New(ctx,
		ydb.WithConnectionString("grpcs://localhost:2135/?database=/local"),
		ydb.WithAnonymousCredentials(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		_ = db.Close(ctx)
	}()
	err = db.Table().Do(
		ctx,
		func(ctx context.Context, s table.Session) (err error) {
			return s.CreateTable(ctx, path.Join(db.Name(), "series"),
				options.WithColumn("series_id", types.Optional(types.TypeUint64)),
				options.WithColumn("title", types.Optional(types.TypeUTF8)),
				options.WithColumn("series_info", types.Optional(types.TypeUTF8)),
				options.WithColumn("release_date", types.Optional(types.TypeDate)),
				options.WithColumn("comment", types.Optional(types.TypeUTF8)),
				options.WithPrimaryKeyColumn("series_id"),
			)
		},
	)
	if err != nil {
		log.Printf("unexpected error: %v", err)
	}
}
Example (TableSelect)

Code:

{
	ctx := context.Background()
	db, err := ydb.New(ctx,
		ydb.WithConnectionString("grpcs://localhost:2135/?database=/local"),
		ydb.WithAnonymousCredentials(),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		_ = db.Close(ctx)
	}()
	var (
		query = `SELECT 42 as id, "my string" as myStr`
		id    int32  // required value
		myStr string // optional value
	)
	err = db.Table().Do( // Do retry operation on errors with best effort
		ctx, // context manage exiting from Do
		func(ctx context.Context, s table.Session) (err error) { // retry operation
			_, res, err := s.Execute(ctx, table.DefaultTxControl(), query, nil)
			if err != nil {
				return err // for driver retry
			}
			defer func() {
				_ = res.Close() // must close always
			}()
			if err = res.NextResultSetErr(ctx); err != nil { // check single result set and switch to it
				return err // for driver retry
			}
			for res.NextRow() { // iterate over rows
				err = res.ScanNamed(
					named.Required("id", &id),
					named.OptionalWithDefault("myStr", &myStr),
				)
				if err != nil {
					return err
				}
				log.Printf("id=%v, myStr='%s'\n", id, myStr)
			}
			return res.Err() // for driver retry if not nil
		},
	)
	if err != nil {
		log.Printf("unexpected error: %v", err)
	}
}

Index

Examples

Constants

const Version = meta.Version

Version reports current version of sdk

Functions

func IsOperationError

func IsOperationError(err error, codes ...Ydb.StatusIds_StatusCode) bool

IsOperationError reports whether any error is an operation error with one of passed codes. If codes not defined IsOperationError returns true on error is an operation error.

func IsOperationErrorAlreadyExistsError

func IsOperationErrorAlreadyExistsError(err error) bool

IsOperationErrorAlreadyExistsError checks whether given err is an operation error with code AlreadyExistsError

func IsOperationErrorNotFoundError

func IsOperationErrorNotFoundError(err error) bool

IsOperationErrorNotFoundError checks whether given err is an operation error with code NotFoundError

func IsOperationErrorOverloaded

func IsOperationErrorOverloaded(err error) bool

IsOperationErrorOverloaded checks whether given err is an operation error with code Overloaded

func IsOperationErrorSchemeError

func IsOperationErrorSchemeError(err error) bool

IsOperationErrorSchemeError checks whether given err is an operation error with code SchemeError

func IsOperationErrorUnavailable

func IsOperationErrorUnavailable(err error) bool

IsOperationErrorUnavailable checks whether given err is an operation error with code Unavailable

func IsRatelimiterAcquireError

func IsRatelimiterAcquireError(err error) bool

IsRatelimiterAcquireError checks whether given err is an ratelimiter acquire error

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError checks whether given err is a some timeout error (context, transport or operation).

func IsTransportError

func IsTransportError(err error, codes ...grpcCodes.Code) bool

IsTransportError checks whether given err is a transport (grpc) error.

func IsYdbError

func IsYdbError(err error) bool

IsYdbError reports when given error is and ydb error (transport, operation or internal driver error)

func IterateByIssues

func IterateByIssues(err error, it func(message string, code Ydb.StatusIds_StatusCode, severity uint32))

IterateByIssues helps to iterate over internal issues of operation error.

func ToRatelimiterAcquireError

func ToRatelimiterAcquireError(err error) ratelimiter.AcquireError

ToRatelimiterAcquireError casts given err to ratelimiter.AcquireError. If given err is not ratelimiter acquire error - returns nil

func WithOperationCancelAfter

func WithOperationCancelAfter(ctx context.Context, operationCancelAfter time.Duration) context.Context

WithOperationCancelAfter returns a copy of parent context in which YDB operation cancel after parameter is set to d. If parent context cancellation timeout is smaller than d, parent context is returned.

func WithOperationTimeout

func WithOperationTimeout(ctx context.Context, operationTimeout time.Duration) context.Context

WithOperationTimeout returns a copy of parent context in which YDB operation timeout parameter is set to d. If parent context timeout is smaller than d, parent context is returned.

func WithRequestType

func WithRequestType(ctx context.Context, requestType string) context.Context

WithRequestType returns a copy of parent context with custom request type

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID returns a copy of parent context with traceID

Types

type Connection

type Connection interface {
	closer.Closer
	database.Info
	grpc.ClientConnInterface

	// Table returns table client
	Table() table.Client

	// Scheme returns scheme client
	Scheme() scheme.Client

	// Coordination returns coordination client
	Coordination() coordination.Client

	// Ratelimiter returns rate limiter client
	Ratelimiter() ratelimiter.Client

	// Discovery returns discovery client
	Discovery() discovery.Client

	// Scripting returns scripting client
	Scripting() scripting.Client

	// With returns Connection specified with custom options
	// Options provide options replacement for all clients taked from new Connection
	With(ctx context.Context, opts ...Option) (Connection, error)
}

Connection interface provide access to YDB service clients Interface and list of clients may be changed in the future

func New

func New(ctx context.Context, opts ...Option) (_ Connection, err error)

New connects to database and return driver runtime holder

type Error

type Error interface {
	error

	// Code reports the error code
	Code() int32

	// Name reports the name of error
	Name() string
}

Error is an interface of error which reports about error code and error name.

func OperationError

func OperationError(err error) Error

OperationError returns operation error description. If given err is not an operation error - returns nil.

func TransportError

func TransportError(err error) Error

TransportError checks when given error is a transport error and returns description of transport error.

type LoggerOption

type LoggerOption logger.Option

func WithErrWriter

func WithErrWriter(err io.Writer) LoggerOption

func WithExternalLogger

func WithExternalLogger(external log.Logger) LoggerOption

func WithMinLevel

func WithMinLevel(minLevel log.Level) LoggerOption

func WithNamespace

func WithNamespace(namespace string) LoggerOption

func WithNoColor

func WithNoColor(b bool) LoggerOption

func WithOutWriter

func WithOutWriter(out io.Writer) LoggerOption

type Option

type Option func(ctx context.Context, c *connection) error

func MergeOptions

func MergeOptions(opts ...Option) Option

func With

func With(options ...config.Option) Option

func WithAccessTokenCredentials

func WithAccessTokenCredentials(accessToken string) Option

func WithAnonymousCredentials

func WithAnonymousCredentials() Option

func WithBalancer

func WithBalancer(balancer balancer.Balancer) Option

func WithCertificate

func WithCertificate(cert *x509.Certificate) Option

func WithCertificatesFromFile

func WithCertificatesFromFile(caFile string) Option

func WithCertificatesFromPem

func WithCertificatesFromPem(bytes []byte) Option

func WithConnectionString

func WithConnectionString(connectionString string) Option

WithConnectionString accept connection string like 'grpc[s]://{endpoint}/?database={database}' Warning: WithConnectionString will be removed at next major release (connection string will be required string param of ydb.New)

func WithConnectionTTL

func WithConnectionTTL(ttl time.Duration) Option

WithConnectionTTL defines duration for parking idle connections Warning: if defined WithSessionPoolIdleThreshold - idleThreshold must be less than connectionTTL

func WithCreateCredentialsFunc

func WithCreateCredentialsFunc(createCredentials func(ctx context.Context) (credentials.Credentials, error)) Option

func WithCredentials

func WithCredentials(c credentials.Credentials) Option

WithCredentials in conjunction with Connection.With function prohibit reuse of conn pool. Thus, Connection.With will effectively create totally separate Connection.

func WithDatabase

func WithDatabase(database string) Option

WithDatabase defines database option Deprecated: use WithConnectionString or dsn package instead

func WithDialTimeout

func WithDialTimeout(timeout time.Duration) Option

func WithDiscoveryInterval

func WithDiscoveryInterval(discoveryInterval time.Duration) Option

func WithEndpoint

func WithEndpoint(endpoint string) Option

WithEndpoint defines endpoint option Deprecated: use WithConnectionString or dsn package instead

func WithInsecure

func WithInsecure() Option

WithInsecure defines secure option Deprecated: use WithConnectionString or dsn package instead

func WithLogger

func WithLogger(details trace.Details, opts ...LoggerOption) Option

func WithMinTLSVersion

func WithMinTLSVersion(minVersion uint16) Option

func WithPanicCallback

func WithPanicCallback(panicCallback func(e interface{})) Option

WithPanicCallback specified behavior on panic Warning: WithPanicCallback must be defined on start of all options (before `WithTrace{Driver,Table,Scheme,Scripting,Coordination,Ratelimiter}` and other options) If not defined - panic would not intercept with driver

func WithRatelimiterOptions

func WithRatelimiterOptions(opts ...ratelimiterConfig.Option) Option

func WithRequestsType

func WithRequestsType(requestsType string) Option

func WithSecure

func WithSecure(secure bool) Option

WithSecure defines secure option Deprecated: use WithConnectionString or dsn package instead

func WithSessionPoolCreateSessionTimeout

func WithSessionPoolCreateSessionTimeout(createSessionTimeout time.Duration) Option

func WithSessionPoolDeleteTimeout

func WithSessionPoolDeleteTimeout(deleteTimeout time.Duration) Option

func WithSessionPoolIdleThreshold

func WithSessionPoolIdleThreshold(idleThreshold time.Duration) Option

WithSessionPoolIdleThreshold defines keep-alive interval for idle sessions Warning: if defined WithConnectionTTL - idleThreshold must be less than connectionTTL

func WithSessionPoolKeepAliveMinSize

func WithSessionPoolKeepAliveMinSize(keepAliveMinSize int) Option

func WithSessionPoolKeepAliveTimeout

func WithSessionPoolKeepAliveTimeout(keepAliveTimeout time.Duration) Option

func WithSessionPoolSizeLimit

func WithSessionPoolSizeLimit(sizeLimit int) Option

func WithTLSSInsecureSkipVerify

func WithTLSSInsecureSkipVerify() Option

func WithTableConfigOption

func WithTableConfigOption(option tableConfig.Option) Option

func WithTraceCoordination

func WithTraceCoordination(t trace.Coordination, opts ...trace.CoordinationComposeOption) Option

WithTraceCoordination returns coordination trace option

func WithTraceDiscovery

func WithTraceDiscovery(t trace.Discovery, opts ...trace.DiscoveryComposeOption) Option

WithTraceDiscovery returns discovery trace option

func WithTraceDriver

func WithTraceDriver(trace trace.Driver, opts ...trace.DriverComposeOption) Option

WithTraceDriver returns deadline which has associated Driver with it.

func WithTraceRatelimiter

func WithTraceRatelimiter(t trace.Ratelimiter, opts ...trace.RatelimiterComposeOption) Option

WithTraceRatelimiter returns ratelimiter trace option

func WithTraceScheme

func WithTraceScheme(t trace.Scheme, opts ...trace.SchemeComposeOption) Option

WithTraceScheme returns scheme trace option

func WithTraceScripting

func WithTraceScripting(t trace.Scripting, opts ...trace.ScriptingComposeOption) Option

WithTraceScripting scripting trace option

func WithTraceTable

func WithTraceTable(t trace.Table, opts ...trace.TableComposeOption) Option

WithTraceTable returns table trace option

func WithUserAgent

func WithUserAgent(userAgent string) Option

Source Files

connection.go context.go doc.go errors.go logger_options.go meta.go options.go version.go with.go

Directories

PathSynopsis
balancers
config
coordination
coordination/config
credentials
discovery
discovery/config
dsn
internal
log
ratelimiter
ratelimiter/config
retry
scheme
scheme/config
scripting
scripting/config
sugar
table
table/config
table/options
table/result
table/result/indexed
table/result/named
table/stats
table/types
test
testutil
testutil/timeutil
testutil/timeutil/timetest
trace
Version
v3.20.2
Published
Apr 12, 2022
Platform
js/wasm
Imports
42 packages
Last checked
now

Tools for package owners.