forked from getredash/redash
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamodb_sql.py
More file actions
137 lines (112 loc) · 3.78 KB
/
dynamodb_sql.py
File metadata and controls
137 lines (112 loc) · 3.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import logging
import sys
from redash.query_runner import *
from redash.utils import json_dumps
logger = logging.getLogger(__name__)
try:
from dql import Engine, FragmentEngine
from pyparsing import ParseException
enabled = True
except ImportError as e:
enabled = False
types_map = {
'UNICODE': TYPE_INTEGER,
'TINYINT': TYPE_INTEGER,
'SMALLINT': TYPE_INTEGER,
'INT': TYPE_INTEGER,
'DOUBLE': TYPE_FLOAT,
'DECIMAL': TYPE_FLOAT,
'FLOAT': TYPE_FLOAT,
'REAL': TYPE_FLOAT,
'BOOLEAN': TYPE_BOOLEAN,
'TIMESTAMP': TYPE_DATETIME,
'DATE': TYPE_DATETIME,
'CHAR': TYPE_STRING,
'STRING': TYPE_STRING,
'VARCHAR': TYPE_STRING
}
class DynamoDBSQL(BaseSQLQueryRunner):
@classmethod
def configuration_schema(cls):
return {
"type": "object",
"properties": {
"region": {
"type": "string",
"default": "us-east-1"
},
"access_key": {
"type": "string",
},
"secret_key": {
"type": "string",
}
},
"required": ["access_key", "secret_key"],
"secret": ["secret_key"]
}
def test_connection(self):
engine = self._connect()
list(engine.connection.list_tables())
@classmethod
def annotate_query(cls):
return False
@classmethod
def type(cls):
return "dynamodb_sql"
@classmethod
def name(cls):
return "DynamoDB (with DQL)"
def _connect(self):
engine = FragmentEngine()
config = self.configuration.to_dict()
if not config.get('region'):
config['region'] = 'us-east-1'
if config.get('host') == '':
config['host'] = None
engine.connect(**config)
return engine
def _get_tables(self, schema):
engine = self._connect()
for table in engine.describe_all():
schema[table.name] = {'name': table.name, 'columns': table.attrs.keys()}
def run_query(self, query, user):
engine = None
try:
engine = self._connect()
result = engine.execute(query if str(query).endswith(';') else str(query)+';')
columns = []
rows = []
# When running a count query it returns the value as a string, in which case
# we transform it into a dictionary to be the same as regular queries.
if isinstance(result, basestring):
# when count < scanned_count, dql returns a string with number of rows scanned
value = result.split(" (")[0]
if value:
value = int(value)
result = [{"value": value}]
for item in result:
if not columns:
for k, v in item.iteritems():
columns.append({
'name': k,
'friendly_name': k,
'type': types_map.get(str(type(v)).upper(), None)
})
rows.append(item)
data = {'columns': columns, 'rows': rows}
json_data = json_dumps(data)
error = None
except ParseException as e:
error = u"Error parsing query at line {} (column {}):\n{}".format(e.lineno, e.column, e.line)
json_data = None
except (SyntaxError, RuntimeError) as e:
error = e.message
json_data = None
except KeyboardInterrupt:
if engine and engine.connection:
engine.connection.cancel()
error = "Query cancelled by user."
json_data = None
return json_data, error
register(DynamoDBSQL)