80349a6f918cb5eb58728785bca258a69a42a9ce
[datasette-pytables.git] / datasette_pytables / __init__.py
1 from moz_sql_parser import parse
2 import re
3 import tables
4
5 _connector_type = 'pytables'
6
7 def inspect(path):
8     "Open file and return tables info"
9     h5tables = {}
10     views = []
11     h5file = tables.open_file(path)
12
13     for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
14         colnames = []
15         if isinstance(table, tables.table.Table):
16             colnames = table.colnames
17
18         h5tables[table._v_pathname] = {
19             'name': table._v_pathname,
20             'columns': colnames,
21             'primary_keys': [],
22             'count': int(table.nrows),
23             'label_column': None,
24             'hidden': False,
25             'fts_table': None,
26             'foreign_keys': {'incoming': [], 'outgoing': []},
27         }
28
29     h5file.close()
30     return h5tables, views, _connector_type
31
32 def _parse_sql(sql, params):
33     # Table name
34     sql = re.sub('(?i)from \[(.*)]', 'from "\g<1>"', sql)
35     # Params
36     for param in params:
37         sql = sql.replace(":" + param, param)
38
39     try:
40         parsed = parse(sql)
41     except:
42         # Propably it's a PyTables expression
43         for token in ['group by', 'order by', 'limit', '']:
44             res = re.search('(?i)where (.*)' + token, sql)
45             if res:
46                 modified_sql = re.sub('(?i)where (.*)(' + token + ')', '\g<2>', sql)
47                 parsed = parse(modified_sql)
48                 parsed['where'] = res.group(1).strip()
49                 break
50
51     # Always a list of fields
52     if type(parsed['select']) is not list:
53         parsed['select'] = [parsed['select']]
54
55     return parsed
56
57 _operators = {
58     'eq': '==',
59     'neq': '!=',
60     'gt': '>',
61     'gte': '>=',
62     'lt': '<',
63     'lte': '<=',
64     'and': '&',
65     'or': '|',
66 }
67
68 class Connection:
69     def __init__(self, path):
70         self.path = path
71         self.h5file = tables.open_file(path)
72
73     def execute(self, sql, params=None, truncate=False, page_size=None, max_returned_rows=None):
74         if params is None:
75             params = {}
76         rows = []
77         truncated = False
78         description = []
79
80         parsed_sql = _parse_sql(sql, params)
81
82         if parsed_sql['from'] == 'sqlite_master':
83             rows = self._execute_datasette_query(sql, params)
84             description = (('value',))
85             return rows, truncated, description
86
87         table = self.h5file.get_node(parsed_sql['from'])
88         table_rows = []
89         fields = parsed_sql['select']
90
91         query = ''
92         start = 0
93         end = table.nrows
94
95         # Use 'where' statement or get all the rows
96         def _cast_param(field, pname):
97             # Cast value to the column type
98             if type(table) is tables.table.Table:
99                 coltype = table.coltypes[field]
100             else:
101                 coltype = table.dtype.name
102             fcast = None
103             if coltype == 'string':
104                 fcast = str
105             elif coltype.startswith('int'):
106                 fcast = int
107             elif coltype.startswith('float'):
108                 fcast = float
109             if fcast:
110                 params[pname] = fcast(params[pname])
111
112         def _translate_where(where):
113             # Translate SQL to PyTables expression
114             nonlocal start, end
115             expr = ''
116             operator = list(where)[0]
117
118             if operator in ['and', 'or']:
119                 subexpr = [_translate_where(e) for e in where[operator]]
120                 subexpr = filter(lambda e: e, subexpr)
121                 subexpr = ["({})".format(e) for e in subexpr]
122                 expr = " {} ".format(_operators[operator]).join(subexpr)
123             elif operator == 'exists':
124                 pass
125             elif where == {'eq': ['rowid', 'p0']}:
126                 start = int(params['p0'])
127                 end = start + 1
128             elif where == {'gt': ['rowid', 'p0']}:
129                 start = int(params['p0']) + 1
130             else:
131                 left, right = where[operator]
132                 if left in params:
133                     _cast_param(right, left)
134                 elif right in params:
135                     _cast_param(left, right)
136
137                 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
138
139             return expr
140
141         if 'where' in parsed_sql:
142             if type(parsed_sql['where']) is dict:
143                 query = _translate_where(parsed_sql['where'])
144             else:
145                 query = parsed_sql['where']
146
147         # Limit number of rows
148         limit = None
149         if 'limit' in parsed_sql:
150             limit = int(parsed_sql['limit'])
151
152         # Truncate if needed
153         if page_size and max_returned_rows and truncate:
154             if max_returned_rows == page_size:
155                 max_returned_rows += 1
156
157         # Execute query
158         if query:
159             table_rows = table.where(query, params, start, end)
160         else:
161             table_rows = table.iterrows(start, end)
162
163         # Prepare rows
164         if len(fields) == 1 and type(fields[0]['value']) is dict and \
165            fields[0]['value'].get('count') == '*':
166             rows.append(Row({'count(*)': int(table.nrows)}))
167         else:
168             if type(table) is tables.table.Table:
169                 count = 0
170                 for table_row in table_rows:
171                     count += 1
172                     if limit and count > limit:
173                         break
174                     if truncate and max_returned_rows and count > max_returned_rows:
175                         truncated = True
176                         break
177                     row = Row()
178                     for field in fields:
179                         field_name = field['value']
180                         if type(field_name) is dict and 'distinct' in field_name:
181                             field_name = field_name['distinct']
182                         if field_name == 'rowid':
183                             row['rowid'] = int(table_row.nrow)
184                         elif field_name == '*':
185                             for col in table.colnames:
186                                 value = table_row[col]
187                                 if type(value) is bytes:
188                                     value = value.decode('utf-8')
189                                 row[col] = value
190                         else:
191                             row[field_name] = table_row[field_name]
192                     rows.append(row)
193             else:
194                 # Any kind of array
195                 rowid = start - 1
196                 count = 0
197                 for table_row in table_rows:
198                     count += 1
199                     if limit and count > limit:
200                         break
201                     if truncate and max_returned_rows and count > max_returned_rows:
202                         truncated = True
203                         break
204                     row = Row()
205                     rowid += 1
206                     for field in fields:
207                         field_name = field['value']
208                         if type(field_name) is dict and 'distinct' in field_name:
209                             field_name = field_name['distinct']
210                         if field_name == 'rowid':
211                             row['rowid'] = rowid
212                         else:
213                             value = table_row
214                             if type(value) is bytes:
215                                 value = value.decode('utf-8')
216                             elif not type(value) in (int, float, complex):
217                                 value = str(value)
218                             row['value'] = value
219                     rows.append(row)
220
221         # Prepare query description
222         for field in [f['value'] for f in fields]:
223             if field == '*':
224                 if type(table) is tables.table.Table:
225                     for col in table.colnames:
226                         description.append((col,))
227                 else:
228                     description.append(('value',))
229             else:
230                 description.append((field,))
231
232         # Return the rows
233         return rows, truncated, tuple(description)
234
235     def _execute_datasette_query(self, sql, params):
236         "Datasette special queries for getting tables info"
237         if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
238             row = Row()
239             row['count(*)'] = 0
240             return [row]
241         elif sql == 'select sql from sqlite_master where name = :n and type="table"':
242             try:
243                 table = self.h5file.get_node(params['n'])
244                 row = Row()
245                 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
246                 return [row]
247             except:
248                 return []
249         else:
250             raise Exception("SQLite queries cannot be executed with this connector")
251
252 class Row(list):
253     def __init__(self, values=None):
254         self.labels = []
255         self.values = []
256         if values:
257             for idx in values:
258                 self.__setitem__(idx, values[idx])
259
260     def __setitem__(self, idx, value):
261         if type(idx) is str:
262             if idx in self.labels:
263                 self.values[self.labels.index(idx)] = value
264             else:
265                 self.labels.append(idx)
266                 self.values.append(value)
267         else:
268             self.values[idx] = value
269
270     def __getitem__(self, idx):
271         if type(idx) is str:
272             return self.values[self.labels.index(idx)]
273         else:
274             return self.values[idx]
275
276     def __iter__(self):
277         return self.values.__iter__()