tarantool

package module
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2022 License: Apache-2.0 Imports: 16 Imported by: 0

README

Client in Go for Tarantool 2.0+

pipeline status coverage report

The tarantool package has everything necessary for interfacing with Tarantool 2.0+.

Table of contents

Installation

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

To download and install, say:

$ go get gitlab.com/komex/tarantool/v2

Example

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

package main

import (
	"context"
	"fmt"
	"net"
	"time"

	"gitlab.com/komex/tarantool/v2"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	var conn *tarantool.Connection
	{
		c, err := net.Dial("tcp", ":3301")
		if err != nil {
			panic(err)
		}
		conn, err = tarantool.NewConnection(c)
		if err != nil {
			_ = c.Close()
			panic(err)
		}
	}
	defer conn.Close()

	// Use your tarantool credentials
	if err := conn.Auth(ctx, "admin", "passwd"); err != nil {
		panic(err)
	}

	spaces, err := conn.Spaces(ctx)
	if err != nil {
		panic(err)
	}

	space := spaces.ByName("tester")

	if space == nil {
		if err := createScheme(ctx, conn); err != nil {
			panic(err)
		}

		// Reload system info
		spaces, err = conn.Spaces(ctx)
		if err != nil {
			panic(err)
		}
		space = spaces.ByName("tester")

		// Insert three tuples (our name for records) into the space
		if err := conn.Exec(ctx, tarantool.NewInsert(space, []interface{}{1, "Roxette", 1986})); err != nil {
			panic(err)
		}
		if err := conn.Exec(ctx, tarantool.NewInsert(space, []interface{}{2, "Scorpions", 2015})); err != nil {
			panic(err)
		}
		if err := conn.Exec(ctx, tarantool.NewInsert(space, []interface{}{3, "Ace of Base", 1993})); err != nil {
			panic(err)
		}
	}

	// Select a tuple using the primary index
	single := tarantool.NewSingleResult(nil)
	if err := conn.Query(ctx, tarantool.NewSelect(space, tarantool.Key{3}, 1), single); err != nil {
		panic(err)
	}

	fmt.Println(single.Result)
}

func createScheme(ctx context.Context, conn *tarantool.Connection) error {
	// unsupported Lua type 'function'
	_ = conn.Exec(ctx, tarantool.NewCall("box.schema.space.create", "tester"))

	// Format the created space by specifying field names and types
	err := conn.Exec(ctx, tarantool.NewCall(
		"box.space.tester:format",
		[]map[string]string{
			{
				"name": "id",
				"type": "unsigned",
			},
			{
				"name": "band_name",
				"type": "string",
			},
			{
				"name": "year",
				"type": "unsigned",
			},
		},
	))
	if err != nil {
		return err
	}

	// Create the first index (named primary)
	err = conn.Exec(ctx, tarantool.NewCall(
		"box.space.tester:create_index",
		"primary",
		map[string]interface{}{
			"type":  "hash",
			"parts": []string{"id"},
		},
	))

	return err
}

Help

To contact go-tarantool developers on any problems, create an issue at komex/tarantool.

Documentation

Index

Constants

View Source
const (
	// Default size for the maximum number of requests sent at a time.
	DefaultSlotsSize = 255
	// Default size of connection buffer.
	DefaultBufferSize = 4096
)
View Source
const ExtUUID msgpack.Ext = 2

ExtUUID is a code of UUID extension.

Variables

View Source
var (
	ErrUnexpectedGreeting      = errors.New("unexpected tarantool server greeting message")
	ErrUnexpectedServerVersion = errors.New("unexpected tarantool server version")
	ErrNoConnectionSpecified   = errors.New("no connection was specified")
	ErrInvalidSaltSize         = errors.New("invalid salt size")
	ErrInvalidPackageSize      = errors.New("invalid package size")
	ErrTooMachResults          = errors.New("received too mach results")
	ErrGateInvalidState        = errors.New("gate has invalid state")
	ErrNotFound                = errors.New("was not found")
	ErrExchangeNotFound        = errors.New("exchange was not found")
	ErrSpaceNotFound           = errors.New("space was not found")
	ErrIndexNotFound           = errors.New("index was not found")
	ErrConnectionClosed        = errors.New("connection closed")
	ErrUnexpectedExtension     = errors.New("unexpected extension code")
)

Functions

func NextSyncSequenceValue

func NextSyncSequenceValue() uint64

NextSyncSequenceValue returns next unique sequence value.

func Skip

func Skip(dec *msgpack.Decoder, num int) error

Skip skips decoding of num elements.

Types

type Auth

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

Auth provides authentication Query.

func NewAuth

func NewAuth(user, password string) *Auth

NewAuth returns a new instance of authentication Query.

func (*Auth) Code

func (*Auth) Code() Code

Code implements Query interface.

func (*Auth) EncodeMsgpack

func (a *Auth) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder interface.

type Call

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

Call provides tarantool call/eval Query.

func NewCall

func NewCall(function string, arguments ...any) *Call

NewCall returns a new call Query.

func NewEval

func NewEval(expression string, arguments ...any) *Call

NewEval returns a new eval Query.

func (*Call) Code

func (c *Call) Code() Code

Code implements Query interface.

func (*Call) EncodeMsgpack

func (c *Call) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder interface.

type Code

type Code uint8

Code represents query type code.

const (
	CodeOK      Code = 0x00 // OK
	CodeSelect  Code = 0x01 // Select
	CodeInsert  Code = 0x02 // Insert
	CodeReplace Code = 0x03 // Replace
	CodeUpdate  Code = 0x04 // Update
	CodeDelete  Code = 0x05 // Delete
	CodeAuth    Code = 0x07 // Auth
	CodeEval    Code = 0x08 // Eval
	CodeUpsert  Code = 0x09 // Upsert
	CodeCall    Code = 0x0a // Call
	CodeExecute Code = 0x0b // Execute
	CodePrepare Code = 0x0d // Prepare
	CodePing    Code = 0x40 // Ping
)

func (*Code) DecodeMsgpack

func (i *Code) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder interface.

func (Code) EncodeMsgpack

func (i Code) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder interface.

func (Code) String

func (i Code) String() string

type Connection

type Connection struct {
	ProtocolVersion string
	SessionID       string
	// contains filtered or unexported fields
}

Connection allows to establish connection and communicates with Tarantool server.

func NewConnection

func NewConnection(conn net.Conn, options ...Option) (*Connection, error)

NewConnection returns a new instance of Connection.

func (*Connection) Auth

func (c *Connection) Auth(ctx context.Context, user, password string) error

Auth authenticates user by password and reload available spaces and indexes.

func (*Connection) Close

func (c *Connection) Close() error

Close closes connection.

func (*Connection) Exec

func (c *Connection) Exec(ctx context.Context, query Query) error

Exec executes a query and do not returns result.

func (*Connection) Indexes

func (c *Connection) Indexes(ctx context.Context) (Indexes, error)

Indexes returns a list of presented on a server indexes available to a user.

func (*Connection) Query

func (c *Connection) Query(ctx context.Context, query Query, result msgpack.CustomDecoder) error

Query executes a query and decodes response to result.

func (*Connection) Spaces

func (c *Connection) Spaces(ctx context.Context) (Spaces, error)

Spaces returns a list of presented on a server spaces available to a user.

type Decoder

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

Decoder is a structure for decoding response packet.

func NewDecoder

func NewDecoder(exchange *Exchange) *Decoder

NewDecoder returns a new instance of Decoder.

func (*Decoder) Fill

func (d *Decoder) Fill(r io.Reader, n uint64) error

Fill resets and fills buffer from r with n bytes.

func (*Decoder) Packet

func (d *Decoder) Packet() error

Packet decodes packet from buffer filled with Fill method.

type Delete

type Delete struct {
	Space *Space
	Index *Index
	Key   Key
}

Delete provides delete tuple Query.

func NewDelete

func NewDelete(space *Space, index *Index, key Key) *Delete

NewDelete returns a new instance of delete tuple Query.

func (*Delete) Code

func (*Delete) Code() Code

Code implements Query interface.

func (*Delete) EncodeMsgpack

func (d *Delete) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder interface.

type Driver

type Driver interface {
	// Auth authenticates user by password and reload available spaces and indexes.
	Auth(ctx context.Context, user, password string) error
	// Spaces returns a list of presented on a server spaces available to a user.
	Spaces(ctx context.Context) (Spaces, error)
	// Indexes returns a list of presented on a server indexes available to a user.
	Indexes(ctx context.Context) (Indexes, error)
	// Exec executes a query and do not returns result.
	Exec(ctx context.Context, query Query) error
	// Query executes a query and decodes response to result.
	Query(ctx context.Context, query Query, result msgpack.CustomDecoder) error
	// Close closes connection.
	Close() error
}

Driver is an interface for communicates with Tarantool Server.

type Error

type Error struct {
	Type    string
	File    string
	Line    uint32
	Message string
	ErrNo   uint16
	ErrCode uint16
	Fields  map[string]any
}

Error is a struct for error response from Tarantool Server.

func (*Error) DecodeMsgpack

func (e *Error) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder interface.

func (*Error) Error

func (e *Error) Error() string

Error implements error interface.

type ErrorCode

type ErrorCode uint8

ErrorCode represents error codes from Tarantool Server.

const (
	ErrorType    ErrorCode = 0x00
	ErrorFile    ErrorCode = 0x01
	ErrorLine    ErrorCode = 0x02
	ErrorMessage ErrorCode = 0x03
	ErrorErrNo   ErrorCode = 0x04
	ErrorErrCode ErrorCode = 0x05
	ErrorFields  ErrorCode = 0x06
)

type Exchange

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

func NewExchange

func NewExchange(size int) *Exchange

NewExchange returns a new instance of Exchange.

func (*Exchange) Clear

func (e *Exchange) Clear(err error)

func (*Exchange) Pull

func (e *Exchange) Pull(id uint64) *Gate

func (*Exchange) Push

func (e *Exchange) Push(gate *Gate)

type Execute

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

Execute defines Tarantool execute query.

func NewExecute

func NewExecute(query string, arguments ...any) *Execute

NewExecute creates a new instance of Execute query.

func (*Execute) Code

func (*Execute) Code() Code

Code implements interface Query.

func (*Execute) EncodeMsgpack

func (e *Execute) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Gate

type Gate struct {
	bytes.Buffer
	*msgpack.Encoder
	// contains filtered or unexported fields
}

Gate links query and response.

func NewGate

func NewGate(code Code, result msgpack.CustomDecoder) (*Gate, error)

NewGate returns a new instance of Gate. Each Gate MUST be Free() after usage.

func (*Gate) Done

func (g *Gate) Done(err error)

func (*Gate) Free

func (g *Gate) Free()

Free frees resources and returns Gate to pool. This gate can't be used after invoking this method.

func (*Gate) ID

func (g *Gate) ID() uint64

ID returns an unique request-response ID.

func (*Gate) Ready

func (g *Gate) Ready() bool

func (*Gate) State

func (g *Gate) State() GateState

func (*Gate) Wait

func (g *Gate) Wait(ctx context.Context) error

Wait blocks goroutine until fetch response.

type GateState

type GateState uint8
const (
	GateStateIdle GateState = iota
	GateStateReady
	GateStateDone
	GateStateFailed
)

func (GateState) String

func (i GateState) String() string
type Header struct {
	Error   error
	Sync    uint64
	Scheme  uint64
	Code    Code
	HasData bool
}

Header represents Tarantool binary protocol message header.

func (*Header) DecodeMsgpack

func (h *Header) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

func (*Header) EncodeMsgpack

func (h *Header) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

func (*Header) Reset

func (h *Header) Reset()

Reset resets header values to default.

type Index

type Index struct {
	SpaceID uint64
	ID      uint64
	Name    string
	Type    string
}

Index defines Tarantool index object.

func GetIndex

func GetIndex(ctx context.Context, conn Driver, space *Space, name string) (*Index, error)

GetIndex finds an index by its name in specified space. Method returns ErrIndexNotFound if index was not found.

func (*Index) DecodeMsgpack

func (i *Index) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

func (*Index) EncodeMsgpack

func (i *Index) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Indexes

type Indexes []Index

Indexes define a list of Index.

func (Indexes) ByID

func (i Indexes) ByID(space *Space, id uint64) *Index

ByID returns an index by its id.

func (Indexes) ByName

func (i Indexes) ByName(space *Space, name string) *Index

ByName returns an index by its name.

func (*Indexes) DecodeMsgpack

func (i *Indexes) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

type Insert

type Insert struct {
	Space   *Space
	Data    any
	Replace bool
}

Insert defines Tarantool insert query.

func NewInsert

func NewInsert(space *Space, data any) *Insert

NewInsert creates a new instance of Insert.

func NewReplace

func NewReplace(space *Space, data any) *Insert

NewReplace creates a new instance of Insert with replace flag.

func (*Insert) Code

func (i *Insert) Code() Code

Code implements interface Query.

func (*Insert) EncodeMsgpack

func (i *Insert) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Iterator

type Iterator uint8
const (
	IterateEqual              Iterator = iota // key == x ASC order
	IterateReverseEqual                       // key == x DESC order
	IterateAll                                // all tuples
	IterateLessThan                           // key < x
	IterateLessThanOrEqual                    // key <= x
	IterateGreaterThan                        // key >= x
	IterateGreaterThanOrEqual                 // key > x
	IterateBitsAllSet                         // all bits from x are set in key
	IterateBitsAnySet                         // at least one x's bit is set
	IterateBitsAllNotSet                      // all bits are not set
)

type Key

type Key []any

Key defines query key.

func (Key) EncodeMsgpack

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

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Operation

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

Operation defines Tarantool operation.

func BitAndOperation

func BitAndOperation(field, argument uint32) Operation

func BitOrOperation

func BitOrOperation(field, argument uint32) Operation

func BitXorOperation

func BitXorOperation(field, argument uint32) Operation

func InsertOperation

func InsertOperation(beforeField uint32, argument any) Operation

func RemoveOperation

func RemoveOperation(field, num uint32) Operation

func SetOperation

func SetOperation(field uint32, argument any) Operation

func SubOperation

func SubOperation(field uint32, argument any) Operation

func SumOperation

func SumOperation(field uint32, argument any) Operation

func (*Operation) EncodeMsgpack

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

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Operations

type Operations []Operation

Operations supports fast encoding slice of Operation in msgpack format.

func (Operations) EncodeMsgpack

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

EncodeMsgpack implements msgpack.CustomEncoder interface.

type Option

type Option func(*Options)

Option defines interface for configure Options.

func BufferSize

func BufferSize(size int) Option

BufferSize creates Option allows to set read and write buffer sizes.

func ReadBufferSize

func ReadBufferSize(size int) Option

ReadBufferSize creates Option allows to set read buffer size.

func SlotSize

func SlotSize(size int) Option

SlotSize creates Option allows to set maximum number of slots.

func WriteBufferSize

func WriteBufferSize(size int) Option

WriteBufferSize creates Option allows to set write buffer size.

type Options

type Options struct {
	// BufferSize allows to configure size of buffers.
	BufferSize struct {
		// Read defines a size of read buffer.
		Read int
		// Write defines a size of write buffer.
		Write int
	}
	// SlotsSize represents maximum number of slots.
	SlotsSize int
}

Options defines full list of supported options.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions creates Options with default values.

type Ping

type Ping struct{}

Ping defines Tarantool Ping query.

func NewPing

func NewPing() *Ping

NewPing creates a new instance of Ping.

func (Ping) Code

func (Ping) Code() Code

Code implements interface Query.

func (Ping) EncodeMsgpack

func (Ping) EncodeMsgpack(*msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Proto

type Proto uint8

Proto defines reserved codes in tarantool binary protocol.

const (
	ProtoCode         Proto = 0x00 // Code
	ProtoSync         Proto = 0x01 // Sync
	ProtoSchema       Proto = 0x05 // Schema
	ProtoSpaceNo      Proto = 0x10 // SpaceNo
	ProtoIndexNo      Proto = 0x11 // IndexNo
	ProtoLimit        Proto = 0x12 // Limit
	ProtoOffset       Proto = 0x13 // Offset
	ProtoIterator     Proto = 0x14 // Iterator
	ProtoKey          Proto = 0x20 // Key
	ProtoTuple        Proto = 0x21 // Tuple
	ProtoFunctionName Proto = 0x22 // FunctionName
	ProtoUserName     Proto = 0x23 // UserName
	ProtoExpression   Proto = 0x27 // Expression
	ProtoDefTuple     Proto = 0x28 // DefTuple
	ProtoData         Proto = 0x30 // Data
	ProtoError24      Proto = 0x31 // Error24
	ProtoMetaData     Proto = 0x32 // MetaData
	ProtoSQLBindMeta  Proto = 0x33 // SQLBindMeta
	ProtoSQLBindCount Proto = 0x34 // SQLBindCount
	ProtoSQLText      Proto = 0x40 // SQLText
	ProtoSQLBind      Proto = 0x41 // SQLBind
	ProtoSQLInfo      Proto = 0x42 // SQLInfo
	ProtoSQLStatement Proto = 0x43 // SQLStatement
	ProtoOptions      Proto = 0x2b // Options
	ProtoError        Proto = 0x52 // Error
)

func (*Proto) DecodeMsgpack

func (i *Proto) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

func (Proto) EncodeMsgpack

func (i Proto) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

func (Proto) String

func (i Proto) String() string

type Query

type Query interface {
	msgpack.CustomEncoder
	// Code returns Code of query.
	Code() Code
}

Query defines interface for all types of tarantool queries.

type QueryError

type QueryError struct {
	Query Query
	Err   error
}

QueryError is a wrapper for failed Query.

func NewQueryError

func NewQueryError(query Query, err error) *QueryError

NewQueryError creates a new instance of QueryError.

func (QueryError) Cause

func (q QueryError) Cause() error

Cause is useful for unwrapping origin error.

func (QueryError) Error

func (q QueryError) Error() string

Error implements error interface.

func (QueryError) Unwrap

func (q QueryError) Unwrap() error

Unwrap is useful for unwrapping origin error.

type Select

type Select struct {
	Space    *Space
	Index    *Index
	Iterator Iterator
	Key      Key
	Limit    uint64
	Offset   uint64
}

Select defines Tarantool select query.

func NewSelect

func NewSelect(space *Space, key Key, limit uint64) *Select

NewSelect creates a new instance of Select.

func (*Select) Code

func (*Select) Code() Code

Code implements interface Query.

func (*Select) EncodeMsgpack

func (s *Select) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

type SingleResult

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

SingleResult helps to decode single response to Result.

func NewSingleResult

func NewSingleResult(dec msgpack.CustomDecoder) *SingleResult

NewSingleResult returns a new instance of SingleResult.

func (*SingleResult) DecodeMsgpack

func (s *SingleResult) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

type Space

type Space struct {
	ID          uint64
	Owner       uint64
	Name        string
	Engine      string
	FieldsCount uint64
}

Space defines Tarantool space object.

func GetSpace

func GetSpace(ctx context.Context, conn Driver, name string) (*Space, error)

GetSpace finds a space by its name. Method returns ErrSpaceNotFound if space was not found.

func (*Space) DecodeMsgpack

func (s *Space) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

func (*Space) EncodeMsgpack

func (s *Space) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface msgpack.CustomEncoder.

type Spaces

type Spaces []Space

Spaces define a list of Space.

func (Spaces) ByID

func (s Spaces) ByID(id uint64) *Space

ByID returns a space by its id.

func (Spaces) ByName

func (s Spaces) ByName(name string) *Space

ByName returns a space by its name.

func (*Spaces) DecodeMsgpack

func (s *Spaces) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements interface msgpack.CustomDecoder.

type UUID

type UUID uuid.UUID

UUID represents wrapper for uuid.UUID with implemented msgpack.CustomDecoder and msgpack.CustomEncoder interfaces.

func (*UUID) DecodeMsgpack

func (u *UUID) DecodeMsgpack(dec *msgpack.Decoder) error

DecodeMsgpack implements msgpack.CustomDecoder interface.

func (UUID) EncodeMsgpack

func (u UUID) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements msgpack.CustomEncoder interface.

type Update

type Update struct {
	Space      *Space
	Index      *Index
	Key        Key
	Operations Operations
}

Update defines Tarantool update query.

func NewUpdate

func NewUpdate(space *Space, index *Index, key Key, operations Operations) *Update

NewUpdate creates a new instance of Update.

func (*Update) Code

func (*Update) Code() Code

Code implements interface Query.

func (*Update) EncodeMsgpack

func (u *Update) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface Query.

type Upsert

type Upsert struct {
	Space      *Space
	Data       any
	Operations Operations
}

Upsert defines Tarantool upsert query.

func NewUpsert

func NewUpsert(space *Space, data any, operations Operations) *Upsert

NewUpsert creates a new instance of Upsert.

func (*Upsert) Code

func (*Upsert) Code() Code

Code implements interface Query.

func (*Upsert) EncodeMsgpack

func (u *Upsert) EncodeMsgpack(enc *msgpack.Encoder) error

EncodeMsgpack implements interface Query.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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