def run_query(self, query, user): connection = sqlite3.connect(':memory:') tables, query_ids, query_params = extract_query_ids_and_params(query) create_tables_from_query_ids(user, connection, tables, query_ids, query_params) cursor = connection.cursor() try: for i, table in enumerate(tables): tmp_table_name = 'query_{}'.format( hashlib.md5(tables[i]).hexdigest()[0:8]) query = query.replace(table, tmp_table_name, 1) cursor.execute(query) if cursor.description is not None: columns = self.fetch_columns([(i[0], None) for i in cursor.description]) rows = [] column_names = [c['name'] for c in columns] for i, row in enumerate(cursor): for j, col in enumerate(row): guess = _guess_type(col) if columns[j]['type'] is None: columns[j]['type'] = guess elif columns[j]['type'] != guess: columns[j]['type'] = TYPE_STRING rows.append(dict(zip(column_names, row))) data = {'columns': columns, 'rows': rows} error = None json_data = json.dumps(data, cls=JSONEncoder) else: error = 'Query completed but it returned no data.' json_data = None except KeyboardInterrupt: connection.cancel() error = 'Query cancelled by user.' json_data = None finally: connection.close() return json_data, error
def test_date(self): self.assertEqual(TYPE_DATETIME, _guess_type('2018-06-28'))
def test_boolean(self): self.assertEqual(TYPE_BOOLEAN, _guess_type('true')) self.assertEqual(TYPE_BOOLEAN, _guess_type('false'))
def test_float(self): self.assertEqual(TYPE_FLOAT, _guess_type(3.14))
def test_integer(self): self.assertEqual(TYPE_INTEGER, _guess_type(42))
def test_string(self): self.assertEqual(TYPE_STRING, _guess_type('')) self.assertEqual(TYPE_STRING, _guess_type(None)) self.assertEqual(TYPE_STRING, _guess_type('redash'))
def test_date(self): self.assertEqual(TYPE_DATETIME, _guess_type('2018-06-28'))
def test_boolean(self): self.assertEqual(TYPE_BOOLEAN, _guess_type('true')) self.assertEqual(TYPE_BOOLEAN, _guess_type('false'))
def test_float(self): self.assertEqual(TYPE_FLOAT, _guess_type(3.14))
def test_integer(self): self.assertEqual(TYPE_INTEGER, _guess_type(42))
def test_string(self): self.assertEqual(TYPE_STRING, _guess_type('')) self.assertEqual(TYPE_STRING, _guess_type(None)) self.assertEqual(TYPE_STRING, _guess_type('redash'))