module tarantool

tarantool.connect(host='localhost', port=33013, user=None, password=None, encoding=None)

Create a connection to the Tarantool server.

Parameters:
  • host (str) – Server hostname or IP-address
  • port (int) – Server port
Return type:

Connection

Raise:

NetworkError

class tarantool.Connection(host, port, user=None, password=None, socket_timeout=None, reconnect_max_attempts=10, reconnect_delay=0.1, connect_now=True, encoding=None, call_16=False, connection_timeout=None)

Represents connection to the Tarantool server.

This class is responsible for connection and network exchange with the server. Also this class provides low-level interface to data manipulation (insert/delete/update/select).

Initialize a connection to the server.

Parameters:
  • host (str) – Server hostname or IP-address
  • port (int) – Server port
  • connect_now (bool) – if True (default) than __init__() actually
creates network connection.
if False than you have to call connect() manualy.
exception DatabaseError

Error related to the database engine

Error = <module 'tarantool.error' from '/home/docs/checkouts/readthedocs.org/user_builds/tarantool-python/envs/0.6.6/lib/python2.7/site-packages/tarantool-0.6.6-py2.7.egg/tarantool/error.pyc'>
exception InterfaceError

Error related to the database interface rather than the database itself

exception NetworkError(orig_exception=None, *args)

Error related to network

exception SchemaError(value)
authenticate(user, password)

Execute AUTHENTICATE request.

Parameters:
  • user (string) – user to authenticate with
  • password (string) – password for the user
Return type:

Response instance

call(func_name, *args)

Execute CALL request. Call stored Lua function.

Parameters:
  • func_name (str) – stored Lua function name
  • args (list or tuple) – list of function arguments
Return type:

Response instance

close()

Close connection to the server

connect()

Create connection to the host and port specified in __init__(). Usually there is no need to call this method directly, since it is called when you create an Connection instance.

Raise:NetworkError
connect_basic()
connect_tcp()

Create connection to the host and port specified in __init__(). :raise: NetworkError

connect_unix()

Create connection to the host and port specified in __init__(). :raise: NetworkError

delete(space_name, key, **kwargs)

Execute DELETE request. Delete single record identified by key. If you’re using secondary index, it must be unique.

Parameters:
  • space_name (int or name) – space number or name to delete a record
  • key (int or str) – key that identifies a record
Return type:

Response instance

eval(expr, *args)

Execute EVAL request. Eval Lua expression.

Parameters:
  • expr (str) – Lua expression
  • args (list or tuple) – list of function arguments
Return type:

Response instance

flush_schema()
generate_sync()

Need override for async io connection

handshake()
insert(space_name, values)

Execute INSERT request. It will throw error if there’s tuple with same PK exists.

Parameters:
  • space_name (int or str) – space id to insert a record
  • values (tuple) – record to be inserted. The tuple must contain only scalar (integer or strings) values
Return type:

Response instance

join(server_uuid)
load_schema()
ping(notime=False)

Execute PING request. Send empty request and receive empty response from server.

Returns:response time in seconds
Return type:float
replace(space_name, values)

Execute REPLACE request. It won’t throw error if there’s no tuple with this PK exists

Parameters:
  • space_name (int or str) – space id to insert a record
  • values (tuple) – record to be inserted. The tuple must contain only scalar (integer or strings) values
Return type:

Response instance

select(space_name, key=None, **kwargs)

Execute SELECT request. Select and retrieve data from the database.

Parameters:
  • space_name (int or str) – specifies which space to query
  • values (list, tuple, set, frozenset of tuples) – values to search over the index
  • index (int or str) – specifies which index to use (default is 0 which means that the primary index will be used)
  • offset (int) – offset in the resulting tuple set
  • limit (int) – limits the total number of returned tuples
Return type:

Response instance

You may use names for index/space. Matching id’s -> names connector will get from server.

Select one single record (from space=0 and using index=0) >>> select(0, 1)

Select single record from space=0 (with name=’space’) using composite index=1 (with name ‘_name’). >>> select(0, [1,’2’], index=1) # OR >>> select(0, [1,’2’], index=’_name’) # OR >>> select(‘space’, [1,’2’], index=’_name’) # OR >>> select(‘space’, [1,’2’], index=1)

Select all records >>> select(0) # OR >>> select(0, [])

space(space_name)

Create Space instance for particular space

Space instance encapsulates the identifier of the space and provides more convenient syntax for accessing the database space.

Parameters:space_name (int or str) – identifier of the space
Return type:Space instance
subscribe(cluster_uuid, server_uuid, vclock=None)
update(space_name, key, op_list, **kwargs)

Execute UPDATE request.

The update function supports operations on fields — assignment, arithmetic (if the field is unsigned numeric), cutting and pasting fragments of a field, deleting or inserting a field. Multiple operations can be combined in a single update request, and in this case they are performed atomically and sequentially. Each operation requires specification of a field number. When multiple operations are present, the field number for each operation is assumed to be relative to the most recent state of the tuple, that is, as if all previous operations in a multi-operation update have already been applied. In other words, it is always safe to merge multiple update invocations into a single invocation, with no change in semantics.

Update single record identified by key.

List of operations allows to update individual fields.

Allowed operations:

(For every operation you must provide field number, to apply this operation to)

  • + for addition (values must be numeric)
  • - for subtraction (values must be numeric)
  • & for bitwise AND (values must be unsigned numeric)
  • | for bitwise OR (values must be unsigned numeric)
  • ^ for bitwise XOR (values must be unsigned numeric)
  • : for string splice (you must provide offset, count and value for this operation)
  • ! for insertion (before) (provide any element to insert)
  • = for assignment (provide any element to assign)
  • # for deletion (provide count of fields to delete)
Parameters:
  • space_name (int or str) – space number or name to update a record
  • index (int or str) – index number or name to update a record
  • key (int or str) – key that identifies a record
  • op_list (a list of the form [(symbol_1, field_1, arg_1), (symbol_2, field_2, arg_2_1, arg_2_2, arg_2_3), ..]) – list of operations. Each operation is tuple of three (or more) values
Return type:

Response instance

Operation examples:

# 'ADD' 55 to second field
# Assign 'x' to third field
[('+', 2, 55), ('=', 3, 'x')]
# 'OR' third field with '1'
# Cut three symbols starting from second and replace them with '!!'
# Insert 'hello, world' field before fifth element of tuple
[('|', 3, 1), (':', 2, 2, 3, '!!'), ('!', 5, 'hello, world')]
# Delete two fields starting with second field
[('#', 2, 2)]
update_schema(schema_version)
upsert(space_name, tuple_value, op_list, **kwargs)

Execute UPSERT request.

If there is an existing tuple which matches the key fields of tuple_value, then the request has the same effect as UPDATE and the [(field_1, symbol_1, arg_1), …] parameter is used.

If there is no existing tuple which matches the key fields of tuple_value, then the request has the same effect as INSERT and the tuple_value parameter is used. However, unlike insert or update, upsert will not read a tuple and perform error checks before returning – this is a design feature which enhances throughput but requires more caution on the part of the user.

If you’re using secondary index, it must be unique.

List of operations allows to update individual fields.

Allowed operations:

(For every operation you must provide field number, to apply this operation to)

  • + for addition (values must be numeric)
  • - for subtraction (values must be numeric)
  • & for bitwise AND (values must be unsigned numeric)
  • | for bitwise OR (values must be unsigned numeric)
  • ^ for bitwise XOR (values must be unsigned numeric)
  • : for string splice (you must provide offset, count and value for this operation)
  • ! for insertion (provide any element to insert)
  • = for assignment (provide any element to assign)
  • # for deletion (provide count of fields to delete)
Parameters:
  • space_name (int or str) – space number or name to update a record
  • index (int or str) – index number or name to update a record
  • tuple_value – tuple, that
  • op_list (a list of the form [(symbol_1, field_1, arg_1), (symbol_2, field_2, arg_2_1, arg_2_2, arg_2_3),..]) – list of operations. Each operation is tuple of three (or more) values
Return type:

Response instance

Operation examples:

# 'ADD' 55 to second field
# Assign 'x' to third field
[('+', 2, 55), ('=', 3, 'x')]
# 'OR' third field with '1'
# Cut three symbols starting from second and replace them with '!!'
# Insert 'hello, world' field before fifth element of tuple
[('|', 3, 1), (':', 2, 2, 3, '!!'), ('!', 5, 'hello, world')]
# Delete two fields starting with second field
[('#', 2, 2)]
tarantool.connectmesh(addrs=({'host': 'localhost', 'port': 3301}, ), user=None, password=None, encoding=None)

Create a connection to the mesh of Tarantool servers.

Parameters:addrs (list) – A list of maps: {‘host’:(HOSTNAME|IP_ADDR), ‘port’:PORT}.
Return type:MeshConnection
Raise:NetworkError
class tarantool.MeshConnection(host=None, port=None, user=None, password=None, socket_timeout=None, reconnect_max_attempts=10, reconnect_delay=0.1, connect_now=True, encoding=None, call_16=False, connection_timeout=None, addrs=None, strategy_class=<class 'tarantool.mesh_connection.RoundRobinStrategy'>, cluster_discovery_function=None, cluster_discovery_delay=60)

Represents a connection to a cluster of Tarantool servers.

This class uses Connection to connect to one of the nodes of the cluster. The initial list of nodes is passed to the constructor in ‘addrs’ parameter. The class set in ‘strategy_class’ parameter is used to select a node from the list and switch nodes in case of unavailability of the current node.

‘cluster_discovery_function’ param of the constructor sets the name of a stored Lua function used to refresh the list of available nodes. The function takes no parameters and returns a list of strings in format ‘host:port’. A generic function for getting the list of nodes looks like this:

function get_cluster_nodes()
    return {
        '192.168.0.1:3301',
        '192.168.0.2:3302',
        -- ...
    }
end

You may put in this list whatever you need depending on your cluster topology. Chances are you’ll want to make the list of nodes from nodes’ replication config. Here is an example for it:

local uri_lib = require('uri')

function get_cluster_nodes()
    local nodes = {}

    local replicas = box.cfg.replication

    for i = 1, #replicas do
        local uri = uri_lib.parse(replicas[i])

        if uri.host and uri.service then
            table.insert(nodes, uri.host .. ':' .. uri.service)
        end
    end

    -- if your replication config doesn't contain the current node
    -- you have to add it manually like this:
    table.insert(nodes, '192.168.0.1:3301')

    return nodes
end
connect()

Create connection to the host and port specified in __init__(). Usually there is no need to call this method directly, since it is called when you create an Connection instance.

Raise:NetworkError
class tarantool.Schema(con)
fetch_index(space_object, index)
fetch_index_all()
fetch_index_from(space, index)
fetch_space(space)
fetch_space_all()
fetch_space_from(space)
flush()
get_field(space, field)
get_index(space, index)
get_space(space)
exception tarantool.Error

Base class for error exceptions

exception tarantool.DatabaseError

Error related to the database engine

exception tarantool.NetworkError(orig_exception=None, *args)

Error related to network

exception tarantool.NetworkWarning

Warning related to network

exception tarantool.SchemaError(value)