tarantool

package module
v2.0.0-...-2a4499d Latest Latest
Warning

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

Go to latest
Published: Aug 8, 2023 License: BSD-2-Clause Imports: 21 Imported by: 0

README

Go Reference Actions Status Code Coverage Telegram GitHub Discussions Stack Overflow

Client in Go for Tarantool

The package go-tarantool contains everything you need to connect to Tarantool 1.10+.

The advantage of integrating Go with Tarantool, which is an application server plus a DBMS, is that Go programmers can handle databases and perform on-the-fly recompilations of embedded Lua routines, just as in C, with responses that are faster than other packages according to public benchmarks.

Table of contents

Installation

We assume that you have Tarantool version 1.10+ and a modern Linux or BSD operating system.

You need a current version of go, version 1.13 or later (use go version to check the version number). Do not use gccgo-go.

Note: If your go version is older than 1.13 or if go is not installed, download and run the latest tarball from golang.org.

The package go-tarantool is located in GruffGemini/go-tarantool repository. To download and install, say:

$ go get github.com/GruffGemini/go-tarantool/v2

This should put the source and binary files in subdirectories of /usr/local/go, so that you can access them by adding github.com/GruffGemini/go-tarantool to the import {...} section at the start of any Go program.

Build tags

We define multiple build tags.

This allows us to introduce new features without losing backward compatibility.

  1. To run fuzz tests with decimals, you can use the build tag:
    go_tarantool_decimal_fuzzing
    
    Note: It crashes old Tarantool versions and requires Go 1.18+.

Documentation

Read the Tarantool documentation to find descriptions of terms such as "connect", "space", "index", and the requests to create and manipulate database objects or Lua functions.

In general, connector methods can be divided into two main parts:

  • Connect() function and functions related to connecting, and
  • Data manipulation functions and Lua invocations such as Insert() or Call().

The supported requests have parameters and results equivalent to requests in the Tarantool CRUD operations. There are also Typed and Async versions of each data-manipulation function.

API Reference

Learn API documentation and examples at pkg.go.dev.

Walking-through example

We can now have a closer look at the example and make some observations about what it does.

package tarantool

import (
	"fmt"
	"github.com/GruffGemini/go-tarantool/v2"
)

func main() {
	opts := tarantool.Opts{User: "guest"}
	conn, err := tarantool.Connect("127.0.0.1:3301", opts)
	if err != nil {
		fmt.Println("Connection refused:", err)
	}
	resp, err := conn.Do(tarantool.NewInsertRequest(999).
		Tuple([]interface{}{99999, "BB"}),
	).Get()
	if err != nil {
		fmt.Println("Error", err)
		fmt.Println("Code", resp.Code)
	}
}

Observation 1: The line "github.com/GruffGemini/go-tarantool/v2" in the import(...) section brings in all Tarantool-related functions and structures.

Observation 2: The line starting with "Opts :=" sets up the options for Connect(). In this example, the structure contains only a single value, the username. The structure may also contain other settings, see more in documentation for the "Opts" structure.

Observation 3: The line containing "tarantool.Connect" is essential for starting a session. There are two parameters:

  • a string with host:port format, and
  • the option structure that was set up earlier.

Observation 4: The err structure will be nil if there is no error, otherwise it will have a description which can be retrieved with err.Error().

Observation 5: The Insert request, like almost all requests, is preceded by the method Do of object conn which is the object that was returned by Connect().

Migration to v2

The article describes migration from go-tarantool to go-tarantool/v2.

datetime package

Now you need to use objects of the Datetime type instead of pointers to it. A new constructor MakeDatetime returns an object. NewDatetime has been removed.

decimal package

Now you need to use objects of the Decimal type instead of pointers to it. A new constructor MakeDecimal returns an object. NewDecimal has been removed.

multi package

The subpackage has been deleted. You could use pool instead.

pool package

The logic has not changed, but there are a few renames:

  • The connection_pool subpackage has been renamed to pool.
  • The type PoolOpts has been renamed to Opts.
msgpack.v5

Most function names and argument types in msgpack.v5 and msgpack.v2 have not changed (in our code, we noticed changes in EncodeInt, EncodeUint and RegisterExt). But there are a lot of changes in a logic of encoding and decoding. On the plus side the migration seems easy, but on the minus side you need to be very careful.

First of all, EncodeInt8, EncodeInt16, EncodeInt32, EncodeInt64 and EncodeUint* analogues at msgpack.v5 encode numbers as is without loss of type. In msgpack.v2 the type of a number is reduced to a value.

Secondly, a base decoding function does not convert numbers to int64 or uint64. It converts numbers to an exact type defined by MessagePack. The change makes manual type conversions much more difficult and can lead to runtime errors with an old code. We do not recommend to use type conversions and give preference to *Typed functions (besides, it's faster).

There are also changes in the logic that can lead to errors in the old code, as example. Although in msgpack.v5 some functions for the logic tuning were added (see UseLooseInterfaceDecoding, UseCompactInts etc), it is still impossible to achieve full compliance of behavior between msgpack.v5 and msgpack.v2. So we don't go this way. We use standard settings if it possible.

Call = Call17

Call requests uses IPROTO_CALL instead of IPROTO_CALL_16.

So now Call = Call17 and NewCallRequest = NewCall17Request. A result of the requests is an array instead of array of arrays.

IPROTO constants

IPROTO constants have been moved to a separate package go-iproto.

Request interface
  • The method Code() uint32 replaced by the Type() iproto.Type.

Contributing

See the contributing guide for detailed instructions on how to get started with our project.

Alternative connectors

There are two other connectors available from the open source community:

See feature comparison in the documentation.

Documentation

Overview

Package with implementation of methods and structures for work with Tarantool instance.

Example (CustomUnpacking)

Example demonstrates how to use custom (un)packing with typed selects and function calls.

You can specify user-defined packing/unpacking functions for your types. This allows you to store complex structures within a tuple and may speed up your requests.

Alternatively, you can just instruct the msgpack library to encode your structure as an array. This is safe "magic". It is easier to implement than a custom packer/unpacker, but it will work slower.

package main

import (
	"fmt"
	"log"
	"time"

	"github.com/vmihailenco/msgpack/v5"

	"github.com/GruffGemini/go-tarantool/v2"
)

type Tuple2 struct {
	Cid     uint
	Orig    string
	Members []Member
}

// Same effect in a "magic" way, but slower.
type Tuple3 struct {
	_msgpack struct{} `msgpack:",asArray"` //nolint: structcheck,unused

	Cid     uint
	Orig    string
	Members []Member
}

func (c *Tuple2) EncodeMsgpack(e *msgpack.Encoder) error {
	if err := e.EncodeArrayLen(3); err != nil {
		return err
	}
	if err := e.EncodeUint(uint64(c.Cid)); err != nil {
		return err
	}
	if err := e.EncodeString(c.Orig); err != nil {
		return err
	}
	e.Encode(c.Members)
	return nil
}

func (c *Tuple2) DecodeMsgpack(d *msgpack.Decoder) error {
	var err error
	var l int
	if l, err = d.DecodeArrayLen(); err != nil {
		return err
	}
	if l != 3 {
		return fmt.Errorf("array len doesn't match: %d", l)
	}
	if c.Cid, err = d.DecodeUint(); err != nil {
		return err
	}
	if c.Orig, err = d.DecodeString(); err != nil {
		return err
	}
	if l, err = d.DecodeArrayLen(); err != nil {
		return err
	}
	c.Members = make([]Member, l)
	for i := 0; i < l; i++ {
		d.Decode(&c.Members[i])
	}
	return nil
}

// Example demonstrates how to use custom (un)packing with typed selects and
// function calls.
//
// You can specify user-defined packing/unpacking functions for your types.
// This allows you to store complex structures within a tuple and may speed up
// your requests.
//
// Alternatively, you can just instruct the msgpack library to encode your
// structure as an array. This is safe "magic". It is easier to implement than
// a custom packer/unpacker, but it will work slower.
func main() {
	// Establish a connection.
	server := "127.0.0.1:3013"
	opts := tarantool.Opts{
		Timeout:       500 * time.Millisecond,
		Reconnect:     1 * time.Second,
		MaxReconnects: 3,
		User:          "test",
		Pass:          "test",
	}
	conn, err := tarantool.Connect(server, opts)
	if err != nil {
		log.Fatalf("Failed to connect: %s", err.Error())
	}

	spaceNo := uint32(617)
	indexNo := uint32(0)

	tuple := Tuple2{Cid: 777, Orig: "orig", Members: []Member{{"lol", "", 1}, {"wut", "", 3}}}
	// Insert a structure itself.
	initReq := tarantool.NewReplaceRequest(spaceNo).Tuple(&tuple)
	resp, err := conn.Do(initReq).Get()
	if err != nil {
		log.Fatalf("Failed to insert: %s", err.Error())
		return
	}
	fmt.Println("Data", resp.Data)
	fmt.Println("Code", resp.Code)

	var tuples1 []Tuple2
	selectReq := tarantool.NewSelectRequest(spaceNo).
		Index(indexNo).
		Limit(1).
		Iterator(tarantool.IterEq).
		Key([]interface{}{777})
	err = conn.Do(selectReq).GetTyped(&tuples1)
	if err != nil {
		log.Fatalf("Failed to SelectTyped: %s", err.Error())
		return
	}
	fmt.Println("Tuples (tuples1)", tuples1)

	// Same result in a "magic" way.
	var tuples2 []Tuple3
	err = conn.Do(selectReq).GetTyped(&tuples2)
	if err != nil {
		log.Fatalf("Failed to SelectTyped: %s", err.Error())
		return
	}
	fmt.Println("Tuples (tuples2):", tuples2)

	// Call a function "func_name" returning a table of custom tuples.
	var tuples3 [][]Tuple3
	callReq := tarantool.NewCallRequest("func_name")
	err = conn.Do(callReq).GetTyped(&tuples3)
	if err != nil {
		log.Fatalf("Failed to CallTyped: %s", err.Error())
		return
	}
	fmt.Println("Tuples (tuples3):", tuples3)

}
Output:

Data [[777 orig [[lol 1] [wut 3]]]]
Code 0
Tuples (tuples1) [{777 orig [{lol  1} {wut  3}]}]
Tuples (tuples2): [{{} 777 orig [{lol  1} {wut  3}]}]
Tuples (tuples3): [[{{} 221  [{Moscow  34} {Minsk  23} {Kiev  31}]}]]

Index

Examples

Constants

View Source
const (
	// Connected signals that connection is established or reestablished.
	Connected ConnEventKind = iota + 1
	// Disconnected signals that connection is broken.
	Disconnected
	// ReconnectFailed signals that attempt to reconnect has failed.
	ReconnectFailed
	// Shutdown signals that shutdown callback is processing.
	Shutdown
	// Either reconnect attempts exhausted, or explicit Close is called.
	Closed

	// LogReconnectFailed is logged when reconnect attempt failed.
	LogReconnectFailed ConnLogKind = iota + 1
	// LogLastReconnectFailed is logged when last reconnect attempt failed,
	// connection will be closed after that.
	LogLastReconnectFailed
	// LogUnexpectedResultId is logged when response with unknown id was received.
	// Most probably it is due to request timeout.
	LogUnexpectedResultId
	// LogWatchEventReadFailed is logged when failed to read a watch event.
	LogWatchEventReadFailed
)
View Source
const (
	OkCode   = uint32(iproto.IPROTO_OK)
	PushCode = uint32(iproto.IPROTO_CHUNK)
)
View Source
const (
	ErrConnectionNotReady = 0x4000 + iota
	ErrConnectionClosed   = 0x4000 + iota
	ErrProtocolError      = 0x4000 + iota
	ErrTimeouted          = 0x4000 + iota
	ErrRateLimited        = 0x4000 + iota
	ErrConnectionShutdown = 0x4000 + iota
	ErrIoError            = 0x4000 + iota
)

Tarantool client error codes.

Variables

This section is empty.

Functions

This section is empty.

Types

type Auth

type Auth int

Auth is used as a parameter to set up an authentication method.

const (
	// AutoAuth does not force any authentication method. A method will be
	// selected automatically (a value from IPROTO_ID response or
	// ChapSha1Auth).
	AutoAuth Auth = iota
	// ChapSha1Auth forces chap-sha1 authentication method. The method is
	// available both in the Tarantool Community Edition (CE) and the
	// Tarantool Enterprise Edition (EE)
	ChapSha1Auth
	// PapSha256Auth forces pap-sha256 authentication method. The method is
	// available only for the Tarantool Enterprise Edition (EE) with
	// SSL transport.
	PapSha256Auth
)

func (Auth) String

func (a Auth) String() string

String returns a string representation of an authentication method.

type BeginRequest

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

BeginRequest helps you to create a begin request object for execution by a Stream. Begin request can not be processed out of stream.

func NewBeginRequest

func NewBeginRequest() *BeginRequest

NewBeginRequest returns a new BeginRequest.

func (*BeginRequest) Async

func (req *BeginRequest) Async() bool

Async returns true if the request does not require a response.

func (*BeginRequest) Body

func (req *BeginRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the begin request body.

func (*BeginRequest) Context

func (req *BeginRequest) Context(ctx context.Context) *BeginRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*BeginRequest) Ctx

func (req *BeginRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*BeginRequest) Timeout

func (req *BeginRequest) Timeout(timeout time.Duration) *BeginRequest

WithTimeout allows to set up a timeout for call BeginRequest.

func (*BeginRequest) TxnIsolation

func (req *BeginRequest) TxnIsolation(txnIsolation TxnIsolationLevel) *BeginRequest

TxnIsolation sets the the transaction isolation level for transaction manager. By default, the isolation level of Tarantool is serializable.

Example
var req tarantool.Request
var resp *tarantool.Response
var err error

// Tarantool supports streams and interactive transactions since version 2.10.0
isLess, _ := test_helpers.IsTarantoolVersionLess(2, 10, 0)
if err != nil || isLess {
	return
}

txnOpts := getTestTxnOpts()
conn := exampleConnect(txnOpts)
defer conn.Close()

stream, _ := conn.NewStream()

// Begin transaction
req = tarantool.NewBeginRequest().
	TxnIsolation(tarantool.ReadConfirmedLevel).
	Timeout(500 * time.Millisecond)
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Begin: %s", err.Error())
	return
}
fmt.Printf("Begin transaction: response is %#v\n", resp.Code)

// Insert in stream
req = tarantool.NewInsertRequest(spaceName).
	Tuple([]interface{}{uint(2001), "rollback_hello", "rollback_world"})
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Insert: %s", err.Error())
	return
}
fmt.Printf("Insert in stream: response is %#v\n", resp.Code)

// Select not related to the transaction
// while transaction is not committed
// result of select is empty
selectReq := tarantool.NewSelectRequest(spaceNo).
	Index(indexNo).
	Limit(1).
	Iterator(tarantool.IterEq).
	Key([]interface{}{uint(2001)})
resp, err = conn.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select out of stream: response is %#v\n", resp.Data)

// Select in stream
resp, err = stream.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select in stream: response is %#v\n", resp.Data)

// Rollback transaction
req = tarantool.NewRollbackRequest()
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Rollback: %s", err.Error())
	return
}
fmt.Printf("Rollback transaction: response is %#v\n", resp.Code)

// Select outside of transaction
resp, err = conn.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select after Rollback: response is %#v\n", resp.Data)
Output:

func (*BeginRequest) Type

func (req *BeginRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type BoxError

type BoxError struct {
	// Type is error type that implies its source (for example, "ClientError").
	Type string
	// File is a source code file where the error was caught.
	File string
	// Line is a number of line in the source code file where the error was caught.
	Line uint64
	// Msg is the text of reason.
	Msg string
	// Errno is the ordinal number of the error.
	Errno uint64
	// Code is the number of the error as defined in `errcode.h`.
	Code uint64
	// Fields are additional fields depending on error type. For example, if
	// type is "AccessDeniedError", then it will include "object_type",
	// "object_name", "access_type".
	Fields map[string]interface{}
	// Prev is the previous error in stack.
	Prev *BoxError
}

BoxError is a type representing Tarantool `box.error` object: a single MP_ERROR_STACK object with a link to the previous stack error. See https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_error/error/

Since 1.10.0

func (*BoxError) Depth

func (e *BoxError) Depth() int

Depth computes the count of errors in stack, including the current one.

func (*BoxError) Error

func (e *BoxError) Error() string

Error converts a BoxError to a string.

func (*BoxError) MarshalMsgpack

func (e *BoxError) MarshalMsgpack() ([]byte, error)

MarshalMsgpack serializes the BoxError into a MessagePack representation.

func (*BoxError) UnmarshalMsgpack

func (e *BoxError) UnmarshalMsgpack(b []byte) error

UnmarshalMsgpack deserializes a BoxError value from a MessagePack representation.

type BroadcastRequest

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

BroadcastRequest helps to send broadcast messages. See: https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_events/broadcast/

func NewBroadcastRequest

func NewBroadcastRequest(key string) *BroadcastRequest

NewBroadcastRequest returns a new broadcast request for a specified key.

func (*BroadcastRequest) Async

func (req *BroadcastRequest) Async() bool

Async returns is the broadcast request expects a response.

func (*BroadcastRequest) Body

func (req *BroadcastRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the broadcast request body.

func (*BroadcastRequest) Context

func (req *BroadcastRequest) Context(ctx context.Context) *BroadcastRequest

Context sets a passed context to the broadcast request.

func (*BroadcastRequest) Ctx

func (req *BroadcastRequest) Ctx() context.Context

Ctx returns a context of the broadcast request.

func (*BroadcastRequest) Type

func (req *BroadcastRequest) Type() iproto.Type

Code returns IPROTO code for the broadcast request.

func (*BroadcastRequest) Value

func (req *BroadcastRequest) Value(value interface{}) *BroadcastRequest

Value sets the value for the broadcast request. Note: default value is nil.

type CallRequest

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

CallRequest helps you to create a call request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

// Call a function 'simple_concat' with arguments.
resp, err := conn.Do(tarantool.NewCallRequest("simple_concat").
	Args([]interface{}{"1"}),
).Get()
fmt.Println("Call simple_concat()")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
Output:

Call simple_concat()
Error <nil>
Code 0
Data [11]

func NewCall16Request

func NewCall16Request(function string) *CallRequest

NewCall16Request returns a new empty Call16Request. It uses request code for Tarantool 1.6. Deprecated since Tarantool 1.7.2.

func NewCall17Request

func NewCall17Request(function string) *CallRequest

NewCall17Request returns a new empty CallRequest. It uses request code for Tarantool >= 1.7.

func NewCallRequest

func NewCallRequest(function string) *CallRequest

NewCallRequest returns a new empty CallRequest. It uses request code for Tarantool >= 1.7.

func (*CallRequest) Args

func (req *CallRequest) Args(args interface{}) *CallRequest

Args sets the args for the call request. Note: default value is empty.

func (*CallRequest) Async

func (req *CallRequest) Async() bool

Async returns true if the request does not require a response.

func (*CallRequest) Body

func (req *CallRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an encoder with the call request body.

func (*CallRequest) Context

func (req *CallRequest) Context(ctx context.Context) *CallRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*CallRequest) Ctx

func (req *CallRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*CallRequest) Type

func (req *CallRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type ClientError

type ClientError struct {
	Code uint32
	Msg  string
}

ClientError is connection error produced by this client, i.e. connection failures or timeouts.

func (ClientError) Error

func (clierr ClientError) Error() string

Error converts a ClientError to a string.

func (ClientError) Temporary

func (clierr ClientError) Temporary() bool

Temporary returns true if next attempt to perform request may succeeded.

Currently it returns true when:

- Connection is not connected at the moment

- request is timeouted

- request is aborted due to rate limit

type ColumnMetaData

type ColumnMetaData struct {
	FieldName            string
	FieldType            string
	FieldCollation       string
	FieldIsNullable      bool
	FieldIsAutoincrement bool
	FieldSpan            string
}

func (*ColumnMetaData) DecodeMsgpack

func (meta *ColumnMetaData) DecodeMsgpack(d *msgpack.Decoder) error

type CommitRequest

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

CommitRequest helps you to create a commit request object for execution by a Stream. Commit request can not be processed out of stream.

Example
var req tarantool.Request
var resp *tarantool.Response
var err error

// Tarantool supports streams and interactive transactions since version 2.10.0
isLess, _ := test_helpers.IsTarantoolVersionLess(2, 10, 0)
if err != nil || isLess {
	return
}

txnOpts := getTestTxnOpts()
conn := exampleConnect(txnOpts)
defer conn.Close()

stream, _ := conn.NewStream()

// Begin transaction
req = tarantool.NewBeginRequest()
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Begin: %s", err.Error())
	return
}
fmt.Printf("Begin transaction: response is %#v\n", resp.Code)

// Insert in stream
req = tarantool.NewInsertRequest(spaceName).
	Tuple([]interface{}{uint(1001), "commit_hello", "commit_world"})
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Insert: %s", err.Error())
	return
}
fmt.Printf("Insert in stream: response is %#v\n", resp.Code)

// Select not related to the transaction
// while transaction is not committed
// result of select is empty
selectReq := tarantool.NewSelectRequest(spaceNo).
	Index(indexNo).
	Limit(1).
	Iterator(tarantool.IterEq).
	Key([]interface{}{uint(1001)})
resp, err = conn.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select out of stream before commit: response is %#v\n", resp.Data)

// Select in stream
resp, err = stream.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select in stream: response is %#v\n", resp.Data)

// Commit transaction
req = tarantool.NewCommitRequest()
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Commit: %s", err.Error())
	return
}
fmt.Printf("Commit transaction: response is %#v\n", resp.Code)

// Select outside of transaction
resp, err = conn.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select after commit: response is %#v\n", resp.Data)
Output:

func NewCommitRequest

func NewCommitRequest() *CommitRequest

NewCommitRequest returns a new CommitRequest.

func (*CommitRequest) Async

func (req *CommitRequest) Async() bool

Async returns true if the request does not require a response.

func (*CommitRequest) Body

func (req *CommitRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the commit request body.

func (*CommitRequest) Context

func (req *CommitRequest) Context(ctx context.Context) *CommitRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*CommitRequest) Ctx

func (req *CommitRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*CommitRequest) Type

func (req *CommitRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type Conn

type Conn interface {
	// Read reads data from the connection.
	Read(b []byte) (int, error)
	// Write writes data to the connection. There may be an internal buffer for
	// better performance control from a client side.
	Write(b []byte) (int, error)
	// Flush writes any buffered data.
	Flush() error
	// Close closes the connection.
	// Any blocked Read or Flush operations will be unblocked and return
	// errors.
	Close() error
	// LocalAddr returns the local network address, if known.
	LocalAddr() net.Addr
	// RemoteAddr returns the remote network address, if known.
	RemoteAddr() net.Addr
	// Greeting returns server greeting.
	Greeting() Greeting
	// ProtocolInfo returns server protocol info.
	ProtocolInfo() ProtocolInfo
}

Conn is a generic stream-oriented network connection to a Tarantool instance.

type ConnEvent

type ConnEvent struct {
	Conn *Connection
	Kind ConnEventKind
	When time.Time
}

ConnEvent is sent throw Notify channel specified in Opts.

type ConnEventKind

type ConnEventKind int

type ConnLogKind

type ConnLogKind int

type ConnectedRequest

type ConnectedRequest interface {
	Request
	// Conn returns a Connection the request belongs to.
	Conn() *Connection
}

ConnectedRequest is an interface that provides the info about a Connection the request belongs to.

type Connection

type Connection struct {

	// Schema contains schema loaded on connection.
	Schema *Schema

	// Greeting contains first message sent by Tarantool.
	Greeting *Greeting
	// contains filtered or unexported fields
}

Connection is a handle with a single connection to a Tarantool instance.

It is created and configured with Connect function, and could not be reconfigured later.

Connection could be in three possible states:

- In "Connected" state it sends queries to Tarantool.

- In "Disconnected" state it rejects queries with ClientError{Code: ErrConnectionNotReady}

- In "Shutdown" state it rejects queries with ClientError{Code: ErrConnectionShutdown}. The state indicates that a graceful shutdown in progress. The connection waits for all active requests to complete.

- In "Closed" state it rejects queries with ClientError{Code: ErrConnectionClosed}. Connection could become "Closed" when Connection.Close() method called, or when Tarantool disconnected and Reconnect pause is not specified or MaxReconnects is specified and MaxReconnect reconnect attempts already performed.

You may perform data manipulation operation by calling its methods: Call*, Insert*, Replace*, Update*, Upsert*, Call*, Eval*.

In any method that accepts space you my pass either space number or space name (in this case it will be looked up in schema). Same is true for index.

ATTENTION: tuple, key, ops and args arguments for any method should be and array or should serialize to msgpack array.

ATTENTION: result argument for *Typed methods should deserialize from msgpack array, cause Tarantool always returns result as an array. For all space related methods and Call16* (but not Call17*) methods Tarantool always returns array of array (array of tuples for space related methods). For Eval* and Call* Tarantool always returns array, but does not forces array of arrays.

If connected to Tarantool 2.10 or newer, connection supports server graceful shutdown. In this case, server will wait until all client requests will be finished and client disconnects before going down (server also may go down by timeout). Client reconnect will happen if connection options enable reconnect. Beware that graceful shutdown event initialization is asynchronous.

More on graceful shutdown: https://www.tarantool.io/en/doc/latest/dev_guide/internals/iproto/graceful_shutdown/

func Connect

func Connect(addr string, opts Opts) (conn *Connection, err error)

Connect creates and configures a new Connection.

Address could be specified in following ways:

- TCP connections (tcp://192.168.1.1:3013, tcp://my.host:3013, tcp:192.168.1.1:3013, tcp:my.host:3013, 192.168.1.1:3013, my.host:3013)

- Unix socket, first '/' or '.' indicates Unix socket (unix:///abs/path/tnt.sock, unix:path/tnt.sock, /abs/path/tnt.sock, ./rel/path/tnt.sock, unix/:path/tnt.sock)

Notes:

- If opts.Reconnect is zero (default), then connection either already connected or error is returned.

- If opts.Reconnect is non-zero, then error will be returned only if authorization fails. But if Tarantool is not reachable, then it will make an attempt to reconnect later and will not finish to make attempts on authorization failures.

Example
conn, err := tarantool.Connect("127.0.0.1:3013", tarantool.Opts{
	Timeout:     5 * time.Second,
	User:        "test",
	Pass:        "test",
	Concurrency: 32,
})
if err != nil {
	fmt.Println("No connection available")
	return
}
defer conn.Close()
if conn != nil {
	fmt.Println("Connection is ready")
}
Output:

Connection is ready

func (*Connection) Addr

func (conn *Connection) Addr() string

Addr returns a configured address of Tarantool socket.

func (*Connection) Call deprecated

func (conn *Connection) Call(functionName string, args interface{}) (*Response, error)

Call calls registered Tarantool function. It uses request code for Tarantool >= 1.7, result is an array.

It is equal to conn.CallAsync(functionName, args).Get().

Deprecated: the method will be removed in the next major version, use a CallRequest object + Do() instead.

func (*Connection) Call16 deprecated

func (conn *Connection) Call16(functionName string, args interface{}) (*Response, error)

Call16 calls registered Tarantool function. It uses request code for Tarantool 1.6, result is an array of arrays. Deprecated since Tarantool 1.7.2.

It is equal to conn.Call16Async(functionName, args).Get().

Deprecated: the method will be removed in the next major version, use a Call16Request object + Do() instead.

func (*Connection) Call16Async deprecated

func (conn *Connection) Call16Async(functionName string, args interface{}) *Future

Call16Async sends a call to registered Tarantool function and returns Future. It uses request code for Tarantool 1.6, so future's result is an array of arrays. Deprecated since Tarantool 1.7.2.

Deprecated: the method will be removed in the next major version, use a Call16Request object + Do() instead.

func (*Connection) Call16Typed deprecated

func (conn *Connection) Call16Typed(functionName string, args interface{},
	result interface{}) error

Call16Typed calls registered function. It uses request code for Tarantool 1.6, result is an array of arrays. Deprecated since Tarantool 1.7.2.

It is equal to conn.Call16Async(functionName, args).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use a Call16Request object + Do() instead.

func (*Connection) Call17 deprecated

func (conn *Connection) Call17(functionName string, args interface{}) (*Response, error)

Call17 calls registered Tarantool function. It uses request code for Tarantool >= 1.7, result is an array.

It is equal to conn.Call17Async(functionName, args).Get().

Deprecated: the method will be removed in the next major version, use a Call17Request object + Do() instead.

func (*Connection) Call17Async deprecated

func (conn *Connection) Call17Async(functionName string, args interface{}) *Future

Call17Async sends a call to registered Tarantool function and returns Future. It uses request code for Tarantool >= 1.7, so future's result is an array.

Deprecated: the method will be removed in the next major version, use a Call17Request object + Do() instead.

func (*Connection) Call17Typed deprecated

func (conn *Connection) Call17Typed(functionName string, args interface{},
	result interface{}) error

Call17Typed calls registered function. It uses request code for Tarantool >= 1.7, result is an array.

It is equal to conn.Call17Async(functionName, args).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use a Call17Request object + Do() instead.

func (*Connection) CallAsync deprecated

func (conn *Connection) CallAsync(functionName string, args interface{}) *Future

CallAsync sends a call to registered Tarantool function and returns Future. It uses request code for Tarantool >= 1.7, so future's result is an array.

Deprecated: the method will be removed in the next major version, use a CallRequest object + Do() instead.

func (*Connection) CallTyped deprecated

func (conn *Connection) CallTyped(functionName string, args interface{},
	result interface{}) error

CallTyped calls registered function. It uses request code for Tarantool >= 1.7, result is an array.

It is equal to conn.Call16Async(functionName, args).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use a CallRequest object + Do() instead.

func (*Connection) ClientProtocolInfo

func (conn *Connection) ClientProtocolInfo() ProtocolInfo

ClientProtocolVersion returns protocol version and protocol features supported by Go connection client. Since 1.10.0

func (*Connection) Close

func (conn *Connection) Close() error

Close closes Connection. After this method called, there is no way to reopen this Connection.

func (*Connection) CloseGraceful

func (conn *Connection) CloseGraceful() error

CloseGraceful closes Connection gracefully. It waits for all requests to complete. After this method called, there is no way to reopen this Connection.

Example (Force)

ExampleConnection_CloseGraceful_force demonstrates how to force close a connection with graceful close in progress after a while.

conn := exampleConnect(opts)

eval := `local fiber = require('fiber')
	local time = ...
	fiber.sleep(time)
`
req := tarantool.NewEvalRequest(eval).Args([]interface{}{10})
fut := conn.Do(req)

done := make(chan struct{})
go func() {
	conn.CloseGraceful()
	fmt.Println("Connection.CloseGraceful() done!")
	close(done)
}()

select {
case <-done:
case <-time.After(time.Second):
	fmt.Println("Force Connection.Close()!")
	conn.Close()
}
<-done

fmt.Println("Result:")
fmt.Println(fut.Get())
Output:

Force Connection.Close()!
Connection.CloseGraceful() done!
Result:
<nil> connection closed by client (0x4001)

func (*Connection) ClosedNow

func (conn *Connection) ClosedNow() bool

ClosedNow reports if connection is closed by user or after reconnect.

func (*Connection) ConfiguredTimeout

func (conn *Connection) ConfiguredTimeout() time.Duration

ConfiguredTimeout returns a timeout from connection config.

func (*Connection) ConnectedNow

func (conn *Connection) ConnectedNow() bool

ConnectedNow reports if connection is established at the moment.

func (*Connection) Delete deprecated

func (conn *Connection) Delete(space, index interface{}, key interface{}) (*Response, error)

Delete performs deletion of a tuple by key. Result will contain array with deleted tuple.

It is equal to conn.DeleteAsync(space, tuple).Get().

Deprecated: the method will be removed in the next major version, use a DeleteRequest object + Do() instead.

func (*Connection) DeleteAsync deprecated

func (conn *Connection) DeleteAsync(space, index interface{}, key interface{}) *Future

DeleteAsync sends deletion action to Tarantool and returns Future. Future's result will contain array with deleted tuple.

Deprecated: the method will be removed in the next major version, use a DeleteRequest object + Do() instead.

func (*Connection) DeleteTyped deprecated

func (conn *Connection) DeleteTyped(space, index interface{}, key interface{},
	result interface{}) error

DeleteTyped performs deletion of a tuple by key and fills result with deleted tuple.

It is equal to conn.DeleteAsync(space, tuple).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use a DeleteRequest object + Do() instead.

func (*Connection) Do

func (conn *Connection) Do(req Request) *Future

Do performs a request asynchronously on the connection.

An error is returned if the request was formed incorrectly, or failed to create the future.

Example

ExampleConnection_Do demonstrates how to send a request and process a response.

conn := exampleConnect(opts)
defer conn.Close()

// It could be any request.
req := tarantool.NewReplaceRequest("test").
	Tuple([]interface{}{int(1111), "foo", "bar"})

// We got a future, the request actually not performed yet.
future := conn.Do(req)

// When the future receives the response, the result of the Future is set
// and becomes available. We could wait for that moment with Future.Get()
// or Future.GetTyped() methods.
resp, err := future.Get()
if err != nil {
	fmt.Printf("Failed to execute the request: %s\n", err)
} else {
	fmt.Println(resp.Data)
}
Output:

[[1111 foo bar]]
Example (Failure)

ExampleConnection_Do_failure demonstrates how to send a request and process failure.

conn := exampleConnect(opts)
defer conn.Close()

// It could be any request.
req := tarantool.NewCallRequest("not_exist")

// We got a future, the request actually not performed yet.
future := conn.Do(req)

// When the future receives the response, the result of the Future is set
// and becomes available. We could wait for that moment with Future.Get()
// or Future.GetTyped() methods.
resp, err := future.Get()
if err != nil {
	// We don't print the error here to keep the example reproducible.
	// fmt.Printf("Failed to execute the request: %s\n", err)
	if resp == nil {
		// Something happens in a client process (timeout, IO error etc).
		fmt.Printf("Resp == nil, ClientErr = %s\n", err.(tarantool.ClientError))
	} else {
		// Response exist. So it could be a Tarantool error or a decode
		// error. We need to check the error code.
		fmt.Printf("Error code from the response: %d\n", resp.Code)
		if resp.Code == tarantool.OkCode {
			fmt.Printf("Decode error: %s\n", err)
		} else {
			code := err.(tarantool.Error).Code
			fmt.Printf("Error code from the error: %d\n", code)
			fmt.Printf("Error short from the error: %s\n", code)
		}
	}
}
Output:

Error code from the response: 33
Error code from the error: 33
Error short from the error: ER_NO_SUCH_PROC

func (*Connection) Eval deprecated

func (conn *Connection) Eval(expr string, args interface{}) (*Response, error)

Eval passes Lua expression for evaluation.

It is equal to conn.EvalAsync(space, tuple).Get().

Deprecated: the method will be removed in the next major version, use an EvalRequest object + Do() instead.

func (*Connection) EvalAsync deprecated

func (conn *Connection) EvalAsync(expr string, args interface{}) *Future

EvalAsync sends a Lua expression for evaluation and returns Future.

Deprecated: the method will be removed in the next major version, use an EvalRequest object + Do() instead.

func (*Connection) EvalTyped deprecated

func (conn *Connection) EvalTyped(expr string, args interface{}, result interface{}) error

EvalTyped passes Lua expression for evaluation.

It is equal to conn.EvalAsync(space, tuple).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use an EvalRequest object + Do() instead.

func (*Connection) Execute deprecated

func (conn *Connection) Execute(expr string, args interface{}) (*Response, error)

Execute passes sql expression to Tarantool for execution.

It is equal to conn.ExecuteAsync(expr, args).Get(). Since 1.6.0

Deprecated: the method will be removed in the next major version, use an ExecuteRequest object + Do() instead.

func (*Connection) ExecuteAsync deprecated

func (conn *Connection) ExecuteAsync(expr string, args interface{}) *Future

ExecuteAsync sends a sql expression for execution and returns Future. Since 1.6.0

Deprecated: the method will be removed in the next major version, use an ExecuteRequest object + Do() instead.

func (*Connection) ExecuteTyped deprecated

func (conn *Connection) ExecuteTyped(expr string, args interface{},
	result interface{}) (SQLInfo, []ColumnMetaData, error)

ExecuteTyped passes sql expression to Tarantool for execution.

In addition to error returns sql info and columns meta data Since 1.6.0

Deprecated: the method will be removed in the next major version, use an ExecuteRequest object + Do() instead.

func (*Connection) GetTyped deprecated

func (conn *Connection) GetTyped(space, index interface{}, key interface{},
	result interface{}) error

GetTyped performs select (with limit = 1 and offset = 0) to box space and fills typed result.

It is equal to conn.SelectAsync(space, index, 0, 1, IterEq, key).GetTyped(&result)

Deprecated: the method will be removed in the next major version, use a SelectRequest object + Do() instead.

func (*Connection) Handle

func (conn *Connection) Handle() interface{}

Handle returns a user-specified handle from Opts.

func (*Connection) Insert deprecated

func (conn *Connection) Insert(space interface{}, tuple interface{}) (*Response, error)

Insert performs insertion to box space. Tarantool will reject Insert when tuple with same primary key exists.

It is equal to conn.InsertAsync(space, tuple).Get().

Deprecated: the method will be removed in the next major version, use an InsertRequest object + Do() instead.

func (*Connection) InsertAsync deprecated

func (conn *Connection) InsertAsync(space interface{}, tuple interface{}) *Future

InsertAsync sends insert action to Tarantool and returns Future. Tarantool will reject Insert when tuple with same primary key exists.

Deprecated: the method will be removed in the next major version, use an InsertRequest object + Do() instead.

func (*Connection) InsertTyped deprecated

func (conn *Connection) InsertTyped(space interface{}, tuple interface{},
	result interface{}) error

InsertTyped performs insertion to box space. Tarantool will reject Insert when tuple with same primary key exists.

It is equal to conn.InsertAsync(space, tuple).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use an InsertRequest object + Do() instead.

func (*Connection) LocalAddr

func (conn *Connection) LocalAddr() string

LocalAddr returns an address of outgoing socket.

func (*Connection) NewPrepared

func (conn *Connection) NewPrepared(expr string) (*Prepared, error)

NewPrepared passes a sql statement to Tarantool for preparation synchronously.

Example

To use prepared statements to query a tarantool instance, call NewPrepared.

// Tarantool supports SQL since version 2.0.0
isLess, err := test_helpers.IsTarantoolVersionLess(2, 0, 0)
if err != nil || isLess {
	return
}

server := "127.0.0.1:3013"
opts := tarantool.Opts{
	Timeout: 5 * time.Second,
	User:    "test",
	Pass:    "test",
}
conn, err := tarantool.Connect(server, opts)
if err != nil {
	fmt.Printf("Failed to connect: %s", err.Error())
}

stmt, err := conn.NewPrepared("SELECT 1")
if err != nil {
	fmt.Printf("Failed to connect: %s", err.Error())
}

executeReq := tarantool.NewExecutePreparedRequest(stmt)
unprepareReq := tarantool.NewUnprepareRequest(stmt)

_, err = conn.Do(executeReq).Get()
if err != nil {
	fmt.Printf("Failed to execute prepared stmt")
}

_, err = conn.Do(unprepareReq).Get()
if err != nil {
	fmt.Printf("Failed to prepare")
}
Output:

func (*Connection) NewStream

func (conn *Connection) NewStream() (*Stream, error)

NewStream creates new Stream object for connection.

Since v. 2.10.0, Tarantool supports streams and interactive transactions over them. To use interactive transactions, memtx_use_mvcc_engine box option should be set to true. Since 1.7.0

func (*Connection) NewWatcher

func (conn *Connection) NewWatcher(key string, callback WatchCallback) (Watcher, error)

NewWatcher creates a new Watcher object for the connection.

You need to require WatchersFeature to use watchers, see examples for the function.

After watcher creation, the watcher callback is invoked for the first time. In this case, the callback is triggered whether or not the key has already been broadcast. All subsequent invocations are triggered with box.broadcast() called on the remote host. If a watcher is subscribed for a key that has not been broadcast yet, the callback is triggered only once, after the registration of the watcher.

The watcher callbacks are always invoked in a separate goroutine. A watcher callback is never executed in parallel with itself, but they can be executed in parallel to other watchers.

If the key is updated while the watcher callback is running, the callback will be invoked again with the latest value as soon as it returns.

Watchers survive reconnection. All registered watchers are automatically resubscribed when the connection is reestablished.

Keep in mind that garbage collection of a watcher handle doesn’t lead to the watcher’s destruction. In this case, the watcher remains registered. You need to call Unregister() directly.

Unregister() guarantees that there will be no the watcher's callback calls after it, but Unregister() call from the callback leads to a deadlock.

See: https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_events/#box-watchers

Since 1.10.0

Example
const key = "foo"
const value = "bar"

// Tarantool watchers since version 2.10
isLess, err := test_helpers.IsTarantoolVersionLess(2, 10, 0)
if err != nil || isLess {
	return
}

server := "127.0.0.1:3013"
opts := tarantool.Opts{
	Timeout:       5 * time.Second,
	Reconnect:     5 * time.Second,
	MaxReconnects: 3,
	User:          "test",
	Pass:          "test",
	// You need to require the feature to create a watcher.
	RequiredProtocolInfo: tarantool.ProtocolInfo{
		Features: []tarantool.ProtocolFeature{tarantool.WatchersFeature},
	},
}
conn, err := tarantool.Connect(server, opts)
if err != nil {
	fmt.Printf("Failed to connect: %s\n", err)
	return
}
defer conn.Close()

callback := func(event tarantool.WatchEvent) {
	fmt.Printf("event connection: %s\n", event.Conn.Addr())
	fmt.Printf("event key: %s\n", event.Key)
	fmt.Printf("event value: %v\n", event.Value)
}
watcher, err := conn.NewWatcher(key, callback)
if err != nil {
	fmt.Printf("Failed to connect: %s\n", err)
	return
}
defer watcher.Unregister()

conn.Do(tarantool.NewBroadcastRequest(key).Value(value)).Get()
time.Sleep(time.Second)
Output:

func (*Connection) OverrideSchema

func (conn *Connection) OverrideSchema(s *Schema)

OverrideSchema sets Schema for the connection.

func (*Connection) Ping deprecated

func (conn *Connection) Ping() (*Response, error)

Ping sends empty request to Tarantool to check connection.

Deprecated: the method will be removed in the next major version, use a PingRequest object + Do() instead.

func (*Connection) RemoteAddr

func (conn *Connection) RemoteAddr() string

RemoteAddr returns an address of Tarantool socket.

func (*Connection) Replace deprecated

func (conn *Connection) Replace(space interface{}, tuple interface{}) (*Response, error)

Replace performs "insert or replace" action to box space. If tuple with same primary key exists, it will be replaced.

It is equal to conn.ReplaceAsync(space, tuple).Get().

Deprecated: the method will be removed in the next major version, use a ReplaceRequest object + Do() instead.

func (*Connection) ReplaceAsync deprecated

func (conn *Connection) ReplaceAsync(space interface{}, tuple interface{}) *Future

ReplaceAsync sends "insert or replace" action to Tarantool and returns Future. If tuple with same primary key exists, it will be replaced.

Deprecated: the method will be removed in the next major version, use a ReplaceRequest object + Do() instead.

func (*Connection) ReplaceTyped deprecated

func (conn *Connection) ReplaceTyped(space interface{}, tuple interface{},
	result interface{}) error

ReplaceTyped performs "insert or replace" action to box space. If tuple with same primary key exists, it will be replaced.

It is equal to conn.ReplaceAsync(space, tuple).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use a ReplaceRequest object + Do() instead.

func (*Connection) Select deprecated

func (conn *Connection) Select(space, index interface{}, offset, limit uint32, iterator Iter,
	key interface{}) (*Response, error)

Select performs select to box space.

It is equal to conn.SelectAsync(...).Get().

Deprecated: the method will be removed in the next major version, use a SelectRequest object + Do() instead.

func (*Connection) SelectAsync deprecated

func (conn *Connection) SelectAsync(space, index interface{}, offset, limit uint32, iterator Iter,
	key interface{}) *Future

SelectAsync sends select request to Tarantool and returns Future.

Deprecated: the method will be removed in the next major version, use a SelectRequest object + Do() instead.

func (*Connection) SelectTyped deprecated

func (conn *Connection) SelectTyped(space, index interface{}, offset, limit uint32, iterator Iter,
	key interface{}, result interface{}) error

SelectTyped performs select to box space and fills typed result.

It is equal to conn.SelectAsync(space, index, offset, limit, iterator, key).GetTyped(&result)

Deprecated: the method will be removed in the next major version, use a SelectRequest object + Do() instead.

func (*Connection) ServerProtocolInfo

func (conn *Connection) ServerProtocolInfo() ProtocolInfo

ServerProtocolVersion returns protocol version and protocol features supported by connected Tarantool server. Beware that values might be outdated if connection is in a disconnected state. Since 1.10.0

func (*Connection) Update deprecated

func (conn *Connection) Update(space, index interface{}, key, ops interface{}) (*Response, error)

Update performs update of a tuple by key. Result will contain array with updated tuple.

It is equal to conn.UpdateAsync(space, tuple).Get().

Deprecated: the method will be removed in the next major version, use a UpdateRequest object + Do() instead.

func (*Connection) UpdateAsync deprecated

func (conn *Connection) UpdateAsync(space, index interface{}, key, ops interface{}) *Future

Update sends deletion of a tuple by key and returns Future. Future's result will contain array with updated tuple.

Deprecated: the method will be removed in the next major version, use a UpdateRequest object + Do() instead.

func (*Connection) UpdateTyped deprecated

func (conn *Connection) UpdateTyped(space, index interface{}, key, ops interface{},
	result interface{}) error

UpdateTyped performs update of a tuple by key and fills result with updated tuple.

It is equal to conn.UpdateAsync(space, tuple, ops).GetTyped(&result).

Deprecated: the method will be removed in the next major version, use a UpdateRequest object + Do() instead.

func (*Connection) Upsert deprecated

func (conn *Connection) Upsert(space interface{}, tuple, ops interface{}) (*Response, error)

Upsert performs "update or insert" action of a tuple by key. Result will not contain any tuple.

It is equal to conn.UpsertAsync(space, tuple, ops).Get().

Deprecated: the method will be removed in the next major version, use a UpsertRequest object + Do() instead.

func (*Connection) UpsertAsync deprecated

func (conn *Connection) UpsertAsync(space interface{}, tuple interface{},
	ops interface{}) *Future

UpsertAsync sends "update or insert" action to Tarantool and returns Future. Future's sesult will not contain any tuple.

Deprecated: the method will be removed in the next major version, use a UpsertRequest object + Do() instead.

type Connector

type Connector interface {
	ConnectedNow() bool
	Close() error
	ConfiguredTimeout() time.Duration
	NewPrepared(expr string) (*Prepared, error)
	NewStream() (*Stream, error)
	NewWatcher(key string, callback WatchCallback) (Watcher, error)
	Do(req Request) (fut *Future)

	// Deprecated: the method will be removed in the next major version,
	// use a PingRequest object + Do() instead.
	Ping() (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a SelectRequest object + Do() instead.
	Select(space, index interface{}, offset, limit uint32, iterator Iter,
		key interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use an InsertRequest object + Do() instead.
	Insert(space interface{}, tuple interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a ReplicaRequest object + Do() instead.
	Replace(space interface{}, tuple interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a DeleteRequest object + Do() instead.
	Delete(space, index interface{}, key interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a UpdateRequest object + Do() instead.
	Update(space, index interface{}, key, ops interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a UpsertRequest object + Do() instead.
	Upsert(space interface{}, tuple, ops interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a CallRequest object + Do() instead.
	Call(functionName string, args interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a Call16Request object + Do() instead.
	Call16(functionName string, args interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use a Call17Request object + Do() instead.
	Call17(functionName string, args interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use an EvalRequest object + Do() instead.
	Eval(expr string, args interface{}) (*Response, error)
	// Deprecated: the method will be removed in the next major version,
	// use an ExecuteRequest object + Do() instead.
	Execute(expr string, args interface{}) (*Response, error)

	// Deprecated: the method will be removed in the next major version,
	// use a SelectRequest object + Do() instead.
	GetTyped(space, index interface{}, key interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a SelectRequest object + Do() instead.
	SelectTyped(space, index interface{}, offset, limit uint32, iterator Iter, key interface{},
		result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use an InsertRequest object + Do() instead.
	InsertTyped(space interface{}, tuple interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a ReplaceRequest object + Do() instead.
	ReplaceTyped(space interface{}, tuple interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a DeleteRequest object + Do() instead.
	DeleteTyped(space, index interface{}, key interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a UpdateRequest object + Do() instead.
	UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a CallRequest object + Do() instead.
	CallTyped(functionName string, args interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a Call16Request object + Do() instead.
	Call16Typed(functionName string, args interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use a Call17Request object + Do() instead.
	Call17Typed(functionName string, args interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use an EvalRequest object + Do() instead.
	EvalTyped(expr string, args interface{}, result interface{}) error
	// Deprecated: the method will be removed in the next major version,
	// use an ExecuteRequest object + Do() instead.
	ExecuteTyped(expr string, args interface{},
		result interface{}) (SQLInfo, []ColumnMetaData, error)

	// Deprecated: the method will be removed in the next major version,
	// use a SelectRequest object + Do() instead.
	SelectAsync(space, index interface{}, offset, limit uint32, iterator Iter,
		key interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use an InsertRequest object + Do() instead.
	InsertAsync(space interface{}, tuple interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a ReplaceRequest object + Do() instead.
	ReplaceAsync(space interface{}, tuple interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a DeleteRequest object + Do() instead.
	DeleteAsync(space, index interface{}, key interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a UpdateRequest object + Do() instead.
	UpdateAsync(space, index interface{}, key, ops interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a UpsertRequest object + Do() instead.
	UpsertAsync(space interface{}, tuple interface{}, ops interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a CallRequest object + Do() instead.
	CallAsync(functionName string, args interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a Call16Request object + Do() instead.
	Call16Async(functionName string, args interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use a Call17Request object + Do() instead.
	Call17Async(functionName string, args interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use an EvalRequest object + Do() instead.
	EvalAsync(expr string, args interface{}) *Future
	// Deprecated: the method will be removed in the next major version,
	// use an ExecuteRequest object + Do() instead.
	ExecuteAsync(expr string, args interface{}) *Future
}

type DeleteRequest

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

DeleteRequest helps you to create a delete request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

// Insert a new tuple { 35, 1 }.
conn.Do(tarantool.NewInsertRequest(spaceNo).
	Tuple([]interface{}{uint(35), "test", "one"}),
).Get()
// Insert a new tuple { 36, 1 }.
conn.Do(tarantool.NewInsertRequest("test").
	Tuple(&Tuple{Id: 36, Msg: "test", Name: "one"}),
).Get()

// Delete tuple with primary key { 35 }.
resp, err := conn.Do(tarantool.NewDeleteRequest(spaceNo).
	Index(indexNo).
	Key([]interface{}{uint(35)}),
).Get()
fmt.Println("Delete 35")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)

// Delete tuple with primary key { 36 }.
resp, err = conn.Do(tarantool.NewDeleteRequest("test").
	Index("primary").
	Key([]interface{}{uint(36)}),
).Get()
fmt.Println("Delete 36")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
Output:

Delete 35
Error <nil>
Code 0
Data [[35 test one]]
Delete 36
Error <nil>
Code 0
Data [[36 test one]]

func NewDeleteRequest

func NewDeleteRequest(space interface{}) *DeleteRequest

NewDeleteRequest returns a new empty DeleteRequest.

func (*DeleteRequest) Body

func (req *DeleteRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the delete request body.

func (*DeleteRequest) Context

func (req *DeleteRequest) Context(ctx context.Context) *DeleteRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*DeleteRequest) Index

func (req *DeleteRequest) Index(index interface{}) *DeleteRequest

Index sets the index for the delete request. Note: default value is 0.

func (*DeleteRequest) Key

func (req *DeleteRequest) Key(key interface{}) *DeleteRequest

Key sets the key of tuple for the delete request. Note: default value is empty.

type DialOpts

type DialOpts struct {
	// DialTimeout is a timeout for an initial network dial.
	DialTimeout time.Duration
	// IoTimeout is a timeout per a network read/write.
	IoTimeout time.Duration
	// Transport is a connect transport type.
	Transport string
	// Ssl configures "ssl" transport.
	Ssl SslOpts
	// RequiredProtocol contains minimal protocol version and
	// list of protocol features that should be supported by
	// Tarantool server. By default there are no restrictions.
	RequiredProtocol ProtocolInfo
	// Auth is an authentication method.
	Auth Auth
	// Username for logging in to Tarantool.
	User string
	// User password for logging in to Tarantool.
	Password string
}

DialOpts is a way to configure a Dial method to create a new Conn.

type Dialer

type Dialer interface {
	// Dial connects to a Tarantool instance to the address with specified
	// options.
	Dial(address string, opts DialOpts) (Conn, error)
}

Dialer is the interface that wraps a method to connect to a Tarantool instance. The main idea is to provide a ready-to-work connection with basic preparation, successful authorization and additional checks.

You can provide your own implementation to Connect() call via Opts.Dialer if some functionality is not implemented in the connector. See TtDialer.Dial() implementation as example.

type Error

type Error struct {
	Code         iproto.Error
	Msg          string
	ExtendedInfo *BoxError
}

Error is wrapper around error returned by Tarantool.

func (Error) Error

func (tnterr Error) Error() string

Error converts an Error to a string.

type EvalRequest

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

EvalRequest helps you to create an eval request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

// Run raw Lua code.
resp, err := conn.Do(tarantool.NewEvalRequest("return 1 + 2")).Get()
fmt.Println("Eval 'return 1 + 2'")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
Output:

Eval 'return 1 + 2'
Error <nil>
Code 0
Data [3]

func NewEvalRequest

func NewEvalRequest(expr string) *EvalRequest

NewEvalRequest returns a new empty EvalRequest.

func (*EvalRequest) Args

func (req *EvalRequest) Args(args interface{}) *EvalRequest

Args sets the args for the eval request. Note: default value is empty.

func (*EvalRequest) Async

func (req *EvalRequest) Async() bool

Async returns true if the request does not require a response.

func (*EvalRequest) Body

func (req *EvalRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the eval request body.

func (*EvalRequest) Context

func (req *EvalRequest) Context(ctx context.Context) *EvalRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*EvalRequest) Ctx

func (req *EvalRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*EvalRequest) Type

func (req *EvalRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type ExecutePreparedRequest

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

ExecutePreparedRequest helps you to create an execute prepared request object for execution by a Connection.

func NewExecutePreparedRequest

func NewExecutePreparedRequest(stmt *Prepared) *ExecutePreparedRequest

NewExecutePreparedRequest returns a new empty preparedExecuteRequest.

func (*ExecutePreparedRequest) Args

func (req *ExecutePreparedRequest) Args(args interface{}) *ExecutePreparedRequest

Args sets the args for execute the prepared request. Note: default value is empty.

func (*ExecutePreparedRequest) Async

func (req *ExecutePreparedRequest) Async() bool

Async returns true if the request does not require a response.

func (*ExecutePreparedRequest) Body

func (req *ExecutePreparedRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the execute request body.

func (*ExecutePreparedRequest) Conn

func (req *ExecutePreparedRequest) Conn() *Connection

Conn returns the Connection object the request belongs to

func (*ExecutePreparedRequest) Context

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*ExecutePreparedRequest) Ctx

func (req *ExecutePreparedRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*ExecutePreparedRequest) Type

func (req *ExecutePreparedRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type ExecuteRequest

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

ExecuteRequest helps you to create an execute request object for execution by a Connection.

Example

To use SQL to query a tarantool instance, use ExecuteRequest.

Pay attention that with different types of queries (DDL, DQL, DML etc.) some fields of the response structure (MetaData and InfoAutoincrementIds in SQLInfo) may be nil.

// Tarantool supports SQL since version 2.0.0
isLess, _ := test_helpers.IsTarantoolVersionLess(2, 0, 0)
if isLess {
	return
}

conn := exampleConnect(opts)
defer conn.Close()

req := tarantool.NewExecuteRequest(
	"CREATE TABLE SQL_TEST (id INTEGER PRIMARY KEY, name STRING)")
resp, err := conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)

// There are 4 options to pass named parameters to an SQL query:
// 1) The simple map;
sqlBind1 := map[string]interface{}{
	"id":   1,
	"name": "test",
}

// 2) Any type of structure;
sqlBind2 := struct {
	Id   int
	Name string
}{1, "test"}

// 3) It is possible to use []tarantool.KeyValueBind;
sqlBind3 := []interface{}{
	tarantool.KeyValueBind{Key: "id", Value: 1},
	tarantool.KeyValueBind{Key: "name", Value: "test"},
}

// 4) []interface{} slice with tarantool.KeyValueBind items inside;
sqlBind4 := []tarantool.KeyValueBind{
	{"id", 1},
	{"name", "test"},
}

// 1)
req = tarantool.NewExecuteRequest(
	"CREATE TABLE SQL_TEST (id INTEGER PRIMARY KEY, name STRING)")
req = req.Args(sqlBind1)
resp, err = conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)

// 2)
req = req.Args(sqlBind2)
resp, err = conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)

// 3)
req = req.Args(sqlBind3)
resp, err = conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)

// 4)
req = req.Args(sqlBind4)
resp, err = conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)

// The way to pass positional arguments to an SQL query.
req = tarantool.NewExecuteRequest(
	"SELECT id FROM SQL_TEST WHERE id=? AND name=?").
	Args([]interface{}{2, "test"})
resp, err = conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)

// The way to pass SQL expression with using custom packing/unpacking for
// a type.
var res []Tuple
req = tarantool.NewExecuteRequest(
	"SELECT id, name, name FROM SQL_TEST WHERE id=?").
	Args([]interface{}{2})
err = conn.Do(req).GetTyped(&res)
fmt.Println("ExecuteTyped")
fmt.Println("Error", err)
fmt.Println("Data", res)

// For using different types of parameters (positioned/named), collect all
// items in []interface{}.
// All "named" items must be passed with tarantool.KeyValueBind{}.
req = tarantool.NewExecuteRequest(
	"SELECT id FROM SQL_TEST WHERE id=? AND name=?").
	Args([]interface{}{tarantool.KeyValueBind{"id", 1}, "test"})
resp, err = conn.Do(req).Get()
fmt.Println("Execute")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
fmt.Println("MetaData", resp.MetaData)
fmt.Println("SQL Info", resp.SQLInfo)
Output:

func NewExecuteRequest

func NewExecuteRequest(expr string) *ExecuteRequest

NewExecuteRequest returns a new empty ExecuteRequest.

func (*ExecuteRequest) Args

func (req *ExecuteRequest) Args(args interface{}) *ExecuteRequest

Args sets the args for the execute request. Note: default value is empty.

func (*ExecuteRequest) Async

func (req *ExecuteRequest) Async() bool

Async returns true if the request does not require a response.

func (*ExecuteRequest) Body

func (req *ExecuteRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the execute request body.

func (*ExecuteRequest) Context

func (req *ExecuteRequest) Context(ctx context.Context) *ExecuteRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*ExecuteRequest) Ctx

func (req *ExecuteRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*ExecuteRequest) Type

func (req *ExecuteRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type Field

type Field struct {
	Id         uint32
	Name       string
	Type       string
	IsNullable bool
}

Field is a schema field.

func (*Field) DecodeMsgpack

func (field *Field) DecodeMsgpack(d *msgpack.Decoder) error

type Future

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

Future is a handle for asynchronous request.

func NewFuture

func NewFuture() (fut *Future)

NewFuture creates a new empty Future.

func (*Future) AppendPush

func (fut *Future) AppendPush(resp *Response)

AppendPush appends the push response to the future. Note: it works only before SetResponse() or SetError()

func (*Future) Err

func (fut *Future) Err() error

Err returns error set on Future. It waits for future to be set. Note: it doesn't decode body, therefore decoding error are not set here.

func (*Future) Get

func (fut *Future) Get() (*Response, error)

Get waits for Future to be filled and returns Response and error.

Response will contain deserialized result in Data field. It will be []interface{}, so if you want more performance, use GetTyped method.

Note: Response could be equal to nil if ClientError is returned in error.

"error" could be Error, if it is error returned by Tarantool, or ClientError, if something bad happens in a client process.

func (*Future) GetIterator

func (fut *Future) GetIterator() (it TimeoutResponseIterator)

GetIterator returns an iterator for iterating through push messages and a response. Push messages and the response will contain deserialized result in Data field as for the Get() function.

See also

Example
conn := exampleConnect(opts)
defer conn.Close()

const timeout = 3 * time.Second
fut := conn.Do(tarantool.NewCallRequest("push_func").
	Args([]interface{}{4}),
)

var it tarantool.ResponseIterator
for it = fut.GetIterator().WithTimeout(timeout); it.Next(); {
	resp := it.Value()
	if resp.Code == tarantool.PushCode {
		// It is a push message.
		fmt.Printf("push message: %v\n", resp.Data[0])
	} else if resp.Code == tarantool.OkCode {
		// It is a regular response.
		fmt.Printf("response: %v", resp.Data[0])
	} else {
		fmt.Printf("an unexpected response code %d", resp.Code)
	}
}
if err := it.Err(); err != nil {
	fmt.Printf("error in call of push_func is %v", err)
	return
}
Output:

push message: 1
push message: 2
push message: 3
push message: 4
response: 4

func (*Future) GetTyped

func (fut *Future) GetTyped(result interface{}) error

GetTyped waits for Future and calls msgpack.Decoder.Decode(result) if no error happens. It is could be much faster than Get() function.

Note: Tarantool usually returns array of tuples (except for Eval and Call17 actions).

func (*Future) SetError

func (fut *Future) SetError(err error)

SetError sets an error for the future and finishes the future.

func (*Future) SetResponse

func (fut *Future) SetResponse(resp *Response)

SetResponse sets a response for the future and finishes the future.

func (*Future) WaitChan

func (fut *Future) WaitChan() <-chan struct{}

WaitChan returns channel which becomes closed when response arrived or error occurred.

type Greeting

type Greeting struct {
	Version string
}

Greeting is a message sent by Tarantool on connect.

type IdRequest

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

IdRequest informs the server about supported protocol version and protocol features.

func NewIdRequest

func NewIdRequest(protocolInfo ProtocolInfo) *IdRequest

NewIdRequest returns a new IdRequest.

func (*IdRequest) Async

func (req *IdRequest) Async() bool

Async returns true if the request does not require a response.

func (*IdRequest) Body

func (req *IdRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the id request body.

func (*IdRequest) Context

func (req *IdRequest) Context(ctx context.Context) *IdRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*IdRequest) Ctx

func (req *IdRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*IdRequest) Type

func (req *IdRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type Index

type Index struct {
	Id      uint32
	SpaceId uint32
	Name    string
	Type    string
	Unique  bool
	Fields  []*IndexField
}

Index contains information about index.

func (*Index) DecodeMsgpack

func (index *Index) DecodeMsgpack(d *msgpack.Decoder) error

type IndexField

type IndexField struct {
	Id   uint32
	Type string
}

IndexFields is an index field.

func (*IndexField) DecodeMsgpack

func (indexField *IndexField) DecodeMsgpack(d *msgpack.Decoder) error

type InsertRequest

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

InsertRequest helps you to create an insert request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

// Insert a new tuple { 31, 1 }.
resp, err := conn.Do(tarantool.NewInsertRequest(spaceNo).
	Tuple([]interface{}{uint(31), "test", "one"}),
).Get()
fmt.Println("Insert 31")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
// Insert a new tuple { 32, 1 }.
resp, err = conn.Do(tarantool.NewInsertRequest("test").
	Tuple(&Tuple{Id: 32, Msg: "test", Name: "one"}),
).Get()
fmt.Println("Insert 32")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)

// Delete tuple with primary key { 31 }.
conn.Do(tarantool.NewDeleteRequest("test").
	Index("primary").
	Key([]interface{}{uint(31)}),
).Get()
// Delete tuple with primary key { 32 }.
conn.Do(tarantool.NewDeleteRequest("test").
	Index(indexNo).
	Key([]interface{}{uint(31)}),
).Get()
Output:

Insert 31
Error <nil>
Code 0
Data [[31 test one]]
Insert 32
Error <nil>
Code 0
Data [[32 test one]]

func NewInsertRequest

func NewInsertRequest(space interface{}) *InsertRequest

NewInsertRequest returns a new empty InsertRequest.

func (*InsertRequest) Body

func (req *InsertRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the insert request body.

func (*InsertRequest) Context

func (req *InsertRequest) Context(ctx context.Context) *InsertRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*InsertRequest) Tuple

func (req *InsertRequest) Tuple(tuple interface{}) *InsertRequest

Tuple sets the tuple for insertion the insert request. Note: default value is nil.

type IntIntKey

type IntIntKey struct {
	I1, I2 int
}

IntIntKey is utility type for passing two integer keys to Select*, Update*, Delete* and GetTyped. It serializes to array with two integer elements.

Example
conn := exampleConnect(opts)
defer conn.Close()

const space = "testintint"
const index = "primary"
tuple := []interface{}{1, 2, "foo"}
conn.Do(tarantool.NewReplaceRequest(space).Tuple(tuple)).Get()

t := []struct {
	Key1  int
	Key2  int
	Value string
}{}
err := conn.Do(tarantool.NewSelectRequest(space).
	Index(index).
	Iterator(tarantool.IterEq).
	Key(tarantool.IntIntKey{1, 2}),
).GetTyped(&t)
fmt.Println("Error", err)
fmt.Println("Data", t)
Output:

Error <nil>
Data [{1 2 foo}]

func (IntIntKey) EncodeMsgpack

func (k IntIntKey) EncodeMsgpack(enc *msgpack.Encoder) error

type IntKey

type IntKey struct {
	I int
}

IntKey is utility type for passing integer key to Select*, Update*, Delete* and GetTyped. It serializes to array with single integer element.

Example
conn := exampleConnect(opts)
defer conn.Close()

const space = "test"
const index = "primary"
tuple := []interface{}{int(1111), "hello", "world"}
conn.Do(tarantool.NewReplaceRequest(space).Tuple(tuple)).Get()

var t []Tuple
err := conn.Do(tarantool.NewSelectRequest(space).
	Index(index).
	Iterator(tarantool.IterEq).
	Key(tarantool.IntKey{1111}),
).GetTyped(&t)
fmt.Println("Error", err)
fmt.Println("Data", t)
Output:

Error <nil>
Data [{{} 1111 hello world}]

func (IntKey) EncodeMsgpack

func (k IntKey) EncodeMsgpack(enc *msgpack.Encoder) error

type Iter

type Iter uint32

Iter is an enumeration type of a select iterator.

const (
	// Key == x ASC order.
	IterEq Iter = Iter(iproto.ITER_EQ)
	// Key == x DESC order.
	IterReq Iter = Iter(iproto.ITER_REQ)
	// All tuples.
	IterAll Iter = Iter(iproto.ITER_ALL)
	// Key < x.
	IterLt Iter = Iter(iproto.ITER_LT)
	// Key <= x.
	IterLe Iter = Iter(iproto.ITER_LE)
	// Key >= x.
	IterGe Iter = Iter(iproto.ITER_GE)
	// Key > x.
	IterGt Iter = Iter(iproto.ITER_GT)
	// All bits from x are set in key.
	IterBitsAllSet Iter = Iter(iproto.ITER_BITS_ALL_SET)
	// All bits are not set.
	IterBitsAnySet Iter = Iter(iproto.ITER_BITS_ANY_SET)
	// All bits are not set.
	IterBitsAllNotSet Iter = Iter(iproto.ITER_BITS_ALL_NOT_SET)
	// Key overlaps x.
	IterOverlaps Iter = Iter(iproto.ITER_OVERLAPS)
	// Tuples in distance ascending order from specified point.
	IterNeighbor Iter = Iter(iproto.ITER_NEIGHBOR)
)

type KeyValueBind

type KeyValueBind struct {
	Key   string
	Value interface{}
}

KeyValueBind is a type for encoding named SQL parameters

type Logger

type Logger interface {
	Report(event ConnLogKind, conn *Connection, v ...interface{})
}

Logger is logger type expected to be passed in options.

type Op

type Op struct {
	Op    string
	Field int
	Arg   interface{}
}

Op - is update operation.

func (Op) EncodeMsgpack

func (o Op) EncodeMsgpack(enc *msgpack.Encoder) error

type OpSplice

type OpSplice struct {
	Op      string
	Field   int
	Pos     int
	Len     int
	Replace string
}

func (OpSplice) EncodeMsgpack

func (o OpSplice) EncodeMsgpack(enc *msgpack.Encoder) error

type Operations

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

Operations is a collection of update operations.

func NewOperations

func NewOperations() *Operations

NewOperations returns a new empty collection of update operations.

func (*Operations) Add

func (ops *Operations) Add(field int, arg interface{}) *Operations

Add adds an additional operation to the collection of update operations.

func (*Operations) Assign

func (ops *Operations) Assign(field int, arg interface{}) *Operations

Assign adds an assign operation to the collection of update operations.

func (*Operations) BitwiseAnd

func (ops *Operations) BitwiseAnd(field int, arg interface{}) *Operations

BitwiseAnd adds a bitwise AND operation to the collection of update operations.

func (*Operations) BitwiseOr

func (ops *Operations) BitwiseOr(field int, arg interface{}) *Operations

BitwiseOr adds a bitwise OR operation to the collection of update operations.

func (*Operations) BitwiseXor

func (ops *Operations) BitwiseXor(field int, arg interface{}) *Operations

BitwiseXor adds a bitwise XOR operation to the collection of update operations.

func (*Operations) Delete

func (ops *Operations) Delete(field int, arg interface{}) *Operations

Delete adds a delete operation to the collection of update operations.

func (*Operations) Insert

func (ops *Operations) Insert(field int, arg interface{}) *Operations

Insert adds an insert operation to the collection of update operations.

func (*Operations) Splice

func (ops *Operations) Splice(field int, arg interface{}) *Operations

Splice adds a splice operation to the collection of update operations.

func (*Operations) Subtract

func (ops *Operations) Subtract(field int, arg interface{}) *Operations

Subtract adds a subtraction operation to the collection of update operations.

type Opts

type Opts struct {
	// Auth is an authentication method.
	Auth Auth
	// Dialer is a Dialer object used to create a new connection to a
	// Tarantool instance. TtDialer is a default one.
	Dialer Dialer
	// Timeout for response to a particular request. The timeout is reset when
	// push messages are received. If Timeout is zero, any request can be
	// blocked infinitely.
	// Also used to setup net.TCPConn.Set(Read|Write)Deadline.
	//
	// Pay attention, when using contexts with request objects,
	// the timeout option for Connection does not affect the lifetime
	// of the request. For those purposes use context.WithTimeout() as
	// the root context.
	Timeout time.Duration
	// Timeout between reconnect attempts. If Reconnect is zero, no
	// reconnect attempts will be made.
	// If specified, then when Tarantool is not reachable or disconnected,
	// new connect attempt is performed after pause.
	// By default, no reconnection attempts are performed,
	// so once disconnected, connection becomes Closed.
	Reconnect time.Duration
	// Maximum number of reconnect failures; after that we give it up to
	// on. If MaxReconnects is zero, the client will try to reconnect
	// endlessly.
	// After MaxReconnects attempts Connection becomes closed.
	MaxReconnects uint
	// Username for logging in to Tarantool.
	User string
	// User password for logging in to Tarantool.
	Pass string
	// RateLimit limits number of 'in-fly' request, i.e. already put into
	// requests queue, but not yet answered by server or timeouted.
	// It is disabled by default.
	// See RLimitAction for possible actions when RateLimit.reached.
	RateLimit uint
	// RLimitAction tells what to do when RateLimit is reached.
	// It is required if RateLimit is specified.
	RLimitAction RLimitAction
	// Concurrency is amount of separate mutexes for request
	// queues and buffers inside of connection.
	// It is rounded up to nearest power of 2.
	// By default it is runtime.GOMAXPROCS(-1) * 4
	Concurrency uint32
	// SkipSchema disables schema loading. Without disabling schema loading,
	// there is no way to create Connection for currently not accessible Tarantool.
	SkipSchema bool
	// Notify is a channel which receives notifications about Connection status
	// changes.
	Notify chan<- ConnEvent
	// Handle is user specified value, that could be retrivied with
	// Handle() method.
	Handle interface{}
	// Logger is user specified logger used for error messages.
	Logger Logger
	// Transport is the connection type, by default the connection is unencrypted.
	Transport string
	// SslOpts is used only if the Transport == 'ssl' is set.
	Ssl SslOpts
	// RequiredProtocolInfo contains minimal protocol version and
	// list of protocol features that should be supported by
	// Tarantool server. By default there are no restrictions.
	RequiredProtocolInfo ProtocolInfo
}

Opts is a way to configure Connection

func (Opts) Clone

func (opts Opts) Clone() Opts

Clone returns a copy of the Opts object. Any changes in copy RequiredProtocolInfo will not affect the original RequiredProtocolInfo value.

type PingRequest

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

PingRequest helps you to create an execute request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

// Ping a Tarantool instance to check connection.
resp, err := conn.Do(tarantool.NewPingRequest()).Get()
fmt.Println("Ping Code", resp.Code)
fmt.Println("Ping Data", resp.Data)
fmt.Println("Ping Error", err)
Output:

Ping Code 0
Ping Data []
Ping Error <nil>

func NewPingRequest

func NewPingRequest() *PingRequest

NewPingRequest returns a new PingRequest.

func (*PingRequest) Async

func (req *PingRequest) Async() bool

Async returns true if the request does not require a response.

func (*PingRequest) Body

func (req *PingRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the ping request body.

func (*PingRequest) Context

func (req *PingRequest) Context(ctx context.Context) *PingRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

Example

To pass contexts to request objects, use the Context() method. Pay attention that when using context with request objects, the timeout option for Connection will not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

conn := exampleConnect(opts)
defer conn.Close()

timeout := time.Nanosecond

// This way you may set the a common timeout for requests with a context.
rootCtx, cancelRoot := context.WithTimeout(context.Background(), timeout)
defer cancelRoot()

// This context will be canceled with the root after commonTimeout.
ctx, cancel := context.WithCancel(rootCtx)
defer cancel()

req := tarantool.NewPingRequest().Context(ctx)

// Ping a Tarantool instance to check connection.
resp, err := conn.Do(req).Get()
fmt.Println("Ping Resp", resp)
fmt.Println("Ping Error", err)
Output:

Ping Resp <nil>
Ping Error context is done

func (*PingRequest) Ctx

func (req *PingRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*PingRequest) Type

func (req *PingRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type PrepareRequest

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

PrepareRequest helps you to create a prepare request object for execution by a Connection.

func NewPrepareRequest

func NewPrepareRequest(expr string) *PrepareRequest

NewPrepareRequest returns a new empty PrepareRequest.

func (*PrepareRequest) Async

func (req *PrepareRequest) Async() bool

Async returns true if the request does not require a response.

func (*PrepareRequest) Body

func (req *PrepareRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the execute request body.

func (*PrepareRequest) Context

func (req *PrepareRequest) Context(ctx context.Context) *PrepareRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*PrepareRequest) Ctx

func (req *PrepareRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*PrepareRequest) Type

func (req *PrepareRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type Prepared

type Prepared struct {
	StatementID PreparedID
	MetaData    []ColumnMetaData
	ParamCount  uint64
	Conn        *Connection
}

Prepared is a type for handling prepared statements

Since 1.7.0

func NewPreparedFromResponse

func NewPreparedFromResponse(conn *Connection, resp *Response) (*Prepared, error)

NewPreparedFromResponse constructs a Prepared object.

type PreparedID

type PreparedID uint64

PreparedID is a type for Prepared Statement ID

type ProtocolFeature

type ProtocolFeature uint64

ProtocolVersion type stores a Tarantool protocol feature.

const (
	// StreamsFeature represents streams support (supported by connector).
	StreamsFeature ProtocolFeature = 0
	// TransactionsFeature represents interactive transactions support.
	// (supported by connector).
	TransactionsFeature ProtocolFeature = 1
	// ErrorExtensionFeature represents support of MP_ERROR objects over MessagePack
	// (supported by connector).
	ErrorExtensionFeature ProtocolFeature = 2
	// WatchersFeature represents support of watchers
	// (supported by connector).
	WatchersFeature ProtocolFeature = 3
	// PaginationFeature represents support of pagination
	// (supported by connector).
	PaginationFeature ProtocolFeature = 4
)

func (ProtocolFeature) String

func (ftr ProtocolFeature) String() string

String returns the name of a Tarantool feature. If value X is not a known feature, returns "Unknown feature (code X)" string.

type ProtocolInfo

type ProtocolInfo struct {
	// Auth is an authentication method.
	Auth Auth
	// Version is the supported protocol version.
	Version ProtocolVersion
	// Features are supported protocol features.
	Features []ProtocolFeature
}

ProtocolInfo type aggregates Tarantool protocol version and features info.

func (ProtocolInfo) Clone

func (info ProtocolInfo) Clone() ProtocolInfo

Clone returns an exact copy of the ProtocolInfo object. Any changes in copy will not affect the original values.

type ProtocolVersion

type ProtocolVersion uint64

ProtocolVersion type stores Tarantool protocol version.

Example
conn := exampleConnect(opts)
defer conn.Close()

clientProtocolInfo := conn.ClientProtocolInfo()
fmt.Println("Connector client protocol version:", clientProtocolInfo.Version)
for _, f := range clientProtocolInfo.Features {
	fmt.Println("Connector client protocol feature:", f)
}
Output:

Connector client protocol version: 4
Connector client protocol feature: StreamsFeature
Connector client protocol feature: TransactionsFeature
Connector client protocol feature: ErrorExtensionFeature
Connector client protocol feature: WatchersFeature
Connector client protocol feature: PaginationFeature

type RLimitAction

type RLimitAction int

RLimitActions is an enumeration type for an action to do when a rate limit is reached.

const (
	// RLimitDrop immediately aborts the request.
	RLimitDrop RLimitAction = iota
	// RLimitWait waits during timeout period for some request to be answered.
	// If no request answered during timeout period, this request is aborted.
	// If no timeout period is set, it will wait forever.
	RLimitWait
)

type ReplaceRequest

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

ReplaceRequest helps you to create a replace request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

// Insert a new tuple { 13, 1 }.
conn.Do(tarantool.NewInsertRequest(spaceNo).
	Tuple([]interface{}{uint(13), "test", "one"}),
).Get()

// Replace a tuple with primary key 13.
// Note, Tuple is defined within tests, and has EncdodeMsgpack and
// DecodeMsgpack methods.
resp, err := conn.Do(tarantool.NewReplaceRequest(spaceNo).
	Tuple([]interface{}{uint(13), 1}),
).Get()
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
resp, err = conn.Do(tarantool.NewReplaceRequest("test").
	Tuple([]interface{}{uint(13), 1}),
).Get()
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
resp, err = conn.Do(tarantool.NewReplaceRequest("test").
	Tuple(&Tuple{Id: 13, Msg: "test", Name: "eleven"}),
).Get()
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
resp, err = conn.Do(tarantool.NewReplaceRequest("test").
	Tuple(&Tuple{Id: 13, Msg: "test", Name: "twelve"}),
).Get()
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
Output:

Replace 13
Error <nil>
Code 0
Data [[13 1]]
Replace 13
Error <nil>
Code 0
Data [[13 1]]
Replace 13
Error <nil>
Code 0
Data [[13 test eleven]]
Replace 13
Error <nil>
Code 0
Data [[13 test twelve]]

func NewReplaceRequest

func NewReplaceRequest(space interface{}) *ReplaceRequest

NewReplaceRequest returns a new empty ReplaceRequest.

func (*ReplaceRequest) Body

func (req *ReplaceRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the replace request body.

func (*ReplaceRequest) Context

func (req *ReplaceRequest) Context(ctx context.Context) *ReplaceRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*ReplaceRequest) Tuple

func (req *ReplaceRequest) Tuple(tuple interface{}) *ReplaceRequest

Tuple sets the tuple for replace by the replace request. Note: default value is nil.

type Request

type Request interface {
	// Type returns a IPROTO type of the request.
	Type() iproto.Type
	// Body fills an msgpack.Encoder with a request body.
	Body(resolver SchemaResolver, enc *msgpack.Encoder) error
	// Ctx returns a context of the request.
	Ctx() context.Context
	// Async returns true if the request does not expect response.
	Async() bool
}

Request is an interface that provides the necessary data to create a request that will be sent to a tarantool instance.

type Response

type Response struct {
	RequestId uint32
	Code      uint32
	// Error contains an error message.
	Error string
	// Data contains deserialized data for untyped requests.
	Data []interface{}
	// Pos contains a position descriptor of last selected tuple.
	Pos      []byte
	MetaData []ColumnMetaData
	SQLInfo  SQLInfo
	// contains filtered or unexported fields
}

func (*Response) String

func (resp *Response) String() (str string)

String implements Stringer interface.

func (*Response) Tuples

func (resp *Response) Tuples() (res [][]interface{})

Tuples converts result of Eval and Call to same format as other actions returns (i.e. array of arrays).

type ResponseIterator

type ResponseIterator interface {
	// Next tries to switch to a next Response and returns true if it exists.
	Next() bool
	// Value returns a current Response if it exists, nil otherwise.
	Value() *Response
	// Err returns error if it happens.
	Err() error
}

ResponseIterator is an interface for iteration over a set of responses.

type RollbackRequest

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

RollbackRequest helps you to create a rollback request object for execution by a Stream. Rollback request can not be processed out of stream.

Example
var req tarantool.Request
var resp *tarantool.Response
var err error

// Tarantool supports streams and interactive transactions since version 2.10.0
isLess, _ := test_helpers.IsTarantoolVersionLess(2, 10, 0)
if err != nil || isLess {
	return
}

txnOpts := getTestTxnOpts()
conn := exampleConnect(txnOpts)
defer conn.Close()

stream, _ := conn.NewStream()

// Begin transaction
req = tarantool.NewBeginRequest()
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Begin: %s", err.Error())
	return
}
fmt.Printf("Begin transaction: response is %#v\n", resp.Code)

// Insert in stream
req = tarantool.NewInsertRequest(spaceName).
	Tuple([]interface{}{uint(2001), "rollback_hello", "rollback_world"})
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Insert: %s", err.Error())
	return
}
fmt.Printf("Insert in stream: response is %#v\n", resp.Code)

// Select not related to the transaction
// while transaction is not committed
// result of select is empty
selectReq := tarantool.NewSelectRequest(spaceNo).
	Index(indexNo).
	Limit(1).
	Iterator(tarantool.IterEq).
	Key([]interface{}{uint(2001)})
resp, err = conn.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select out of stream: response is %#v\n", resp.Data)

// Select in stream
resp, err = stream.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select in stream: response is %#v\n", resp.Data)

// Rollback transaction
req = tarantool.NewRollbackRequest()
resp, err = stream.Do(req).Get()
if err != nil {
	fmt.Printf("Failed to Rollback: %s", err.Error())
	return
}
fmt.Printf("Rollback transaction: response is %#v\n", resp.Code)

// Select outside of transaction
resp, err = conn.Do(selectReq).Get()
if err != nil {
	fmt.Printf("Failed to Select: %s", err.Error())
	return
}
fmt.Printf("Select after Rollback: response is %#v\n", resp.Data)
Output:

func NewRollbackRequest

func NewRollbackRequest() *RollbackRequest

NewRollbackRequest returns a new RollbackRequest.

func (*RollbackRequest) Async

func (req *RollbackRequest) Async() bool

Async returns true if the request does not require a response.

func (*RollbackRequest) Body

func (req *RollbackRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the rollback request body.

func (*RollbackRequest) Context

func (req *RollbackRequest) Context(ctx context.Context) *RollbackRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*RollbackRequest) Ctx

func (req *RollbackRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*RollbackRequest) Type

func (req *RollbackRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type SQLInfo

type SQLInfo struct {
	AffectedCount        uint64
	InfoAutoincrementIds []uint64
}

func (*SQLInfo) DecodeMsgpack

func (info *SQLInfo) DecodeMsgpack(d *msgpack.Decoder) error

type Schema

type Schema struct {
	Version uint
	// Spaces is map from space names to spaces.
	Spaces map[string]*Space
	// SpacesById is map from space numbers to spaces.
	SpacesById map[uint32]*Space
}

Schema contains information about spaces and indexes.

Example

Example demonstrates how to retrieve information with space schema.

conn := exampleConnect(opts)
defer conn.Close()

schema := conn.Schema
if schema.SpacesById == nil {
	fmt.Println("schema.SpacesById is nil")
}
if schema.Spaces == nil {
	fmt.Println("schema.Spaces is nil")
}

space1 := schema.Spaces["test"]
space2 := schema.SpacesById[616]
fmt.Printf("Space 1 ID %d %s\n", space1.Id, space1.Name)
fmt.Printf("Space 2 ID %d %s\n", space2.Id, space2.Name)
Output:

Space 1 ID 617 test
Space 2 ID 616 schematest

func (*Schema) ResolveSpaceIndex

func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (uint32, uint32, error)

ResolveSpaceIndex tries to resolve space and index numbers. Note: s can be a number, string, or an object of Space type. Note: i can be a number, string, or an object of Index type.

type SchemaResolver

type SchemaResolver interface {
	// ResolveSpaceIndex returns resolved space and index numbers or an
	// error if it cannot be resolved.
	ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, indexNo uint32, err error)
}

SchemaResolver is an interface for resolving schema details.

type SelectRequest

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

SelectRequest allows you to create a select request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

for i := 1111; i <= 1112; i++ {
	conn.Do(tarantool.NewReplaceRequest(spaceNo).
		Tuple([]interface{}{uint(i), "hello", "world"}),
	).Get()
}

key := []interface{}{uint(1111)}
resp, err := conn.Do(tarantool.NewSelectRequest(617).
	Limit(100).
	Iterator(tarantool.IterEq).
	Key(key),
).Get()

if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)

var res []Tuple
err = conn.Do(tarantool.NewSelectRequest("test").
	Index("primary").
	Limit(100).
	Iterator(tarantool.IterEq).
	Key(key),
).GetTyped(&res)
if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %v\n", res)
Output:

response is []interface {}{[]interface {}{0x457, "hello", "world"}}
response is [{{} 1111 hello world}]

func NewSelectRequest

func NewSelectRequest(space interface{}) *SelectRequest

NewSelectRequest returns a new empty SelectRequest.

func (*SelectRequest) After

func (req *SelectRequest) After(after interface{}) *SelectRequest

After must contain a tuple from which selection must continue or its position (a value from Response.Pos).

Note: default value in nil.

Requires Tarantool >= 2.11. Since 1.11.0

func (*SelectRequest) Body

func (req *SelectRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an encoder with the select request body.

func (*SelectRequest) Context

func (req *SelectRequest) Context(ctx context.Context) *SelectRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*SelectRequest) FetchPos

func (req *SelectRequest) FetchPos(fetch bool) *SelectRequest

FetchPos determines whether to fetch positions of the last tuple. A position descriptor will be saved in Response.Pos value.

Note: default value is false.

Requires Tarantool >= 2.11. Since 1.11.0

func (*SelectRequest) Index

func (req *SelectRequest) Index(index interface{}) *SelectRequest

Index sets the index for the select request. Note: default value is 0.

func (*SelectRequest) Iterator

func (req *SelectRequest) Iterator(iterator Iter) *SelectRequest

Iterator set the iterator for the select request. Note: default value is IterAll if key is not set or IterEq otherwise.

func (*SelectRequest) Key

func (req *SelectRequest) Key(key interface{}) *SelectRequest

Key set the key for the select request. Note: default value is empty.

func (*SelectRequest) Limit

func (req *SelectRequest) Limit(limit uint32) *SelectRequest

Limit sets the limit for the select request. Note: default value is 0xFFFFFFFF.

func (*SelectRequest) Offset

func (req *SelectRequest) Offset(offset uint32) *SelectRequest

Offset sets the offset for the select request. Note: default value is 0.

type Space

type Space struct {
	Id   uint32
	Name string
	// Could be "memtx" or "vinyl".
	Engine    string
	Temporary bool // Is this space temporary?
	// Field configuration is not mandatory and not checked by Tarantool.
	FieldsCount uint32
	Fields      map[string]*Field
	FieldsById  map[uint32]*Field
	// Indexes is map from index names to indexes.
	Indexes map[string]*Index
	// IndexesById is map from index numbers to indexes.
	IndexesById map[uint32]*Index
}

Space contains information about Tarantool's space.

Example

Example demonstrates how to retrieve information with space schema.

conn := exampleConnect(opts)
defer conn.Close()

// Save Schema to a local variable to avoid races
schema := conn.Schema
if schema.SpacesById == nil {
	fmt.Println("schema.SpacesById is nil")
}
if schema.Spaces == nil {
	fmt.Println("schema.Spaces is nil")
}

// Access Space objects by name or ID.
space1 := schema.Spaces["test"]
space2 := schema.SpacesById[616] // It's a map.
fmt.Printf("Space 1 ID %d %s %s\n", space1.Id, space1.Name, space1.Engine)
fmt.Printf("Space 1 ID %d %t\n", space1.FieldsCount, space1.Temporary)

// Access index information by name or ID.
index1 := space1.Indexes["primary"]
index2 := space2.IndexesById[3] // It's a map.
fmt.Printf("Index %d %s\n", index1.Id, index1.Name)

// Access index fields information by index.
indexField1 := index1.Fields[0] // It's a slice.
indexField2 := index2.Fields[1] // It's a slice.
fmt.Println(indexField1, indexField2)

// Access space fields information by name or id (index).
spaceField1 := space2.Fields["name0"]
spaceField2 := space2.FieldsById[3]
fmt.Printf("SpaceField 1 %s %s\n", spaceField1.Name, spaceField1.Type)
fmt.Printf("SpaceField 2 %s %s\n", spaceField2.Name, spaceField2.Type)
Output:

Space 1 ID 617 test memtx
Space 1 ID 0 false
Index 0 primary
&{0 unsigned} &{2 string}
SpaceField 1 name0 unsigned
SpaceField 2 name3 unsigned

func (*Space) DecodeMsgpack

func (space *Space) DecodeMsgpack(d *msgpack.Decoder) error

type SslOpts

type SslOpts struct {
	// KeyFile is a path to a private SSL key file.
	KeyFile string
	// CertFile is a path to an SSL certificate file.
	CertFile string
	// CaFile is a path to a trusted certificate authorities (CA) file.
	CaFile string
	// Ciphers is a colon-separated (:) list of SSL cipher suites the connection
	// can use.
	//
	// We don't provide a list of supported ciphers. This is what OpenSSL
	// does. The only limitation is usage of TLSv1.2 (because other protocol
	// versions don't seem to support the GOST cipher). To add additional
	// ciphers (GOST cipher), you must configure OpenSSL.
	//
	// See also
	//
	// * https://www.openssl.org/docs/man1.1.1/man1/ciphers.html
	Ciphers string
	// Password is a password for decrypting the private SSL key file.
	// The priority is as follows: try to decrypt with Password, then
	// try PasswordFile.
	Password string
	// PasswordFile is a path to the list of passwords for decrypting
	// the private SSL key file. The connection tries every line from the
	// file as a password.
	PasswordFile string
}

SslOpts is a way to configure ssl transport.

Example

Example demonstrates how to use SSL transport.

var opts = tarantool.Opts{
	User:      "test",
	Pass:      "test",
	Transport: "ssl",
	Ssl: tarantool.SslOpts{
		KeyFile:  "testdata/localhost.key",
		CertFile: "testdata/localhost.crt",
		CaFile:   "testdata/ca.crt",
	},
}
_, err := tarantool.Connect("127.0.0.1:3013", opts)
if err != nil {
	panic("Connection is not established: " + err.Error())
}
Output:

type Stream

type Stream struct {
	Id   uint64
	Conn *Connection
}

func (*Stream) Do

func (s *Stream) Do(req Request) *Future

Do verifies, sends the request and returns a future.

An error is returned if the request was formed incorrectly, or failure to create the future.

type StringKey

type StringKey struct {
	S string
}

StringKey is utility type for passing string key to Select*, Update*, Delete* and GetTyped. It serializes to array with single string element.

Example
conn := exampleConnect(opts)
defer conn.Close()

const space = "teststring"
const index = "primary"
tuple := []interface{}{"any", []byte{0x01, 0x02}}
conn.Do(tarantool.NewReplaceRequest(space).Tuple(tuple)).Get()

t := []struct {
	Key   string
	Value []byte
}{}
err := conn.Do(tarantool.NewSelectRequest(space).
	Index(index).
	Iterator(tarantool.IterEq).
	Key(tarantool.StringKey{"any"}),
).GetTyped(&t)
fmt.Println("Error", err)
fmt.Println("Data", t)
Output:

Error <nil>
Data [{any [1 2]}]

func (StringKey) EncodeMsgpack

func (k StringKey) EncodeMsgpack(enc *msgpack.Encoder) error

type TimeoutResponseIterator

type TimeoutResponseIterator interface {
	ResponseIterator
	// WithTimeout allows to set up a timeout for the Next() call.
	// Note: in the current implementation, there is a timeout for each
	// response (the timeout for the request is reset by each push message):
	// Connection's Opts.Timeout. You need to increase the value if necessary.
	WithTimeout(timeout time.Duration) TimeoutResponseIterator
}

TimeoutResponseIterator is an interface that extends ResponseIterator and adds the ability to change a timeout for the Next() call.

type TtDialer

type TtDialer struct {
}

TtDialer is a default implementation of the Dialer interface which is used by the connector.

func (TtDialer) Dial

func (t TtDialer) Dial(address string, opts DialOpts) (Conn, error)

Dial connects to a Tarantool instance to the address with specified options.

type TxnIsolationLevel

type TxnIsolationLevel uint
const (
	// By default, the isolation level of Tarantool is serializable.
	DefaultIsolationLevel TxnIsolationLevel = 0
	// The ReadCommittedLevel isolation level makes visible all transactions
	// that started commit (stream.Do(NewCommitRequest()) was called).
	ReadCommittedLevel TxnIsolationLevel = 1
	// The ReadConfirmedLevel isolation level makes visible all transactions
	// that finished the commit (stream.Do(NewCommitRequest()) was returned).
	ReadConfirmedLevel TxnIsolationLevel = 2
	// If the BestEffortLevel (serializable) isolation level becomes unreachable,
	// the transaction is marked as «conflicted» and can no longer be committed.
	BestEffortLevel TxnIsolationLevel = 3
)

type UintKey

type UintKey struct {
	I uint
}

UintKey is utility type for passing unsigned integer key to Select*, Update*, Delete* and GetTyped. It serializes to array with single unsigned integer element.

Example
conn := exampleConnect(opts)
defer conn.Close()

const space = "test"
const index = "primary"
tuple := []interface{}{uint(1111), "hello", "world"}
conn.Do(tarantool.NewReplaceRequest(space).Tuple(tuple)).Get()

var t []Tuple
err := conn.Do(tarantool.NewSelectRequest(space).
	Index(index).
	Iterator(tarantool.IterEq).
	Key(tarantool.UintKey{1111}),
).GetTyped(&t)
fmt.Println("Error", err)
fmt.Println("Data", t)
Output:

Error <nil>
Data [{{} 1111 hello world}]

func (UintKey) EncodeMsgpack

func (k UintKey) EncodeMsgpack(enc *msgpack.Encoder) error

type UnprepareRequest

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

UnprepareRequest helps you to create an unprepare request object for execution by a Connection.

func NewUnprepareRequest

func NewUnprepareRequest(stmt *Prepared) *UnprepareRequest

NewUnprepareRequest returns a new empty UnprepareRequest.

func (*UnprepareRequest) Async

func (req *UnprepareRequest) Async() bool

Async returns true if the request does not require a response.

func (*UnprepareRequest) Body

func (req *UnprepareRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the execute request body.

func (*UnprepareRequest) Conn

func (req *UnprepareRequest) Conn() *Connection

Conn returns the Connection object the request belongs to

func (*UnprepareRequest) Context

func (req *UnprepareRequest) Context(ctx context.Context) *UnprepareRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*UnprepareRequest) Ctx

func (req *UnprepareRequest) Ctx() context.Context

Ctx returns a context of the request.

func (*UnprepareRequest) Type

func (req *UnprepareRequest) Type() iproto.Type

Type returns a IPROTO type for the request.

type UpdateRequest

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

UpdateRequest helps you to create an update request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

for i := 1111; i <= 1112; i++ {
	conn.Do(tarantool.NewReplaceRequest(spaceNo).
		Tuple([]interface{}{uint(i), "hello", "world"}),
	).Get()
}

req := tarantool.NewUpdateRequest(617).
	Key(tarantool.IntKey{1111}).
	Operations(tarantool.NewOperations().Assign(1, "bye"))
resp, err := conn.Do(req).Get()
if err != nil {
	fmt.Printf("error in do update request is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)

req = tarantool.NewUpdateRequest("test").
	Index("primary").
	Key(tarantool.IntKey{1111}).
	Operations(tarantool.NewOperations().Assign(1, "hello"))
fut := conn.Do(req)
resp, err = fut.Get()
if err != nil {
	fmt.Printf("error in do async update request is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)
Output:

response is []interface {}{[]interface {}{0x457, "bye", "world"}}
response is []interface {}{[]interface {}{0x457, "hello", "world"}}

func NewUpdateRequest

func NewUpdateRequest(space interface{}) *UpdateRequest

NewUpdateRequest returns a new empty UpdateRequest.

func (*UpdateRequest) Body

func (req *UpdateRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the update request body.

func (*UpdateRequest) Context

func (req *UpdateRequest) Context(ctx context.Context) *UpdateRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*UpdateRequest) Index

func (req *UpdateRequest) Index(index interface{}) *UpdateRequest

Index sets the index for the update request. Note: default value is 0.

func (*UpdateRequest) Key

func (req *UpdateRequest) Key(key interface{}) *UpdateRequest

Key sets the key of tuple for the update request. Note: default value is empty.

func (*UpdateRequest) Operations

func (req *UpdateRequest) Operations(ops *Operations) *UpdateRequest

Operations sets operations to be performed on update. Note: default value is empty.

type UpsertRequest

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

UpsertRequest helps you to create an upsert request object for execution by a Connection.

Example
conn := exampleConnect(opts)
defer conn.Close()

var req tarantool.Request
req = tarantool.NewUpsertRequest(617).
	Tuple([]interface{}{uint(1113), "first", "first"}).
	Operations(tarantool.NewOperations().Assign(1, "updated"))
resp, err := conn.Do(req).Get()
if err != nil {
	fmt.Printf("error in do select upsert is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)

req = tarantool.NewUpsertRequest("test").
	Tuple([]interface{}{uint(1113), "second", "second"}).
	Operations(tarantool.NewOperations().Assign(2, "updated"))
fut := conn.Do(req)
resp, err = fut.Get()
if err != nil {
	fmt.Printf("error in do async upsert request is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)

req = tarantool.NewSelectRequest(617).
	Limit(100).
	Key(tarantool.IntKey{1113})
resp, err = conn.Do(req).Get()
if err != nil {
	fmt.Printf("error in do select request is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)
Output:

response is []interface {}{}
response is []interface {}{}
response is []interface {}{[]interface {}{0x459, "first", "updated"}}

func NewUpsertRequest

func NewUpsertRequest(space interface{}) *UpsertRequest

NewUpsertRequest returns a new empty UpsertRequest.

func (*UpsertRequest) Body

func (req *UpsertRequest) Body(res SchemaResolver, enc *msgpack.Encoder) error

Body fills an msgpack.Encoder with the upsert request body.

func (*UpsertRequest) Context

func (req *UpsertRequest) Context(ctx context.Context) *UpsertRequest

Context sets a passed context to the request.

Pay attention that when using context with request objects, the timeout option for Connection does not affect the lifetime of the request. For those purposes use context.WithTimeout() as the root context.

func (*UpsertRequest) Operations

func (req *UpsertRequest) Operations(ops *Operations) *UpsertRequest

Operations sets operations to be performed on update case by the upsert request. Note: default value is empty.

func (*UpsertRequest) Tuple

func (req *UpsertRequest) Tuple(tuple interface{}) *UpsertRequest

Tuple sets the tuple for insertion or update by the upsert request. Note: default value is empty.

type WatchCallback

type WatchCallback func(event WatchEvent)

WatchCallback is a callback to invoke when the key value is updated.

type WatchEvent

type WatchEvent struct {
	Conn  *Connection // A source connection.
	Key   string      // A key.
	Value interface{} // A value.
}

WatchEvent is a watch notification event received from a server.

type Watcher

type Watcher interface {
	// Unregister unregisters the watcher.
	Unregister()
}

Watcher is a subscription to broadcast events.

Directories

Path Synopsis
Package crud with support of API of Tarantool's CRUD module.
Package crud with support of API of Tarantool's CRUD module.
Package with support of Tarantool's datetime data type.
Package with support of Tarantool's datetime data type.
Package decimal with support of Tarantool's decimal data type.
Package decimal with support of Tarantool's decimal data type.
Package with methods to work with a Tarantool cluster considering master discovery.
Package with methods to work with a Tarantool cluster considering master discovery.
Package with implementation of methods for work with a Tarantool's queue implementations.
Package with implementation of methods for work with a Tarantool's queue implementations.
Package settings is a collection of requests to set a connection session setting or get current session configuration.
Package settings is a collection of requests to set a connection session setting or get current session configuration.
Helpers for managing Tarantool process for testing purposes.
Helpers for managing Tarantool process for testing purposes.
Package with support of Tarantool's UUID data type.
Package with support of Tarantool's UUID data type.

Jump to

Keyboard shortcuts

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