module tarantool

This package provides API for interaction with a Tarantool server.

class tarantool.Connection(host=None, port=None, socket_fd=None, user=None, password=None, socket_timeout=None, reconnect_max_attempts=10, reconnect_delay=0.1, connect_now=True, encoding='utf-8', use_list=True, call_16=False, connection_timeout=None, transport='', ssl_key_file=None, ssl_cert_file=None, ssl_ca_file=None, ssl_ciphers=None, ssl_password=None, ssl_password_file=None, packer_factory=<function packer_factory>, unpacker_factory=<function unpacker_factory>, auth_type=None, fetch_schema=True, required_protocol_version=None, required_features=None)

Represents a connection to the Tarantool server.

A connection object has methods to open and close a connection, check its status, call procedures and evaluate Lua code on server, make simple data manipulations and execute SQL queries.

Parameters:
  • host (str or None) – Server hostname or IP address. Use None for Unix sockets.

  • port (int or str or None) – Server port, or Unix socket path.

  • socket_fd (int or None) – socket fd number.

  • user (str or None, optional) – User name for authentication on the Tarantool server.

  • password (str or None, optional) – User password for authentication on the Tarantool server.

  • socket_timeout (float or None, optional) – Timeout on blocking socket operations, in seconds (see socket.settimeout()).

  • reconnect_max_attempts (int, optional) – Count of maximum attempts to reconnect on API call if connection is lost.

  • reconnect_delay (float, optional) – Delay between attempts to reconnect on API call if connection is lost, in seconds.

  • connect_now (bool, optional) – If True, connect to server on initialization. Otherwise, you have to call connect() manually after initialization.

  • encoding (str or None, optional) –

    'utf-8' or None. Use None to work with non-UTF8 strings.

    If non-default packer_factory option is used, encoding option value is ignored on encode until the factory explicitly uses its value. If non-default unpacker_factory option is used, encoding option value is ignored on decode until the factory explicitly uses its value.

    If 'utf-8', pack Unicode string (str) to MessagePack string (mp_str) and unpack MessagePack string (mp_str) Unicode string (str), pack bytes to MessagePack binary (mp_bin) and unpack MessagePack binary (mp_bin) to bytes.

    Python

    ->

    MessagePack (Tarantool/Lua)

    ->

    Python

    str

    ->

    mp_str (string)

    ->

    str

    bytes

    ->

    mp_bin (binary/cdata)

    ->

    bytes

    If None, pack Unicode string (str) and bytes to MessagePack string (mp_str), unpack MessagePack string (mp_str) and MessagePack binary (mp_bin) to bytes.

    Python

    ->

    MessagePack (Tarantool/Lua)

    ->

    Python

    bytes

    ->

    mp_str (string)

    ->

    bytes

    str

    ->

    mp_str (string)

    ->

    bytes

    ->

    mp_bin (binary/cdata)

    ->

    bytes

  • use_list (bool, optional) –

    If True, unpack MessagePack array (mp_array) to list. Otherwise, unpack to tuple.

    If non-default unpacker_factory option is used, use_list option value is ignored on decode until the factory explicitly uses its value.

  • call_16 (bool, optional) – If True, enables compatibility mode with Tarantool 1.6 and older for call operations.

  • connection_timeout (float or None, optional) – Time to establish initial socket connection, in seconds.

  • transport (str, optional) – '' or 'ssl'. Set to 'ssl' to enable SSL encryption for a connection (requires Python >= 3.5).

  • ssl_key_file (str or None, optional) – Path to a private SSL key file. Mandatory, if the server uses a trusted certificate authorities (CA) file.

  • ssl_cert_file (str or None, optional) – Path to a SSL certificate file. Mandatory, if the server uses a trusted certificate authorities (CA) file.

  • ssl_ca_file (str or None, optional) – Path to a trusted certificate authority (CA) file.

  • ssl_ciphers (str or None, optional) – Colon-separated (:) list of SSL cipher suites the connection can use.

  • ssl_password (str or None, optional) – Password for decrypting ssl_key_file.

  • ssl_password_file (str or None, optional) – File with password for decrypting ssl_key_file. Connection tries every line from the file as a password.

  • packer_factory (callable[[Connection], Packer], optional) – Request MessagePack packer factory. Supersedes encoding. See packer_factory() for example of a packer factory.

  • unpacker_factory (callable[[Connection], Unpacker], optional) – Response MessagePack unpacker factory. Supersedes encoding and use_list. See unpacker_factory() for example of an unpacker factory.

  • auth_type (None or str, optional) – Authentication method: "chap-sha1" (supported in Tarantool CE and EE) or "pap-sha256" (supported in Tarantool EE, "ssl" transport must be used). If None, use authentication method provided by server in IPROTO_ID exchange. If server does not provide an authentication method, use "chap-sha1".

  • fetch_schema (bool, optional) – If False, schema is not loaded on connect and schema updates are not automatically loaded. As a result, these methods become unavailable: replace(), insert(), delete(), upsert(), update(), select(), space().

  • required_protocol_version (int or None, optional) – Minimal protocol version that should be supported by Tarantool server.

  • required_features (list or None, optional) – List of protocol features that should be supported by Tarantool server.

Raise:

ConfigurationError, connect() exceptions

Error = <class 'tarantool.error.Error'>

DBAPI compatibility.

Value:

Error

DatabaseError = <class 'tarantool.error.DatabaseError'>

DBAPI compatibility.

Value:

DatabaseError

InterfaceError = <class 'tarantool.error.InterfaceError'>

DBAPI compatibility.

Value:

InterfaceError

ConfigurationError = <class 'tarantool.error.ConfigurationError'>

DBAPI compatibility.

Value:

ConfigurationError

SchemaError = <class 'tarantool.error.SchemaError'>

DBAPI compatibility.

Value:

SchemaError

NetworkError = <class 'tarantool.error.NetworkError'>

DBAPI compatibility.

Value:

NetworkError

Warning = <class 'Warning'>

DBAPI compatibility.

Value:

Warning

DataError = <class 'tarantool.error.DataError'>

DBAPI compatibility.

Value:

DataError

OperationalError = <class 'tarantool.error.OperationalError'>

DBAPI compatibility.

Value:

OperationalError

IntegrityError = <class 'tarantool.error.IntegrityError'>

DBAPI compatibility.

Value:

IntegrityError

InternalError = <class 'tarantool.error.InternalError'>

DBAPI compatibility.

Value:

InternalError

ProgrammingError = <class 'tarantool.error.ProgrammingError'>

DBAPI compatibility.

Value:

ProgrammingError

NotSupportedError = <class 'tarantool.error.NotSupportedError'>

DBAPI compatibility.

Value:

NotSupportedError

exception CrudModuleError(_, error)

Exception raised for errors that are related to the operation result of crud module.

Sets fields with result and errors.

Parameters:

args (tuple) – The tuple from the crud module with result and errors.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

authenticate(user, password)

Execute an AUTHENTICATE request: authenticate a connection. There is no need to call this method explicitly until you want to reauthenticate with different parameters.

Parameters:
  • user (str) – User to authenticate.

  • password (str) – Password for the user.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

call(func_name, *args, on_push=None, on_push_ctx=None)

Execute a CALL request: call a stored Lua function.

Parameters:
  • func_name (str) – Stored Lua function name.

  • args (tuple) – Stored Lua function arguments.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, SchemaError, NetworkError, SslError

close()

Close a connection to the server. The method is idempotent.

connect()

Create a connection to the host and port specified on initialization. There is no need to call this method explicitly until you have set connect_now=False on initialization.

Raise:

NetworkError, SslError, SchemaError, DatabaseError

crud_count(space_name: str, conditions: Optional[list] = None, opts: Optional[dict] = None) int

Gets rows count through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • conditions (list, optional) – The conditions for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

int

Raise:

CrudModuleError, DatabaseError

crud_delete(space_name: str, key: int, opts: Optional[dict] = None) CrudResult

Deletes row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • key (int) – The primary key value.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_get(space_name: str, key: int, opts: Optional[dict] = None) CrudResult

Gets row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • key (int) – The primary key value.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Inserts row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Inserts batch rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_object(space_name: str, values: dict, opts: Optional[dict] = None) CrudResult

Inserts object row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (dict) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_object_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Inserts batch object rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_len(space_name: str, opts: Optional[dict] = None) int

Gets the number of tuples in the space through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • opts (dict, optional) – The opts for the crud module.

Return type:

int

Raise:

CrudModuleError, DatabaseError

crud_max(space_name: str, index_name: str, opts: Optional[dict] = None) CrudResult

Gets rows with maximum value in the specified index through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • index_name (str) – The name of the index.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_min(space_name: str, index_name: str, opts: Optional[dict] = None) CrudResult

Gets rows with minimum value in the specified index through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • index_name (str) – The name of the index.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Replaces row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Replaces batch rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_object(space_name: str, values: dict, opts: Optional[dict] = None) CrudResult

Replaces object row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (dict) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_object_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Replaces batch object rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_select(space_name: str, conditions: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Selects rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • conditions (list, optional) – The select conditions for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, :exc:`~tarantool.error.DatabaseError`select

crud_stats(space_name: Optional[str] = None) CrudResult

Gets statistics from the crud.

Parameters:

space_name (str, optional) – The name of the target space.

Return type:

CrudResult

Raise:

DatabaseError

crud_storage_info(opts: Optional[dict] = None) dict

Gets storages status through the crud.

Parameters:

opts (dict, optional) – The opts for the crud module.

Return type:

dict

Raise:

CrudModuleError, DatabaseError

crud_truncate(space_name: str, opts: Optional[dict] = None) bool

Truncate rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • opts (dict, optional) – The opts for the crud module.

Return type:

bool

Raise:

CrudModuleError, DatabaseError

crud_unflatten_rows(rows: list, metadata: list) list

Makes rows unflatten through the crud.

Parameters:
  • rows (list) – The rows to unflatten.

  • metadata (list) – The metadata to unflatten.

Return type:

list

crud_update(space_name: str, key: int, operations: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Updates row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • key (int) – The primary key value.

  • operations (list, optional) – The update operations for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert(space_name: str, values: Union[tuple, list], operations: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Upserts row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • operations (list, optional) – The update operations for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_many(space_name: str, values_operation: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Upserts batch rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values_operation (tuple or list) – The data with update operations.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_object(space_name: str, values: dict, operations: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Upserts object row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (dict) – Tuple to be inserted.

  • operations (list, optional) – The update operations for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_object_many(space_name: str, values_operation: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Upserts batch object rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values_operation (tuple or list) – The data with update operations.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

delete(space_name, key, *, index=0, on_push=None, on_push_ctx=None)

Execute a DELETE request: delete a tuple in the space.

Parameters:
  • space_name (str or int) – Space name or space id.

  • key – Key of a tuple to be deleted.

  • index (str or int, optional) – Index name or index id. If you’re using a secondary index, it must be unique. Defaults to primary index.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

eval(expr, *args, on_push=None, on_push_ctx=None)

Execute an EVAL request: evaluate a Lua expression.

Parameters:
  • expr (str) – Lua expression.

  • args (tuple) – Lua expression arguments.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

execute(query, params=None)

Execute an SQL request: see documentation for syntax reference.

The Tarantool binary protocol for SQL requests supports “qmark” and “named” param styles. A sequence of values can be used for “qmark” style. A mapping is used for “named” param style without the leading colon in the keys.

Example for “qmark” arguments:

args = ['email@example.com']
c.execute('select * from "users" where "email"=?', args)

Example for “named” arguments:

args = {'email': 'email@example.com'}
c.execute('select * from "users" where "email"=:email', args)
Parameters:
  • query (str) – SQL query.

  • params (dict or list or None, optional) – SQL query bind values.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

flush_schema()

Reload space and index schema.

Raise:

SchemaError, DatabaseError

insert(space_name, values, *, on_push=None, on_push_ctx=None)

Execute an INSERT request: insert a tuple to the space. Throws an error if there is already a tuple with the same primary key.

Parameters:
  • space_name (str or int) – Space name or space id.

  • values (tuple or list) – Record to be inserted.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

is_closed()

Returns True if connection is closed. False otherwise.

Return type:

bool

ping(notime=False)

Execute a PING request: send an empty request and receive an empty response from the server.

Parameters:

notime (bool, optional) – If False, returns response time. Otherwise, it returns 'Success'.

Returns:

Response time or 'Success'.

Return type:

float or str

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

replace(space_name, values, *, on_push=None, on_push_ctx=None)

Execute a REPLACE request: replace a tuple in the space. Doesn’t throw an error if there is no tuple with the specified primary key.

Parameters:
  • space_name (str or int) – Space name or space id.

  • values (tuple or list) – Tuple to be replaced.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

select(space_name, key=None, *, offset=0, limit=4294967295, index=0, iterator=None, on_push=None, on_push_ctx=None)

Execute a SELECT request: select a tuple from the space.

Parameters:
  • space_name (str or int) – Space name or space id.

  • key (optional) – Key of a tuple to be selected.

  • offset (int, optional) – Number of tuples to skip.

  • limit (str or int, optional) – Maximum number of tuples to select.

  • index – Index name or index id to select. Defaults to primary index.

  • iterator

    Index iterator type.

    Iterator types for TREE indexes:

    Iterator type

    Arguments

    Description

    'EQ'

    search value

    The comparison operator is ‘==’ (equal to). If an index key is equal to a search value, it matches. Tuples are returned in ascending order by index key. This is the default.

    'REQ'

    search value

    Matching is the same as for 'EQ'. Tuples are returned in descending order by index key.

    'GT'

    search value

    The comparison operator is ‘>’ (greater than). If an index key is greater than a search value, it matches. Tuples are returned in ascending order by index key.

    'GE'

    search value

    The comparison operator is ‘>=’ (greater than or equal to). If an index key is greater than or equal to a search value, it matches. Tuples are returned in ascending order by index key.

    'ALL'

    search value

    Same as 'GE'

    'LT'

    search value

    The comparison operator is ‘<’ (less than). If an index key is less than a search value, it matches. Tuples are returned in descending order by index key.

    'LE'

    search value

    The comparison operator is ‘<=’ (less than or equal to). If an index key is less than or equal to a search value, it matches. Tuples are returned in descending order by index key.

    Iterator types for HASH indexes:

    Type

    Arguments

    Description

    'ALL'

    none

    All index keys match. Tuples are returned in ascending order by hash of index key, which will appear to be random.

    'EQ'

    search value

    The comparison operator is ‘==’ (equal to). If an index key is equal to a search value, it matches. The number of returned tuples will be 0 or 1. This is the default.

    'GT'

    search value

    The comparison operator is ‘>’ (greater than). If a hash of an index key is greater than a hash of a search value, it matches. Tuples are returned in ascending order by hash of index key, which will appear to be random. Provided that the space is not being updated, one can retrieve all the tuples in a space, N tuples at a time, by using iterator='GT',limit=N in each search, and using the last returned value from the previous result as the start search value for the next search.

    Iterator types for BITSET indexes:

    Type

    Arguments

    Description

    'ALL'

    none

    All index keys match. Tuples are returned in their order within the space.

    'EQ'

    bitset value

    If an index key is equal to a bitset value, it matches. Tuples are returned in their order within the space. This is the default.

    'BITS_ALL_SET'

    bitset value

    If all of the bits which are 1 in the bitset value are 1 in the index key, it matches. Tuples are returned in their order within the space.

    'BITS_ANY_SET'

    bitset value

    If any of the bits which are 1 in the bitset value are 1 in the index key, it matches. Tuples are returned in their order within the space.

    'BITS_ALL_NOT_SET'

    bitset value

    If all of the bits which are 1 in the bitset value are 0 in the index key, it matches. Tuples are returned in their order within the space.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

space(space_name)

Create a Space instance for a particular space.

Parameters:

space_name (str or int) – Space name or space id.

Return type:

Space

Raise:

SchemaError

update(space_name, key, op_list, *, index=0, on_push=None, on_push_ctx=None)

Execute an UPDATE request: update a tuple in the space.

Parameters:
  • space_name (str or int) – Space name or space id.

  • key – Key of a tuple to be updated.

  • op_list (tuple or list) –

    The list of operations to update individual fields. Each operation is a tuple of three (or more) values: (operator, field_identifier, value).

    Possible operators are:

    • '+' 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)

    Possible field_identifiers are:

    • Positive field number. The first field is 1, the second field is 2, and so on.

    • Negative field number. The last field is -1, the second-last field is -2, and so on. In other words: (#tuple + negative field number + 1).

    • Name. If the space was formatted with space_object:format(), then this can be a string for the field name (Since Tarantool 2.3.1).

    Operation examples:

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

  • index (str or int, optional) – Index name or index id. If you’re using a secondary index, it must be unique. Defaults to primary index.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

upsert(space_name, tuple_value, op_list, *, index=0, on_push=None, on_push_ctx=None)

Execute an UPSERT request: upsert a tuple to the space.

If an existing tuple 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 tuple matching 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 neither read the tuple nor perform error checks before returning – this is a design feature which enhances throughput but requires more caution on the part of the user.

Parameters:
  • space_name (str or int) – Space name or space id.

  • tuple_value (tuple or list) – Tuple to be upserted.

  • op_list (tuple or list) – Refer to update() op_list.

  • index (str or int, optional) – Index name or index id. If you’re using a secondary index, it must be unique. Defaults to primary index.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

class tarantool.MeshConnection(host=None, port=None, socket_fd=None, user=None, password=None, socket_timeout=None, reconnect_max_attempts=10, reconnect_delay=0.1, connect_now=True, encoding='utf-8', call_16=False, connection_timeout=None, transport='', ssl_key_file=None, ssl_cert_file=None, ssl_ca_file=None, ssl_ciphers=None, ssl_password=None, ssl_password_file=None, auth_type=None, addrs=None, strategy_class=<class 'tarantool.mesh_connection.RoundRobinStrategy'>, cluster_discovery_function=None, cluster_discovery_delay=60, fetch_schema=True)

Represents a connection to a cluster of Tarantool servers.

Parameters:
  • host – Refer to host. Value would be used to add one more server in addrs list.

  • port – Refer to port. Value would be used to add one more server in addrs list.

  • socket_fd – Refer to socket_fd. Value would be used to add one more server in addrs list.

  • user – Refer to user. Value would be used to add one more server in addrs list.

  • password – Refer to password. Value would be used to add one more server in addrs list.

  • socket_timeout – Refer to socket_timeout. Value would be used for the current active connection.

  • reconnect_max_attempts – Refer to reconnect_max_attempts. Value would be used for the current active connection.

  • reconnect_delay – Refer to reconnect_delay. Value would be used for the current active connection.

  • connect_now (bool, optional) – If True, connect to server on initialization. Otherwise, you have to call connect() manually after initialization.

  • encoding – Refer to encoding. Value would be used for the current active connection.

  • call_16 – Refer to call_16. Value would be used for the current active connection.

  • connection_timeout – Refer to connection_timeout. Value would be used for the current active connection.

  • transport – Refer to transport. Value would be used to add one more server in addrs list.

  • ssl_key_file – Refer to ssl_key_file. Value would be used to add one more server in addrs list.

  • ssl_cert_file – Refer to ssl_cert_file. Value would be used to add one more server in addrs list.

  • ssl_ca_file – Refer to ssl_ca_file. Value would be used to add one more server in addrs list.

  • ssl_ciphers – Refer to ssl_ciphers. Value would be used to add one more server in addrs list.

  • auth_type – Refer to auth_type. Value would be used to add one more server in addrs list.

  • addrs – Cluster servers addresses list. Refer to addrs.

  • strategy_class (object, optional) – Strategy for choosing a server after the current server fails. Defaults to the round-robin strategy.

  • cluster_discovery_function (str or None, optional) –

    sets the name of the stored Lua function used to refresh the list of available nodes. The function takes no parameters and returns a list of strings in the 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?transport=ssl&ssl_ca_file=/path/to/ca.cert',
            -- ...
        }
    end
    

    You can put in this list whatever you need, depending on your cluster topology. Chances are you’ll want to derive the list of nodes from the nodes’ replication configuration. Here is an example:

    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
    

  • cluster_discovery_delay (float, optional) – Minimal time between address list refresh.

  • fetch_schema – Refer to fetch_schema.

Raises:

ConfigurationError, Connection exceptions, connect exceptions

Error = <class 'tarantool.error.Error'>

DBAPI compatibility.

Value:

Error

DatabaseError = <class 'tarantool.error.DatabaseError'>

DBAPI compatibility.

Value:

DatabaseError

InterfaceError = <class 'tarantool.error.InterfaceError'>

DBAPI compatibility.

Value:

InterfaceError

ConfigurationError = <class 'tarantool.error.ConfigurationError'>

DBAPI compatibility.

Value:

ConfigurationError

SchemaError = <class 'tarantool.error.SchemaError'>

DBAPI compatibility.

Value:

SchemaError

NetworkError = <class 'tarantool.error.NetworkError'>

DBAPI compatibility.

Value:

NetworkError

Warning = <class 'Warning'>

DBAPI compatibility.

Value:

Warning

DataError = <class 'tarantool.error.DataError'>

DBAPI compatibility.

Value:

DataError

OperationalError = <class 'tarantool.error.OperationalError'>

DBAPI compatibility.

Value:

OperationalError

IntegrityError = <class 'tarantool.error.IntegrityError'>

DBAPI compatibility.

Value:

IntegrityError

InternalError = <class 'tarantool.error.InternalError'>

DBAPI compatibility.

Value:

InternalError

ProgrammingError = <class 'tarantool.error.ProgrammingError'>

DBAPI compatibility.

Value:

ProgrammingError

NotSupportedError = <class 'tarantool.error.NotSupportedError'>

DBAPI compatibility.

Value:

NotSupportedError

exception CrudModuleError(_, error)

Exception raised for errors that are related to the operation result of crud module.

Sets fields with result and errors.

Parameters:

args (tuple) – The tuple from the crud module with result and errors.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

authenticate(user, password)

Execute an AUTHENTICATE request: authenticate a connection. There is no need to call this method explicitly until you want to reauthenticate with different parameters.

Parameters:
  • user (str) – User to authenticate.

  • password (str) – Password for the user.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

call(func_name, *args, on_push=None, on_push_ctx=None)

Execute a CALL request: call a stored Lua function.

Parameters:
  • func_name (str) – Stored Lua function name.

  • args (tuple) – Stored Lua function arguments.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, SchemaError, NetworkError, SslError

close()

Close a connection to the server. The method is idempotent.

connect()

Create a connection to some server in the cluster. Refresh addresses info after success. There is no need to call this method explicitly until you have set connect_now=False on initialization.

Raise:

AssertionError, SchemaError, NetworkError, connect exceptions

crud_count(space_name: str, conditions: Optional[list] = None, opts: Optional[dict] = None) int

Gets rows count through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • conditions (list, optional) – The conditions for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

int

Raise:

CrudModuleError, DatabaseError

crud_delete(space_name: str, key: int, opts: Optional[dict] = None) CrudResult

Deletes row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • key (int) – The primary key value.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_get(space_name: str, key: int, opts: Optional[dict] = None) CrudResult

Gets row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • key (int) – The primary key value.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Inserts row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Inserts batch rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_object(space_name: str, values: dict, opts: Optional[dict] = None) CrudResult

Inserts object row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (dict) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_object_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Inserts batch object rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_len(space_name: str, opts: Optional[dict] = None) int

Gets the number of tuples in the space through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • opts (dict, optional) – The opts for the crud module.

Return type:

int

Raise:

CrudModuleError, DatabaseError

crud_max(space_name: str, index_name: str, opts: Optional[dict] = None) CrudResult

Gets rows with maximum value in the specified index through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • index_name (str) – The name of the index.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_min(space_name: str, index_name: str, opts: Optional[dict] = None) CrudResult

Gets rows with minimum value in the specified index through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • index_name (str) – The name of the index.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Replaces row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Replaces batch rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_object(space_name: str, values: dict, opts: Optional[dict] = None) CrudResult

Replaces object row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (dict) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_object_many(space_name: str, values: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Replaces batch object rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_select(space_name: str, conditions: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Selects rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • conditions (list, optional) – The select conditions for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, :exc:`~tarantool.error.DatabaseError`select

crud_stats(space_name: Optional[str] = None) CrudResult

Gets statistics from the crud.

Parameters:

space_name (str, optional) – The name of the target space.

Return type:

CrudResult

Raise:

DatabaseError

crud_storage_info(opts: Optional[dict] = None) dict

Gets storages status through the crud.

Parameters:

opts (dict, optional) – The opts for the crud module.

Return type:

dict

Raise:

CrudModuleError, DatabaseError

crud_truncate(space_name: str, opts: Optional[dict] = None) bool

Truncate rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • opts (dict, optional) – The opts for the crud module.

Return type:

bool

Raise:

CrudModuleError, DatabaseError

crud_unflatten_rows(rows: list, metadata: list) list

Makes rows unflatten through the crud.

Parameters:
  • rows (list) – The rows to unflatten.

  • metadata (list) – The metadata to unflatten.

Return type:

list

crud_update(space_name: str, key: int, operations: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Updates row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • key (int) – The primary key value.

  • operations (list, optional) – The update operations for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert(space_name: str, values: Union[tuple, list], operations: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Upserts row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (tuple or list) – Tuple to be inserted.

  • operations (list, optional) – The update operations for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_many(space_name: str, values_operation: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Upserts batch rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values_operation (tuple or list) – The data with update operations.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_object(space_name: str, values: dict, operations: Optional[list] = None, opts: Optional[dict] = None) CrudResult

Upserts object row through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values (dict) – Tuple to be inserted.

  • operations (list, optional) – The update operations for the crud module.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_object_many(space_name: str, values_operation: Union[tuple, list], opts: Optional[dict] = None) CrudResult

Upserts batch object rows through the crud.

Parameters:
  • space_name (str) – The name of the target space.

  • values_operation (tuple or list) – The data with update operations.

  • opts (dict, optional) – The opts for the crud module.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

delete(space_name, key, *, index=0, on_push=None, on_push_ctx=None)

Execute a DELETE request: delete a tuple in the space.

Parameters:
  • space_name (str or int) – Space name or space id.

  • key – Key of a tuple to be deleted.

  • index (str or int, optional) – Index name or index id. If you’re using a secondary index, it must be unique. Defaults to primary index.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

eval(expr, *args, on_push=None, on_push_ctx=None)

Execute an EVAL request: evaluate a Lua expression.

Parameters:
  • expr (str) – Lua expression.

  • args (tuple) – Lua expression arguments.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

execute(query, params=None)

Execute an SQL request: see documentation for syntax reference.

The Tarantool binary protocol for SQL requests supports “qmark” and “named” param styles. A sequence of values can be used for “qmark” style. A mapping is used for “named” param style without the leading colon in the keys.

Example for “qmark” arguments:

args = ['email@example.com']
c.execute('select * from "users" where "email"=?', args)

Example for “named” arguments:

args = {'email': 'email@example.com'}
c.execute('select * from "users" where "email"=:email', args)
Parameters:
  • query (str) – SQL query.

  • params (dict or list or None, optional) – SQL query bind values.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

flush_schema()

Reload space and index schema.

Raise:

SchemaError, DatabaseError

insert(space_name, values, *, on_push=None, on_push_ctx=None)

Execute an INSERT request: insert a tuple to the space. Throws an error if there is already a tuple with the same primary key.

Parameters:
  • space_name (str or int) – Space name or space id.

  • values (tuple or list) – Record to be inserted.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

is_closed()

Returns True if connection is closed. False otherwise.

Return type:

bool

ping(notime=False)

Execute a PING request: send an empty request and receive an empty response from the server.

Parameters:

notime (bool, optional) – If False, returns response time. Otherwise, it returns 'Success'.

Returns:

Response time or 'Success'.

Return type:

float or str

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError

replace(space_name, values, *, on_push=None, on_push_ctx=None)

Execute a REPLACE request: replace a tuple in the space. Doesn’t throw an error if there is no tuple with the specified primary key.

Parameters:
  • space_name (str or int) – Space name or space id.

  • values (tuple or list) – Tuple to be replaced.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

select(space_name, key=None, *, offset=0, limit=4294967295, index=0, iterator=None, on_push=None, on_push_ctx=None)

Execute a SELECT request: select a tuple from the space.

Parameters:
  • space_name (str or int) – Space name or space id.

  • key (optional) – Key of a tuple to be selected.

  • offset (int, optional) – Number of tuples to skip.

  • limit (str or int, optional) – Maximum number of tuples to select.

  • index – Index name or index id to select. Defaults to primary index.

  • iterator

    Index iterator type.

    Iterator types for TREE indexes:

    Iterator type

    Arguments

    Description

    'EQ'

    search value

    The comparison operator is ‘==’ (equal to). If an index key is equal to a search value, it matches. Tuples are returned in ascending order by index key. This is the default.

    'REQ'

    search value

    Matching is the same as for 'EQ'. Tuples are returned in descending order by index key.

    'GT'

    search value

    The comparison operator is ‘>’ (greater than). If an index key is greater than a search value, it matches. Tuples are returned in ascending order by index key.

    'GE'

    search value

    The comparison operator is ‘>=’ (greater than or equal to). If an index key is greater than or equal to a search value, it matches. Tuples are returned in ascending order by index key.

    'ALL'

    search value

    Same as 'GE'

    'LT'

    search value

    The comparison operator is ‘<’ (less than). If an index key is less than a search value, it matches. Tuples are returned in descending order by index key.

    'LE'

    search value

    The comparison operator is ‘<=’ (less than or equal to). If an index key is less than or equal to a search value, it matches. Tuples are returned in descending order by index key.

    Iterator types for HASH indexes:

    Type

    Arguments

    Description

    'ALL'

    none

    All index keys match. Tuples are returned in ascending order by hash of index key, which will appear to be random.

    'EQ'

    search value

    The comparison operator is ‘==’ (equal to). If an index key is equal to a search value, it matches. The number of returned tuples will be 0 or 1. This is the default.

    'GT'

    search value

    The comparison operator is ‘>’ (greater than). If a hash of an index key is greater than a hash of a search value, it matches. Tuples are returned in ascending order by hash of index key, which will appear to be random. Provided that the space is not being updated, one can retrieve all the tuples in a space, N tuples at a time, by using iterator='GT',limit=N in each search, and using the last returned value from the previous result as the start search value for the next search.

    Iterator types for BITSET indexes:

    Type

    Arguments

    Description

    'ALL'

    none

    All index keys match. Tuples are returned in their order within the space.

    'EQ'

    bitset value

    If an index key is equal to a bitset value, it matches. Tuples are returned in their order within the space. This is the default.

    'BITS_ALL_SET'

    bitset value

    If all of the bits which are 1 in the bitset value are 1 in the index key, it matches. Tuples are returned in their order within the space.

    'BITS_ANY_SET'

    bitset value

    If any of the bits which are 1 in the bitset value are 1 in the index key, it matches. Tuples are returned in their order within the space.

    'BITS_ALL_NOT_SET'

    bitset value

    If all of the bits which are 1 in the bitset value are 0 in the index key, it matches. Tuples are returned in their order within the space.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

space(space_name)

Create a Space instance for a particular space.

Parameters:

space_name (str or int) – Space name or space id.

Return type:

Space

Raise:

SchemaError

update(space_name, key, op_list, *, index=0, on_push=None, on_push_ctx=None)

Execute an UPDATE request: update a tuple in the space.

Parameters:
  • space_name (str or int) – Space name or space id.

  • key – Key of a tuple to be updated.

  • op_list (tuple or list) –

    The list of operations to update individual fields. Each operation is a tuple of three (or more) values: (operator, field_identifier, value).

    Possible operators are:

    • '+' 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)

    Possible field_identifiers are:

    • Positive field number. The first field is 1, the second field is 2, and so on.

    • Negative field number. The last field is -1, the second-last field is -2, and so on. In other words: (#tuple + negative field number + 1).

    • Name. If the space was formatted with space_object:format(), then this can be a string for the field name (Since Tarantool 2.3.1).

    Operation examples:

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

  • index (str or int, optional) – Index name or index id. If you’re using a secondary index, it must be unique. Defaults to primary index.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

upsert(space_name, tuple_value, op_list, *, index=0, on_push=None, on_push_ctx=None)

Execute an UPSERT request: upsert a tuple to the space.

If an existing tuple 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 tuple matching 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 neither read the tuple nor perform error checks before returning – this is a design feature which enhances throughput but requires more caution on the part of the user.

Parameters:
  • space_name (str or int) – Space name or space id.

  • tuple_value (tuple or list) – Tuple to be upserted.

  • op_list (tuple or list) – Refer to update() op_list.

  • index (str or int, optional) – Index name or index id. If you’re using a secondary index, it must be unique. Defaults to primary index.

  • on_push (function, optional) – Сallback for processing out-of-band messages.

  • on_push_ctx (optional) – Сontext for working with on_push callback.

Return type:

Response

Raise:

AssertionError, DatabaseError, SchemaError, NetworkError, SslError, NotSupportedError

exception tarantool.Error

Base class for error exceptions.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception tarantool.DatabaseError(*args, extra_info=None)

Exception raised for errors that are related to the database.

Parameters:
  • args (tuple) – (code, message) or (message,).

  • extra_info (BoxError or None, optional) – Additional box.error information with backtrace.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception tarantool.DatabaseError(*args, extra_info=None)

Exception raised for errors that are related to the database.

Parameters:
  • args (tuple) – (code, message) or (message,).

  • extra_info (BoxError or None, optional) – Additional box.error information with backtrace.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception tarantool.NetworkError(*args, **kwargs)

Error related to network.

Parameters:
  • args (dict, optional) – Exception arguments. If the first argument is a socket exception, it is wrapped.

  • kwargs – Exception to wrap.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception tarantool.NetworkWarning

Warning related to network.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

exception tarantool.SchemaError(value)

Error related to extracting space and index schema.

Parameters:

value – Error value.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class tarantool.BoxError(type: Union[str, bytes], file: Union[str, bytes], line: int, message: Union[str, bytes], errno: int, errcode: int, fields: Optional[dict] = None, prev: Optional[List[BoxError]] = None)

Type representing Tarantool box.error object: a single MP_ERROR_STACK object with a link to the previous stack error.

errcode: int

Number of the error as defined in errcode.h.

errno: int

Ordinal number of the error.

fields: Optional[dict] = None

Additional fields depending on error type. For example, if type is "AccessDeniedError", then it will include "object_type", "object_name", "access_type".

file: Union[str, bytes]

Source code file where error was caught.

Value type depends on Connection encoding.

line: int

Line number in source code file.

message: Union[str, bytes]

Text of reason.

Value type depends on Connection encoding.

prev: Optional[List[BoxError]] = None

Previous error in stack.

type: Union[str, bytes]

Type that implies source, for example "ClientError".

Value type depends on Connection encoding.

class tarantool.ConnectionPool(addrs, user=None, password=None, socket_timeout=None, reconnect_max_attempts=0, reconnect_delay=0, connect_now=True, encoding='utf-8', call_16=False, connection_timeout=None, strategy_class=<class 'tarantool.connection_pool.RoundRobinStrategy'>, refresh_delay=1, fetch_schema=True)

Represents the pool of connections to a cluster of Tarantool servers.

To work with ConnectionPool, box.info must be callable for the user on each server.

ConnectionPool is best suited to work with a single replicaset. Its API is the same as a single server Connection, but requests support mode parameter (a tarantool.Mode value) to choose between read-write and read-only pool instances:

>>> resp = conn.select('demo', 'AAAA', mode=tarantool.Mode.PREFER_RO)
>>> resp
- ['AAAA', 'Alpha']
Parameters:
  • addrs (list) –

    List of dictionaries describing server addresses:

    {
        "host': "str" or None,     # mandatory
        "port": int or "str",      # mandatory
        "socket_fd": int,          # optional
        "transport": "str",        # optional
        "ssl_key_file": "str",     # optional
        "ssl_cert_file": "str",    # optional
        "ssl_ca_file": "str",      # optional
        "ssl_ciphers": "str"       # optional
        "ssl_password": "str",     # optional
        "ssl_password_file": "str" # optional
        "auth_type": "str"         # optional
    }
    

    Refer to corresponding Connection parameters.

  • user – Refer to user. The value is used for each connection in the pool.

  • password – Refer to password. The value is used for each connection in the pool.

  • socket_timeout – Refer to socket_timeout. The value is used for each connection in the pool.

  • reconnect_max_attempts – Refer to reconnect_max_attempts. The value is used for each connection in the pool. Be careful: it is internal Connection reconnect unrelated to pool reconnect mechanisms.

  • reconnect_delay – Refer to reconnect_delay. The value is used for each connection in the pool. Be careful: it is internal Connection reconnect unrelated to pool reconnect mechanisms.

  • connect_now (bool, optional) – If True, connect to all pool servers on initialization. Otherwise, you have to call connect() manually after initialization.

  • encoding – Refer to encoding. The value is used for each connection in the pool.

  • call_16 – Refer to call_16. The value is used for each connection in the pool.

  • connection_timeout (float, optional) – Refer to connection_timeout. The value is used for each connection in the pool.

  • strategy_class (StrategyInterface, optional) – Strategy for choosing a server based on a request mode. Defaults to the round-robin strategy.

  • refresh_delay – Minimal time between pool server box.info.ro status background refreshes, in seconds.

  • fetch_schema – Refer to fetch_schema.

Raise:

ConfigurationError, Connection exceptions

call(func_name, *args, mode=None, on_push=None, on_push_ctx=None)

Execute a CALL request on the pool server: call a stored Lua function. Refer to call().

Parameters:
Return type:

Response

Raise:

ValueError, call() exceptions

close()

Stop request processing, close each connection in the pool.

connect()

Create a connection to each address specified on initialization and start background process threads for them. There is no need to call this method explicitly until you have set connect_now=False on initialization.

If some connections have failed to connect successfully or provide box.info status (including the case when all of them have failed), no exceptions are raised. Attempts to reconnect and refresh the info would be processed in the background.

crud_count(space_name, conditions=None, opts=None, *, mode=Mode.ANY)

Execute an crud_count request on the pool server: gets rows count through the crud. Refer to crud_count().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_delete(space_name, key, opts=None, *, mode=Mode.ANY)

Execute an crud_delete request on the pool server: deletes row through the crud. Refer to crud_delete().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_get(space_name, key, opts=None, *, mode=Mode.ANY)

Execute an crud_get request on the pool server: gets row through the crud. Refer to crud_get().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_insert request on the pool server: inserts row through the crud. Refer to crud_insert().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_many(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_insert_many request on the pool server: inserts batch rows through the crud. Refer to crud_insert_many().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_object(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_insert_object request on the pool server: inserts object row through the crud. Refer to crud_insert_object().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_insert_object_many(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_insert_object_many request on the pool server: inserts batch object rows through the crud. Refer to crud_insert_object_many().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_len(space_name, opts=None, *, mode=Mode.ANY)

Execute an crud_len request on the pool server: gets the number of tuples in the space through crud. Refer to crud_len().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_max(space_name, index_name, opts=None, *, mode=Mode.ANY)

Execute an crud_max request on the pool server: gets rows with maximum value in the specified index through crud. Refer to crud_max().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_min(space_name, index_name, opts=None, *, mode=Mode.ANY)

Execute an crud_min request on the pool server: gets rows with minimum value in the specified index through crud. Refer to crud_min().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_replace request on the pool server: replaces row through the crud. Refer to crud_replace().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_many(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_replace_many request on the pool server: replaces batch rows through the crud. Refer to crud_replace_many().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_object(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_replace_object request on the pool server: replaces object row through the crud. Refer to crud_replace_object().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_replace_object_many(space_name, values, opts=None, *, mode=Mode.ANY)

Execute an crud_replace_object_many request on the pool server: replaces batch object rows through the crud. Refer to crud_replace_object_many().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_select(space_name, conditions=None, opts=None, *, mode=Mode.ANY)

Execute an crud_select request on the pool server: selects rows through the crud. Refer to crud_select().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_stats(space_name=None, *, mode=Mode.ANY)

Execute an crud_stats request on the pool server: gets statistics through the crud. Refer to crud_stats().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_storage_info(opts=None, *, mode=Mode.ANY)

Execute an crud_storage_info request on the pool server: gets storages status through the crud. Refer to crud_storage_info().

Parameters:
  • opts – Refer to opts.

  • mode (Mode, optional) – Request mode.

Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_truncate(space_name, opts=None, *, mode=Mode.ANY)

Execute an crud_truncate request on the pool server: truncates rows through crud. Refer to crud_truncate().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_unflatten_rows(rows, metadata, *, mode=Mode.ANY)

Makes rows unflatten through the crud. Refer to crud_unflatten_rows().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_update(space_name, key, operations=None, opts=None, *, mode=Mode.ANY)

Execute an crud_update request on the pool server: updates row through the crud. Refer to crud_update().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert(space_name, values, operations=None, opts=None, *, mode=Mode.ANY)

Execute an crud_upsert request on the pool server: upserts row through the crud. Refer to crud_upsert().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_many(space_name, values_operation, opts=None, *, mode=Mode.ANY)

Execute an crud_upsert_many request on the pool server: upserts batch rows through the crud. Refer to crud_upsert_many().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_object(space_name, values, operations=None, opts=None, *, mode=Mode.ANY)

Execute an crud_upsert_object request on the pool server: upserts object row through the crud. Refer to crud_upsert_object().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

crud_upsert_object_many(space_name, values_operation, opts=None, *, mode=Mode.ANY)

Execute an crud_upsert_object_many request on the pool server: upserts batch object rows through the crud. Refer to crud_upsert_object_many().

Parameters:
Return type:

CrudResult

Raise:

CrudModuleError, DatabaseError

delete(space_name, key, *, index=0, mode=Mode.RW, on_push=None, on_push_ctx=None)

Execute an DELETE request on the pool server: delete a tuple in the space. Refer to delete().

Parameters:
Return type:

Response

Raise:

delete() exceptions

eval(expr, *args, mode=None, on_push=None, on_push_ctx=None)

Execute an EVAL request on the pool server: evaluate a Lua expression. Refer to eval().

Parameters:
Return type:

Response

Raise:

ValueError, eval() exceptions

execute(query, params=None, *, mode=None)

Execute an SQL request on the pool server. Refer to execute().

Parameters:
Return type:

Response

Raise:

ValueError, execute() exceptions

insert(space_name, values, *, mode=Mode.RW, on_push=None, on_push_ctx=None)

Execute an INSERT request on the pool server: insert a tuple to the space. Refer to insert().

Parameters:
Return type:

Response

Raise:

insert() exceptions

is_closed()

Returns False if at least one connection is not closed and is ready to process requests. Otherwise, returns True.

Return type:

bool

ping(notime=False, *, mode=None)

Execute a PING request on the pool server: send an empty request and receive an empty response from the server. Refer to ping().

Parameters:
Returns:

Refer to ping().

Raise:

ValueError, ping() exceptions

replace(space_name, values, *, mode=Mode.RW, on_push=None, on_push_ctx=None)

Execute a REPLACE request on the pool server: replace a tuple in the space. Refer to replace().

Parameters:
Return type:

Response

Raise:

replace() exceptions

select(space_name, key, *, offset=0, limit=4294967295, index=0, iterator=None, mode=Mode.ANY, on_push=None, on_push_ctx=None)

Execute a SELECT request on the pool server: update a tuple from the space. Refer to select().

Parameters:
Return type:

Response

Raise:

select() exceptions

update(space_name, key, op_list, *, index=0, mode=Mode.RW, on_push=None, on_push_ctx=None)

Execute an UPDATE request on the pool server: update a tuple in the space. Refer to update().

Parameters:
Return type:

Response

Raise:

upsert() exceptions

upsert(space_name, tuple_value, op_list, *, index=0, mode=Mode.RW, on_push=None, on_push_ctx=None)

Execute an UPSERT request on the pool server: upsert a tuple to the space. Refer to upsert().

Parameters:
Return type:

Response

Raise:

upsert() exceptions

class tarantool.Datetime(*, timestamp=None, year=None, month=None, day=None, hour=None, minute=None, sec=None, nsec=None, tzoffset=0, tz='', timestamp_since_utc_epoch=False)

Class representing Tarantool datetime info. Internals are based on datetime.datetime.

You can create Datetime objects by using the same API as in Tarantool:

dt1 = tarantool.Datetime(year=2022, month=8, day=31,
                         hour=18, minute=7, sec=54,
                         nsec=308543321)

dt2 = tarantool.Datetime(timestamp=1661969274)

dt3 = tarantool.Datetime(timestamp=1661969274, nsec=308543321)

Datetime exposes year, month, day, hour, minute, sec, nsec, timestamp and value (integer epoch time with nanoseconds precision) properties if you need to convert Datetime to any other kind of datetime object:

pdt = pandas.Timestamp(year=dt.year, month=dt.month, day=dt.day,
                       hour=dt.hour, minute=dt.minute, second=dt.sec,
                       microsecond=(dt.nsec // 1000),
                       nanosecond=(dt.nsec % 1000))

Use tzoffset parameter to set up offset timezone:

dt = tarantool.Datetime(year=2022, month=8, day=31,
                        hour=18, minute=7, sec=54,
                        nsec=308543321, tzoffset=180)

You may use the tzoffset property to get the timezone offset of a datetime object.

Use tz parameter to set up timezone name:

dt = tarantool.Datetime(year=2022, month=8, day=31,
                        hour=18, minute=7, sec=54,
                        nsec=308543321, tz='Europe/Moscow')

If both tz and tzoffset are specified, tz is used.

You may use the tz property to get the timezone name of a datetime object.

Parameters:
  • timestamp (float or int, optional) – Timestamp since epoch. Cannot be provided together with year, month, day, hour, minute, sec. If nsec is provided, it must be int. Refer to timestamp_since_utc_epoch to clarify how timezone-aware datetime is computed from the timestamp.

  • year (int, optional) – Datetime year value. Must be a valid datetime.datetime year parameter. Must be provided unless the object is built with data or timestamp.

  • month (int, optional) – Datetime month value. Must be a valid datetime.datetime month parameter. Must be provided unless the object is built with data or timestamp.

  • day (int, optional) – Datetime day value. Must be a valid datetime.datetime day parameter. Must be provided unless the object is built with data or timestamp.

  • hour (int, optional) – Datetime hour value. Must be a valid datetime.datetime hour parameter.

  • minute (int, optional) – Datetime minute value. Must be a valid datetime.datetime minute parameter.

  • sec (int, optional) – Datetime seconds value. Must be a valid datetime.datetime second parameter.

  • nsec – Datetime nanoseconds value.

  • tzoffset (int, optional) – Timezone offset. Ignored, if provided together with tz.

  • tz (str, optional) – Timezone name from Olson timezone database.

  • timestamp_since_utc_epoch (bool, optional) –

    Parameter to set timestamp conversion behavior for timezone-aware datetimes.

    If False (default), behaves similar to Tarantool datetime.new():

    >>> dt = tarantool.Datetime(timestamp=1640995200, timestamp_since_utc_epoch=False)
    >>> dt
    datetime: Timestamp('2022-01-01 00:00:00'), tz: ""
    >>> dt.timestamp
    1640995200.0
    >>> dt = tarantool.Datetime(timestamp=1640995200, tz='Europe/Moscow',
    ...                         timestamp_since_utc_epoch=False)
    >>> dt
    datetime: Timestamp('2022-01-01 00:00:00+0300', tz='Europe/Moscow'), tz: "Europe/Moscow"
    >>> dt.timestamp
    1640984400.0
    

    Thus, if False, datetime is computed from timestamp since epoch and then timezone is applied without any conversion. In that case, timestamp won’t be equal to initialization timestamp for all timezones with non-zero offset.

    If True, behaves similar to datetime.datetime:

    >>> dt = tarantool.Datetime(timestamp=1640995200, timestamp_since_utc_epoch=True)
    >>> dt
    datetime: Timestamp('2022-01-01 00:00:00'), tz: ""
    >>> dt.timestamp
    1640995200.0
    >>> dt = tarantool.Datetime(timestamp=1640995200, tz='Europe/Moscow',
    ...                         timestamp_since_utc_epoch=True)
    >>> dt
    datetime: Timestamp('2022-01-01 03:00:00+0300', tz='Europe/Moscow'), tz: "Europe/Moscow"
    >>> dt.timestamp
    1640995200.0
    

    Thus, if True, datetime is computed in a way that timestamp will always be equal to initialization timestamp.

Raise:

ValueError, MsgpackError, datetime.datetime exceptions

property day

Datetime day.

Return type:

int

property hour

Datetime day.

Return type:

int

property minute

Datetime minute.

Return type:

int

property month

Datetime month.

Return type:

int

property nsec

Datetime nanoseconds (everything less than seconds is included).

Return type:

int

property sec

Datetime seconds.

Return type:

int

property timestamp

Datetime time since epoch, in seconds.

Return type:

float

property tz

Datetime timezone name.

Return type:

str

property tzoffset

Datetime current timezone offset.

Return type:

int

property value

Datetime time since epoch, in nanoseconds.

Return type:

int

property year

Datetime year.

Return type:

int

class tarantool.Interval(*, year=0, month=0, week=0, day=0, hour=0, minute=0, sec=0, nsec=0, adjust=Adjust.NONE)

Class representing Tarantool datetime.interval info.

You can create Interval objects either from MessagePack data or by using the same API as in Tarantool:

di = tarantool.Interval(year=-1, month=2, week=-3,
                        day=4, hour=5, minute=-6, sec=7,
                        nsec=308543321,
                        adjust=tarantool.IntervalAdjust.NONE)

Its attributes (same as in init API) are exposed, so you can use them if needed.

Parameters:
  • year (int, optional) – Interval year value.

  • month (int, optional) – Interval month value.

  • week (int, optional) – Interval week value.

  • day (int, optional) – Interval day value.

  • hour (int, optional) – Interval hour value.

  • minute (int, optional) – Interval minute value.

  • sec (int, optional) – Interval seconds value.

  • nsec (int, optional) – Interval nanoseconds value.

  • adjust (IntervalAdjust, optional) – Interval adjustment rule. Refer to __add__().

Raise:

ValueError

tarantool.IntervalAdjust

alias of Adjust

class tarantool.Mode(value)

Request mode.

ANY = 1

Send a request to any server.

PREFER_RO = 5

Send a request to RO server, if possible, RW server otherwise.

PREFER_RW = 4

Send a request to RW server, if possible, RO server otherwise.

RO = 3

Send a request to RO server.

RW = 2

Send a request to RW server.

class tarantool.Schema(con)

Contains Tarantool server spaces schema.

Parameters:

con (Connection) – Related Tarantool server connection.

fetch_index(space_object, index)

Fetch a single index space schema from the Tarantool server and build a schema object.

Parameters:
Return type:

SchemaIndex

Raises:

SchemaError, fetch_index_from() exceptions

fetch_index_all()

Fetch all spaces indexes schema from the Tarantool server and build corresponding schema objects.

Raises:

fetch_index_from() exceptions

fetch_index_from(space, index)

Fetch space index schema from the Tarantool server.

Parameters:
  • space (int or None) – Space id. If None, fetch all spaces index schema.

  • index (str or int or None) – Index name or id. If None, fetch all space indexes schema.

Returns:

Space index format data received from Tarantool.

Return type:

list or tuple

Raises:

select() exceptions

fetch_space(space)

Fetch a single space schema from the Tarantool server and build a schema object.

Parameters:

space (str or int) – Space name or space id to fetch.

Return type:

SchemaSpace

Raises:

SchemaError, fetch_space_from() exceptions

fetch_space_all()

Fetch all spaces schema from the Tarantool server and build corresponding schema objects.

Raises:

fetch_space_from() exceptions

fetch_space_from(space)

Fetch space schema from the Tarantool server.

Parameters:

space (str or int or None) – Space name or space id to fetch. If None, fetch all spaces.

Returns:

Space format data received from Tarantool.

Return type:

list or tuple

Raises:

select() exceptions

flush()

Clean existing schema data.

get_field(space, field)

Get space field format info.

Parameters:
  • space (str or int) – Space name or space id.

  • field (str or int) – Field name or field id.

Returns:

Field format info.

Return type:

dict

Raises:

SchemaError, fetch_space() exceptions

get_index(space, index)

Get space index schema. If it exists in the local schema, return local data, otherwise fetch data from the Tarantool server.

Parameters:
  • space (str or int) – Space id or space name.

  • index (str or int) – Index id or index name.

Return type:

SchemaIndex

Raises:

fetch_index() exceptions

get_space(space)

Get space schema. If it exists in the local schema, return local data, otherwise fetch data from the Tarantool server.

Parameters:

space (str or int) – Space name or space id.

Return type:

SchemaSpace

Raises:

fetch_space() exceptions

tarantool.connect(host='localhost', port=33013, socket_fd=None, user=None, password=None, encoding='utf-8', transport='', ssl_key_file=None, ssl_cert_file=None, ssl_ca_file=None, ssl_ciphers=None)

Create a connection to the Tarantool server.

Parameters:
Return type:

Connection

Raise:

Connection exceptions

tarantool.connectmesh(addrs=({'host': 'localhost', 'port': 3301},), user=None, password=None, encoding='utf-8')

Create a connection to a cluster of Tarantool servers.

Parameters:
Return type:

MeshConnection

Raise:

MeshConnection exceptions