Esempio n. 1
0
    def testQueryOrderByWithOffset(self):
        offset = 4
        num_get = 8
        # test order by primary index field with offset
        statement = ('DECLARE $offset INTEGER; SELECT fld_str FROM ' +
                     table_name + ' ORDER BY fld_sid, fld_id OFFSET $offset')
        prepare_request = PrepareRequest().set_statement(statement)
        prepare_result = self.handle.prepare(prepare_request)
        prepared_statement = prepare_result.get_prepared_statement()
        prepared_statement.set_variable('$offset', offset)
        query_request = QueryRequest().set_prepared_statement(
            prepared_statement)
        count = 0
        while True:
            count += 1
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_get, rec=records)
                for idx in range(num_get):
                    self.assertEqual(
                        records[idx], {
                            'fld_str':
                            '{"name": u' + str(num_get - idx - 1).zfill(2) +
                            '}'
                        })
                self.check_cost(result, 0, 0, 0, 0)
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
                self.check_cost(result, 0, 0, 0, 0, True)
        self.assertEqual(count, 2)

        # test order by secondary index field with offset
        statement = ('DECLARE $offset INTEGER; SELECT fld_str FROM ' +
                     table_name + ' ORDER BY fld_str OFFSET $offset')
        prepare_request = PrepareRequest().set_statement(statement)
        prepare_result = self.handle.prepare(prepare_request)
        prepared_statement = prepare_result.get_prepared_statement()
        prepared_statement.set_variable('$offset', offset)
        query_request = QueryRequest().set_prepared_statement(
            prepared_statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_get, rec=records)
                for idx in range(num_get):
                    self.assertEqual(records[idx], {
                        'fld_str':
                        '{"name": u' + str(offset + idx).zfill(2) + '}'
                    })
                self.check_cost(result, 0, 0, 0, 0)
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
                self.check_cost(result, 0, 0, 0, 0, True)
Esempio n. 2
0
    def testQueryFuncSumGroupBy(self):
        num_records = 12
        num_sids = 2
        # test sum function
        statement = ('SELECT sum(fld_double) FROM ' + table_name)
        query_request = QueryRequest().set_statement(statement)
        result = self.handle.query(query_request)
        records = self.check_query_result(result, 1)
        self.assertEqual(records[0], {'Column_1': 3.1415 * num_records})
        self.check_cost(result, prepare_cost, prepare_cost, 0, 0, True)

        # test sum function group by primary index field
        statement = ('SELECT sum(fld_double) FROM ' + table_name +
                     ' GROUP BY fld_sid')
        query_request = QueryRequest().set_statement(statement)
        count = 0
        while True:
            count += 1
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(
                        records[idx],
                        {'Column_1': 3.1415 * (num_records // num_sids)})
                self.check_cost(result, 0, 0, 0, 0)
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
                self.check_cost(result, 0, 0, 0, 0, True)
        self.assertEqual(count, 2)

        # test sum function group by secondary index field
        statement = ('SELECT sum(fld_double) FROM ' + table_name +
                     ' GROUP BY fld_bool')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(
                        records[idx],
                        {'Column_1': 3.1415 * (num_records // num_sids)})
                self.check_cost(result, 0, 0, 0, 0)
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
                self.check_cost(result, 0, 0, 0, 0, True)
Esempio n. 3
0
        def testQueryOrderByWithLimit(self):
            num_records = 12
            limit = 10
            # test order by primary index field with limit
            statement = ('SELECT fld_str FROM ' + table_name +
                         ' ORDER BY fld_sid, fld_id LIMIT 10')
            query_request = QueryRequest().set_statement(statement)
            count = 0
            while True:
                count += 1
                result = self.handle.query(query_request)
                records = result.get_results()
                if query_request.is_done():
                    self.check_query_result(result, limit, rec=records)
                    for idx in range(limit):
                        self.assertEqual(
                            records[idx], {
                                'fld_str':
                                '{"name": u' +
                                str(num_records - idx - 1).zfill(2) + '}'
                            })
                    self.check_cost(result, 0, 0, 0, 0)
                    break
                else:
                    self.check_query_result(result, 0, True, records)
                    self.assertEqual(records, [])
                    self.check_cost(result, 0, 0, 0, 0, True)
            self.assertEqual(count, 2)

            # test order by secondary index field with limit
            statement = ('SELECT fld_str FROM ' + table_name +
                         ' ORDER BY fld_str LIMIT 10')
            query_request = QueryRequest().set_statement(statement)
            while True:
                result = self.handle.query(query_request)
                records = result.get_results()
                if query_request.is_done():
                    self.check_query_result(result, limit, rec=records)
                    for idx in range(limit):
                        self.assertEqual(records[idx], {
                            'fld_str':
                            '{"name": u' + str(idx).zfill(2) + '}'
                        })
                    self.check_cost(result, 0, 0, 0, 0)
                    break
                else:
                    self.check_query_result(result, 0, True, records)
                    self.assertEqual(records, [])
                    self.check_cost(result, 0, 0, 0, 0, True)
Esempio n. 4
0
 def setUp(self):
     TestBase.set_up(self)
     self.shardkeys = [0, 1]
     ids = [0, 1, 2, 3, 4, 5]
     write_multiple_request = WriteMultipleRequest()
     for sk in self.shardkeys:
         for i in ids:
             row = {'fld_sid': sk, 'fld_id': i, 'fld_long': 2147483648,
                    'fld_float': 3.1414999961853027, 'fld_double': 3.1415,
                    'fld_bool': True,
                    'fld_str': '{"name": u1, "phone": null}',
                    'fld_bin': bytearray(pack('>i', 4)),
                    'fld_time': datetime.now(), 'fld_num': Decimal(5),
                    'fld_json': {'a': '1', 'b': None, 'c': '3'},
                    'fld_arr': ['a', 'b', 'c'],
                    'fld_map': {'a': '1', 'b': '2', 'c': '3'},
                    'fld_rec': {'fld_id': 1, 'fld_bool': False,
                                'fld_str': None}}
             write_multiple_request.add(
                 PutRequest().set_value(row).set_table_name(table_name),
                 True)
         self.handle.write_multiple(write_multiple_request)
         write_multiple_request.clear()
     self.key = {'fld_sid': 1}
     self.multi_delete_request = MultiDeleteRequest().set_timeout(timeout)
     prep_request = PrepareRequest().set_statement(
         'SELECT fld_sid, fld_id FROM ' + table_name)
     prep_result = self.handle.prepare(prep_request)
     self.query_request = QueryRequest().set_prepared_statement(prep_result)
def get_user_id(username):
    sql = 'SELECT id FROM fotogal_ntable_users WHERE username = "******" LIMIT 1' % (
        username, )
    nosql_request = QueryRequest().set_statement(sql)
    nosql_result = nosql_handler.query(nosql_request).get_results()

    return nosql_result[0]['id']
Esempio n. 6
0
        def testQueryOrderBy(self):
            num_records = 12
            num_ids = 6
            # test order by primary index field
            statement = ('SELECT fld_sid, fld_id FROM ' + table_name +
                         ' ORDER BY fld_sid, fld_id')
            query_request = QueryRequest().set_statement(statement)
            count = 0
            while True:
                count += 1
                result = self.handle.query(query_request)
                records = result.get_results()
                if query_request.is_done():
                    self.check_query_result(result, num_records, rec=records)
                    for idx in range(num_records):
                        self.assertEqual(
                            records[idx],
                            self._expected_row(idx // num_ids, idx % num_ids))
                    self.check_cost(result, 0, 0, 0, 0)
                    break
                else:
                    self.check_query_result(result, 0, True, records)
                    self.assertEqual(records, [])
                    self.check_cost(result, 0, 0, 0, 0, True)
            self.assertEqual(count, 2)

            # test order by secondary index field
            statement = ('SELECT fld_str FROM ' + table_name +
                         ' ORDER BY fld_str')
            query_request = QueryRequest().set_statement(statement)
            while True:
                result = self.handle.query(query_request)
                records = result.get_results()
                if query_request.is_done():
                    self.check_query_result(result, num_records, rec=records)
                    for idx in range(num_records):
                        self.assertEqual(records[idx], {
                            'fld_str':
                            '{"name": u' + str(idx).zfill(2) + '}'
                        })
                    self.check_cost(result, 0, 0, 0, 0)
                    break
                else:
                    self.check_query_result(result, 0, True, records)
                    self.assertEqual(records, [])
                    self.check_cost(result, 0, 0, 0, 0, True)
Esempio n. 7
0
 def setUp(self):
     TestBase.set_up(self)
     self.handle_config = get_handle_config(tenant_id)
     shardkeys = [0, 1]
     ids = [0, 1, 2, 3, 4, 5]
     write_multiple_request = WriteMultipleRequest()
     for sk in shardkeys:
         for i in ids:
             row = {
                 'fld_sid': sk,
                 'fld_id': i,
                 'fld_long': 2147483648,
                 'fld_float': 3.1414999961853027,
                 'fld_double': 3.1415,
                 'fld_bool': True,
                 'fld_str': '{"name": u1, "phone": null}',
                 'fld_bin': bytearray(pack('>i', 4)),
                 'fld_time': datetime.now(),
                 'fld_num': Decimal(5),
                 'fld_json': {
                     'a': '1',
                     'b': None,
                     'c': '3'
                 },
                 'fld_arr': ['a', 'b', 'c'],
                 'fld_map': {
                     'a': '1',
                     'b': '2',
                     'c': '3'
                 },
                 'fld_rec': {
                     'fld_id': 1,
                     'fld_bool': False,
                     'fld_str': None
                 }
             }
             write_multiple_request.add(
                 PutRequest().set_value(row).set_table_name(table_name),
                 True)
         self.handle.write_multiple(write_multiple_request)
         write_multiple_request.clear()
     prepare_statement_update = (
         'DECLARE $fld_sid INTEGER; $fld_id INTEGER; UPDATE ' + table_name +
         ' u SET u.fld_long = u.fld_long + 1 WHERE fld_sid = $fld_sid ' +
         'AND fld_id = $fld_id')
     prepare_request_update = PrepareRequest().set_statement(
         prepare_statement_update)
     self.prepare_result_update = self.handle.prepare(
         prepare_request_update)
     prepare_statement_select = (
         'DECLARE $fld_long LONG; SELECT fld_sid, fld_id, fld_long FROM ' +
         table_name + ' WHERE fld_long = $fld_long')
     prepare_request_select = PrepareRequest().set_statement(
         prepare_statement_select)
     self.prepare_result_select = self.handle.prepare(
         prepare_request_select)
     self.query_request = QueryRequest().set_timeout(timeout)
     self.get_request = GetRequest().set_table_name(table_name)
def update_user_img_profile(user_id, username, email, profile_img_url):
    sql = 'UPDATE fotogal_ntable_users SET profile_image_url = "%s" WHERE id = %d AND username = "******" AND email = "%s"' % (
        profile_img_url,
        user_id,
        username,
        email,
    )
    nosql_request = QueryRequest().set_statement(sql)
    nosql_result = nosql_handler.query(nosql_request).get_results()
Esempio n. 9
0
    def testQueryFuncCountGroupBy(self):
        num_records = 12
        num_sids = 2
        # test count function
        statement = ('SELECT count(*) FROM ' + table_name)
        query_request = QueryRequest().set_statement(statement)
        result = self.handle.query(query_request)
        records = self.check_query_result(result, 1)
        self.assertEqual(records[0], {'Column_1': num_records})

        # test count function group by primary index field
        statement = ('SELECT count(*) FROM ' + table_name +
                     ' GROUP BY fld_sid')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(records[idx],
                                     {'Column_1': num_records // num_sids})
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])

        # test count function group by secondary index field
        statement = ('SELECT count(*) FROM ' + table_name +
                     ' GROUP BY fld_bool')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(records[idx],
                                     {'Column_1': num_records // num_sids})
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
Esempio n. 10
0
    def exec_query(self, table=None, sql=None):
        """Execute a SQL Query that return a single result.

      """
        nosql_result = []

        query_request = QueryRequest()
        nosql_request = query_request.set_statement(sql)
        query_request.close()

        nosql_result = self._nosql_handle.query(query_request)

        return nosql_result.get_results()
Esempio n. 11
0
 def setUp(self):
     self.set_up()
     self.handle_config = get_handle_config(tenant_id)
     self.min_time = list()
     self.max_time = list()
     shardkeys = 2
     ids = 6
     write_multiple_request = WriteMultipleRequest()
     for sk in range(shardkeys):
         for i in range(ids):
             row = get_row()
             if i == 0:
                 self.min_time.append(row['fld_time'])
             elif i == ids - 1:
                 self.max_time.append(row['fld_time'])
             row['fld_sid'] = sk
             row['fld_id'] = i
             row['fld_bool'] = False if sk == 0 else True
             row['fld_str'] = (
                 '{"name": u' +
                 str(shardkeys * ids - sk * ids - i - 1).zfill(2) + '}')
             row['fld_json']['location']['coordinates'] = ([
                 23.549 - sk * 0.5 - i, 35.2908 + sk * 0.5 + i
             ])
             write_multiple_request.add(
                 PutRequest().set_value(row).set_table_name(table_name),
                 True)
         self.handle.write_multiple(write_multiple_request)
         write_multiple_request.clear()
     prepare_statement_update = (
         'DECLARE $fld_sid INTEGER; $fld_id INTEGER; UPDATE ' + table_name +
         ' u SET u.fld_long = u.fld_long + 1 WHERE fld_sid = $fld_sid ' +
         'AND fld_id = $fld_id')
     prepare_request_update = PrepareRequest().set_statement(
         prepare_statement_update)
     self.prepare_result_update = self.handle.prepare(
         prepare_request_update)
     prepare_statement_select = (
         'DECLARE $fld_long LONG; SELECT fld_sid, fld_id, fld_long FROM ' +
         table_name + ' WHERE fld_long = $fld_long')
     prepare_request_select = PrepareRequest().set_statement(
         prepare_statement_select)
     self.prepare_result_select = self.handle.prepare(
         prepare_request_select)
     self.query_request = QueryRequest().set_timeout(timeout)
     self.get_request = GetRequest().set_table_name(table_name)
Esempio n. 12
0
def handler(ctx, data: io.BytesIO = None):

    return_citizens = []

    try:
        provider = SignatureProvider(
            tenant_id='Your Tenant OCID',
            user_id='Your User OCID',
            private_key='location of Pem file',
            fingerprint='The fingerprint for your key pair goes here',
            pass_phrase='The pass phrase for your key goes here')
        compartment = 'Your Compartment Name Goes Here'
        config = NoSQLHandleConfig(Regions.US_ASHBURN_1, provider)
        config.set_default_compartment(compartment)
        logger = logging.getLogger('Citizens')
        logger.setLevel(logging.WARNING)
        config.set_logger(logger)
        handle = NoSQLHandle(config)
        table_name = 'Citizens'

        ## Prepare select statement#
        statement = 'select * from ' + table_name
        request = PrepareRequest().set_statement(statement)
        prepared_result = handle.prepare(request)

        ## Query, using the prepared statement#
        request = QueryRequest().set_prepared_statement(prepared_result)

        while True:
            result = handle.query(request)
            for r in result.get_results():
                return_citizens.append(dict(r))
            if request.is_done():
                break

    except (Exception, ValueError) as ex:
        logging.getLogger().info('error parsing json payload: ' + str(ex))

    logging.getLogger().info("Inside OCI function")
    return response.Response(ctx,
                             response_data=json.dumps(return_citizens),
                             headers={"Content-Type": "application/json"})
Esempio n. 13
0
    def exec_query_loop(self, table=None, sql=None):
        """Execute a SQL Query that return multiples results.

      """
        nosql_result = []

        query_request = QueryRequest()
        nosql_request = query_request.set_statement(sql)
        query_request.close()

        while True:
            nosql_exec_query = self._nosql_handle.query(query_request)
            nosql_result = nosql_exec_query.get_results()

            if len(nosql_result) > 0:
                break

            if nosql_request.is_done():
                break

        return nosql_result
Esempio n. 14
0
 def setUp(self):
     self.set_up()
     self.shardkeys = [0, 1]
     ids = [0, 1, 2, 3, 4, 5]
     write_multiple_request = WriteMultipleRequest()
     for sk in self.shardkeys:
         for i in ids:
             row = get_row()
             row['fld_sid'] = sk
             row['fld_id'] = i
             write_multiple_request.add(
                 PutRequest().set_value(row).set_table_name(table_name),
                 True)
         self.handle.write_multiple(write_multiple_request)
         write_multiple_request.clear()
     self.key = {'fld_sid': 1}
     self.multi_delete_request = MultiDeleteRequest().set_timeout(timeout)
     prep_request = PrepareRequest().set_statement(
         'SELECT fld_sid, fld_id FROM ' + table_name)
     prep_result = self.handle.prepare(prep_request)
     self.query_request = QueryRequest().set_prepared_statement(prep_result)
Esempio n. 15
0
    def testQueryFuncMinMaxGroupBy(self):
        num_sids = 2
        # test min function
        statement = 'SELECT min(fld_time) FROM ' + table_name
        query_request = QueryRequest().set_statement(statement)
        result = self.handle.query(query_request)
        records = self.check_query_result(result, 1)
        self.assertEqual(records[0], {'Column_1': self.min_time[0]})

        # test max function
        statement = 'SELECT max(fld_time) FROM ' + table_name
        query_request = QueryRequest().set_statement(statement)
        result = self.handle.query(query_request)
        records = self.check_query_result(result, 1)
        self.assertEqual(records[0], {'Column_1': self.max_time[1]})

        # test min function group by primary index field
        statement = ('SELECT min(fld_time) FROM ' + table_name +
                     ' GROUP BY fld_sid')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(
                        records[idx], {'Column_1': self.min_time[idx]})
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])

        # test max function group by primary index field
        statement = ('SELECT max(fld_time) FROM ' + table_name +
                     ' GROUP BY fld_sid')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(
                        records[idx], {'Column_1': self.max_time[idx]})
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])

        # test min function group by secondary index field
        statement = ('SELECT min(fld_time) FROM ' + table_name +
                     ' GROUP BY fld_bool ORDER BY fld_bool')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(
                        records[idx], {'Column_1': self.min_time[idx]})
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])

        # test max function group by secondary index field
        statement = ('SELECT max(fld_time) FROM ' + table_name +
                     ' GROUP BY fld_bool ORDER BY fld_bool')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_sids, rec=records)
                for idx in range(num_sids):
                    self.assertEqual(
                        records[idx], {'Column_1': self.max_time[idx]})
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
Esempio n. 16
0
    def testQueryFuncGeoNear(self):
        num_get = 6
        longitude = 21.547
        latitude = 37.291
        # test geo_near function
        statement = ('SELECT tb.fld_json.location FROM ' + table_name +
                     ' tb WHERE geo_near(tb.fld_json.location, ' +
                     '{"type": "point", "coordinates": [' + str(longitude) +
                     ', ' + str(latitude) + ']}, 215000)')
        query_request = QueryRequest().set_statement(statement)
        result = self.handle.query(query_request)
        records = self.check_query_result(result, num_get)
        for i in range(1, num_get):
            pre = records[i - 1]['location']['coordinates']
            curr = records[i]['location']['coordinates']
            self.assertLess(abs(pre[0] - longitude), abs(curr[0] - longitude))
            self.assertLess(abs(pre[1] - latitude), abs(curr[1] - latitude))
        self.check_cost(result, prepare_cost, prepare_cost, 0, 0, True)

        # test geo_near function order by primary index field
        statement = (
            'SELECT fld_str FROM ' + table_name + ' tb WHERE geo_near(' +
            'tb.fld_json.location, {"type": "point", "coordinates": [' +
            str(longitude) + ', ' + str(latitude) + ']}, 215000) ' +
            'ORDER BY fld_sid, fld_id')
        query_request = QueryRequest().set_statement(statement)
        count = 0
        while True:
            count += 1
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_get, rec=records)
                name = [10, 9, 8, 4, 3, 2]
                for i in range(num_get):
                    self.assertEqual(records[i], {
                        'fld_str':
                        '{"name": u' + str(name[i]).zfill(2) + '}'
                    })
                self.check_cost(result, 0, 0, 0, 0)
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
                self.check_cost(result, 0, 0, 0, 0, True)
        self.assertEqual(count, 2)

        # test geo_near function order by secondary index field
        statement = (
            'SELECT fld_str FROM ' + table_name + ' tb WHERE geo_near(' +
            'tb.fld_json.location, {"type": "point", "coordinates": [' +
            str(longitude) + ', ' + str(latitude) + ']}, 215000) ' +
            'ORDER BY fld_str')
        query_request = QueryRequest().set_statement(statement)
        while True:
            result = self.handle.query(query_request)
            records = result.get_results()
            if query_request.is_done():
                self.check_query_result(result, num_get, rec=records)
                name = [2, 3, 4, 8, 9, 10]
                for i in range(num_get):
                    self.assertEqual(records[i], {
                        'fld_str':
                        '{"name": u' + str(name[i]).zfill(2) + '}'
                    })
                self.check_cost(result, 0, 0, 0, 0)
                break
            else:
                self.check_query_result(result, 0, True, records)
                self.assertEqual(records, [])
                self.check_cost(result, 0, 0, 0, 0, True)
def main():

    handle = None
    try:
        #
        # Create a handle
        #
        handle = get_handle(tenant_id)

        #
        # Create a table
        #
        statement = 'Create table if not exists ' + table_name + '(id integer, \
sid integer, name string, primary key(shard(sid), id))'

        print('Creating table: ' + statement)
        request = TableRequest().set_statement(statement).set_table_limits(
            TableLimits(30, 10, 1))
        result = handle.table_request(request)

        #
        # Table creation can take time, depending on the state of the system.
        # If if fails after 40s, re-run the program
        #
        result.wait_for_state(handle, table_name, State.ACTIVE, 50000, 3000)
        print('After create table')

        #
        # Put a few rows
        #
        request = PutRequest().set_table_name(table_name)
        for i in range(10):
            value = {'id': i, 'sid': 0, 'name': 'myname' + str(i)}
            request.set_value(value)
            handle.put(request)
        print('After put of 10 rows')

        #
        # Get the row
        #
        request = GetRequest().set_key({
            'id': 1,
            'sid': 0
        }).set_table_name(table_name)
        result = handle.get(request)
        print('After get: ' + str(result))

        #
        # Query, using a range
        #
        statement = 'select * from ' + table_name + ' where id > 2 and id < 8'
        request = QueryRequest().set_statement(statement)
        result = handle.query(request)
        print('Query results for: ' + statement)
        for r in result.get_results():
            print('\t' + str(r))

        #
        # Delete the row
        #
        request = DeleteRequest().set_key({
            'id': 1,
            'sid': 0
        }).set_table_name(table_name)
        result = handle.delete(request)
        print('After delete: ' + str(result))

        #
        # Get again to show deletion
        #
        request = GetRequest().set_key({
            'id': 1,
            'sid': 0
        }).set_table_name(table_name)
        result = handle.get(request)
        print('After get (should be None): ' + str(result))

        #
        # Drop the table
        #
        if drop_table:
            request = TableRequest().set_statement('drop table if exists ' +
                                                   table_name)
            result = handle.table_request(request)

            #
            # Table drop can take time, depending on the state of the system.
            # If this wait fails the table will still probably been dropped
            #
            result.wait_for_state(handle, table_name, State.DROPPED, 40000,
                                  2000)
            print('After drop table')
        else:
            print('Not dropping table')

        print('Example is complete')
    except Exception as e:
        print(e)
        traceback.print_exc()
    finally:
        # If the handle isn't closed Python will not exit properly
        if handle is not None:
            handle.close()
Esempio n. 18
0
# create handle config using a desired region as endpoint and set a
# default compartment.
handle_config = NoSQLHandleConfig(Regions.SA_SAOPAULO_1)
handle_config.set_authorization_provider(at_provider)
handle_config.set_default_compartment('<your-compartment-id>')

# create the handle.
nosql_handle = NoSQLHandle(handle_config)

query = """

  SELECT propriedades, valor, frete_gratis FROM produtos

"""

query_request = QueryRequest()

# set ABSOLUTE consistency for read requests.
query_request.set_consistency(Consistency.ABSOLUTE)

query_request.set_statement(query)

while True:
    query_result = nosql_handle.query(query_request)
    print(query_result)

    if query_request.is_done():
        break

# free up the resources from handle.
nosql_handle.close()
Esempio n. 19
0
def main():

    handle = None
    try:
        #
        # Create a handle
        #
        handle = get_handle(tenant_id)

        #
        # Create a table
        #
        statement = 'Create table if not exists ' + table_name + '(id integer, \
sid integer, name string, primary key(shard(sid), id))'

        print('Creating table: ' + statement)
        request = TableRequest().set_statement(statement).set_table_limits(
            TableLimits(30, 10, 1))
        handle.do_table_request(request, 50000, 3000)
        print('After create table')

        #
        # Put a few rows
        #
        request = PutRequest().set_table_name(table_name)
        for i in range(10):
            value = {'id': i, 'sid': 0, 'name': 'myname' + str(i)}
            request.set_value(value)
            handle.put(request)
        print('After put of 10 rows')

        #
        # Multiple write a few rows
        #
        request = WriteMultipleRequest()
        for i in range(10):
            value = {'id': i, 'sid': 0, 'name': 'newname' + str(i)}
            request.add(
                PutRequest().set_value(value).set_table_name(table_name), True)
        result = handle.write_multiple(request)
        print('After multiple write: ' + str(result))

        #
        # Prepare a statement
        #
        statement = 'select * from ' + table_name + ' where id > 2 and id < 8'
        request = PrepareRequest().set_statement(statement)
        prepared_result = handle.prepare(request)
        print('After prepare the statement: ' + statement)

        #
        # Query, using the prepared statement
        #
        request = QueryRequest().set_prepared_statement(prepared_result)
        print('Query results for the prepared statement: ')
        while True:
            result = handle.query(request)
            for r in result.get_results():
                print('\t' + str(r))
            if request.is_done():
                break

        #
        # Multiple delete the rows
        #
        request = MultiDeleteRequest().set_table_name(table_name).set_key(
            {'sid': 0})
        result = handle.multi_delete(request)
        print('After multiple delete: ' + str(result))

        #
        # Query again to show deletions, using the prepared statement
        #
        request = QueryRequest().set_prepared_statement(prepared_result)
        print('Query results for the prepared statement (should be no rows): ')
        while True:
            result = handle.query(request)
            for r in result.get_results():
                print('\t' + str(r))
            if request.is_done():
                break

        #
        # Drop the table
        #
        if drop_table:
            request = TableRequest().set_statement('drop table if exists ' +
                                                   table_name)
            handle.do_table_request(request, 40000, 2000)
            print('After drop table')
        else:
            print('Not dropping table')

        print('Example is complete')
    except Exception as e:
        print(e)
        traceback.print_exc()
    finally:
        # If the handle isn't closed Python will not exit properly
        if handle is not None:
            handle.close()
Esempio n. 20
0
        def _do_rate_limited_queries(self, num_seconds, read_limit, max_kb,
                                     single_partition, use_percent,
                                     use_external_limiters):
            """
            Runs queries continuously for N seconds.

            Verify that the resultant RUs used match the given rate limit.
            """
            start_time = int(round(time() * 1000))
            end_time = start_time + num_seconds * 1000
            read_units_used = 0
            rlim = None
            wlim = None
            if not use_external_limiters:
                # Reset internal limiters so they don't have unused units.
                self.handle.get_client().reset_rate_limiters(table_name)
            else:
                rlim = SimpleRateLimiter(read_limit * use_percent / 100.0, 1)
                wlim = SimpleRateLimiter(read_limit * use_percent / 100.0, 1)
            prep_req = PrepareRequest()
            if single_partition:
                # Query based on single partition scanning.
                fld_id = int(random() * 500)
                prep_req.set_statement('SELECT * FROM ' + table_name +
                                       ' WHERE id = ' + str(fld_id))
            else:
                # Query based on all partitions scanning.
                prep_req.set_statement('SELECT * FROM ' + table_name +
                                       ' WHERE name = "jane"')
            prep_res = self.handle.prepare(prep_req)
            self.assertTrue(prep_res.get_prepared_statement() is not None,
                            'Prepare statement failed.')
            read_units_used += prep_res.get_read_units()

            while True:
                """
                We need a 20 second timeout because in some cases this is called
                on a table with 500 rows and 50RUs (uses 1000RUs = 20 seconds).
                """
                query_req = QueryRequest().set_prepared_statement(
                    prep_res).set_timeout(20000).set_read_rate_limiter(
                        rlim).set_write_rate_limiter(wlim)
                if max_kb > 0:
                    # Query with size limit.
                    query_req.set_max_read_kb(max_kb)
                try:
                    while True:
                        res = self.handle.query(query_req)
                        res.get_results()
                        read_units_used += res.get_read_units()
                        if query_req.is_done():
                            break
                except ReadThrottlingException:
                    self.fail('Expected no throttling exceptions, got one.')
                except RequestTimeoutException:
                    # This may happen for very small limit tests.
                    pass

                if int(round(time() * 1000)) >= end_time:
                    break

            num_seconds = (int(round(time() * 1000)) - start_time) / 1000
            use_percent /= 100.0
            rus = read_units_used / num_seconds
            expected_rus = read_limit * use_percent
            # For very small expected amounts, just verify within 1 RU.
            if (expected_rus < 4
                    and expected_rus - 1 <= rus <= expected_rus + 1):
                return
            if rus < expected_rus * 0.6 or rus > expected_rus * 1.5:
                self.fail('Queries: Expected around ' + str(expected_rus) +
                          ' RUs, got ' + str(rus))