tarantool

package module
v0.0.0-...-4ab5602 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2022 License: BSD-2-Clause Imports: 15 Imported by: 1

README

Client in Go for Tarantool 1.6+

The go-tarantool package has everything necessary for interfacing with 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 will need a current version of go, version 1.3 or later (use go version to check the version number). Do not use gccgo-go.

Note: If your go version is younger than 1.3, or if go is not installed, download the latest tarball from golang.org and say:

$ sudo tar -C /usr/local -xzf go1.7.5.linux-amd64.tar.gz
$ export PATH=$PATH:/usr/local/go/bin
$ export GOPATH="/usr/local/go/go-tarantool"
$ sudo chmod -R a+rwx /usr/local/go </pre>

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

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

This should bring source and binary files into subdirectories of /usr/local/go, making it possible to access by adding github.com/framey-io/go-tarantool in the import {...} section at the start of any Go program.

Hello World

In the "Connectors" chapter of the Tarantool manual, there is an explanation of a very short (18-line) program written in Go. Follow the instructions at the start of the "Connectors" chapter carefully. Then cut and paste the example into a file named example.go, and run it. You should see: nothing.

If that is what you see, then you have successfully installed go-tarantool and successfully executed a program that manipulated the contents of a Tarantool database.

API reference

Read the Tarantool manual to find descriptions of terms like "connect", "space", "index", and the requests for creating and manipulating database objects or Lua functions.

The source files for the requests library are:

  • connection.go for the Connect() function plus functions related to connecting, and
  • request.go for data-manipulation functions and Lua invocations.

See comments in those files for syntax details:

Ping
closeConnection
Select
Insert
Replace
Delete
Update
Upsert
Call
Call17
Eval

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

The source file for error-handling tools is errors.go, which has structure definitions and constants whose names are equivalent to names of errors that the Tarantool server returns.

Walking-through example in Go

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

package main

import (
     "fmt"
     "github.com/framey-io/go-tarantool"
)

func main() {
   opts := tarantool.Opts{User: "guest"}
   conn, err := tarantool.Connect("127.0.0.1:3301", opts)
   // conn, err := tarantool.Connect("/path/to/tarantool.socket", 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/framey-io/go-tarantool" in the import(...) section brings in all Tarantool-related functions and structures.

Observation 2: the line beginning with "Opts :=" sets up the options for Connect(). In this example, there is only one thing in the structure, a user name. The structure can also contain:

  • Pass (password),
  • Timeout (maximum number of milliseconds to wait before giving up),
  • Reconnect (number of seconds to wait before retrying if a connection fails),
  • MaxReconnect (maximum number of times to retry).

Observation 3: the line containing "tarantool.Connect" is essential for beginning any 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.

Help

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

The developers of the Tarantool server will also be happy to provide advice or receive feedback.

Usage

package main

import (
	"github.com/framey-io/go-tarantool"
	"log"
	"time"
)

func main() {
	spaceNo := uint32(513)
	indexNo := uint32(0)

	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 {
		log.Fatalf("Failed to connect: %s", err.Error())
	}

	resp, err := client.Ping()
	log.Println(resp.Code)
	log.Println(resp.Data)
	log.Println(err)

	// insert new tuple { 10, 1 }
	resp, err = client.Insert(spaceNo, []interface{}{uint(10), 1})
    // or
	resp, err = client.Insert("test", []interface{}{uint(10), 1})
	log.Println("Insert")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// delete tuple with primary key { 10 }
	resp, err = client.Delete(spaceNo, indexNo, []interface{}{uint(10)})
    // or
	resp, err = client.Delete("test", "primary", []interface{}{uint(10)})
	log.Println("Delete")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// replace tuple with { 13, 1 }
	resp, err = client.Replace(spaceNo, []interface{}{uint(13), 1})
    // or
	resp, err = client.Replace("test", []interface{}{uint(13), 1})
	log.Println("Replace")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// update tuple with primary key { 13 }, incrementing second field by 3
	resp, err = client.Update(spaceNo, indexNo, []interface{}{uint(13)}, []interface{}{[]interface{}{"+", 1, 3}})
    // or
	resp, err = client.Update("test", "primary", []interface{}{uint(13)}, []interface{}{[]interface{}{"+", 1, 3}})
	log.Println("Update")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// insert tuple {15, 1} or increment second field by 1
	resp, err = client.Upsert(spaceNo, []interface{}{uint(15), 1}, []interface{}{[]interface{}{"+", 1, 1}})
    // or
	resp, err = client.Upsert("test", []interface{}{uint(15), 1}, []interface{}{[]interface{}{"+", 1, 1}})
	log.Println("Upsert")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// select just one tuple with primay key { 15 }
	resp, err = client.Select(spaceNo, indexNo, 0, 1, tarantool.IterEq, []interface{}{uint(15)})
    // or
	resp, err = client.Select("test", "primary", 0, 1, tarantool.IterEq, []interface{}{uint(15)})
	log.Println("Select")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// select tuples by condition ( primay key > 15 ) with offset 7 limit 5
	// BTREE index supposed
	resp, err = client.Select(spaceNo, indexNo, 7, 5, tarantool.IterGt, []interface{}{uint(15)})
    // or
	resp, err = client.Select("test", "primary", 7, 5, tarantool.IterGt, []interface{}{uint(15)})
	log.Println("Select")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// call function 'func_name' with arguments
	resp, err = client.Call("func_name", []interface{}{1, 2, 3})
	log.Println("Call")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)

	// run raw lua code
	resp, err = client.Eval("return 1 + 2", []interface{}{})
	log.Println("Eval")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)
}

To enable support of UUID in msgpack with google/uuid, import tarantool/uuid submodule.

package main

import (
	"log"
	"time"

	"github.com/tarantool/go-tarantool"
	_ "github.com/tarantool/go-tarantool/uuid"
	"github.com/google/uuid"
)

func main() {
	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 {
		log.Fatalf("Failed to connect: %s", err.Error())
	}

	spaceNo := uint32(524)

	id, uuidErr := uuid.Parse("c8f0fa1f-da29-438c-a040-393f1126ad39")
	if uuidErr != nil {
		log.Fatalf("Failed to prepare uuid: %s", uuidErr)
	}

	resp, err := client.Replace(spaceNo, []interface{}{ id })

	log.Println("UUID tuple replace")
	log.Println("Error", err)
	log.Println("Code", resp.Code)
	log.Println("Data", resp.Data)
}

Schema

    // save Schema to local variable to avoid races
    schema := client.Schema

    // access Space objects by name or id
    space1 := schema.Spaces["some_space"]
    space2 := schema.SpacesById[20] // it's a map
    fmt.Printf("Space %d %s %s\n", space1.Id, space1.Name, space1.Engine)
    fmt.Printf("Space %d %d\n", space1.FieldsCount, space1.Temporary)

    // access index information by name or id
    index1 := space1.Indexes["some_index"]
    index2 := space1.IndexesById[2] // 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 := index1.Fields[1] // it's a slice
    fmt.Printf("IndexFields %s %s\n", indexField1.Name, indexField1.Type)

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

Custom (un)packing and typed selects and function calls

You can specify custom pack/unpack functions for your types. This will allow you to store complex structures inside a tuple and may speed up you requests.

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

import (
	"github.com/framey-io/go-tarantool"
	"github.com/vmihailenco/msgpack/v5"
)

type Member struct {
	Name  string
	Nonce string
	Val   uint
}

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

/* same effect in a "magic" way, but slower */
type Tuple2 struct {
	_msgpack struct{} `msgpack:",asArray"`

	Cid     uint
	Orig    string
	Members []Member
}

func (m *Member) EncodeMsgpack(e *msgpack.Encoder) error {
	if err := e.EncodeSliceLen(2); err != nil {
		return err
	}
	if err := e.EncodeString(m.Name); err != nil {
		return err
	}
	if err := e.EncodeUint(m.Val); err != nil {
		return err
	}
	return nil
}

func (m *Member) DecodeMsgpack(d *msgpack.Decoder) error {
	var err error
	var l int
	if l, err = d.DecodeSliceLen(); err != nil {
		return err
	}
	if l != 2 {
		return fmt.Errorf("array len doesn't match: %d", l)
	}
	if m.Name, err = d.DecodeString(); err != nil {
		return err
	}
	if m.Val, err = d.DecodeUint(); err != nil {
		return err
	}
	return nil
}

func (c *Tuple) 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
	}
	if err := e.EncodeSliceLen(len(c.Members)); err != nil {
		return err
	}
	for _, m := range c.Members {
		e.Encode(m)
	}
	return nil
}

func (c *Tuple) 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
}

func main() {
	// establish connection ...

	tuple := Tuple{777, "orig", []Member{{"lol", "", 1}, {"wut", "", 3}}}
	_, err = conn.Replace(spaceNo, tuple)  // NOTE: insert structure itself
	if err != nil {
		t.Errorf("Failed to insert: %s", err.Error())
		return
	}

	var tuples []Tuple
	err = conn.SelectTyped(spaceNo, indexNo, 0, 1, IterEq, []interface{}{777}, &tuples)
	if err != nil {
		t.Errorf("Failed to SelectTyped: %s", err.Error())
		return
	}

	// same result in a "magic" way
	var tuples2 []Tuple2
	err = conn.SelectTyped(spaceNo, indexNo, 0, 1, IterEq, []interface{}{777}, &tuples2)
	if err != nil {
		t.Errorf("Failed to SelectTyped: %s", err.Error())
		return
	}

	// call function 'func_name' returning a table of custom tuples
	var tuples3 []Tuple
	err = client.CallTyped("func_name", []interface{}{1, 2, 3}, &tuples3)
	if err != nil {
		t.Errorf("Failed to CallTyped: %s", err.Error())
		return
	}
}

/*
// Old way to register types
func init() {
	msgpack.Register(reflect.TypeOf(Tuple{}), encodeTuple, decodeTuple)
	msgpack.Register(reflect.TypeOf(Member{}), encodeMember, decodeMember)
}

func encodeMember(e *msgpack.Encoder, v reflect.Value) error {
	m := v.Interface().(Member)
	// same code as in EncodeMsgpack
	return nil
}

func decodeMember(d *msgpack.Decoder, v reflect.Value) error {
	m := v.Addr().Interface().(*Member)
	// same code as in DecodeMsgpack
	return nil
}

func encodeTuple(e *msgpack.Encoder, v reflect.Value) error {
	c := v.Interface().(Tuple)
	// same code as in EncodeMsgpack
	return nil
}

func decodeTuple(d *msgpack.Decoder, v reflect.Value) error {
	c := v.Addr().Interface().(*Tuple)
	// same code as in DecodeMsgpack
	return nil
}
*/

Options

  • Timeout - timeout for any particular request. If Timeout is zero request, any request may block infinitely.
  • Reconnect - timeout between reconnect attempts. If Reconnect is zero, no reconnects will be performed.
  • MaxReconnects - maximal number of reconnect failures; after that we give it up. If MaxReconnects is zero, the client will try to reconnect endlessly.
  • User - user name to log into Tarantool.
  • Pass - user password to log into Tarantool.

Working with queue

package main
import (
	"github.com/vmihailenco/msgpack/v5"
	"github.com/framey-io/go-tarantool"
	"github.com/framey-io/go-tarantool/queue"
	"time"
	"fmt"
	"log"
)

type customData struct{
	Dummy bool
}

func (c *customData) DecodeMsgpack(d *msgpack.Decoder) error {
	var err error
	if c.Dummy, err = d.DecodeBool(); err != nil {
		return err
	}
	return nil
}

func (c *customData) EncodeMsgpack(e *msgpack.Encoder) error {
	return e.EncodeBool(c.Dummy)
}

func main() {
	opts := tarantool.Opts{
		Timeout: time.Second,
		Reconnect: time.Second,
		MaxReconnects: 5,
		User: "user",
		Pass: "pass",
		// ...
	}
	conn, err := tarantool.Connect("127.0.0.1:3301", opts)

	if err != nil {
		log.Fatalf("connection: %s", err)
		return
	}

	cfg := queue.Cfg{
		Temporary:  true,
		IfNotExists: true,
		Kind:       queue.FIFO,
		Opts: queue.Opts{
			Ttl:   10 * time.Second,
			Ttr:   5 * time.Second,
			Delay: 3 * time.Second,
			Pri:   1,
		},
	}

	que := queue.New(conn, "test_queue")
	if err = que.Create(cfg); err != nil {
		log.Fatalf("queue create: %s", err)
		return
	}

	// put data
	task, err := que.Put("test_data")
	if err != nil {
		log.Fatalf("put task: %s", err)
	}
	fmt.Println("Task id is", task.Id())

	// take data
	task, err = que.Take() //blocking operation
	if err != nil {
		log.Fatalf("take task: %s", err)
	}
	fmt.Println("Data is", task.Data())
	task.Ack()

	// take typed example
	putData := customData{}
	// put data
	task, err = que.Put(&putData)
	if err != nil {
		log.Fatalf("put typed task: %s", err)
	}
	fmt.Println("Task id is ", task.Id())

	takeData := customData{}
	//take data
	task, err = que.TakeTyped(&takeData) //blocking operation
	if err != nil {
		log.Fatalf("take take typed: %s", err)
	}
	fmt.Println("Data is ", takeData)
	// same data
	fmt.Println("Data is ", task.Data())

	task, err = que.Put([]int{1, 2, 3})
	task.Bury()

	task, err = que.TakeTimeout(2 * time.Second)
	if task == nil {
		fmt.Println("Task is nil")
	}

	que.Drop()
}

Features of the implementation:

  • If you use connection timeout and call TakeWithTimeout with parameter greater than the connection timeout then parameter reduced to it
  • If you use connection timeout and call Take then we return a error if we can not take task from queue in a time equal to the connection timeout

Multi connections

You can use multiple connections config with tarantool/multi.

Main features:

  • Check active connection with configurable time interval and on connection fail switch to next in pool.
  • Get addresses list from server and reconfigure to use in MultiConnection.

Additional options (configurable via ConnectWithOpts):

  • CheckTimeout - time interval to check for connection timeout and try to switch connection
  • ClusterDiscoveryTime - time interval to ask server for updated address list (works on with NodesGetFunctionName set)
  • NodesGetFunctionName - server lua function name to call for getting address list

Alternative connectors

Documentation

Overview

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

server := "127.0.0.1:3013"
opts := tarantool.Opts{
	Timeout:       50 * time.Millisecond,
	Reconnect:     100 * time.Millisecond,
	MaxReconnects: 3,
	User:          "test",
	Pass:          "test",
}
client, err := tarantool.Connect(server, opts)
if err != nil {
	fmt.Errorf("Failed to connect: %s", err.Error())
	return
}

resp, err := client.Ping()
fmt.Println("Ping Code", resp.Code)
fmt.Println("Ping Data", resp.Data)
fmt.Println("Ping Error", err)

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

// insert new tuple { 10, 1 }
resp, err = client.Insert(spaceNo, []interface{}{uint(10), "test", "one"})
fmt.Println("Insert Error", err)
fmt.Println("Insert Code", resp.Code)
fmt.Println("Insert Data", resp.Data)

// insert new tuple { 11, 1 }
resp, err = client.Insert("test", &Tuple{Id: 11, Msg: "test", Name: "one"})
fmt.Println("Insert Error", err)
fmt.Println("Insert Code", resp.Code)
fmt.Println("Insert Data", resp.Data)

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

// replace tuple with primary key 13
// note, Tuple is defined within tests, and has EncdodeMsgpack and DecodeMsgpack
// methods
resp, err = client.Replace(spaceNo, []interface{}{uint(13), 1})
fmt.Println("Replace Error", err)
fmt.Println("Replace Code", resp.Code)
fmt.Println("Replace Data", resp.Data)

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

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

// call function 'func_name' with arguments
resp, err = client.Call17("simple_incr", []interface{}{1})
fmt.Println("Call17 Error", err)
fmt.Println("Call17 Code", resp.Code)
fmt.Println("Call17 Data", resp.Data)

// run raw lua code
resp, err = client.Eval("return 1 + 2", []interface{}{})
fmt.Println("Eval Error", err)
fmt.Println("Eval Code", resp.Code)
fmt.Println("Eval Data", resp.Data)

resp, err = client.Replace("test", &Tuple{Id: 11, Msg: "test", Name: "eleven"})
resp, err = client.Replace("test", &Tuple{Id: 12, Msg: "test", Name: "twelve"})

var futs [3]*tarantool.Future
futs[0] = client.SelectAsync("test", "primary", 0, 2, tarantool.IterLe, tarantool.UintKey{12})
futs[1] = client.SelectAsync("test", "primary", 0, 1, tarantool.IterEq, tarantool.UintKey{13})
futs[2] = client.SelectAsync("test", "primary", 0, 1, tarantool.IterEq, tarantool.UintKey{15})
var t []Tuple
err = futs[0].GetTyped(&t)
fmt.Println("Fut", 0, "Error", err)
fmt.Println("Fut", 0, "Data", t)

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

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

Ping Code 0
Ping Data []
Ping Error <nil>
Insert Error <nil>
Insert Code 0
Insert Data [[10 test one]]
Insert Error <nil>
Insert Code 0
Insert Data [[11 test one]]
Delete Error <nil>
Delete Code 0
Delete Data [[10 test one]]
Replace Error <nil>
Replace Code 0
Replace Data [[13 1]]
Update Error <nil>
Update Code 0
Update Data [[13 4]]
Select Error <nil>
Select Code 0
Select Data [[15 val 15 bla]]
Call17 Error <nil>
Call17 Code 0
Call17 Data [2]
Eval Error <nil>
Eval Code 0
Eval Data [3]
Fut 0 Error <nil>
Fut 0 Data [{{} 12 test twelve} {{} 11 test eleven}]
Fut 1 Error <nil>
Fut 1 Data [[13 4]]
Fut 2 Error <nil>
Fut 2 Data [[15 val 15 bla]]

Index

Examples

Constants

View Source
const (
	// Connect signals that connection is established or reestablished
	Connected ConnEventKind = iota + 1
	// Disconnect 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 were received.
	// Most probably it is due to request timeout.
	LogUnexpectedResultId
)
View Source
const (
	SelectRequest    = 1
	InsertRequest    = 2
	ReplaceRequest   = 3
	UpdateRequest    = 4
	DeleteRequest    = 5
	CallRequest      = 6 /* call in 1.6 format */
	AuthRequest      = 7
	EvalRequest      = 8
	UpsertRequest    = 9
	Call17Request    = 10
	ExecuteRequest   = 11
	PrepareRequest   = 13
	PingRequest      = 64
	SubscribeRequest = 66

	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

	KeySqlText        = 0x40
	KeySqlBind        = 0x41
	KeySqlStmtId      = 0x43
	KeyPrepareOptions = 0x2b
	/* DML - any operation that manipulates/changes data */
	KeySqlDMLResponseData = 0x42

	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)
	ErrorCodeBit      = 0x8000
	PacketLengthBytes = 5
)
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 (
	ER_UNKNOWN uint32 = iota
	ER_ILLEGAL_PARAMS
	ER_MEMORY_ISSUE
	ER_TUPLE_FOUND
	ER_TUPLE_NOT_FOUND
	ER_UNSUPPORTED
	ER_NONMASTER
	ER_READONLY
	ER_INJECTION
	ER_CREATE_SPACE
	ER_SPACE_EXISTS
	ER_DROP_SPACE
	ER_ALTER_SPACE
	ER_INDEX_TYPE
	ER_MODIFY_INDEX
	ER_LAST_DROP
	ER_TUPLE_FORMAT_LIMIT
	ER_DROP_PRIMARY_KEY
	ER_KEY_PART_TYPE
	ER_EXACT_MATCH
	ER_INVALID_MSGPACK
	ER_PROC_RET
	ER_TUPLE_NOT_ARRAY
	ER_FIELD_TYPE
	ER_INDEX_PART_TYPE_MISMATCH
	ER_UPDATE_SPLICE
	ER_UPDATE_ARG_TYPE
	ER_FORMAT_MISMATCH_INDEX_PART
	ER_UNKNOWN_UPDATE_OP
	ER_UPDATE_FIELD
	ER_FUNCTION_TX_ACTIVE
	ER_KEY_PART_COUNT
	ER_PROC_LUA
	ER_NO_SUCH_PROC
	ER_NO_SUCH_TRIGGER
	ER_NO_SUCH_INDEX_ID
	ER_NO_SUCH_SPACE
	ER_NO_SUCH_FIELD_NO
	ER_EXACT_FIELD_COUNT
	ER_FIELD_MISSING
	ER_WAL_IO
	ER_MORE_THAN_ONE_TUPLE
	ER_ACCESS_DENIED
	ER_CREATE_USER
	ER_DROP_USER
	ER_NO_SUCH_USER
	ER_USER_EXISTS
	ER_PASSWORD_MISMATCH
	ER_UNKNOWN_REQUEST_TYPE
	ER_UNKNOWN_SCHEMA_OBJECT
	ER_CREATE_FUNCTION
	ER_NO_SUCH_FUNCTION
	ER_FUNCTION_EXISTS
	ER_BEFORE_REPLACE_RET
	ER_MULTISTATEMENT_TRANSACTION
	ER_TRIGGER_EXISTS
	ER_USER_MAX
	ER_NO_SUCH_ENGINE
	ER_RELOAD_CFG
	ER_CFG
	ER_SAVEPOINT_EMPTY_TX
	ER_NO_SUCH_SAVEPOINT
	ER_UNKNOWN_REPLICA
	ER_REPLICASET_UUID_MISMATCH
	ER_INVALID_UUID
	ER_REPLICASET_UUID_IS_RO
	ER_INSTANCE_UUID_MISMATCH
	ER_REPLICA_ID_IS_RESERVED
	ER_INVALID_ORDER
	ER_MISSING_REQUEST_FIELD
	ER_IDENTIFIER
	ER_DROP_FUNCTION
	ER_ITERATOR_TYPE
	ER_REPLICA_MAX
	ER_INVALID_XLOG
	ER_INVALID_XLOG_NAME
	ER_INVALID_XLOG_ORDER
	ER_NO_CONNECTION
	ER_TIMEOUT
	ER_ACTIVE_TRANSACTION
	ER_CURSOR_NO_TRANSACTION
	ER_CROSS_ENGINE_TRANSACTION
	ER_NO_SUCH_ROLE
	ER_ROLE_EXISTS
	ER_CREATE_ROLE
	ER_INDEX_EXISTS
	ER_SESSION_CLOSED
	ER_ROLE_LOOP
	ER_GRANT
	ER_PRIV_GRANTED
	ER_ROLE_GRANTED
	ER_PRIV_NOT_GRANTED
	ER_ROLE_NOT_GRANTED
	ER_MISSING_SNAPSHOT
	ER_CANT_UPDATE_PRIMARY_KEY
	ER_UPDATE_INTEGER_OVERFLOW
	ER_GUEST_USER_PASSWORD
	ER_TRANSACTION_CONFLICT
	ER_UNSUPPORTED_PRIV
	ER_LOAD_FUNCTION
	ER_FUNCTION_LANGUAGE
	ER_RTREE_RECT
	ER_PROC_C
	ER_UNKNOWN_RTREE_INDEX_DISTANCE_TYPE
	ER_PROTOCOL
	ER_UPSERT_UNIQUE_SECONDARY_KEY
	ER_WRONG_INDEX_RECORD
	ER_WRONG_INDEX_PARTS
	ER_WRONG_INDEX_OPTIONS
	ER_WRONG_SCHEMA_VERSION
	ER_MEMTX_MAX_TUPLE_SIZE
	ER_WRONG_SPACE_OPTIONS
	ER_UNSUPPORTED_INDEX_FEATURE
	ER_VIEW_IS_RO
	ER_NO_TRANSACTION
	ER_SYSTEM
	ER_LOADING
	ER_CONNECTION_TO_SELF
	ER_KEY_PART_IS_TOO_LONG
	ER_COMPRESSION
	ER_CHECKPOINT_IN_PROGRESS
	ER_SUB_STMT_MAX
	ER_COMMIT_IN_SUB_STMT
	ER_ROLLBACK_IN_SUB_STMT
	ER_DECOMPRESSION
	ER_INVALID_XLOG_TYPE
	ER_ALREADY_RUNNING
	ER_INDEX_FIELD_COUNT_LIMIT
	ER_LOCAL_INSTANCE_ID_IS_READ_ONLY
	ER_BACKUP_IN_PROGRESS
	ER_READ_VIEW_ABORTED
	ER_INVALID_INDEX_FILE
	ER_INVALID_RUN_FILE
	ER_INVALID_VYLOG_FILE
	ER_CASCADE_ROLLBACK
	ER_VY_QUOTA_TIMEOUT
	ER_PARTIAL_KEY
	ER_TRUNCATE_SYSTEM_SPACE
	ER_LOAD_MODULE
	ER_VINYL_MAX_TUPLE_SIZE
	ER_WRONG_DD_VERSION
	ER_WRONG_SPACE_FORMAT
	ER_CREATE_SEQUENCE
	ER_ALTER_SEQUENCE
	ER_DROP_SEQUENCE
	ER_NO_SUCH_SEQUENCE
	ER_SEQUENCE_EXISTS
	ER_SEQUENCE_OVERFLOW
	ER_NO_SUCH_INDEX_NAME
	ER_SPACE_FIELD_IS_DUPLICATE
	ER_CANT_CREATE_COLLATION
	ER_WRONG_COLLATION_OPTIONS
	ER_NULLABLE_PRIMARY
	ER_NO_SUCH_FIELD_NAME_IN_SPACE
	ER_TRANSACTION_YIELD
	ER_NO_SUCH_GROUP
	ER_SQL_BIND_VALUE
	ER_SQL_BIND_TYPE
	ER_SQL_BIND_PARAMETER_MAX
	ER_SQL_EXECUTE
	ER_UPDATE_DECIMAL_OVERFLOW
	ER_SQL_BIND_NOT_FOUND
	ER_ACTION_MISMATCH
	ER_VIEW_MISSING_SQL
	ER_FOREIGN_KEY_CONSTRAINT
	ER_NO_SUCH_MODULE
	ER_NO_SUCH_COLLATION
	ER_CREATE_FK_CONSTRAINT
	ER_DROP_FK_CONSTRAINT
	ER_NO_SUCH_CONSTRAINT
	ER_CONSTRAINT_EXISTS
	ER_SQL_TYPE_MISMATCH
	ER_ROWID_OVERFLOW
	ER_DROP_COLLATION
	ER_ILLEGAL_COLLATION_MIX
	ER_SQL_NO_SUCH_PRAGMA
	ER_SQL_CANT_RESOLVE_FIELD
	ER_INDEX_EXISTS_IN_SPACE
	ER_INCONSISTENT_TYPES
	ER_SQL_SYNTAX_WITH_POS
	ER_SQL_STACK_OVERFLOW
	ER_SQL_SELECT_WILDCARD
	ER_SQL_STATEMENT_EMPTY
	ER_SQL_KEYWORD_IS_RESERVED
	ER_SQL_SYNTAX_NEAR_TOKEN
	ER_SQL_UNKNOWN_TOKEN
	ER_SQL_PARSER_GENERIC
	ER_SQL_ANALYZE_ARGUMENT
	ER_SQL_COLUMN_COUNT_MAX
	ER_HEX_LITERAL_MAX
	ER_INT_LITERAL_MAX
	ER_SQL_PARSER_LIMIT
	ER_INDEX_DEF_UNSUPPORTED
	ER_CK_DEF_UNSUPPORTED
	ER_MULTIKEY_INDEX_MISMATCH
	ER_CREATE_CK_CONSTRAINT
	ER_CK_CONSTRAINT_FAILED
	ER_SQL_COLUMN_COUNT
	ER_FUNC_INDEX_FUNC
	ER_FUNC_INDEX_FORMAT
	ER_FUNC_INDEX_PARTS
	ER_NO_SUCH_FIELD_NAME
	ER_FUNC_WRONG_ARG_COUNT
	ER_BOOTSTRAP_READONLY
	ER_SQL_FUNC_WRONG_RET_COUNT
	ER_FUNC_INVALID_RETURN_TYPE
	ER_SQL_PARSER_GENERIC_WITH_POS
	ER_REPLICA_NOT_ANON
	ER_CANNOT_REGISTER
	ER_SESSION_SETTING_INVALID_VALUE
	ER_SQL_PREPARE
	ER_WRONG_QUERY_ID
	ER_SEQUENCE_NOT_STARTED
	ER_NO_SUCH_SESSION_SETTING
	ER_UNCOMMITTED_FOREIGN_SYNC_TXNS
	ER_SYNC_MASTER_MISMATCH
	ER_SYNC_QUORUM_TIMEOUT
	ER_SYNC_ROLLBACK
	ER_TUPLE_METADATA_IS_TOO_BIG
	ER_XLOG_GAP
	ER_TOO_EARLY_SUBSCRIBE
	ER_SQL_CANT_ADD_AUTOINC
	ER_QUORUM_WAIT
	ER_INTERFERING_PROMOTE
	ER_ELECTION_DISABLED
	ER_TXN_ROLLBACK
	ER_NOT_LEADER
	ER_SYNC_QUEUE_UNCLAIMED
	ER_SYNC_QUEUE_FOREIGN
	ER_UNABLE_TO_PROCESS_IN_STREAM
	ER_UNABLE_TO_PROCESS_OUT_OF_STREAM
	ER_TRANSACTION_TIMEOUT
	ER_ACTIVE_TIMER
)

Tarantool server error codes https://github.com/tarantool/tarantool/blob/master/src/box/errcode.h

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, ie connection failures or timeouts.

func (ClientError) Error

func (clierr ClientError) Error() 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, - or request is timeouted, - 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

type ConnLogKind

type ConnLogKind int

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
}

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:

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: - unix:///abs/path/tnt.sock - unix:path/tnt.sock - /abs/path/tnt.sock - first '/' indicates unix socket - ./rel/path/tnt.sock - first '.' indicates unix socket - unix/:path/tnt.sock - 'unix/' acts as a "host" and "/path..." as a port

Note:

- 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 attempt to reconnect later and will not end attempts on authorization failures.

func (*Connection) Addr

func (conn *Connection) Addr() string

Addr is 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.6, so result is converted to array of arrays

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

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.6, so future's result is always array of arrays

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.6, so result is converted to array of arrays

It is equal to conn.CallAsync(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 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().

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

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) 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 user specified handle from Opts

func (*Connection) InUseNow

func (conn *Connection) InUseNow() bool

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

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 is address of outgoing socket

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.

func (*Connection) PrepareExecute

func (conn *Connection) PrepareExecute(sql string, args map[string]interface{}) (resp *Response, err error)

func (*Connection) PrepareExecuteTyped

func (conn *Connection) PrepareExecuteTyped(sql string, args map[string]interface{}, result interface{}) (err error)

func (*Connection) RemoteAddr

func (conn *Connection) RemoteAddr() string

RemoteAddr is 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().

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
var conn *tarantool.Connection
conn, err := example_connect()
if err != nil {
	fmt.Printf("error in prepare is %v", err)
	return
}
defer conn.Close()
resp, err := conn.Select(513, 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.

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
var conn *tarantool.Connection
conn, err := example_connect()
if err != nil {
	fmt.Printf("error in prepare is %v", err)
	return
}
defer conn.Close()
var res []Tuple
err = conn.SelectTyped(513, 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().

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.

func (*Connection) UpsertTyped

func (conn *Connection) UpsertTyped(space, tuple, ops, result interface{}) (err error)

UpsertTyped performs insert of a tuple or updates existing one, by tuple's primary key.

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

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)
	Call17(functionName string, args interface{}) (resp *Response, err error)
	Eval(expr string, args interface{}) (resp *Response, err error)
	PrepareExecute(sql string, args map[string]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)
	UpsertTyped(space, tuple, ops, result interface{}) (err error)
	CallTyped(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)
	PrepareExecuteTyped(sql string, args map[string]interface{}, result interface{}) (err 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
	Call17Async(functionName string, args interface{}) *Future
	EvalAsync(expr string, args interface{}) *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 Error

type Error struct {
	Code uint32
	Msg  string
}

Error is wrapper around error returned by Tarantool

func (Error) Error

func (tnterr Error) Error() string

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 (*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) 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) 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 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 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 Opts

type Opts struct {
	// Timeout is requests timeout.
	// Also used to setup net.TCPConn.Set(Read|Write)Deadline
	Timeout time.Duration
	// Reconnect 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.
	Reconnect time.Duration
	// MaxReconnects is a maximum reconnect attempts.
	// After MaxReconnects attempts Connection becomes closed.
	MaxReconnects uint
	// User name for authorization
	User string
	// Pass is password for authorization
	Pass string
	// RateLimit limits number of 'in-fly' request, ie 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
}

Opts is a way to configure Connection

type Response

type Response struct {
	RequestId uint32
	Code      uint32
	Error     string // error message
	// Data contains deserialized data for untyped requests
	Data []interface{}
	// 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 Call17 to same format as other actions returns (ie array of arrays).

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.

type Space

type Space struct {
	Id        uint32
	Name      string
	Engine    string
	Temporary bool // Is this space temporaray?
	// 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
}

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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