package query

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

Example (SelectWithParameters)

Code:

{
	ctx := context.TODO()
	db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
	if err != nil {
		fmt.Printf("failed connect: %v", err)

		return
	}
	defer db.Close(ctx) // cleanup resources
	var (
		id    int32  // required value
		myStr string // optional value
	)
	// Do retry operation on errors with best effort
	err = db.Query().Do(ctx, // context manage exiting from Do
		func(ctx context.Context, s query.Session) (err error) { // retry operation
			_, res, err := s.Execute(ctx,
				`SELECT CAST($id AS Uint64) AS id, CAST($myStr AS Text) AS myStr`,
				query.WithParameters(
					ydb.ParamsBuilder().
						Param("$id").Uint64(123).
						Param("$myStr").Text("123").
						Build(),
				),
			)
			if err != nil {
				return err // for auto-retry with driver
			}
			defer func() { _ = res.Close(ctx) }() // cleanup resources
			for {                                 // iterate over result sets
				rs, err := res.NextResultSet(ctx)
				if err != nil {
					if errors.Is(err, io.EOF) {
						break
					}

					return err
				}
				for { // iterate over rows
					row, err := rs.NextRow(ctx)
					if err != nil {
						if errors.Is(err, io.EOF) {
							break
						}

						return err
					}
					if err = row.ScanNamed(
						query.Named("id", &id),
						query.Named("myStr", &myStr),
					); err != nil {
						return err // generally scan error not retryable, return it for driver check error
					}
				}
			}

			return res.Err() // return finally result error for auto-retry with driver
		},
		query.WithIdempotent(),
	)
	if err != nil {
		fmt.Printf("unexpected error: %v", err)
	}
	fmt.Printf("id=%v, myStr='%s'\n", id, myStr)
}
Example (SelectWithoutParameters)

Code:

{
	ctx := context.TODO()
	db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
	if err != nil {
		fmt.Printf("failed connect: %v", err)

		return
	}
	defer db.Close(ctx) // cleanup resources
	var (
		id    int32  // required value
		myStr string // optional value
	)
	// Do retry operation on errors with best effort
	err = db.Query().Do(ctx, // context manage exiting from Do
		func(ctx context.Context, s query.Session) (err error) { // retry operation
			_, res, err := s.Execute(ctx,
				`SELECT 42 as id, "my string" as myStr`,
			)
			if err != nil {
				return err // for auto-retry with driver
			}
			defer func() { _ = res.Close(ctx) }() // cleanup resources
			for {                                 // iterate over result sets
				rs, err := res.NextResultSet(ctx)
				if err != nil {
					if errors.Is(err, io.EOF) {
						break
					}

					return err
				}
				for { // iterate over rows
					row, err := rs.NextRow(ctx)
					if err != nil {
						if errors.Is(err, io.EOF) {
							break
						}

						return err
					}
					if err = row.Scan(&id, &myStr); err != nil {
						return err // generally scan error not retryable, return it for driver check error
					}
				}
			}

			return res.Err() // return finally result error for auto-retry with driver
		},
		query.WithIdempotent(),
	)
	if err != nil {
		fmt.Printf("unexpected error: %v", err)
	}
	fmt.Printf("id=%v, myStr='%s'\n", id, myStr)
}
Example (TxSelect)

Code:

{
	ctx := context.TODO()
	db, err := ydb.Open(ctx, "grpc://localhost:2136/local")
	if err != nil {
		fmt.Printf("failed connect: %v", err)

		return
	}
	defer db.Close(ctx) // cleanup resources
	var (
		id    int32  // required value
		myStr string // optional value
	)
	// Do retry operation on errors with best effort
	err = db.Query().DoTx(ctx, // context manage exiting from Do
		func(ctx context.Context, tx query.TxActor) (err error) { // retry operation
			res, err := tx.Execute(ctx,
				`SELECT 42 as id, "my string" as myStr`,
			)
			if err != nil {
				return err // for auto-retry with driver
			}
			defer func() { _ = res.Close(ctx) }() // cleanup resources
			for {                                 // iterate over result sets
				rs, err := res.NextResultSet(ctx)
				if err != nil {
					if errors.Is(err, io.EOF) {
						break
					}

					return err
				}
				for { // iterate over rows
					row, err := rs.NextRow(ctx)
					if err != nil {
						if errors.Is(err, io.EOF) {
							break
						}

						return err
					}
					if err = row.ScanNamed(
						query.Named("id", &id),
						query.Named("myStr", &myStr),
					); err != nil {
						return err // generally scan error not retryable, return it for driver check error
					}
				}
			}

			return res.Err() // return finally result error for auto-retry with driver
		},
		query.WithIdempotent(),
		query.WithTxSettings(query.TxSettings(
			query.WithSnapshotReadOnly(),
		)),
	)
	if err != nil {
		fmt.Printf("unexpected error: %v", err)
	}
	fmt.Printf("id=%v, myStr='%s'\n", id, myStr)
}

Index

Examples

Constants

const (
	SyntaxYQL        = Syntax(Ydb_Query.Syntax_SYNTAX_YQL_V1)
	SyntaxPostgreSQL = Syntax(Ydb_Query.Syntax_SYNTAX_PG)
)
const (
	SessionStatusUnknown = SessionStatus(iota)
	SessionStatusReady
	SessionStatusInUse
	SessionStatusClosed
)

Functions

func BeginTx

func BeginTx(opts ...txSettingsOption) beginTxOptions

BeginTx returns selector transaction control option

func CommitTx

func CommitTx() txControlOption

CommitTx returns commit transaction control option

func ExecuteSettings

func ExecuteSettings(opts ...ExecuteOption) (settings *executeSettings)

func Named

func Named(columnName string, destinationValueReference interface{}) (dst scanner.NamedDestination)

func TxExecuteSettings

func TxExecuteSettings(id string, opts ...TxExecuteOption) (settings *txExecuteSettings)

func WithCallOptions

func WithCallOptions(opts ...grpc.CallOption) callOptions

func WithCommit

func WithCommit() txCommitOption

func WithDefaultTxMode

func WithDefaultTxMode() txSettingsOption

func WithIdempotent

func WithIdempotent() idempotentOption

func WithOnlineReadOnly

func WithOnlineReadOnly(opts ...TxOnlineReadOnlyOption) onlineReadOnlySettingsOption

func WithParameters

func WithParameters(parameters *params.Parameters) *parametersOption

func WithScanStructAllowMissingColumnsFromSelect

func WithScanStructAllowMissingColumnsFromSelect() scanner.ScanStructOption

func WithScanStructAllowMissingFieldsInStruct

func WithScanStructAllowMissingFieldsInStruct() scanner.ScanStructOption

func WithScanStructTagName

func WithScanStructTagName(name string) scanner.ScanStructOption

func WithSerializableReadWrite

func WithSerializableReadWrite() txSettingsOption

func WithSnapshotReadOnly

func WithSnapshotReadOnly() txSettingsOption

func WithStaleReadOnly

func WithStaleReadOnly() txSettingsOption

func WithTrace

func WithTrace(t trace.Query) traceOption

func WithTx

func WithTx(t TxIdentifier) txIDTxControlOption

func WithTxControl

func WithTxControl(txControl *TransactionControl) *transactionControlOption

func WithTxID

func WithTxID(txID string) txIDTxControlOption

func WithTxSettings

func WithTxSettings(txSettings TransactionSettings) doTxSettingsOption

Types

type Client

type Client interface {
	// Do provide the best effort for execute operation.
	//
	// Do implements internal busy loop until one of the following conditions is met:
	// - deadline was canceled or deadlined
	// - retry operation returned nil as error
	//
	// Warning: if context without deadline or cancellation func than Do can run indefinitely.
	Do(ctx context.Context, op Operation, opts ...DoOption) error

	// DoTx provide the best effort for execute transaction.
	//
	// DoTx implements internal busy loop until one of the following conditions is met:
	// - deadline was canceled or deadlined
	// - retry operation returned nil as error
	//
	// DoTx makes auto selector (with TransactionSettings, by default - SerializableReadWrite), commit and
	// rollback (on error) of transaction.
	//
	// If op TxOperation returns nil - transaction will be committed
	// If op TxOperation return non nil - transaction will be rollback
	// Warning: if context without deadline or cancellation func than DoTx can run indefinitely
	DoTx(ctx context.Context, op TxOperation, opts ...DoTxOption) error
}

type ClosableSession

type ClosableSession interface {
	closer.Closer

	Session
}

type DoOption

type DoOption interface {
	// contains filtered or unexported methods
}

type DoOptions

type DoOptions struct {
	Label        string
	Idempotent   bool
	RetryOptions []retry.Option
	Trace        *trace.Query
}

func NewDoOptions

func NewDoOptions(opts ...DoOption) (doOptions DoOptions)

type DoTxOption

type DoTxOption interface {
	// contains filtered or unexported methods
}

type DoTxOptions

type DoTxOptions struct {
	DoOptions

	TxSettings TransactionSettings
}

func NewDoTxOptions

func NewDoTxOptions(opts ...DoTxOption) (doTxOptions DoTxOptions)

type ExecMode

type ExecMode Ydb_Query.ExecMode

func WithExecMode

func WithExecMode(mode ExecMode) ExecMode

type ExecuteOption

type ExecuteOption interface {
	// contains filtered or unexported methods
}

type Operation

type Operation func(ctx context.Context, s Session) error

Operation is the interface that holds an operation for retry. if Operation returns not nil - operation will retry if Operation returns nil - retry loop will break

type Result

type Result interface {
	closer.Closer

	NextResultSet(ctx context.Context) (ResultSet, error)
	Err() error
}

type ResultSet

type ResultSet interface {
	NextRow(ctx context.Context) (Row, error)
}

type Row

type Row interface {
	Scan(dst ...interface{}) error
	ScanNamed(dst ...scanner.NamedDestination) error
	ScanStruct(dst interface{}, opts ...scanner.ScanStructOption) error
}

type Session

type Session interface {
	SessionInfo

	// Execute executes query.
	//
	// Execute used by default:
	// - DefaultTxControl
	// - flag WithKeepInCache(true) if params is not empty.
	Execute(ctx context.Context, query string, opts ...ExecuteOption) (tx Transaction, r Result, err error)

	Begin(ctx context.Context, txSettings TransactionSettings) (Transaction, error)
}

type SessionInfo

type SessionInfo interface {
	ID() string
	NodeID() int64
	Status() SessionStatus
}

type SessionStatus

type SessionStatus uint32

func (SessionStatus) String

func (s SessionStatus) String() string

type StatsMode

type StatsMode Ydb_Query.StatsMode

func WithStatsMode

func WithStatsMode(mode StatsMode) StatsMode

type Syntax

type Syntax Ydb_Query.Syntax

func WithSyntax

func WithSyntax(syntax Syntax) Syntax

type Transaction

type Transaction interface {
	TxActor

	CommitTx(ctx context.Context) (err error)
	Rollback(ctx context.Context) (err error)
}

type TransactionControl

type TransactionControl struct {
	// contains filtered or unexported fields
}

func DefaultTxControl

func DefaultTxControl() *TransactionControl

DefaultTxControl returns default transaction control with serializable read-write isolation mode and auto-commit

func NoTx

func NoTx() *TransactionControl

func OnlineReadOnlyTxControl

func OnlineReadOnlyTxControl(opts ...TxOnlineReadOnlyOption) *TransactionControl

OnlineReadOnlyTxControl returns online read-only transaction control

func SerializableReadWriteTxControl

func SerializableReadWriteTxControl(opts ...txControlOption) *TransactionControl

SerializableReadWriteTxControl returns transaction control with serializable read-write isolation mode

func SnapshotReadOnlyTxControl

func SnapshotReadOnlyTxControl() *TransactionControl

SnapshotReadOnlyTxControl returns snapshot read-only transaction control

func StaleReadOnlyTxControl

func StaleReadOnlyTxControl() *TransactionControl

StaleReadOnlyTxControl returns stale read-only transaction control

func TxControl

func TxControl(opts ...txControlOption) *TransactionControl

TxControl makes transaction control from given options

func (*TransactionControl) ToYDB

type TransactionSettings

type TransactionSettings []txSettingsOption

Transaction settings options

func TxSettings

func TxSettings(opts ...txSettingsOption) TransactionSettings

TxSettings returns transaction settings

func (TransactionSettings) ToYDB

type TxActor

type TxActor interface {
	TxIdentifier

	// Execute executes query.
	//
	// Execute used by default:
	// - DefaultTxControl
	// - flag WithKeepInCache(true) if params is not empty.
	Execute(ctx context.Context, query string, opts ...TxExecuteOption) (r Result, err error)
}

type TxExecuteOption

type TxExecuteOption interface {
	// contains filtered or unexported methods
}

type TxIdentifier

type TxIdentifier interface {
	ID() string
}

type TxOnlineReadOnlyOption

type TxOnlineReadOnlyOption interface {
	// contains filtered or unexported methods
}

func WithInconsistentReads

func WithInconsistentReads() TxOnlineReadOnlyOption

type TxOperation

type TxOperation func(ctx context.Context, tx TxActor) error

TxOperation is the interface that holds an operation for retry. if TxOperation returns not nil - operation will retry if TxOperation returns nil - retry loop will break

Source Files

client.go do_options.go do_tx_options.go execute_options.go options.go result.go session.go session_status.go transaction.go transaction_control.go transaction_settings.go

Version
v3.57.0
Published
Mar 7, 2024
Platform
darwin/amd64
Imports
11 packages
Last checked
9 seconds ago

Tools for package owners.