tarantool

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: May 25, 2022 License: BSD-2-Clause Imports: 17 Imported by: 3

README

Build Status GoDoc

Tarantool client in Go language

The tarantool package allows communicating with Tarantool 1.7.1+.

This is an opinionated modification of github.com/tarantool/go-tarantool package. The original license kept unchanged here at the moment.

Differences from the original package

  • API changed, some non-obvious (mostly to me personally) API removed.
  • This package uses the latest msgpack library github.com/vmihailenco/msgpack/v5 instead of v2 in original.
  • Uses UseArrayEncodedStructs(true) for msgpack.Encoder by default so there is no need to define msgpack:",as_array" struct tags. If you need to disable this (for example when using nested structs) then this behavior can be disabled using DisableArrayEncodedStructs option.
  • Uses UseLooseInterfaceDecoding(true) for msgpack.Decoder to decode response into untyped []interface{} result. See decoding rules.
  • Supports out-of-bound pushes (see box.session.push)
  • Adds optional support for context.Context (though performance will suffer a bit, if you want a maximum performance then use non-context methods which use per-connection timeout). Context cancellation does not cancel a query (Tarantool has no such functionality) - just stops waiting for request future resolving.
  • Uses sync.Pool for *msgpack.Decoder to reduce allocations on decoding stage a bit. Actually this package allocates a bit more than the original one, but allocations are small and overall performance is comparable to the original (based on observations from internal benchmarks).
  • No multi and queue packages.
  • Only one version of Call which uses Tarantool 1.7 request code.
  • Modified connection address behavior: refer to Connect function docs to see details.
  • Per-request timeout detached from underlying connection read and write timeouts.
  • Op type to express different update/upsert operations.
  • Some other cosmetic changes including several linter fixes.
  • No default Logger – developer needs to provide custom implementation explicitly.

The networking core of github.com/tarantool/go-tarantool kept mostly unchanged at the moment so this package should behave in similar way.

Installation

$ go get github.com/FZambia/tarantool

Status

This library is a prototype for Centrifuge/Centrifugo ongoing Tarantool Engine experiment.

API is not stable here and can have changes as experiment evolves. Also, there are no concrete plans at the moment regarding the package maintenance.

The versioning politics before v1 will be the following: patch version updates will only contain backwards compatible changes, minor version updates may have backwards incompatible changes.

Quick start

Create example.lua file with content:

box.cfg{listen = 3301}
box.schema.space.create('examples', {id = 999})
box.space.examples:create_index('primary', {type = 'hash', parts = {1, 'unsigned'}})
box.schema.user.grant('guest', 'read,write', 'space', 'examples')

Run it with Tarantool:

tarantool example.lua

Then create main.go file:

package main

import (
	"log"
	"time"

	"github.com/FZambia/tarantool"
)

type Row struct {
	ID    uint64
	Value string
}

func main() {
	opts := tarantool.Opts{
		RequestTimeout: 500 * time.Millisecond,
		User:           "guest",
	}
	conn, err := tarantool.Connect("127.0.0.1:3301", opts)
	if err != nil {
		log.Fatalf("Connection refused: %v", err)
	}
	defer func() { _ = conn.Close() }()

	_, err = conn.Exec(tarantool.Insert("examples", Row{ID: 999, Value: "hello"}))
	if err != nil {
		log.Fatalf("Insert failed: %v", err)
	}
	log.Println("Insert succeeded")
}

Finally, run it with:

go run main.go

Documentation

Overview

Example
spaceNo := uint32(512)
indexNo := uint32(0)

server := "127.0.0.1:3301"
opts := Opts{
	RequestTimeout: 50 * time.Millisecond,
	ReconnectDelay: 100 * time.Millisecond,
	MaxReconnects:  3,
	User:           "test",
	Password:       "test",
}
client, err := Connect(server, opts)
if err != nil {
	fmt.Printf("failed to connect: %s", err.Error())
	return
}

result, err := client.Exec(Ping())
if err != nil {
	fmt.Printf("failed to ping: %s", err.Error())
	return
}
fmt.Println("Ping Result", result)

// Delete tuple for cleaning.
_, _ = client.Exec(Delete(spaceNo, indexNo, []interface{}{uint(10)}))
_, _ = client.Exec(Delete(spaceNo, indexNo, []interface{}{uint(11)}))

// Insert new tuple { 10, 1 }.
result, err = client.Exec(Insert(spaceNo, []interface{}{uint(10), "test", "one"}))
fmt.Println("Insert Error", err)
fmt.Println("Insert Result", result)

// Insert new tuple { 11, 1 }.
result, err = client.Exec(Insert("test", &Tuple{ID: 10, Msg: "test", Name: "one"}))
fmt.Println("Insert Error", err)
fmt.Println("Insert Result", result)

// Delete tuple with primary key { 10 }.
result, err = client.Exec(Delete(spaceNo, indexNo, []interface{}{uint(10)}))
// or
// result, err = client.Exec(Delete("test", "primary", UintKey{10}}))
fmt.Println("Delete Error", err)
fmt.Println("Delete Result", result)

// Replace tuple with primary key 13.
result, err = client.Exec(Replace(spaceNo, []interface{}{uint(13), 1}))
fmt.Println("Replace Error", err)
fmt.Println("Replace Result", result)

// Update tuple with primary key { 13 }, incrementing second field by 3.
result, err = client.Exec(Update("test", "primary", UintKey{13}, []Op{OpAdd(1, 3)}))
// or
// resp, err = client.Exec(Update(spaceNo, indexNo, []interface{}{uint(13)}, []Op{OpAdd(1, 3)}))
fmt.Println("Update Error", err)
fmt.Println("Update Result", result)

// Select just one tuple with primary key { 15 }.
result, err = client.Exec(Select(spaceNo, indexNo, 0, 1, IterEq, []interface{}{uint(15)}))
// or
// resp, err = client.Exec(Select("test", "primary", 0, 1, IterEq, UintKey{15}))
fmt.Println("Select Error", err)
fmt.Println("Select Result", result)

// Call function 'func_name' with arguments.
result, err = client.Exec(Call("simple_incr", []interface{}{1}))
fmt.Println("Call Error", err)
fmt.Println("Call Result", result)

// Run raw lua code.
result, err = client.Exec(Eval("return 1 + 2", []interface{}{}))
fmt.Println("Eval Error", err)
fmt.Println("Eval Result", result)
Output:

Ping Result []
Insert Error <nil>
Insert Result [[10 test one]]
Insert Error Duplicate key exists in unique index 'primary' in space 'test' (0x3)
Insert Result []
Delete Error <nil>
Delete Result [[10 test one]]
Replace Error <nil>
Replace Result [[13 1]]
Update Error <nil>
Update Result [[13 4]]
Select Error <nil>
Select Result [[15 val 15 bla]]
Call Error <nil>
Call Result [2]
Eval Error <nil>
Eval Result [3]

Index

Examples

Constants

View Source
const (
	SelectRequest  = 1
	InsertRequest  = 2
	ReplaceRequest = 3
	UpdateRequest  = 4
	DeleteRequest  = 5
	AuthRequest    = 7
	EvalRequest    = 8
	UpsertRequest  = 9
	Call17Request  = 10
	PingRequest    = 64
)

Request code possible values.

View Source
const (
	KeyCode         = 0x00
	KeySync         = 0x01
	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
	KeyPush         = 0x80
)

Key possible values.

View Source
const (
	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
)

Iter op possible values.

View Source
const (
	RLimitDrop = 1
	RLimitWait = 2
)

RLimit possible values.

View Source
const (
	ErrConnectionNotReady = 0x4000 + iota
	ErrConnectionClosed   = 0x4000 + iota
	ErrProtocolError      = 0x4000 + iota
	ErrTimedOut           = 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 GetContext()
	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
	ErrPrivilegeGranted              = 89  // User '%s' already has %s access on %s '%s'
	ErrRoleGranted                   = 90  // User '%s' already has role '%s'
	ErrPrivilegeNotGranted           = 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
	ErrUnsupportedRolePrivilege      = 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
	ErrWrongSchemaVersion            = 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 DefaultConnectTimeout = time.Second

DefaultConnectTimeout to Tarantool.

View Source
const DefaultReadTimeout = 30 * time.Second

DefaultReadTimeout to Tarantool.

View Source
const DefaultWriteTimeout = 5 * time.Second

DefaultWriteTimeout to Tarantool.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientError

type ClientError struct {
	Code uint32
	Msg  string
}

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

func (ClientError) Error

func (err ClientError) Error() string

func (ClientError) Temporary

func (err ClientError) Temporary() bool

Temporary returns true if next attempt to perform request may succeed. Currently, it returns true when: - Connection is not connected at the moment, - or request is timed out, - or request is aborted due to rate limit.

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
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
	// Closed means either reconnect attempts exhausted, or explicit Close is called.
	Closed
)

type ConnLogKind

type ConnLogKind int
const (
	// 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 were received.
	// Most probably it is due to request timeout.
	LogUnexpectedResultID
)

type Connection

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

Connection to Tarantool.

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

Connection can be "Connected", "Disconnected", and "Closed".

When "Connected" it sends queries to Tarantool.

When "Disconnected" it rejects queries with ClientError{Code: ErrConnectionNotReady}

When "Closed" it rejects queries with ClientError{Code: ErrConnectionClosed}

Connection could become "Closed" when Connection.Close() method called, or when Tarantool disconnected and ReconnectDelay pause is not specified or MaxReconnects is specified and MaxReconnect reconnect attempts already performed.

You may perform data manipulation operation by executing: Call, Insert, Replace, Update, Upsert, Eval.

In any method that accepts `space` you may 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.

func Connect

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

Connect creates and configures new Connection.

Address could be specified in following ways:

host:port (no way to provide other options over DSN in this case)
tcp://[[username[:password]@]host[:port][/?option1=value1&optionN=valueN]
unix://[[username[:password]@]path[?option1=value1&optionN=valueN]

TCP connections:

  • 127.0.0.1:3301
  • tcp://[fe80::1]:3301
  • tcp://user:pass@example.com:3301
  • tcp://user@example.com/?connect_timeout=5s&request_timeout=1s

Unix socket:

  • unix:///var/run/tarantool/my_instance.sock
  • unix://user:pass@/var/run/tarantool/my_instance.sock?connect_timeout=5s

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

func (conn *Connection) Exec(req *Request) ([]interface{}, error)

Exec Request on Tarantool server. Return untyped result and error. Use ExecTyped for more performance and convenience.

Example
var conn *Connection
conn, err := exampleConnect()
if err != nil {
	fmt.Printf("error in prepare is %v", err)
	return
}
defer func() { _ = conn.Close() }()
result, err := conn.Exec(Select(512, 0, 0, 100, IterEq, []interface{}{uint(1111)}))
if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("result is %#v\n", result)
result, err = conn.Exec(Select("test", "primary", 0, 100, IterEq, IntKey{1111}))
if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("result is %#v\n", result)
Output:

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

func (*Connection) ExecAsync

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

ExecAsync execs Request but does not wait for a result - it's then possible to get a result from the returned Future.

func (*Connection) ExecAsyncContext

func (conn *Connection) ExecAsyncContext(req *Request) FutureContext

ExecAsyncContext execs Request but does not wait for a result - it's then possible to get a result from the returned FutureContext. Note, that context cancellation/timeout won't result into ongoing request cancellation on Tarantool side.

func (*Connection) ExecContext

func (conn *Connection) ExecContext(ctx context.Context, req *Request) ([]interface{}, error)

ExecContext execs Request with context.Context. Note, that context cancellation/timeout won't result into ongoing request cancellation on Tarantool side.

func (*Connection) ExecTyped

func (conn *Connection) ExecTyped(req *Request, result interface{}) error

ExecTyped execs request and decodes it to a typed result.

Example
var conn *Connection
conn, err := exampleConnect()
if err != nil {
	fmt.Printf("error in prepare is %v", err)
	return
}
defer func() { _ = conn.Close() }()
var res []Tuple
err = conn.ExecTyped(Select(512, 0, 0, 100, IterEq, IntKey{1111}), &res)
if err != nil {
	fmt.Printf("error in select is %v", err)
	return
}
fmt.Printf("response is %v\n", res)
err = conn.ExecTyped(Select("test", "primary", 0, 100, IterEq, 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) ExecTypedContext

func (conn *Connection) ExecTypedContext(ctx context.Context, req *Request, result interface{}) error

ExecTypedContext execs Request with context.Context and decodes it to a typed result. Note, that context cancellation/timeout won't result into ongoing request cancellation on Tarantool side.

func (*Connection) Greeting

func (conn *Connection) Greeting() *Greeting

Greeting sent by Tarantool on connect.

func (*Connection) NetConn

func (conn *Connection) NetConn() net.Conn

NetConn returns underlying net.Conn.

func (*Connection) Schema

func (conn *Connection) Schema() *Schema

Schema loaded from Tarantool.

type Error

type Error struct {
	Code uint32
	Msg  string
}

Error is wrapper around error returned by Tarantool.

func (Error) Error

func (err Error) Error() string

type Field

type Field struct {
	ID   uint32
	Name string
	Type string
}

type Future

type Future interface {
	Get() ([]interface{}, error)
	GetTyped(result interface{}) error
}

Future allows to extract response from server as soon as it's ready.

type FutureContext

type FutureContext interface {
	GetContext(ctx context.Context) ([]interface{}, error)
	GetTypedContext(ctx context.Context, result interface{}) error
}

FutureContext allows extracting response from server as soon as it's ready with Context.

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 IntIntKey

type IntIntKey struct {
	I1, I2 int64
}

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 int64
}

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 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 {
	// contains filtered or unexported fields
}

func OpAdd

func OpAdd(field uint64, val interface{}) Op

OpAdd ...

func OpAssign

func OpAssign(field uint64, val interface{}) Op

OpAssign ...

func OpBitAND

func OpBitAND(field, val uint64) Op

OpBitAND ...

func OpBitOR

func OpBitOR(field, val uint64) Op

OpBitOR ...

func OpBitXOR

func OpBitXOR(field, val uint64) Op

OpBitXOR ...

func OpDelete

func OpDelete(from, count uint64) Op

OpDelete ...

func OpInsert

func OpInsert(before uint64, val interface{}) Op

OpInsert ...

func OpSplice

func OpSplice(field, offset, position uint64, replace string) Op

OpSplice ...

func OpSub

func OpSub(field uint64, val interface{}) Op

OpSub ...

func (Op) EncodeMsgpack

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

type Opts

type Opts struct {
	// User for auth.
	User string
	// Password for auth.
	Password string

	// ConnectTimeout sets connect timeout. If not set then DefaultConnectTimeout will be used.
	ConnectTimeout time.Duration
	// RequestTimeout is a default requests timeout. Can be overridden
	// on per-operation basis using context.Context.
	RequestTimeout time.Duration
	// ReadTimeout used to set up underlying connection ReadDeadline.
	ReadTimeout time.Duration
	// WriteTimeout used to set up underlying connection WriteDeadline.
	WriteTimeout time.Duration
	// ReconnectDelay is a pause between reconnection attempts.
	// 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.
	ReconnectDelay time.Duration
	// MaxReconnects is a maximum reconnect attempts.
	// After MaxReconnects attempts Connection becomes closed.
	MaxReconnects uint64

	// SkipSchema disables schema loading. Without disabling schema loading, there
	// is no way to create Connection for currently not accessible tarantool.
	SkipSchema bool

	// RateLimit limits number of 'in-fly' request, ie already put into
	// requests queue, but not yet answered by server or timed out.
	// It is disabled by default.
	// See RLimitAction for possible actions when RateLimit.reached.
	RateLimit uint32
	// RLimitAction tells what to do when RateLimit reached:
	//   RLimitDrop - immediately abort request,
	//   RLimitWait - waitContext 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 waitContext forever.
	// It is required if RateLimit is specified.
	RLimitAction uint32
	// Concurrency is amount of separate mutexes for request
	// queues and buffers inside of connection.
	// It is rounded upto the nearest power of 2.
	// By default, it is runtime.GOMAXPROCS(-1) * 4
	Concurrency uint32

	// Notify is a channel which receives notifications about Connection status changes.
	Notify chan<- ConnEvent
	// Handle is user specified value, that could be retrieved with Handle() method.
	Handle interface{}
	// Logger is user specified logger used for log messages.
	Logger Logger

	// DisableArrayEncodedStructs allows disabling usage of UseArrayEncodedStructs option
	// of msgpack Encoder.
	DisableArrayEncodedStructs bool
	// contains filtered or unexported fields
}

Opts is a way to configure Connection.

type Request

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

Request to be executed in Tarantool.

func Call

func Call(functionName string, args interface{}) *Request

Call sends a call to registered Tarantool function. 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 Delete

func Delete(space, index interface{}, key interface{}) *Request

Delete sends deletion action to Tarantool. Result will contain array with deleted tuple.

func Eval

func Eval(expr string, args interface{}) *Request

Eval sends a lua expression for evaluation.

func Insert

func Insert(space interface{}, tuple interface{}) *Request

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

func Ping

func Ping() *Request

Ping sends empty request to Tarantool to check connection.

func Replace

func Replace(space interface{}, tuple interface{}) *Request

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

func Select

func Select(space, index interface{}, offset, limit, iterator uint32, key interface{}) *Request

Select sends select request to Tarantool.

func Update

func Update(space, index interface{}, key interface{}, ops []Op) *Request

Update sends deletion of a tuple by key. Result will contain array with updated tuple.

func Upsert

func Upsert(space interface{}, tuple interface{}, ops []Op) *Request

Upsert sends "update or insert" action to Tarantool. Result will not contain any tuple.

func (*Request) WithPush

func (req *Request) WithPush(pushCB func([]interface{})) *Request

WithPush allows setting Push handler to Request.

func (*Request) WithPushTyped

func (req *Request) WithPushTyped(pushTypedCB func(func(interface{}) error)) *Request

WithPushTyped allows setting typed Push handler to Request.

type Schema

type Schema struct {
	// 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.

type Space

type Space struct {
	ID        uint32
	Name      string
	Engine    string
	Temporary bool

	// 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 space.

type StringKey

type StringKey struct {
	S string
}

StringKey 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 UintKey

type UintKey struct {
	I uint64
}

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

Jump to

Keyboard shortcuts

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