query

package
v3.66.3 Latest Latest
Warning

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

Go to latest
Published: May 3, 2024 License: Apache-2.0 Imports: 12 Imported by: 3

Documentation

Overview

Example (SelectWithParameters)
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`,
			options.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
	},
	options.WithIdempotent(),
)
if err != nil {
	fmt.Printf("unexpected error: %v", err)
}
fmt.Printf("id=%v, myStr='%s'\n", id, myStr)
Output:

Example (SelectWithoutParameters)
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)
Output:

Example (TxSelect)
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
	},
	options.WithIdempotent(),
	options.WithTxSettings(query.TxSettings(
		query.WithSnapshotReadOnly(),
	)),
)
if err != nil {
	fmt.Printf("unexpected error: %v", err)
}
fmt.Printf("id=%v, myStr='%s'\n", id, myStr)
Output:

Index

Examples

Constants

View Source
const (
	SyntaxYQL        = options.SyntaxYQL
	SyntaxPostgreSQL = options.SyntaxPostgreSQL
)
View Source
const (
	ExecModeParse    = options.ExecModeParse
	ExecModeValidate = options.ExecModeValidate
	ExecModeExplain  = options.ExecModeExplain
	ExecModeExecute  = options.ExecModeExecute
)
View Source
const (
	StatsModeBasic   = options.StatsModeBasic
	StatsModeNone    = options.StatsModeNone
	StatsModeFull    = options.StatsModeFull
	StatsModeProfile = options.StatsModeProfile
)

Variables

This section is empty.

Functions

func BeginTx

func BeginTx(opts ...tx.Option) tx.ControlOption

BeginTx returns selector transaction control option

func CommitTx

func CommitTx() tx.ControlOption

CommitTx returns commit transaction control option

func Named

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

func Stats added in v3.59.0

func Stats(client Client) (*stats.Stats, error)

func WithCallOptions

func WithCallOptions(opts ...grpc.CallOption) options.CallOptions

func WithCommit

func WithCommit() options.TxExecuteOption

func WithDefaultTxMode

func WithDefaultTxMode() tx.Option

func WithExecMode

func WithExecMode(mode options.ExecMode) options.ExecModeOption

func WithIdempotent

func WithIdempotent() bothDoAndDoTxOption

func WithInconsistentReads

func WithInconsistentReads() tx.OnlineReadOnlyOption

func WithLabel added in v3.57.1

func WithLabel(lbl string) bothDoAndDoTxOption

func WithOnlineReadOnly

func WithOnlineReadOnly(opts ...tx.OnlineReadOnlyOption) tx.Option

func WithParameters

func WithParameters(parameters *params.Parameters) options.ParametersOption

func WithRetryBudget added in v3.66.0

func WithRetryBudget(b budget.Budget) bothDoAndDoTxOption

Experimental: https://github.com/ydb-platform/ydb-go-sdk/blob/master/VERSIONING.md#experimental

func WithScanStructAllowMissingColumnsFromSelect

func WithScanStructAllowMissingColumnsFromSelect() scanner.ScanStructOption

func WithScanStructAllowMissingFieldsInStruct

func WithScanStructAllowMissingFieldsInStruct() scanner.ScanStructOption

func WithScanStructTagName

func WithScanStructTagName(name string) scanner.ScanStructOption

func WithSerializableReadWrite

func WithSerializableReadWrite() tx.Option

func WithSnapshotReadOnly

func WithSnapshotReadOnly() tx.Option

func WithStaleReadOnly

func WithStaleReadOnly() tx.Option

func WithStatsMode

func WithStatsMode(mode options.StatsMode) options.StatsModeOption

func WithSyntax

func WithSyntax(syntax options.Syntax) options.SyntaxOption

func WithTrace

func WithTrace(t *trace.Query) bothDoAndDoTxOption

func WithTx

func WithTx(t tx.Identifier) tx.ControlOption

func WithTxControl

func WithTxControl(txControl *tx.Control) options.TxControlOption

func WithTxID

func WithTxID(txID string) tx.ControlOption

func WithTxSettings

func WithTxSettings(txSettings tx.Settings) options.DoTxOption

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 ...options.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 ...options.DoTxOption) error
}

type ClosableSession

type ClosableSession interface {
	closer.Closer

	Session
}

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 (NoTx)
	// - flag WithKeepInCache(true) if params is not empty.
	Execute(ctx context.Context, query string, opts ...options.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() string
}

type Transaction

type Transaction interface {
	TxActor

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

type TransactionControl

type TransactionControl = tx.Control

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 ...tx.OnlineReadOnlyOption) *TransactionControl

OnlineReadOnlyTxControl returns online read-only transaction control

func SerializableReadWriteTxControl

func SerializableReadWriteTxControl(opts ...tx.ControlOption) *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 ...tx.ControlOption) *TransactionControl

TxControl makes transaction control from given options

type TransactionSettings

type TransactionSettings = tx.Settings

func TxSettings

func TxSettings(opts ...tx.Option) TransactionSettings

TxSettings returns transaction settings

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 ...options.TxExecuteOption) (r Result, err error)
}

type TxIdentifier

type TxIdentifier interface {
	ID() string
}

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

Jump to

Keyboard shortcuts

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