Categorygithub.com/tarantool/go-tarantool/v2
modulepackage
2.2.1
Repository: https://github.com/tarantool/go-tarantool.git
Documentation: pkg.go.dev

# README

Go Reference Actions Status Code Coverage Telegram GitHub Discussions Stack Overflow

Client in Go for Tarantool

The package go-tarantool contains everything you need to connect to Tarantool 1.10+.

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.10+ and a modern Linux or BSD operating system.

You need a current version of go, version 1.20 or later (use go version to check the version number). Do not use gccgo-go.

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

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

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

This should put the source and binary files in subdirectories of /usr/local/go, so that you can access them by adding github.com/tarantool/go-tarantool to the import {...} section at the start of any Go program.

Build tags

We define multiple build tags.

This allows us to introduce new features without losing backward compatibility.

  1. To run fuzz tests with decimals, you can use the build tag:
    go_tarantool_decimal_fuzzing
    
    Note: It crashes old Tarantool versions.

Documentation

Read the Tarantool documentation to find descriptions of terms such as "connect", "space", "index", and the requests to create and manipulate database objects or Lua functions.

In general, connector methods can be divided into two main parts:

  • Connect() function and functions related to connecting, and
  • Data manipulation functions and Lua invocations such as Insert() or Call().

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

API Reference

Learn API documentation and examples at pkg.go.dev.

Walking-through example

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

package tarantool

import (
	"context"
	"fmt"
	"time"

	"github.com/tarantool/go-tarantool/v2"
	_ "github.com/tarantool/go-tarantool/v2/datetime"
	_ "github.com/tarantool/go-tarantool/v2/decimal"
	_ "github.com/tarantool/go-tarantool/v2/uuid"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	dialer := tarantool.NetDialer{
		Address: "127.0.0.1:3301",
		User: 	 "guest",
	}
	opts := tarantool.Opts{
		Timeout: time.Second,
	}

	conn, err := tarantool.Connect(ctx, dialer, opts)
	if err != nil {
		fmt.Println("Connection refused:", err)
		return
	}

	data, err := conn.Do(
		tarantool.NewInsertRequest(999).Tuple([]interface{}{99999, "BB"})).Get()
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Data:", data)
	}
}

Observation 1: The line "github.com/tarantool/go-tarantool/v2" in the import(...) section brings in all Tarantool-related functions and structures.

Observation 2: Unused import lines are required to initialize encoders and decoders for external msgpack types.

Observation 3: The line starting with "ctx, cancel :=" creates a context object for Connect(). The Connect() call will return an error when a timeout expires before the connection is established.

Observation 4: The line starting with "dialer :=" creates dialer for Connect(). This structure contains fields required to establish a connection.

Observation 5: The line starting with "opts :=" sets up the options for Connect(). In this example, the structure contains only a single value, the timeout. The structure may also contain other settings, see more in documentation for the "Opts" structure.

Observation 6: The line containing "tarantool.Connect" is essential for starting a session. There are three parameters:

  • a context,
  • the dialer that was set up earlier,
  • the option structure that was set up earlier.

There will be only one attempt to connect. If multiple attempts needed, "tarantool.Connect" could be placed inside the loop with some timeout between each try. Example could be found in the example_test, name - ExampleConnect_reconnects.

Observation 7: 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 8: The Insert request, like almost all requests, is preceded by the method Do of object conn which is the object that was returned by Connect().

Example with encrypting traffic

For SSL-enabled connections, use OpenSSLDialer from the go-tlsdialer package.

Here is small example with importing the go-tlsdialer library and using the OpenSSLDialer:

package tarantool

import (
	"context"
	"fmt"
	"time"

	"github.com/tarantool/go-tarantool/v2"
	_ "github.com/tarantool/go-tarantool/v2/datetime"
	_ "github.com/tarantool/go-tarantool/v2/decimal"
	_ "github.com/tarantool/go-tarantool/v2/uuid"
	"github.com/tarantool/go-tlsdialer"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	dialer := tlsdialer.OpenSSLDialer{
		Address:     "127.0.0.1:3013", 
		User:        "test", 
		Password:    "test", 
		SslKeyFile:  "testdata/localhost.key",
		SslCertFile: "testdata/localhost.crt",
		SslCaFile:   "testdata/ca.crt",
	}
	opts := tarantool.Opts{
		Timeout: time.Second,
	}

	conn, err := tarantool.Connect(ctx, dialer, opts)
	if err != nil {
		fmt.Println("Connection refused:", err)
		return
	}

	data, err := conn.Do(
		tarantool.NewInsertRequest(999).Tuple([]interface{}{99999, "BB"})).Get()
	if err != nil {
		fmt.Println("Error:", err)
	} else {
		fmt.Println("Data:", data)
	}
}

Note that traffic encryption is only available in Tarantool Enterprise Edition 2.10 or newer.

Migration guide

You can review the changes between major versions in the migration guide.

Contributing

See the contributing guide for detailed instructions on how to get started with our project.

Alternative connectors

There are two other connectors available from the open source community:

See feature comparison in the documentation.

# Packages

No description provided by the author
No description provided by the author
Package crud with support of API of Tarantool's CRUD module.
Package with support of Tarantool's datetime data type.
Package decimal with support of Tarantool's decimal data type.
go:generate stringer -type Role -linecomment.
Package with implementation of methods for work with a Tarantool's queue implementations.
Package settings is a collection of requests to set a connection session setting or get current session configuration.
Helpers for managing Tarantool process for testing purposes.
Package with support of Tarantool's UUID data type.

# Functions

Connect creates and configures a new Connection.
DecodeBaseResponse parse response header and body.
No description provided by the author
GetSchema returns the actual schema for the Doer.
NewBeginRequest returns a new BeginRequest.
NewBroadcastRequest returns a new broadcast request for a specified key.
NewCall16Request returns a new empty Call16Request.
NewCall17Request returns a new empty CallRequest.
NewCallRequest returns a new empty CallRequest.
NewCommitRequest returns a new CommitRequest.
NewDeleteRequest returns a new empty DeleteRequest.
NewEvalRequest returns a new empty EvalRequest.
NewExecutePreparedRequest returns a new empty preparedExecuteRequest.
NewExecuteRequest returns a new empty ExecuteRequest.
NewFuture creates a new empty Future for a given Request.
NewIdRequest returns a new IdRequest.
NewInsertRequest returns a new empty InsertRequest.
NewOperations returns a new empty collection of update operations.
NewPingRequest returns a new PingRequest.
NewPreparedFromResponse constructs a Prepared object.
NewPrepareRequest returns a new empty PrepareRequest.
NewReplaceRequest returns a new empty ReplaceRequest.
NewRollbackRequest returns a new RollbackRequest.
NewSelectRequest returns a new empty SelectRequest.
NewUnprepareRequest returns a new empty UnprepareRequest.
NewUpdateRequest returns a new empty UpdateRequest.
NewUpsertRequest returns a new empty UpsertRequest.
NewWatchOnceRequest returns a new watchOnceRequest.

# Constants

AutoAuth does not force any authentication method.
If the BestEffortLevel (serializable) isolation level becomes unreachable, the transaction is marked as «conflicted» and can no longer be committed.
ChapSha1Auth forces chap-sha1 authentication method.
Either reconnect attempts exhausted, or explicit Close is called.
Connected signals that connection is established or reestablished.
By default, the isolation level of Tarantool is serializable.
Disconnected signals that connection is broken.
Tarantool client error codes.
Tarantool client error codes.
Tarantool client error codes.
Tarantool client error codes.
ErrorNo indicates that no error has occurred.
Tarantool client error codes.
Tarantool client error codes.
Tarantool client error codes.
All tuples.
All bits are not set.
All bits from x are set in key.
All bits are not set.
Key == x ASC order.
Key >= x.
Key > x.
Key <= x.
Key < x.
Tuples in distance ascending order from specified point.
Key overlaps x.
Key == x DESC order.
LogAppendPushFailed is logged when failed to append a push response.
LogLastReconnectFailed is logged when last reconnect attempt failed, connection will be closed after that.
LogReconnectFailed is logged when reconnect attempt failed.
LogUnexpectedResultId is logged when response with unknown id was received.
LogWatchEventReadFailed is logged when failed to read a watch event.
PapSha256Auth forces pap-sha256 authentication method.
The ReadCommittedLevel isolation level makes visible all transactions that started commit (stream.Do(NewCommitRequest()) was called).
The ReadConfirmedLevel isolation level makes visible all transactions that finished the commit (stream.Do(NewCommitRequest()) was returned).
ReconnectFailed signals that attempt to reconnect has failed.
RLimitDrop immediately aborts the request.
RLimitWait waits during timeout period for some request to be answered.
Shutdown signals that shutdown callback is processing.

# Structs

AuthDialer is a dialer-wrapper that does authentication of a user.
BeginRequest helps you to create a begin request object for execution by a Stream.
BoxError is a type representing Tarantool `box.error` object: a single MP_ERROR_STACK object with a link to the previous stack error.
BroadcastRequest helps to send broadcast messages.
CallRequest helps you to create a call request object for execution by a Connection.
ClientError is connection error produced by this client, i.e.
No description provided by the author
CommitRequest helps you to create a commit request object for execution by a Stream.
Connection is a handle with a single connection to a Tarantool instance.
ConnEvent is sent throw Notify channel specified in Opts.
DeleteRequest helps you to create a delete request object for execution by a Connection.
DialOpts is a way to configure a Dial method to create a new Conn.
Error is wrapper around error returned by Tarantool.
EvalRequest helps you to create an eval request object for execution by a Connection.
ExecutePreparedRequest helps you to create an execute prepared request object for execution by a Connection.
ExecuteRequest helps you to create an execute request object for execution by a Connection.
ExecuteResponse is used for the execute requests.
FdDialer allows using an existing socket fd for connection.
Field is a schema field.
Future is a handle for asynchronous request.
Greeting is a message sent by Tarantool on connect.
GreetingDialer is a dialer-wrapper that reads and fills the Greeting of a connection.
Header is a response header.
IdRequest informs the server about supported protocol version and protocol features.
Index contains information about index.
IndexFields is an index field.
InsertRequest helps you to create an insert request object for execution by a Connection.
IntIntKey is utility type for passing two integer keys to Select*, Update*, Delete* and GetTyped.
IntKey is utility type for passing integer key to Select*, Update*, Delete* and GetTyped.
KeyValueBind is a type for encoding named SQL parameters.
NetDialer is a basic Dialer implementation.
Operations is a collection of update operations.
Opts is a way to configure Connection.
PingRequest helps you to create an execute request object for execution by a Connection.
Prepared is a type for handling prepared statements Since 1.7.0.
PrepareRequest helps you to create a prepare request object for execution by a Connection.
ProtocolDialer is a dialer-wrapper that reads and fills the ProtocolInfo of a connection.
ProtocolInfo type aggregates Tarantool protocol version and features info.
PushResponse is used for push requests for the Future.
ReplaceRequest helps you to create a replace request object for execution by a Connection.
RollbackRequest helps you to create a rollback request object for execution by a Stream.
Schema contains information about spaces and indexes.
SelectRequest allows you to create a select request object for execution by a Connection.
SelectResponse is used for the select requests.
Space contains information about Tarantool's space.
No description provided by the author
No description provided by the author
StringKey is utility type for passing string key to Select*, Update*, Delete* and GetTyped.
UintKey is utility type for passing unsigned integer key to Select*, Update*, Delete* and GetTyped.
UnprepareRequest helps you to create an unprepare request object for execution by a Connection.
UpdateRequest helps you to create an update request object for execution by a Connection.
UpsertRequest helps you to create an upsert request object for execution by a Connection.
WatchEvent is a watch notification event received from a server.
WatchOnceRequest synchronously fetches the value currently associated with a specified notification key without subscribing to changes.

# Interfaces

Conn is a generic stream-oriented network connection to a Tarantool instance.
ConnectedRequest is an interface that provides the info about a Connection the request belongs to.
No description provided by the author
Dialer is the interface that wraps a method to connect to a Tarantool instance.
Doer is an interface that performs requests asynchronously.
Logger is logger type expected to be passed in options.
Request is an interface that provides the necessary data to create a request that will be sent to a tarantool instance.
Response is an interface with operations for the server responses.
ResponseIterator is an interface for iteration over a set of responses.
SchemaResolver is an interface for resolving schema details.
TimeoutResponseIterator is an interface that extends ResponseIterator and adds the ability to change a timeout for the Next() call.
Watcher is a subscription to broadcast events.

# Type aliases

Auth is used as a parameter to set up an authentication method.
No description provided by the author
No description provided by the author
Iter is an enumeration type of a select iterator.
PreparedID is a type for Prepared Statement ID.
PrepareResponse is used for the prepare requests.
ProtocolVersion type stores Tarantool protocol version.
RLimitActions is an enumeration type for an action to do when a rate limit is reached.
No description provided by the author
WatchCallback is a callback to invoke when the key value is updated.