-
Notifications
You must be signed in to change notification settings - Fork 4.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feature: add couchbase query runner #3658
Merged
arikfr
merged 7 commits into
getredash:master
from
AntonZarutsky:add-couchbase-as-data-source
Apr 24, 2019
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
a89d19c
feature: add couchbase query runner
AntonZarutsky 54e7134
fix style
AntonZarutsky 95c80f1
fix style
AntonZarutsky dc2f936
fix style
AntonZarutsky 6135eab
Merge branch 'master' into add-couchbase-as-data-source
AntonZarutsky 92f198e
fix naming due to convention
AntonZarutsky ae8756e
extracting protocol as parameter
AntonZarutsky File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
import datetime | ||
import logging | ||
|
||
from dateutil.parser import parse | ||
|
||
from redash.query_runner import * | ||
from redash.utils import JSONEncoder, json_dumps, json_loads, parse_human_time | ||
import json | ||
|
||
logger = logging.getLogger(__name__) | ||
try: | ||
import requests | ||
import httplib2 | ||
except ImportError as e: | ||
logger.error('Failed to import: ' + str(e)) | ||
|
||
|
||
TYPES_MAP = { | ||
str: TYPE_STRING, | ||
unicode: TYPE_STRING, | ||
int: TYPE_INTEGER, | ||
long: TYPE_INTEGER, | ||
float: TYPE_FLOAT, | ||
bool: TYPE_BOOLEAN, | ||
datetime.datetime: TYPE_DATETIME, | ||
datetime.datetime: TYPE_STRING | ||
} | ||
|
||
|
||
def _get_column_by_name(columns, column_name): | ||
for c in columns: | ||
if "name" in c and c["name"] == column_name: | ||
return c | ||
return None | ||
|
||
|
||
def parse_results(results): | ||
rows = [] | ||
columns = [] | ||
|
||
for row in results: | ||
parsed_row = {} | ||
for key in row: | ||
if isinstance(row[key], dict): | ||
for inner_key in row[key]: | ||
column_name = u'{}.{}'.format(key, inner_key) | ||
if _get_column_by_name(columns, column_name) is None: | ||
columns.append({ | ||
"name": column_name, | ||
"friendly_name": column_name, | ||
"type": TYPES_MAP.get(type(row[key][inner_key]), TYPE_STRING) | ||
}) | ||
|
||
parsed_row[column_name] = row[key][inner_key] | ||
|
||
else: | ||
if _get_column_by_name(columns, key) is None: | ||
columns.append({ | ||
"name": key, | ||
"friendly_name": key, | ||
"type": TYPES_MAP.get(type(row[key]), TYPE_STRING) | ||
}) | ||
|
||
parsed_row[key] = row[key] | ||
|
||
rows.append(parsed_row) | ||
return rows, columns | ||
|
||
|
||
class Couchbase(BaseQueryRunner): | ||
|
||
noop_query = 'Select 1' | ||
|
||
@classmethod | ||
def configuration_schema(cls): | ||
return { | ||
'type': 'object', | ||
'properties': { | ||
'host': { | ||
'type': 'string', | ||
}, | ||
'port': { | ||
'type': 'string', | ||
'title': 'Port (Defaults: 8095 - Analytics, 8093 - N1QL)', | ||
'default': '8095' | ||
}, | ||
'user': { | ||
'type': 'string', | ||
}, | ||
'password': { | ||
'type': 'string', | ||
}, | ||
}, | ||
'required': ['host', 'user', 'password'], | ||
"order": ['host', 'port', 'user', 'password'], | ||
"secret": ["password"] | ||
} | ||
|
||
def __init__(self, configuration): | ||
super(Couchbase, self).__init__(configuration) | ||
|
||
@classmethod | ||
def enabled(cls): | ||
return True | ||
|
||
@classmethod | ||
def annotate_query(cls): | ||
return False | ||
|
||
def test_connection(self): | ||
result = self.call_service(self.noop_query, '') | ||
|
||
def get_buckets(self, query, nameParam): | ||
defaultColumns = [ | ||
'meta().id' | ||
] | ||
result = self.call_service(query, "").json()['results'] | ||
schema = {} | ||
for row in result: | ||
table_name = row.get(nameParam) | ||
schema[table_name] = {'name': table_name, 'columns': defaultColumns} | ||
|
||
return schema.values() | ||
|
||
def get_schema(self, get_stats=False): | ||
|
||
try: | ||
# Try fetch from Analytics | ||
return self.get_buckets( | ||
"SELECT ds.GroupName as name FROM Metadata.`Dataset` ds where ds.DataverseName <> 'Metadata'", "name") | ||
except Exception: | ||
# Try fetch from N1QL | ||
return self.get_buckets("select name from system:keyspaces", "name") | ||
|
||
def call_service(self, query, user): | ||
try: | ||
user = self.configuration.get("user") | ||
password = self.configuration.get("password") | ||
host = self.configuration.get("host") | ||
port = self.configuration.get('port', 8095) | ||
params = {'statement': query} | ||
|
||
url = "http://%s:%s/query/service" % (host, port) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does Couchbase support HTTPS? In such case, we should probably make the protocol (http) configurable. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. extracted as parameter |
||
|
||
r = requests.post(url, params=params, auth=(user, password)) | ||
r.raise_for_status() | ||
return r | ||
except requests.exceptions.HTTPError as err: | ||
if (err.response.status_code == 401): | ||
raise Exception("Wrong username/password") | ||
raise Exception("Couchbase connection error") | ||
|
||
def run_query(self, query, user): | ||
try: | ||
result = self.call_service(query, user) | ||
|
||
rows, columns = parse_results(result.json()['results']) | ||
data = { | ||
"columns": columns, | ||
"rows": rows | ||
} | ||
|
||
return json_dumps(data), None | ||
except KeyboardInterrupt: | ||
return None, "Query cancelled by user." | ||
|
||
@classmethod | ||
def name(cls): | ||
return "Couchbase" | ||
|
||
|
||
register(Couchbase) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nameParam
should bename_param
to be consistent with PEP-8/our naming convention.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@arikfr. thx for review. Fixed nameParams.