-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
api_handler.py
363 lines (271 loc) · 10.5 KB
/
api_handler.py
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
from typing import Any, List
import ast as py_ast
import pandas as pd
from mindsdb_sql.parser.ast import ASTNode, Select, Insert, Update, Delete, Star
from mindsdb_sql.parser.ast.select.identifier import Identifier
from mindsdb.integrations.utilities.sql_utils import (
extract_comparison_conditions, filter_dataframe,
FilterCondition, FilterOperator, SortColumn
)
from mindsdb.integrations.libs.base import BaseHandler
from mindsdb.integrations.libs.api_handler_exceptions import TableAlreadyExists, TableNotFound
from mindsdb.integrations.libs.response import (
HandlerResponse as Response,
RESPONSE_TYPE
)
class FuncParser:
def from_string(self, query_string):
body = py_ast.parse(query_string.strip(), mode='eval').body
if not isinstance(body, py_ast.Call):
raise RuntimeError(f'Api function not found {query_string}')
fnc_name = body.func.id
params = {}
for keyword in body.keywords:
name = keyword.arg
value = self.process(keyword.value)
params[name] = value
return fnc_name, params
def process(self, node):
if isinstance(node, py_ast.List):
elements = []
for node2 in node.elts:
elements.append(self.process(node2))
return elements
if isinstance(node, py_ast.Dict):
keys = []
for node2 in node.keys:
if isinstance(node2, py_ast.Constant):
value = node2.value
elif isinstance(node2, py_ast.Str): # py37
value = node2.s
else:
raise NotImplementedError(f'Unknown dict key {node2}')
keys.append(value)
values = []
for node2 in node.values:
values.append(self.process(node2))
return dict(zip(keys, values))
if isinstance(node, py_ast.Name):
# special attributes
name = node.id
if name == 'true':
return True
elif name == 'false':
return False
elif name == 'null':
return None
if isinstance(node, py_ast.Constant):
return node.value
# ---- python 3.7 objects -----
if isinstance(node, py_ast.Str):
return node.s
if isinstance(node, py_ast.Num):
return node.n
# -----------------------------
if isinstance(node, py_ast.UnaryOp):
if isinstance(node.op, py_ast.USub):
value = self.process(node.operand)
return -value
raise NotImplementedError(f'Unknown node {node}')
class APITable():
def __init__(self, handler):
self.handler = handler
def select(self, query: Select) -> pd.DataFrame:
"""Receive query as AST (abstract syntax tree) and act upon it.
Args:
query (ASTNode): sql query represented as AST. Usually it should be ast.Select
Returns:
pd.DataFrame
"""
raise NotImplementedError()
def insert(self, query: Insert) -> None:
"""Receive query as AST (abstract syntax tree) and act upon it somehow.
Args:
query (ASTNode): sql query represented as AST. Usually it should be ast.Insert
Returns:
None
"""
raise NotImplementedError()
def update(self, query: ASTNode) -> None:
"""Receive query as AST (abstract syntax tree) and act upon it somehow.
Args:
query (ASTNode): sql query represented as AST. Usually it should be ast.Update
Returns:
None
"""
raise NotImplementedError()
def delete(self, query: ASTNode) -> None:
"""Receive query as AST (abstract syntax tree) and act upon it somehow.
Args:
query (ASTNode): sql query represented as AST. Usually it should be ast.Delete
Returns:
None
"""
raise NotImplementedError()
def get_columns(self) -> list:
"""Maps the columns names from the API call resource
Returns:
List
"""
raise NotImplementedError()
class APIResource(APITable):
def select(self, query: Select) -> pd.DataFrame:
"""Receive query as AST (abstract syntax tree) and act upon it.
Args:
query (ASTNode): sql query represented as AST. Usually it should be ast.Select
Returns:
pd.DataFrame
"""
conditions = [
FilterCondition(i[1], FilterOperator(i[0].upper()), i[2])
for i in extract_comparison_conditions(query.where)
]
limit = None
if query.limit:
limit = query.limit.value
sort = None
if query.order_by and len(query.order_by) > 0:
sort = []
for an_order in query.order_by:
sort.append(SortColumn(an_order.field.parts[-1],
an_order.direction.upper() != 'DESC'))
targets = []
for col in query.targets:
if isinstance(col, Identifier):
targets.append(col.parts[-1])
result = self.list(
conditions=conditions,
limit=limit,
sort=sort,
targets=targets
)
filters = []
for cond in conditions:
if not cond.applied:
filters.append([cond.op.value, cond.column, cond.value])
result = filter_dataframe(result, filters)
if limit is not None and len(result) > limit:
result = result[:int(limit)]
return result
def list(self,
conditions: List[FilterCondition] = None,
limit: int = None,
sort: List[SortColumn] = None,
targets: List[str] = None
):
"""
List items based on specified conditions, limits, sorting, and targets.
Args:
conditions (List[FilterCondition]): Optional. A list of conditions to filter the items. Each condition
should be an instance of the FilterCondition class.
limit (int): Optional. An integer to limit the number of items to be listed.
sort (List[SortColumn]): Optional. A list of sorting criteria
targets (List[str]): Optional. A list of strings representing specific fields
Raises:
NotImplementedError: This is an abstract method and should be implemented in a subclass.
"""
raise NotImplementedError()
def insert(self, query: Insert) -> None:
"""Receive query as AST (abstract syntax tree) and act upon it somehow.
Args:
query (ASTNode): sql query represented as AST. Usually it should be ast.Insert
Returns:
None
"""
columns = [col.name for col in query.columns]
for a_row in query.values:
row = dict(zip(columns, a_row))
self.add(row)
def add(self, row: dict):
"""
Add a single item to the dataa collection
Args:
r ow (dict): A dictionary representing the item to be added.
Raises:
NotImplementedError: This is an abstract method and should be implemented in a subclass.
"""
raise NotImplementedError()
class APIHandler(BaseHandler):
"""
Base class for handlers associated to the applications APIs (e.g. twitter, slack, discord etc.)
"""
def __init__(self, name: str):
super().__init__(name)
""" constructor
Args:
name (str): the handler name
"""
self._tables = {}
def _register_table(self, table_name: str, table_class: Any):
"""
Register the data resource. For e.g if you are using Twitter API it registers the `tweets` resource from `/api/v2/tweets`.
"""
if table_name in self._tables:
raise TableAlreadyExists(f"Table with name {table_name} already exists for this handler")
self._tables[table_name] = table_class
def _get_table(self, name: Identifier):
"""
Check if the table name was added to the the _register_table
Args:
name (Identifier): the table name
"""
name = name.parts[-1]
if name not in self._tables:
raise TableNotFound(f'Table not found: {name}')
return self._tables[name]
def query(self, query: ASTNode):
if isinstance(query, Select):
table = self._get_table(query.from_table)
if not hasattr(table, 'list'):
# for back compatibility, targets wasn't passed in previous version
query.targets = [Star()]
result = self._get_table(query.from_table).select(query)
elif isinstance(query, Update):
result = self._get_table(query.table).update(query)
elif isinstance(query, Insert):
result = self._get_table(query.table).insert(query)
elif isinstance(query, Delete):
result = self._get_table(query.table).delete(query)
else:
raise NotImplementedError
if result is None:
return Response(RESPONSE_TYPE.OK)
elif isinstance(result, pd.DataFrame):
return Response(RESPONSE_TYPE.TABLE, result)
else:
raise NotImplementedError
def get_columns(self, table_name: str) -> Response:
"""
Returns a list of entity columns
Args:
table_name (str): the table name
Returns:
RESPONSE_TYPE.TABLE
"""
result = self._get_table(Identifier(table_name)).get_columns()
df = pd.DataFrame(result, columns=['Field'])
df['Type'] = 'str'
return Response(RESPONSE_TYPE.TABLE, df)
def get_tables(self) -> Response:
"""
Return list of entities
Returns:
RESPONSE_TYPE.TABLE
"""
result = list(self._tables.keys())
df = pd.DataFrame(result, columns=['table_name'])
df['table_type'] = 'BASE TABLE'
return Response(RESPONSE_TYPE.TABLE, df)
class APIChatHandler(APIHandler):
def get_chat_config(self):
"""Return configuration to connect to chatbot
Returns:
Dict
"""
raise NotImplementedError()
def get_my_user_name(self) -> list:
"""Return configuration to connect to chatbot
Returns:
Dict
"""
raise NotImplementedError()