def get_connection(alias=DEFAULT_ALIAS, reconnect=False): """Return connection by alias. :param alias: :param reconnect: """ global _connections if reconnect: disconnect(alias) if alias not in _connections: alias_settings = _connection_settings.get(alias) if not alias_settings: raise ValueError( 'Connection with alias {alias} have not defined.'.format( alias=alias)) try: conn_settings = alias_settings.copy() host = conn_settings.pop('host') port = conn_settings.pop('port') conn_settings.pop('space', None) _connections[alias] = Connection(host, port, **conn_settings) except DatabaseError as exc: message = 'Connect error for alias "{alias}": "{message}".'.format( alias=alias, message=exc) raise ConnectionError, message, sys.exc_info()[2] return _connections[alias]
def key_exists(key): logger("key_exists()", key) c = Connection("127.0.0.1", 3301) print("key_exists()") exists = list(c.select("KVstorage", key)) print(exists != []) return exists != []
def connect_to_tarantool(self, host, port, user=None, password=None, alias=None): """ Connection to Tarantool DB. *Args:*\n _host_ - host for db connection;\n _port_ - port for db connection;\n _user_ - username for db connection;\n _password_ - password for db connection;\n _alias_ - connection alias, used for switching between open connections;\n *Returns:*\n Returns ID of the new connection. The connection is set as active. *Example:*\n | Connect To Tarantool | 127.0.0.1 | 3301 | """ logger.debug('Connecting to the Tarantool DB using \ host={host}, port={port}, user={user}'.format(host=host, port=port, user=user)) try: self._connection = Connection(host=host, port=int(port), user=user, password=password) return self._cache.register(self._connection, alias) except Exception as exc: raise Exception("Logon to Tarantool error:", str(exc))
def add_kv(key, value): print("sdfgh") logger("add_kv()", key + " " + value) c = Connection("127.0.0.1", 3301) print("add_key()") try: c.insert("KVstorage", (key, value)) print(c.select("KVstorage", key)) return True except: return False
def produce(table: str): tnt_connection = Connection("127.0.0.1", 3302) trace(table, "Produce start") start = time.perf_counter_ns() for row in range(0, 100000, 1): next_id = tnt_connection.call("box.sequence.test_seq:next") tnt_connection.insert(table, (str(uuid.uuid1()), next_id[0], "TestBook_" + str(row), randint(1900, 2000))) if row % 1000 == 0: trace(table, "Done insert row: {}".format(row)) end = time.perf_counter_ns() table_size = tnt_connection.call("box.space.{}:len".format(table)) diff = (end - start) / 1000.0 trace(table, "Completed, table size: {}, time spent: {}" .format(table_size[0], diff)) return diff
def run_requests(table: str, debug: bool = True): tnt_connection = Connection("127.0.0.1", 3302) trace(table, "Run requests") ids = get_ids(tnt_connection, table, 1000) start = time.perf_counter_ns() row = 0 for item in ids: result = tnt_connection.select(table, [item]) if row % 100 == 0 and debug: trace(table, "Request completed: {}, last result: {}".format(row, result[0])) row += 1 end = time.perf_counter_ns() diff = (end - start) / 1000.0 trace(table, "Completed, request count: {}, time spent: {}" .format(row, diff)) return diff
def test(header, body): # Connect and authenticate c = Connection('localhost', server.iproto.port) c.connect() print 'query', repr_dict(header), repr_dict(body) header = msgpack.dumps(header) body = msgpack.dumps(body) query = msgpack.dumps(len(header) + len(body)) + header + body # Send raw request using connectred socket s = c._socket try: s.send(query) except OSError as e: print ' => ', 'Failed to send request' c.close() print iproto.py_con.ping() > 0
#!/usr/bin/python import sys from tarantool import Connection c = Connection("127.0.0.1", 3301) for line in sys.stdin: fields = line.rstrip().split('\t') num_fields = [int(x) for x in fields] c.insert("test1", tuple(num_fields))
def __init__(self, *, host, port, user, password): self.space = "kv" self.conn = Connection(host, port, user=user, password=password)
print("IPROTO_REPLACE") test({IPROTO_CODE: REQUEST_TYPE_REPLACE}, {IPROTO_SPACE_ID: 280}) print("\n") print("IPROTO_CALL") test({IPROTO_CODE: REQUEST_TYPE_CALL}, {}) test({IPROTO_CODE: REQUEST_TYPE_CALL}, {IPROTO_KEY: ("procname", )}) print("\n") # gh-434 Tarantool crashes on multiple iproto requests with WAL enabled admin("box.cfg.wal_mode") admin("space = box.schema.space.create('test', { id = 567 })") admin("index = space:create_index('primary', { type = 'hash' })") admin("box.schema.user.grant('guest', 'read,write,execute', 'space', 'test')") c = Connection("localhost", server.iproto.port) c.connect() request1 = RequestInsert(c, 567, [1, "baobab"]) request2 = RequestInsert(c, 567, [2, "obbaba"]) s = c._socket try: s.send(bytes(request1) + bytes(request2)) except OSError as e: print(" => ", "Failed to send request") response1 = Response(c, c._read_response()) response2 = Response(c, c._read_response()) print(response1.__str__()) print(response2.__str__()) request1 = RequestInsert(c, 567, [3, "occama"]) request2 = RequestSelect(c, 567, 0, [1], 0, 1, 0)
def update_value(key, value): logger("update_value", key + " " + value) c = Connection("127.0.0.1", 3301) print("update_value()") c.update("KVstorage", str(key), [('=', 1, value)] ) print(c.select("KVstorage", key))
def get_kv(key): logger("get_kv()", key) c = Connection("127.0.0.1", 3301) print("get_kv()") print(c.select("KVstorage", key)) return list(c.select("KVstorage", key))
def delete_value_by_key(key): c = Connection('127.0.0.1', 3301) c.delete("KVStorage", key) return
def update_value_by_key(key, value): c = Connection('127.0.0.1', 3301) c.update("KVStorage", key, [('=', 1, str(value))]) return
def delete_kv(key): logger("delete_kv()", key) c = Connection("127.0.0.1", 3301) print("delete_kv()") c.delete("KVstorage", key) return
def add_value_by_key(key, value): c = Connection('127.0.0.1', 3301) c.insert("KVStorage", (key, value)) return
print "IPROTO_REPLACE" test({IPROTO_CODE: REQUEST_TYPE_REPLACE}, {IPROTO_SPACE_ID: 280}) print "\n" print "IPROTO_CALL" test({IPROTO_CODE: REQUEST_TYPE_CALL}, {}) test({IPROTO_CODE: REQUEST_TYPE_CALL}, {IPROTO_KEY: ('procname', )}) print "\n" # gh-434 Tarantool crashes on multiple iproto requests with WAL enabled admin("box.cfg.wal_mode") admin("space = box.schema.space.create('test', { id = 567 })") admin("index = space:create_index('primary', { type = 'hash' })") admin("box.schema.user.grant('guest', 'read,write,execute', 'space', 'test')") c = Connection('localhost', server.iproto.port) c.connect() request1 = RequestInsert(c, 567, [1, "baobab"]) request2 = RequestInsert(c, 567, [2, "obbaba"]) s = c._socket try: s.send(bytes(request1) + bytes(request2)) except OSError as e: print ' => ', 'Failed to send request' response1 = Response(c, c._read_response()) response2 = Response(c, c._read_response()) print response1.__str__() print response2.__str__() request1 = RequestInsert(c, 567, [3, "occama"]) request2 = RequestSelect(c, 567, 0, [1], 0, 1, 0)
from tarantool import Connection conn = Connection("localhost", 3302) conn.insert("user", ( None, 'a', 1, )) conn.insert("user", ( None, 'b', 1, )) conn.insert("user", ( None, 'a', 0, )) conn.insert("user", ( None, 'b', 0, )) conn.insert("channel", (None, '1001373637514', 1, 't.me/ofka')) conn.insert("channel", (None, '1236565135464', 1, 't.me/root')) conn.insert("channel", (None, 'icqchannel1', 0, 'icq.com/qwe')) conn.insert("channel", (None, 'icqchannel2', 0, 'icq.com/zxcvbnm')) conn.insert("link", (None, 1, 3, 1))
def show_samples(table: str): tnt_connection = Connection("127.0.0.1", 3302) trace(table, "Show samples") result = tnt_connection.select(space_name=table, offset=0, limit=10) for item in result: print(item)
def db_connect(self): return Connection(self.host, self.port)
def get_value_by_key(key): c = Connection('127.0.0.1', 3301) value = list(c.select("KVStorage", key)) return value