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