tarantool

package module
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2022 License: BSD-2-Clause Imports: 19 Imported by: 151

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.6+.

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.6+ 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 tarantool/go-tarantool repository. To download and install, say:

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

This should put the source and binary files in subdirectories of /usr/local/go, so that you can access them by adding github.com/tarantool/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 disable SSL support and linking with OpenSSL, you can use the tag:
    go_tarantool_ssl_disable
    
  2. To change the default Call behavior from Call16 to Call17, you can use the build tag:
    go_tarantool_call_17
    
    Note: In future releases, Call17 may be used as default Call behavior.
  3. 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/tarantool/go-tarantool"
)

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.Insert(999, []interface{}{99999, "BB"})
	if err != nil {
		fmt.Println("Error", err)
		fmt.Println("Code", resp.Code)
	}
}

Observation 1: The line "github.com/tarantool/go-tarantool" 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 "conn." which is the name of the object that was returned by Connect(). There are two parameters:

  • a space number (it could just as easily have been a space name), and
  • a tuple.

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/tarantool/go-tarantool"
	"gopkg.in/vmihailenco/msgpack.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.EncodeSliceLen(3); err != nil {
		return err
	}
	if err := e.EncodeUint(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.DecodeSliceLen(); 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.DecodeSliceLen(); 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(517)
	indexNo := uint32(0)

	tuple := Tuple2{Cid: 777, Orig: "orig", Members: []Member{{"lol", "", 1}, {"wut", "", 3}}}
	resp, err := conn.Replace(spaceNo, &tuple) // NOTE: insert a structure itself.
	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
	err = conn.SelectTyped(spaceNo, indexNo, 0, 1, tarantool.IterEq, []interface{}{777}, &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.SelectTyped(spaceNo, indexNo, 0, 1, tarantool.IterEq, []interface{}{777}, &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
	err = conn.Call17Typed("func_name", []interface{}{}, &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
	// 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
)
View Source
const (
	SelectRequestCode    = 1
	InsertRequestCode    = 2
	ReplaceRequestCode   = 3
	UpdateRequestCode    = 4
	DeleteRequestCode    = 5
	Call16RequestCode    = 6 /* call in 1.6 format */
	AuthRequestCode      = 7
	EvalRequestCode      = 8
	UpsertRequestCode    = 9
	Call17RequestCode    = 10 /* call in >= 1.7 format */
	ExecuteRequestCode   = 11
	PrepareRequestCode   = 13
	BeginRequestCode     = 14
	CommitRequestCode    = 15
	RollbackRequestCode  = 16
	PingRequestCode      = 64
	SubscribeRequestCode = 66

	KeyCode         = 0x00
	KeySync         = 0x01
	KeyStreamId     = 0x0a
	KeySpaceNo      = 0x10
	KeyIndexNo      = 0x11
	KeyLimit        = 0x12
	KeyOffset       = 0x13
	KeyIterator     = 0x14
	KeyKey          = 0x20
	KeyTuple        = 0x21
	KeyFunctionName = 0x22
	KeyUserName     = 0x23
	KeyExpression   = 0x27
	KeyDefTuple     = 0x28
	KeyData         = 0x30
	KeyError        = 0x31
	KeyMetaData     = 0x32
	KeyBindCount    = 0x34
	KeySQLText      = 0x40
	KeySQLBind      = 0x41
	KeySQLInfo      = 0x42
	KeyStmtID       = 0x43
	KeyTimeout      = 0x56
	KeyTxnIsolation = 0x59

	KeyFieldName               = 0x00
	KeyFieldType               = 0x01
	KeyFieldColl               = 0x02
	KeyFieldIsNullable         = 0x03
	KeyIsAutoincrement         = 0x04
	KeyFieldSpan               = 0x05
	KeySQLInfoRowCount         = 0x00
	KeySQLInfoAutoincrementIds = 0x01

	IterEq            = uint32(0) // key == x ASC order
	IterReq           = uint32(1) // key == x DESC order
	IterAll           = uint32(2) // all tuples
	IterLt            = uint32(3) // key < x
	IterLe            = uint32(4) // key <= x
	IterGe            = uint32(5) // key >= x
	IterGt            = uint32(6) // key > x
	IterBitsAllSet    = uint32(7) // all bits from x are set in key
	IterBitsAnySet    = uint32(8) // at least one x's bit is set
	IterBitsAllNotSet = uint32(9) // all bits are not set

	RLimitDrop = 1
	RLimitWait = 2

	OkCode            = uint32(0)
	PushCode          = uint32(0x80)
	ErrorCodeBit      = 0x8000
	PacketLengthBytes = 5
	ErSpaceExistsCode = 0xa
	IteratorCode      = 0x14
)
View Source
const (
	ErrConnectionNotReady = 0x4000 + iota
	ErrConnectionClosed   = 0x4000 + iota
	ErrProtocolError      = 0x4000 + iota
	ErrTimeouted          = 0x4000 + iota
	ErrRateLimited        = 0x4000 + iota
)

Tarantool client error codes.

View Source
const (
	ErrUnknown                       = 0   // Unknown error
	ErrIllegalParams                 = 1   // Illegal parameters, %s
	ErrMemoryIssue                   = 2   // Failed to allocate %u bytes in %s for %s
	ErrTupleFound                    = 3   // Duplicate key exists in unique index '%s' in space '%s'
	ErrTupleNotFound                 = 4   // Tuple doesn't exist in index '%s' in space '%s'
	ErrUnsupported                   = 5   // %s does not support %s
	ErrNonmaster                     = 6   // Can't modify data on a replication slave. My master is: %s
	ErrReadonly                      = 7   // Can't modify data because this server is in read-only mode.
	ErrInjection                     = 8   // Error injection '%s'
	ErrCreateSpace                   = 9   // Failed to create space '%s': %s
	ErrSpaceExists                   = 10  // Space '%s' already exists
	ErrDropSpace                     = 11  // Can't drop space '%s': %s
	ErrAlterSpace                    = 12  // Can't modify space '%s': %s
	ErrIndexType                     = 13  // Unsupported index type supplied for index '%s' in space '%s'
	ErrModifyIndex                   = 14  // Can't create or modify index '%s' in space '%s': %s
	ErrLastDrop                      = 15  // Can't drop the primary key in a system space, space '%s'
	ErrTupleFormatLimit              = 16  // Tuple format limit reached: %u
	ErrDropPrimaryKey                = 17  // Can't drop primary key in space '%s' while secondary keys exist
	ErrKeyPartType                   = 18  // Supplied key type of part %u does not match index part type: expected %s
	ErrExactMatch                    = 19  // Invalid key part count in an exact match (expected %u, got %u)
	ErrInvalidMsgpack                = 20  // Invalid MsgPack - %s
	ErrProcRet                       = 21  // msgpack.encode: can not encode Lua type '%s'
	ErrTupleNotArray                 = 22  // Tuple/Key must be MsgPack array
	ErrFieldType                     = 23  // Tuple field %u type does not match one required by operation: expected %s
	ErrFieldTypeMismatch             = 24  // Ambiguous field type in index '%s', key part %u. Requested type is %s but the field has previously been defined as %s
	ErrSplice                        = 25  // SPLICE error on field %u: %s
	ErrArgType                       = 26  // Argument type in operation '%c' on field %u does not match field type: expected a %s
	ErrTupleIsTooLong                = 27  // Tuple is too long %u
	ErrUnknownUpdateOp               = 28  // Unknown UPDATE operation
	ErrUpdateField                   = 29  // Field %u UPDATE error: %s
	ErrFiberStack                    = 30  // Can not create a new fiber: recursion limit reached
	ErrKeyPartCount                  = 31  // Invalid key part count (expected [0..%u], got %u)
	ErrProcLua                       = 32  // %s
	ErrNoSuchProc                    = 33  // Procedure '%.*s' is not defined
	ErrNoSuchTrigger                 = 34  // Trigger is not found
	ErrNoSuchIndex                   = 35  // No index #%u is defined in space '%s'
	ErrNoSuchSpace                   = 36  // Space '%s' does not exist
	ErrNoSuchField                   = 37  // Field %d was not found in the tuple
	ErrSpaceFieldCount               = 38  // Tuple field count %u does not match space '%s' field count %u
	ErrIndexFieldCount               = 39  // Tuple field count %u is less than required by a defined index (expected %u)
	ErrWalIo                         = 40  // Failed to write to disk
	ErrMoreThanOneTuple              = 41  // More than one tuple found by get()
	ErrAccessDenied                  = 42  // %s access denied for user '%s'
	ErrCreateUser                    = 43  // Failed to create user '%s': %s
	ErrDropUser                      = 44  // Failed to drop user '%s': %s
	ErrNoSuchUser                    = 45  // User '%s' is not found
	ErrUserExists                    = 46  // User '%s' already exists
	ErrPasswordMismatch              = 47  // Incorrect password supplied for user '%s'
	ErrUnknownRequestType            = 48  // Unknown request type %u
	ErrUnknownSchemaObject           = 49  // Unknown object type '%s'
	ErrCreateFunction                = 50  // Failed to create function '%s': %s
	ErrNoSuchFunction                = 51  // Function '%s' does not exist
	ErrFunctionExists                = 52  // Function '%s' already exists
	ErrFunctionAccessDenied          = 53  // %s access denied for user '%s' to function '%s'
	ErrFunctionMax                   = 54  // A limit on the total number of functions has been reached: %u
	ErrSpaceAccessDenied             = 55  // %s access denied for user '%s' to space '%s'
	ErrUserMax                       = 56  // A limit on the total number of users has been reached: %u
	ErrNoSuchEngine                  = 57  // Space engine '%s' does not exist
	ErrReloadCfg                     = 58  // Can't set option '%s' dynamically
	ErrCfg                           = 59  // Incorrect value for option '%s': %s
	ErrSophia                        = 60  // %s
	ErrLocalServerIsNotActive        = 61  // Local server is not active
	ErrUnknownServer                 = 62  // Server %s is not registered with the cluster
	ErrClusterIdMismatch             = 63  // Cluster id of the replica %s doesn't match cluster id of the master %s
	ErrInvalidUUID                   = 64  // Invalid UUID: %s
	ErrClusterIdIsRo                 = 65  // Can't reset cluster id: it is already assigned
	ErrReserved66                    = 66  // Reserved66
	ErrServerIdIsReserved            = 67  // Can't initialize server id with a reserved value %u
	ErrInvalidOrder                  = 68  // Invalid LSN order for server %u: previous LSN = %llu, new lsn = %llu
	ErrMissingRequestField           = 69  // Missing mandatory field '%s' in request
	ErrIdentifier                    = 70  // Invalid identifier '%s' (expected letters, digits or an underscore)
	ErrDropFunction                  = 71  // Can't drop function %u: %s
	ErrIteratorType                  = 72  // Unknown iterator type '%s'
	ErrReplicaMax                    = 73  // Replica count limit reached: %u
	ErrInvalidXlog                   = 74  // Failed to read xlog: %lld
	ErrInvalidXlogName               = 75  // Invalid xlog name: expected %lld got %lld
	ErrInvalidXlogOrder              = 76  // Invalid xlog order: %lld and %lld
	ErrNoConnection                  = 77  // Connection is not established
	ErrTimeout                       = 78  // Timeout exceeded
	ErrActiveTransaction             = 79  // Operation is not permitted when there is an active transaction
	ErrNoActiveTransaction           = 80  // Operation is not permitted when there is no active transaction
	ErrCrossEngineTransaction        = 81  // A multi-statement transaction can not use multiple storage engines
	ErrNoSuchRole                    = 82  // Role '%s' is not found
	ErrRoleExists                    = 83  // Role '%s' already exists
	ErrCreateRole                    = 84  // Failed to create role '%s': %s
	ErrIndexExists                   = 85  // Index '%s' already exists
	ErrTupleRefOverflow              = 86  // Tuple reference counter overflow
	ErrRoleLoop                      = 87  // Granting role '%s' to role '%s' would create a loop
	ErrGrant                         = 88  // Incorrect grant arguments: %s
	ErrPrivGranted                   = 89  // User '%s' already has %s access on %s '%s'
	ErrRoleGranted                   = 90  // User '%s' already has role '%s'
	ErrPrivNotGranted                = 91  // User '%s' does not have %s access on %s '%s'
	ErrRoleNotGranted                = 92  // User '%s' does not have role '%s'
	ErrMissingSnapshot               = 93  // Can't find snapshot
	ErrCantUpdatePrimaryKey          = 94  // Attempt to modify a tuple field which is part of index '%s' in space '%s'
	ErrUpdateIntegerOverflow         = 95  // Integer overflow when performing '%c' operation on field %u
	ErrGuestUserPassword             = 96  // Setting password for guest user has no effect
	ErrTransactionConflict           = 97  // Transaction has been aborted by conflict
	ErrUnsupportedRolePriv           = 98  // Unsupported role privilege '%s'
	ErrLoadFunction                  = 99  // Failed to dynamically load function '%s': %s
	ErrFunctionLanguage              = 100 // Unsupported language '%s' specified for function '%s'
	ErrRtreeRect                     = 101 // RTree: %s must be an array with %u (point) or %u (rectangle/box) numeric coordinates
	ErrProcC                         = 102 // ???
	ErrUnknownRtreeIndexDistanceType = 103 //Unknown RTREE index distance type %s
	ErrProtocol                      = 104 // %s
	ErrUpsertUniqueSecondaryKey      = 105 // Space %s has a unique secondary index and does not support UPSERT
	ErrWrongIndexRecord              = 106 // Wrong record in _index space: got {%s}, expected {%s}
	ErrWrongIndexParts               = 107 // Wrong index parts (field %u): %s; expected field1 id (number), field1 type (string), ...
	ErrWrongIndexOptions             = 108 // Wrong index options (field %u): %s
	ErrWrongSchemaVaersion           = 109 // Wrong schema version, current: %d, in request: %u
	ErrSlabAllocMax                  = 110 // Failed to allocate %u bytes for tuple in the slab allocator: tuple is too large. Check 'slab_alloc_maximal' configuration option.
)

Tarantool server error codes.

View Source
const (
	CallRequestCode = Call16RequestCode
)

Variables

This section is empty.

Functions

This section is empty.

Types

type BeginRequest added in v1.7.0

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 added in v1.7.0

func NewBeginRequest() *BeginRequest

NewBeginRequest returns a new BeginRequest.

func (*BeginRequest) Body added in v1.7.0

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

Body fills an encoder with the begin request body.

func (*BeginRequest) Code added in v1.7.0

func (req *BeginRequest) Code() int32

Code returns a IPROTO code for the request.

func (*BeginRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of the request.

func (*BeginRequest) Timeout added in v1.7.0

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

WithTimeout allows to set up a timeout for call BeginRequest.

func (*BeginRequest) TxnIsolation added in v1.7.0

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
}

conn := example_connect()
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 commited
// 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)

type CallRequest

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

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

func NewCall16Request added in v1.7.0

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 added in v1.7.0

func NewCall17Request(function string) *CallRequest

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

func NewCallRequest added in v1.7.0

func NewCallRequest(function string) *CallRequest

NewCallRequest return a new empty CallRequest. It uses request code for Tarantool >= 1.7 if go-tarantool was build with go_tarantool_call_17 tag. Otherwise, uses request code for Tarantool 1.6.

func (*CallRequest) Args added in v1.7.0

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

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

func (*CallRequest) Body added in v1.7.0

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

Body fills an encoder with the call request body.

func (*CallRequest) Code added in v1.7.0

func (req *CallRequest) Code() int32

Code returns a IPROTO code for the request.

func (*CallRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of 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 succeeed.

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 added in v1.7.0

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
}

conn := example_connect()
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 commited
// 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)

func NewCommitRequest added in v1.7.0

func NewCommitRequest() *CommitRequest

NewCommitRequest returns a new CommitRequest.

func (*CommitRequest) Body added in v1.7.0

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

Body fills an encoder with the commit request body.

func (*CommitRequest) Code added in v1.7.0

func (req *CommitRequest) Code() int32

Code returns a IPROTO code for the request.

func (*CommitRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of the request.

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 added in v1.7.0

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 "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.

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:     500 * time.Millisecond,
	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

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

Call calls registered Tarantool function. It uses request code for Tarantool >= 1.7 if go-tarantool was build with go_tarantool_call_17 tag. Otherwise, uses request code for Tarantool 1.6.

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

Example
conn := example_connect()
defer conn.Close()

// Call a function 'simple_incr' with arguments.
resp, err := conn.Call17("simple_incr", []interface{}{1})
fmt.Println("Call simple_incr()")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
Output:

Call simple_incr()
Error <nil>
Code 0
Data [2]

func (*Connection) Call16 added in v1.7.0

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

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

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

func (*Connection) Call16Async added in v1.7.0

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 always array of arrays. Deprecated since Tarantool 1.7.2.

func (*Connection) Call16Typed added in v1.7.0

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

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

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

func (*Connection) Call17

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

Call17 calls registered Tarantool function. It uses request code for Tarantool >= 1.7, so result is not converted (though, keep in mind, result is always array)

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

func (*Connection) Call17Async

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 will not be converted (though, keep in mind, result is always array)

func (*Connection) Call17Typed

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

Call17Typed calls registered function. It uses request code for Tarantool >= 1.7, so result is not converted (though, keep in mind, result is always array)

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

func (*Connection) CallAsync

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 if go-tarantool was build with go_tarantool_call_17 tag. Otherwise, uses request code for Tarantool 1.6.

func (*Connection) CallTyped

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

CallTyped calls registered function. It uses request code for Tarantool >= 1.7 if go-tarantool was build with go_tarantool_call_17 tag. Otherwise, uses request code for Tarantool 1.6.

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

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) 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

func (conn *Connection) Delete(space, index interface{}, key interface{}) (resp *Response, err 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().

Example
conn := example_connect()
defer conn.Close()

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

// Delete tuple with primary key { 35 }.
resp, err := conn.Delete(spaceNo, indexNo, []interface{}{uint(35)})
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.Delete("test", "primary", []interface{}{uint(36)})
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 (*Connection) DeleteAsync

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.

func (*Connection) DeleteTyped

func (conn *Connection) DeleteTyped(space, index interface{}, key interface{}, result interface{}) (err 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).

func (*Connection) Do added in v1.7.0

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.

func (*Connection) Eval

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

Eval passes Lua expression for evaluation.

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

Example
conn := example_connect()
defer conn.Close()

// Run raw Lua code.
resp, err := conn.Eval("return 1 + 2", []interface{}{})
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 (*Connection) EvalAsync

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

EvalAsync sends a Lua expression for evaluation and returns Future.

func (*Connection) EvalTyped

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

EvalTyped passes Lua expression for evaluation.

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

func (*Connection) Execute

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

Execute passes sql expression to Tarantool for execution.

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

Example

To use SQL to query a tarantool instance, call Execute.

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
}
server := "127.0.0.1:3013"
opts := tarantool.Opts{
	Timeout:       500 * time.Millisecond,
	Reconnect:     1 * time.Second,
	MaxReconnects: 3,
	User:          "test",
	Pass:          "test",
}
client, err := tarantool.Connect(server, opts)
if err != nil {
	fmt.Printf("Failed to connect: %s", err.Error())
}

resp, err := client.Execute("CREATE TABLE SQL_TEST (id INTEGER PRIMARY KEY, name STRING)", []interface{}{})
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
// the simple map:
sqlBind1 := map[string]interface{}{
	"id":   1,
	"name": "test",
}

// any type of structure
sqlBind2 := struct {
	Id   int
	Name string
}{1, "test"}

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

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

// the next usage
resp, err = client.Execute("SELECT id FROM SQL_TEST WHERE id=:id AND name=:name", sqlBind1)
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 same as
resp, err = client.Execute("SELECT id FROM SQL_TEST WHERE id=:id AND name=:name", sqlBind2)
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 same as
resp, err = client.Execute("SELECT id FROM SQL_TEST WHERE id=:id AND name=:name", sqlBind3)
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 same as
resp, err = client.Execute("SELECT id FROM SQL_TEST WHERE id=:id AND name=:name", sqlBind4)
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
resp, err = client.Execute("SELECT id FROM SQL_TEST WHERE id=? AND name=?", []interface{}{2, "test"})
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
sqlInfo, metaData, err := client.ExecuteTyped("SELECT id, name, name FROM SQL_TEST WHERE id=?", []interface{}{2}, &res)
fmt.Println("ExecuteTyped")
fmt.Println("Error", err)
fmt.Println("Data", res)
fmt.Println("MetaData", metaData)
fmt.Println("SQL Info", sqlInfo)

// for using different types of parameters (positioned/named), collect all items in []interface{}
// all "named" items must be passed with tarantool.KeyValueBind{}
resp, err = client.Execute("SELECT id FROM SQL_TEST WHERE id=:id AND name=?",
	[]interface{}{tarantool.KeyValueBind{"id", 1}, "test"})
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)

func (*Connection) ExecuteAsync

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

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

func (*Connection) ExecuteTyped

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

func (*Connection) GetTyped

func (conn *Connection) GetTyped(space, index interface{}, key interface{}, result interface{}) (err 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)

func (*Connection) Handle

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

Handle returns a user-specified handle from Opts.

func (*Connection) Insert

func (conn *Connection) Insert(space interface{}, tuple interface{}) (resp *Response, err 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().

Example
conn := example_connect()
defer conn.Close()

// Insert a new tuple { 31, 1 }.
resp, err := conn.Insert(spaceNo, []interface{}{uint(31), "test", "one"})
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.Insert("test", &Tuple{Id: 32, Msg: "test", Name: "one"})
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.Delete("test", "primary", []interface{}{uint(31)})
// Delete tuple with primary key { 32 }.
conn.Delete(spaceNo, indexNo, []interface{}{uint(32)})
Output:

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

func (*Connection) InsertAsync

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.

func (*Connection) InsertTyped

func (conn *Connection) InsertTyped(space interface{}, tuple interface{}, result interface{}) (err 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).

func (*Connection) LocalAddr

func (conn *Connection) LocalAddr() string

LocalAddr returns an address of outgoing socket.

func (*Connection) NewPrepared added in v1.7.0

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:       500 * time.Millisecond,
	Reconnect:     1 * time.Second,
	MaxReconnects: 3,
	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")
}

func (*Connection) NewStream added in v1.7.0

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) OverrideSchema

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

OverrideSchema sets Schema for the connection.

func (*Connection) Ping

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

Ping sends empty request to Tarantool to check connection.

Example
conn := example_connect()
defer conn.Close()

// Ping a Tarantool instance to check connection.
resp, err := conn.Ping()
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 (*Connection) RemoteAddr

func (conn *Connection) RemoteAddr() string

RemoteAddr returns an address of Tarantool socket.

func (*Connection) Replace

func (conn *Connection) Replace(space interface{}, tuple interface{}) (resp *Response, err 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().

Example
conn := example_connect()
defer conn.Close()

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

// Replace a tuple with primary key 13.
// Note, Tuple is defined within tests, and has EncdodeMsgpack and
// DecodeMsgpack methods.
resp, err := conn.Replace(spaceNo, []interface{}{uint(13), 1})
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
resp, err = conn.Replace("test", []interface{}{uint(13), 1})
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
resp, err = conn.Replace("test", &Tuple{Id: 13, Msg: "test", Name: "eleven"})
fmt.Println("Replace 13")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
resp, err = conn.Replace("test", &Tuple{Id: 13, Msg: "test", Name: "twelve"})
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 (*Connection) ReplaceAsync

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.

func (*Connection) ReplaceTyped

func (conn *Connection) ReplaceTyped(space interface{}, tuple interface{}, result interface{}) (err 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).

func (*Connection) Select

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

Select performs select to box space.

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

Example
conn := example_connect()
defer conn.Close()

conn.Replace(spaceNo, []interface{}{uint(1111), "hello", "world"})
conn.Replace(spaceNo, []interface{}{uint(1112), "hallo", "werld"})

resp, err := conn.Select(517, 0, 0, 100, tarantool.IterEq, []interface{}{uint(1111)})

if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)
resp, err = conn.Select("test", "primary", 0, 100, tarantool.IterEq, tarantool.IntKey{1111})
if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %#v\n", resp.Data)
Output:

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

func (*Connection) SelectAsync

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

SelectAsync sends select request to Tarantool and returns Future.

Example
conn := example_connect()
defer conn.Close()
spaceNo := uint32(517)

conn.Insert(spaceNo, []interface{}{uint(16), "test", "one"})
conn.Insert(spaceNo, []interface{}{uint(17), "test", "one"})
conn.Insert(spaceNo, []interface{}{uint(18), "test", "one"})

var futs [3]*tarantool.Future
futs[0] = conn.SelectAsync("test", "primary", 0, 2, tarantool.IterLe, tarantool.UintKey{16})
futs[1] = conn.SelectAsync("test", "primary", 0, 1, tarantool.IterEq, tarantool.UintKey{17})
futs[2] = conn.SelectAsync("test", "primary", 0, 1, tarantool.IterEq, tarantool.UintKey{18})
var t []Tuple
err := futs[0].GetTyped(&t)
fmt.Println("Future", 0, "Error", err)
fmt.Println("Future", 0, "Data", t)

resp, err := futs[1].Get()
fmt.Println("Future", 1, "Error", err)
fmt.Println("Future", 1, "Data", resp.Data)

resp, err = futs[2].Get()
fmt.Println("Future", 2, "Error", err)
fmt.Println("Future", 2, "Data", resp.Data)
Output:

Future 0 Error <nil>
Future 0 Data [{{} 16 val 16 bla} {{} 15 val 15 bla}]
Future 1 Error <nil>
Future 1 Data [[17 val 17 bla]]
Future 2 Error <nil>
Future 2 Data [[18 val 18 bla]]

func (*Connection) SelectTyped

func (conn *Connection) SelectTyped(space, index interface{}, offset, limit, iterator uint32, key interface{}, result interface{}) (err 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)

Example
conn := example_connect()
defer conn.Close()
var res []Tuple

err := conn.SelectTyped(517, 0, 0, 100, tarantool.IterEq, tarantool.IntKey{1111}, &res)

if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %v\n", res)
err = conn.SelectTyped("test", "primary", 0, 100, tarantool.IterEq, tarantool.IntKey{1111}, &res)
if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %v\n", res)
Output:

response is [{{} 1111 hello world}]
response is [{{} 1111 hello world}]

func (*Connection) Update

func (conn *Connection) Update(space, index interface{}, key, ops interface{}) (resp *Response, err 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().

Example
conn := example_connect()
defer conn.Close()

// Insert a new tuple { 14, 1 }.
conn.Insert(spaceNo, []interface{}{uint(14), "test", "one"})

// Update tuple with primary key { 14 }.
resp, err := conn.Update(spaceName, indexName, []interface{}{uint(14)}, []interface{}{[]interface{}{"=", 1, "bye"}})
fmt.Println("Update 14")
fmt.Println("Error", err)
fmt.Println("Code", resp.Code)
fmt.Println("Data", resp.Data)
Output:

Update 14
Error <nil>
Code 0
Data [[14 bye bla]]

func (*Connection) UpdateAsync

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.

func (*Connection) UpdateTyped

func (conn *Connection) UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}) (err 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).

func (*Connection) Upsert

func (conn *Connection) Upsert(space interface{}, tuple, ops interface{}) (resp *Response, err 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().

func (*Connection) UpsertAsync

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.

type Connector

type Connector interface {
	ConnectedNow() bool
	Close() error
	Ping() (resp *Response, err error)
	ConfiguredTimeout() time.Duration

	Select(space, index interface{}, offset, limit, iterator uint32, key interface{}) (resp *Response, err error)
	Insert(space interface{}, tuple interface{}) (resp *Response, err error)
	Replace(space interface{}, tuple interface{}) (resp *Response, err error)
	Delete(space, index interface{}, key interface{}) (resp *Response, err error)
	Update(space, index interface{}, key, ops interface{}) (resp *Response, err error)
	Upsert(space interface{}, tuple, ops interface{}) (resp *Response, err error)
	Call(functionName string, args interface{}) (resp *Response, err error)
	Call16(functionName string, args interface{}) (resp *Response, err error)
	Call17(functionName string, args interface{}) (resp *Response, err error)
	Eval(expr string, args interface{}) (resp *Response, err error)
	Execute(expr string, args interface{}) (resp *Response, err error)

	GetTyped(space, index interface{}, key interface{}, result interface{}) (err error)
	SelectTyped(space, index interface{}, offset, limit, iterator uint32, key interface{}, result interface{}) (err error)
	InsertTyped(space interface{}, tuple interface{}, result interface{}) (err error)
	ReplaceTyped(space interface{}, tuple interface{}, result interface{}) (err error)
	DeleteTyped(space, index interface{}, key interface{}, result interface{}) (err error)
	UpdateTyped(space, index interface{}, key, ops interface{}, result interface{}) (err error)
	CallTyped(functionName string, args interface{}, result interface{}) (err error)
	Call16Typed(functionName string, args interface{}, result interface{}) (err error)
	Call17Typed(functionName string, args interface{}, result interface{}) (err error)
	EvalTyped(expr string, args interface{}, result interface{}) (err error)
	ExecuteTyped(expr string, args interface{}, result interface{}) (SQLInfo, []ColumnMetaData, error)

	SelectAsync(space, index interface{}, offset, limit, iterator uint32, key interface{}) *Future
	InsertAsync(space interface{}, tuple interface{}) *Future
	ReplaceAsync(space interface{}, tuple interface{}) *Future
	DeleteAsync(space, index interface{}, key interface{}) *Future
	UpdateAsync(space, index interface{}, key, ops interface{}) *Future
	UpsertAsync(space interface{}, tuple interface{}, ops interface{}) *Future
	CallAsync(functionName string, args interface{}) *Future
	Call16Async(functionName string, args interface{}) *Future
	Call17Async(functionName string, args interface{}) *Future
	EvalAsync(expr string, args interface{}) *Future
	ExecuteAsync(expr string, args interface{}) *Future

	NewPrepared(expr string) (*Prepared, error)
	NewStream() (*Stream, error)

	Do(req Request) (fut *Future)
}

type DeadlineIO

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

func (*DeadlineIO) Read

func (d *DeadlineIO) Read(b []byte) (n int, err error)

func (*DeadlineIO) Write

func (d *DeadlineIO) Write(b []byte) (n int, err error)

type DeleteRequest

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

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

func NewDeleteRequest added in v1.7.0

func NewDeleteRequest(space interface{}) *DeleteRequest

NewDeleteRequest returns a new empty DeleteRequest.

func (*DeleteRequest) Body added in v1.7.0

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

Body fills an encoder with the delete request body.

func (*DeleteRequest) Context added in v1.7.0

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 added in v1.7.0

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

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

func (*DeleteRequest) Key added in v1.7.0

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

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

type Error

type Error struct {
	Code uint32
	Msg  string
}

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.

func NewEvalRequest added in v1.7.0

func NewEvalRequest(expr string) *EvalRequest

NewEvalRequest returns a new empty EvalRequest.

func (*EvalRequest) Args added in v1.7.0

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

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

func (*EvalRequest) Body added in v1.7.0

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

Body fills an encoder with the eval request body.

func (*EvalRequest) Code added in v1.7.0

func (req *EvalRequest) Code() int32

Code returns a IPROTO code for the request.

func (*EvalRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of the request.

type ExecutePreparedRequest added in v1.7.0

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 added in v1.7.0

func NewExecutePreparedRequest(stmt *Prepared) *ExecutePreparedRequest

NewExecutePreparedRequest returns a new empty preparedExecuteRequest.

func (*ExecutePreparedRequest) Args added in v1.7.0

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

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

func (*ExecutePreparedRequest) Body added in v1.7.0

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

Body fills an encoder with the execute request body.

func (*ExecutePreparedRequest) Code added in v1.7.0

func (req *ExecutePreparedRequest) Code() int32

Code returns a IPROTO code for the request.

func (*ExecutePreparedRequest) Conn added in v1.7.0

func (req *ExecutePreparedRequest) Conn() *Connection

Conn returns the Connection object the request belongs to

func (*ExecutePreparedRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of 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.

func NewExecuteRequest added in v1.7.0

func NewExecuteRequest(expr string) *ExecuteRequest

NewExecuteRequest returns a new empty ExecuteRequest.

func (*ExecuteRequest) Args added in v1.7.0

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

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

func (*ExecuteRequest) Body added in v1.7.0

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

Body fills an encoder with the execute request body.

func (*ExecuteRequest) Code added in v1.7.0

func (req *ExecuteRequest) Code() int32

Code returns a IPROTO code for the request.

func (*ExecuteRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of the request.

type Field

type Field struct {
	Id   uint32
	Name string
	Type string
}

type Future

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

Future is a handle for asynchronous request.

func NewFuture added in v1.7.0

func NewFuture() (fut *Future)

NewFuture creates a new empty Future.

func (*Future) AppendPush added in v1.7.0

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 performace, 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 added in v1.7.0

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

* box.session.push() https://www.tarantool.io/en/doc/latest/reference/reference_lua/box_session/push/

Example
conn := example_connect()
defer conn.Close()

const timeout = 3 * time.Second
// Or any other Connection.*Async() call.
fut := conn.Call17Async("push_func", []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: %d\n", resp.Data[0].(uint64))
	} else if resp.Code == tarantool.OkCode {
		// It is a regular response.
		fmt.Printf("response: %d", resp.Data[0].(uint64))
	} 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 added in v1.7.0

func (fut *Future) SetError(err error)

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

func (*Future) SetResponse added in v1.7.0

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 occured.

type Greeting

type Greeting struct {
	Version string
	// contains filtered or unexported fields
}

Greeting is a message sent by Tarantool on connect.

type Index

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

Index contains information about index.

type IndexField

type IndexField struct {
	Id   uint32
	Type string
}

type InsertRequest

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

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

func NewInsertRequest added in v1.7.0

func NewInsertRequest(space interface{}) *InsertRequest

NewInsertRequest returns a new empty InsertRequest.

func (*InsertRequest) Body added in v1.7.0

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

Body fills an encoder with the insert request body.

func (*InsertRequest) Context added in v1.7.0

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 added in v1.7.0

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* and Delete*. It serializes to array with two integer elements.

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* and Delete*. It serializes to array with single integer element.

func (IntKey) EncodeMsgpack

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

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 added in v1.7.0

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

Operations is a collection of update operations.

func NewOperations added in v1.7.0

func NewOperations() *Operations

NewOperations returns a new empty collection of update operations.

func (*Operations) Add added in v1.7.0

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

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

func (*Operations) Assign added in v1.7.0

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

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

func (*Operations) BitwiseAnd added in v1.7.0

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

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

func (*Operations) BitwiseOr added in v1.7.0

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

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

func (*Operations) BitwiseXor added in v1.7.0

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

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

func (*Operations) Delete added in v1.7.0

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

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

func (*Operations) Insert added in v1.7.0

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

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

func (*Operations) Splice added in v1.7.0

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

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

func (*Operations) Subtract added in v1.7.0

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 {
	// 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 reached:
	//   RLimitDrop - immediatly abort request,
	//   RLimitWait - wait 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.
	// It is required if RateLimit is specified.
	RLimitAction uint
	// Concurrency is amount of separate mutexes for request
	// queues and buffers inside of connection.
	// It is rounded upto 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
}

Opts is a way to configure Connection

type PingRequest

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

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

func NewPingRequest added in v1.7.0

func NewPingRequest() *PingRequest

NewPingRequest returns a new PingRequest.

func (*PingRequest) Body added in v1.7.0

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

Body fills an encoder with the ping request body.

func (*PingRequest) Code added in v1.7.0

func (req *PingRequest) Code() int32

Code returns a IPROTO code for the request.

func (*PingRequest) Context added in v1.7.0

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 := example_connect()
defer conn.Close()

timeout := time.Nanosecond

// this way you may set the common timeout for requests with 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 added in v1.7.0

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

Ctx returns a context of the request.

type PrepareRequest added in v1.7.0

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

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

func NewPrepareRequest added in v1.7.0

func NewPrepareRequest(expr string) *PrepareRequest

NewPrepareRequest returns a new empty PrepareRequest.

func (*PrepareRequest) Body added in v1.7.0

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

Body fills an encoder with the execute request body.

func (*PrepareRequest) Code added in v1.7.0

func (req *PrepareRequest) Code() int32

Code returns a IPROTO code for the request.

func (*PrepareRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of the request.

type Prepared added in v1.7.0

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 added in v1.7.0

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

NewPreparedFromResponse constructs a Prepared object.

type PreparedID added in v1.7.0

type PreparedID uint64

PreparedID is a type for Prepared Statement ID

type ReplaceRequest

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

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

func NewReplaceRequest added in v1.7.0

func NewReplaceRequest(space interface{}) *ReplaceRequest

NewReplaceRequest returns a new empty ReplaceRequest.

func (*ReplaceRequest) Body added in v1.7.0

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

Body fills an encoder with the replace request body.

func (*ReplaceRequest) Context added in v1.7.0

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 added in v1.7.0

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

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

type Request added in v1.7.0

type Request interface {
	// Code returns a IPROTO code for the request.
	Code() int32
	// Body fills an encoder with a request body.
	Body(resolver SchemaResolver, enc *msgpack.Encoder) error
	// Ctx returns a context of the request.
	Ctx() context.Context
}

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     string // error message
	// Data contains deserialized data for untyped requests
	Data     []interface{}
	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 added in v1.7.0

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 added in v1.7.0

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
}

conn := example_connect()
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 commited
// 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)

func NewRollbackRequest added in v1.7.0

func NewRollbackRequest() *RollbackRequest

NewRollbackRequest returns a new RollbackRequest.

func (*RollbackRequest) Body added in v1.7.0

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

Body fills an encoder with the rollback request body.

func (*RollbackRequest) Code added in v1.7.0

func (req *RollbackRequest) Code() int32

Code returns a IPROTO code for the request.

func (*RollbackRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of 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 := example_connect()
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[516]
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 517 test
Space 2 ID 516 schematest

func (*Schema) ResolveSpaceIndex added in v1.7.0

func (schema *Schema) ResolveSpaceIndex(s interface{}, i interface{}) (spaceNo, indexNo uint32, err 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 added in v1.7.0

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 := example_connect()
defer conn.Close()

req := tarantool.NewSelectRequest(517).
	Limit(100).
	Key(tarantool.IntKey{1111})
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)

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

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

func NewSelectRequest added in v1.7.0

func NewSelectRequest(space interface{}) *SelectRequest

NewSelectRequest returns a new empty SelectRequest.

func (*SelectRequest) Body added in v1.7.0

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

Body fills an encoder with the select request body.

func (*SelectRequest) Context added in v1.7.0

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) Index added in v1.7.0

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

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

func (*SelectRequest) Iterator added in v1.7.0

func (req *SelectRequest) Iterator(iterator uint32) *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 added in v1.7.0

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

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

func (*SelectRequest) Limit added in v1.7.0

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

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

func (*SelectRequest) Offset added in v1.7.0

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 := example_connect()
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[516] // 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 517 test memtx
Space 1 ID 0 false
Index 0 primary
&{0 unsigned} &{2 string}
SpaceField 1 name0 unsigned
SpaceField 2 name3 unsigned

type SslOpts added in v1.7.0

type SslOpts struct {
	// KeyFile is a path to a private SSL key file.
	KeyFile string
	// CertFile is a path to an SSL sertificate 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
}

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())
}

type Stream added in v1.7.0

type Stream struct {
	Id   uint64
	Conn *Connection
}

func (*Stream) Do added in v1.7.0

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
}

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

func (StringKey) EncodeMsgpack

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

type TimeoutResponseIterator added in v1.7.0

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 TxnIsolationLevel added in v1.7.0

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* and Delete*. It serializes to array with single integer element.

func (UintKey) EncodeMsgpack

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

type UnprepareRequest added in v1.7.0

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

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

func NewUnprepareRequest added in v1.7.0

func NewUnprepareRequest(stmt *Prepared) *UnprepareRequest

NewUnprepareRequest returns a new empty UnprepareRequest.

func (*UnprepareRequest) Body added in v1.7.0

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

Body fills an encoder with the execute request body.

func (*UnprepareRequest) Code added in v1.7.0

func (req *UnprepareRequest) Code() int32

Code returns a IPROTO code for the request.

func (*UnprepareRequest) Conn added in v1.7.0

func (req *UnprepareRequest) Conn() *Connection

Conn returns the Connection object the request belongs to

func (*UnprepareRequest) Context added in v1.7.0

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 added in v1.7.0

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

Ctx returns a context of 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 := example_connect()
defer conn.Close()

req := tarantool.NewUpdateRequest(517).
	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 added in v1.7.0

func NewUpdateRequest(space interface{}) *UpdateRequest

NewUpdateRequest returns a new empty UpdateRequest.

func (*UpdateRequest) Body added in v1.7.0

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

Body fills an encoder with the update request body.

func (*UpdateRequest) Context added in v1.7.0

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 added in v1.7.0

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

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

func (*UpdateRequest) Key added in v1.7.0

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 added in v1.7.0

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 := example_connect()
defer conn.Close()

var req tarantool.Request
req = tarantool.NewUpsertRequest(517).
	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(517).
	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 added in v1.7.0

func NewUpsertRequest(space interface{}) *UpsertRequest

NewUpsertRequest returns a new empty UpsertRequest.

func (*UpsertRequest) Body added in v1.7.0

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

Body fills an encoder with the upsert request body.

func (*UpsertRequest) Context added in v1.7.0

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 added in v1.7.0

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 added in v1.7.0

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

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

Directories

Path Synopsis
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 support of Tarantool's datetime data type.
Package with support of Tarantool's datetime data type.
Package decimal implements methods to encode and decode BCD.
Package decimal implements methods to encode and decode BCD.
Package with methods to work with a Tarantool cluster.
Package with methods to work with a Tarantool cluster.
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.
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