Categorygithub.com/fizikroot/go-tarantool
modulepackage
0.0.0-20200903122708-13f719aede34
Repository: https://github.com/fizikroot/go-tarantool.git
Documentation: pkg.go.dev

# README

go-tarantool GoDoc Build Status

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 with responses that are faster than other packages according to public benchmarks.

Table of contents

Key features

  • Support for both encoding and decoding of Tarantool queries/commands, which leads us to the following advantages:
    • implementing services that mimic a real Tarantool DBMS is relatively easy; for example, you can code a service which would relay queries and commands to a real Tarantool instance; the server interface is documented here;
    • replication support: you can implement a service which would mimic a Tarantool replication slave and get on-the-fly data updates from the Tarantool master, an example is provided here.
  • The interface for sending and packing queries is different from other go-tarantool implementations, which you may find more aesthetically pleasant to work with: all queries are represented with different types that follow the same interface rather than with individual methods in the connector, e.g. conn.Exec(&Update{...}) vs conn.Update({}).

Installation

Pre-requisites:

  • Tarantool version 1.6 or 1.7,
  • a modern Linux, BSD or Mac OS operating system,
  • a current version of go, version 1.8 or later (use go version to check the version number).

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

sudo tar -C /usr/local -xzf go1.8.3.linux-amd64.tar.gz
sudo chmod -R a+rwx /usr/local/go

Make sure go and go-tarantool are on your path. For example:

export PATH=$PATH:/usr/local/go/bin
export GOPATH="/usr/local/go/go-tarantool"

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

go get github.com/viciious/go-tarantool

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

Hello World

Here is a very short example Go program which tries to connect to a Tarantool server.

package main

import (
    "context"
    "fmt"
    "github.com/viciious/go-tarantool"
)

func main() {
    opts := tarantool.Options{User: "guest"}
    conn, err := tarantool.Connect("127.0.0.1:3301", &opts)
    if err != nil {
        fmt.Printf("Connection refused: %s\n", err.Error())
	return
    }

    query := &tarantool.Insert{Space: "examples", Tuple: []interface{}{uint64(99999), "BB"}}
    resp := conn.Exec(context.Background(), query)

    if resp.Error != nil {
        fmt.Println("Insert failed", resp.Error)
    } else {
        fmt.Println(fmt.Sprintf("Insert succeeded: %#v", resp.Data))
    }

    conn.Close()
}

Cut and paste this example into a file named example.go.

Start a Tarantool server on localhost, and make sure it is listening on port 3301. Set up a space named examples exactly as described in the Tarantool manual's Connectors section.

Again, make sure PATH and GOPATH point to the right places. Then build and run example.go:

go build example.go
./example

You should see: messages saying "Insert failed" or "Insert succeeded".

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

Walking through the example

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

Observation 1: the line "github.com/viciious/go-tarantool" in the import(...) section brings in all Tarantool-related functions and structures. It is common to bring in context and fmt as well.

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:

  • ConnectTimeout (the number of milliseconds the connector will wait a new connection to be established before giving up),
  • QueryTimeout (the default maximum number of milliseconds to wait before giving up - can be overriden on per-query basis),
  • DefaultSpace (the name of default Tarantool space)
  • Password (user's password)
  • UUID (used for replication)
  • ReplicaSetUUID (used for replication)

Observation 3: the line containing "tarantool.Connect" is one way to begin a session. There are two parameters:

  • a string with host:port format (or "/path/to/tarantool.socket"), and
  • the option structure that was set up earlier.

There is an alternative way to connect, we will describe it later.

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 conn.exec request, like many requests, is preceded by "conn." which is the name of the object that was returned by Connect(). In this case, for Insert, there are two parameters:

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

All the requests described in the Tarantool manual can be expressed in a similar way within connect.Exec(), with the format "&name-of-request{arguments}". For example: &ping{}. For a long example:

    data, err := conn.Exec(context.Background(), &Update{
        Space: "tester",
        Index: "primary",
        Key:   1,
        Set: []Operator{
            &OpAdd{
                Field:    2,
                Argument: 17,
            },
            &OpAssign{
                Field:    1,
                Argument: "Hello World",
            },
        },
    })

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
  • insert_test.go for an example of a data-manipulation function used in tests.

See comments in these files for syntax details:

The supported requests have parameters and results equivalent to requests in the Tarantool manual. Browsing through the other *.go programs in the package will show how the packagers have paid attention to some of the more advanced features of Tarantool, such as vclock and replication.

Alternative way to connect

Here we show a variation of example.go, where the connect is done a different way.


package main

import (
    "context"
    "fmt"
    "github.com/viciious/go-tarantool"
)

func main() {
    opts := tarantool.Options{User: "guest"}
    tnt := tarantool.New("127.0.0.1:3301", &opts)
    conn, err := tnt.Connect()
    if err != nil {
        fmt.Printf("Connection refused: %s\n", err.Error())
	return
    }

    query := &tarantool.Insert{Space: "examples", Tuple: []interface{}{uint64(99999), "BB"}}
    resp := conn.Exec(context.Background(), query)

    if resp.Error != nil {
        fmt.Println("Insert failed", resp.Error)
    } else {
        fmt.Println(fmt.Sprintf("Insert succeeded: %#v", resp.Data))
    }

    conn.Close()
}

In this variation, tarantool.New returns a Connector instance, which is a goroutine-safe singleton object that can transparently handle reconnects.

Help

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

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

# Packages

No description provided by the author
No description provided by the author

# Functions

Connect to tarantool instance with options.
Connect to tarantool instance with options using the provided context.
ConnectionClosedError returns ConnectionError with message about closed connection or error depending on the connection state.
New Connector instance.
No description provided by the author
NewConnectionError returns ConnectionError with message and remoteAddr in error text.
NewContextError returns ContextError with message and remoteAddr in error text.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
NewQueryError returns ContextError with message and Code.
NewReplicaSet returns empty ReplicaSet.
NewSlave instance with tarantool master uri.
NewVectorClock returns VectorClock with clocks equal to the given lsn elements sequentially.
No description provided by the author
No description provided by the author

# Constants

No description provided by the author
Tarantool >= 1.7.2.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
%s access denied for user '%s'.
Operation is not permitted when there is an active transaction.
Can't modify space '%s': %s.
Argument type in operation '%c' on field %u does not match field type: expected a %s.
Attempt to modify a tuple field which is part of index '%s' in space '%s'.
Incorrect value for option '%s': %s.
Can't reset cluster id: it is already assigned.
Cluster id of the replica %s doesn't match cluster id of the master %s.
Failed to create function '%s': %s.
Failed to create role '%s': %s.
Failed to create space '%s': %s.
Failed to create user '%s': %s.
A multi-statement transaction can not use multiple storage engines.
Can't drop function %u: %s.
Can't drop primary key in space '%s' while secondary keys exist.
Can't drop space '%s': %s.
Failed to drop user '%s': %s.
Invalid key part count in an exact match (expected %u, got %u).
Can not create a new fiber: recursion limit reached.
Tuple field %u type does not match one required by operation: expected %s.
Ambiguous field type in index '%s', key part %u.
%s access denied for user '%s' to function '%s'.
Function '%s' already exists.
Unsupported language '%s' specified for function '%s'.
A limit on the total number of functions has been reached: %u.
Incorrect grant arguments: %s.
Setting password for guest user has no effect.
Invalid identifier '%s' (expected letters, digits or an underscore).
Illegal parameters, %s.
Index '%s' already exists.
Tuple field count %u is less than required by a defined index (expected %u).
Unsupported index type supplied for index '%s' in space '%s'.
Error injection '%s'.
Invalid MsgPack - %s.
Invalid LSN order for server %u: previous LSN = %llu, new lsn = %llu.
Invalid UUID: %s.
Failed to read xlog: %lld.
Invalid xlog name: expected %lld got %lld.
Invalid xlog order: %lld and %lld.
Unknown iterator type '%s'.
Invalid key part count (expected [0..%u], got %u).
Supplied key type of part %u does not match index part type: expected %s.
Can't drop the primary key in a system space, space '%s'.
Failed to dynamically load function '%s': %s.
Local server is not active.
Failed to allocate %u bytes in %s for %s.
Missing mandatory field '%s' in request.
Can't find snapshot.
Can't create or modify index '%s' in space '%s': %s.
More than one tuple found by get().
Operation is not permitted when there is no active transaction.
Connection is not established.
Can't modify data on a replication slave.
Space engine '%s' does not exist.
Field %d was not found in the tuple.
Function '%s' does not exist.
No index #%u is defined in space '%s'.
Procedure '%.*s' is not defined.
Role '%s' is not found.
Space '%s' does not exist.
Trigger is not found.
User '%s' is not found.
No description provided by the author
Incorrect password supplied for user '%s'.
User '%s' already has %s access on %s '%s'.
User '%s' does not have %s access on %s '%s'.
???.
%s.
msgpack.encode: can not encode Lua type '%s'.
%s.
Can't modify data because this server is in read-only mode.
Can't set option '%s' dynamically.
Replica count limit reached: %u.
Reserved66.
Role '%s' already exists.
User '%s' already has role '%s'.
Granting role '%s' to role '%s' would create a loop.
User '%s' does not have role '%s'.
RTree: %s must be an array with %u (point) or %u (rectangle/box) numeric coordinates.
Can't initialize server id with a reserved value %u.
Failed to allocate %u bytes for tuple in the slab allocator: tuple is too large.
%s.
%s access denied for user '%s' to space '%s'.
Space '%s' already exists.
Tuple field count %u does not match space '%s' field count %u.
SPLICE error on field %u: %s.
Timeout exceeded.
Transaction has been aborted by conflict.
Tuple format limit reached: %u.
Duplicate key exists in unique index '%s' in space '%s'.
Tuple is too long %u.
Tuple/Key must be MsgPack array.
Tuple doesn't exist in index '%s' in space '%s'.
Tuple reference counter overflow.
Unknown error.
Unknown request type %u.
Unknown RTREE index distance type %s.
Unknown object type '%s'.
Server %s is not registered with the cluster.
Unknown UPDATE operation.
%s does not support %s.
Unsupported role privilege '%s'.
Field %u UPDATE error: %s.
Integer overflow when performing '%c' operation on field %u.
Space %s has a unique secondary index and does not support UPSERT.
User '%s' already exists.
A limit on the total number of users has been reached: %u.
Failed to write to disk.
Wrong index options (field %u): %s.
Wrong index parts (field %u): %s; expected field1 id (number), field1 type (string), ...
Wrong record in _index space: got {%s}, expected {%s}.
Wrong schema version, current: %d, in request: %u.
No description provided by the author
No description provided by the author
No description provided by the author
all tuples.
all bits are not set.
all bits from x are set in key.
at least one x's bit is set.
key == x ASC order.
key >= x.
key > x.
key <= x.
key < x.
key == x DESC order.
No description provided by the author
Tarantool >= 1.9.0.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Tarantool >= 1.9.0.

# Variables

No description provided by the author
No description provided by the author
ErrBadResult means that query result was of invalid type or length.
No description provided by the author
No description provided by the author
ErrNotInReplicaSet means that join operation can not be performed on a replica set due to missing parameters.
ErrNotSupported is returned when an unimplemented query type or operation is encountered.
No description provided by the author
No description provided by the author
ErrUnknownError is returns when ErrorCode isn't OK but Error is nil in Result.
ErrVectorClock is returns in case of bad manipulation with vector clock.

# Structs

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Box is tarantool instance.
No description provided by the author
No description provided by the author
Call17 is available since Tarantool >= 1.7.2.
No description provided by the author
ConnectionError is returned when something have been happened with connection.
No description provided by the author
ContextError is returned when request has been ended with context timeout or cancel.
No description provided by the author
No description provided by the author
No description provided by the author
Eval query.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
Join is the JOIN command.
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
QueryError is returned when query error has been happened.
No description provided by the author
ReplicaSet is used to store params of the Replica Set.
No description provided by the author
No description provided by the author
Slave connects to Tarantool 1.6, 1.7 or 1.10 instance and subscribes for changes.
Subscribe is the SUBSCRIBE command.
No description provided by the author
No description provided by the author
VClock response (in OK).

# Interfaces

Error has Temporary method which returns true if error is temporary.
No description provided by the author
No description provided by the author
PacketIterator is a wrapper around Slave provided iteration over new Packets functionality.
No description provided by the author

# Type aliases

No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
VectorClock is used to store logical clocks (direct dependency clock implementation).