9cb90051037c91770f7b10af62dc7ea21435e5e1
[datasette-pytables.git] / datasette_pytables / __init__.py
1 import tables
2 import datasette_connectors as dc
3 from .utils import parse_sql
4
5
6 class PyTablesConnection(dc.Connection):
7     def __init__(self, path, connector):
8         super().__init__(path, connector)
9         self.h5file = tables.open_file(path)
10
11
12 class PyTablesConnector(dc.Connector):
13     connector_type = 'pytables'
14     connection_class = PyTablesConnection
15
16     operators = {
17         'eq': '==',
18         'neq': '!=',
19         'gt': '>',
20         'gte': '>=',
21         'lt': '<',
22         'lte': '<=',
23         'and': '&',
24         'or': '|',
25         'binary_and': '&',
26         'binary_or': '|',
27     }
28
29     def table_names(self):
30         return [
31             node._v_pathname
32             for node in self.conn.h5file
33             if not(isinstance(node, tables.group.Group))
34         ]
35
36     def table_count(self, table_name):
37         table = self.conn.h5file.get_node(table_name)
38         return int(table.nrows)
39
40     def table_info(self, table_name):
41         table = self.conn.h5file.get_node(table_name)
42         colnames = ['value']
43         if isinstance(table, tables.table.Table):
44             colnames = table.colnames
45
46         return [
47             {
48                 'idx': idx,
49                 'name': colname,
50                 'primary_key': False,
51             }
52             for idx, colname in enumerate(colnames)
53         ]
54
55     def hidden_table_names(self):
56         return []
57
58     def detect_spatialite(self):
59         return False
60
61     def view_names(self):
62         return []
63
64     def detect_fts(self, table_name):
65         return False
66
67     def foreign_keys(self, table_name):
68         return []
69
70     def table_exists(self, table_name):
71         try:
72             self.conn.h5file.get_node(table_name)
73             return True
74         except:
75             return False
76
77     def table_definition(self, table_type, table_name):
78         table = self.conn.h5file.get_node(table_name)
79         colnames = ['value']
80         if isinstance(table, tables.table.Table):
81             colnames = table.colnames
82
83         return 'CREATE TABLE {} ({})'.format(
84             table_name,
85             ', '.join(colnames),
86         )
87
88     def indices_definition(self, table_name):
89         return []
90
91     def execute(
92         self,
93         sql,
94         params=None,
95         truncate=False,
96         custom_time_limit=None,
97         page_size=None,
98         log_sql_errors=True,
99     ):
100         results = []
101         truncated = False
102         description = ()
103
104         parsed_sql = parse_sql(sql, params)
105
106         while isinstance(parsed_sql['from'], dict):
107             # Pytables does not support subqueries
108             parsed_sql['from'] = parsed_sql['from']['value']['from']
109
110         table = self.conn.h5file.get_node(parsed_sql['from'])
111         table_rows = []
112         fields = parsed_sql['select']
113         colnames = ['value']
114         if type(table) is tables.table.Table:
115             colnames = table.colnames
116
117         query = ''
118         start = 0
119         end = table.nrows
120
121         def _get_field_type(field):
122             coltype = table.dtype.name
123             if type(table) is tables.table.Table:
124                 coltype = table.coltypes[field]
125             return coltype
126
127         # Use 'where' statement or get all the rows
128         def _cast_param(field, pname):
129             # Cast value to the column type
130             coltype = _get_field_type(field)
131             fcast = None
132             if coltype == 'string':
133                 fcast = str
134             elif coltype.startswith('int'):
135                 fcast = int
136             elif coltype.startswith('float'):
137                 fcast = float
138             if fcast:
139                 params[pname] = fcast(params[pname])
140
141         def _translate_where(where):
142             # Translate SQL to PyTables expression
143             nonlocal start, end
144             expr = ''
145             operator = list(where)[0]
146
147             if operator in ['and', 'or']:
148                 subexpr = [_translate_where(e) for e in where[operator]]
149                 subexpr = filter(lambda e: e, subexpr)
150                 subexpr = ["({})".format(e) for e in subexpr]
151                 expr = " {} ".format(self.operators[operator]).join(subexpr)
152             elif operator == 'exists':
153                 pass
154             elif where == {'eq': ['rowid', 'p0']}:
155                 start = int(params['p0'])
156                 end = start + 1
157             elif where == {'gt': ['rowid', 'p0']}:
158                 start = int(params['p0']) + 1
159             else:
160                 left, right = where[operator]
161
162                 if isinstance(left, dict):
163                     left = "(" + _translate_where(left) + ")"
164                 elif left in params:
165                     _cast_param(right, left)
166
167                 if isinstance(right, dict):
168                     right = "(" + _translate_where(right) + ")"
169                 elif right in params:
170                     _cast_param(left, right)
171
172                 expr = "{left} {operator} {right}".format(
173                     left=left,
174                     operator=self.operators.get(operator, operator),
175                     right=right,
176                 )
177
178             return expr
179
180         if 'where' in parsed_sql:
181             if type(parsed_sql['where']) is dict:
182                 query = _translate_where(parsed_sql['where'])
183             else:
184                 query = parsed_sql['where']
185
186         # Sort by column
187         orderby = ''
188         if 'orderby' in parsed_sql:
189             orderby = parsed_sql['orderby']
190             if type(orderby) is list:
191                 orderby = orderby[0]
192             orderby = orderby['value']
193             if orderby == 'rowid':
194                 orderby = ''
195
196         # Limit number of rows
197         limit = None
198         if 'limit' in parsed_sql:
199             limit = int(parsed_sql['limit'])
200
201         # Truncate if needed
202         if page_size and max_returned_rows and truncate:
203             if max_returned_rows == page_size:
204                 max_returned_rows += 1
205
206         # Execute query
207         if query:
208             if not ' glob ' in query:
209                 table_rows = table.where(query, params, start, end)
210         elif orderby:
211             table_rows = table.itersorted(orderby, start=start, stop=end)
212         else:
213             table_rows = table.iterrows(start, end)
214
215         # Prepare rows
216         def normalize_field_value(value):
217             if type(value) is bytes:
218                 return value.decode('utf-8')
219             elif not type(value) in (int, float, complex):
220                 return str(value)
221             else:
222                 return value
223
224         def make_get_rowid():
225             if type(table) is tables.table.Table:
226                 def get_rowid(row):
227                     return int(row.nrow)
228             else:
229                 rowid = start - 1
230                 def get_rowid(row):
231                     nonlocal rowid
232                     rowid += 1
233                     return rowid
234             return get_rowid
235
236         def make_get_row_value():
237             if type(table) is tables.table.Table:
238                 def get_row_value(row, field):
239                     return row[field]
240             else:
241                 def get_row_value(row, field):
242                     return row
243             return get_row_value
244
245         # Get results
246         get_rowid = make_get_rowid()
247         get_row_value = make_get_row_value()
248         count = 0
249         for table_row in table_rows:
250             count += 1
251             if limit is not None and count > limit:
252                 break
253             if truncate and max_returned_rows and count > max_returned_rows:
254                 truncated = True
255                 break
256             row = {}
257             for field in fields:
258                 field_name = field
259                 if isinstance(field, dict):
260                     field_name = field['value']
261                 if isinstance(field_name, dict) and 'distinct' in field_name:
262                     field_name = field_name['distinct']
263                 if field_name == 'rowid':
264                     row['rowid'] = get_rowid(table_row)
265                 elif field_name == '*':
266                     for col in colnames:
267                         row[col] = normalize_field_value(get_row_value(table_row, col))
268                 elif isinstance(field_name, dict):
269                     if field_name.get('count') == '*':
270                         row['count(*)'] = int(table.nrows)
271                     elif field_name.get('json_type'):
272                         field_name = field_name.get('json_type')
273                         row['json_type(' + field_name + ')'] = _get_field_type(field)
274                     else:
275                         raise Exception("Function not recognized")
276                 else:
277                     row[field_name] = normalize_field_value(get_row_value(table_row, field_name))
278             results.append(row)
279
280         # Prepare query description
281         for field in [f['value'] if isinstance(f, dict) else f for f in fields]:
282             if field == '*':
283                 for col in colnames:
284                     description += ((col,),)
285             else:
286                 description += ((field,),)
287
288         return results, truncated, description