Execute return always rows, truncated, description tuple
[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         if 'limit' in parsed_sql:
149             max_rows = int(parsed_sql['limit'])
150             if end - start > max_rows:
151                 end = start + max_rows
152
153         # Truncate if needed
154         if page_size and max_returned_rows and truncate:
155             if max_returned_rows == page_size:
156                 max_returned_rows += 1
157             if end - start > max_returned_rows:
158                 end = start + max_returned_rows
159                 truncated = True
160
161         # Execute query
162         if query:
163             table_rows = table.where(query, params, start, end)
164         else:
165             table_rows = table.iterrows(start, end)
166
167         # Prepare rows
168         if len(fields) == 1 and type(fields[0]['value']) is dict and \
169            fields[0]['value'].get('count') == '*':
170             rows.append(Row({'count(*)': int(table.nrows)}))
171         else:
172             if type(table) is tables.table.Table:
173                 for table_row in table_rows:
174                     row = Row()
175                     for field in fields:
176                         field_name = field['value']
177                         if type(field_name) is dict and 'distinct' in field_name:
178                             field_name = field_name['distinct']
179                         if field_name == 'rowid':
180                             row['rowid'] = int(table_row.nrow)
181                         elif field_name == '*':
182                             for col in table.colnames:
183                                 value = table_row[col]
184                                 if type(value) is bytes:
185                                     value = value.decode('utf-8')
186                                 row[col] = value
187                         else:
188                             row[field_name] = table_row[field_name]
189                     rows.append(row)
190             else:
191                 # Any kind of array
192                 rowid = start - 1
193                 for table_row in table_rows:
194                     row = Row()
195                     rowid += 1
196                     for field in fields:
197                         field_name = field['value']
198                         if type(field_name) is dict and 'distinct' in field_name:
199                             field_name = field_name['distinct']
200                         if field_name == 'rowid':
201                             row['rowid'] = rowid
202                         else:
203                             value = table_row
204                             if type(value) is bytes:
205                                 value = value.decode('utf-8')
206                             row['value'] = value
207                     rows.append(row)
208
209         # Prepare query description
210         for field in [f['value'] for f in fields]:
211             if field == '*':
212                 if type(table) is tables.table.Table:
213                     for col in table.colnames:
214                         description.append((col,))
215                 else:
216                     description.append(('value',))
217             else:
218                 description.append((field,))
219
220         # Return the rows
221         return rows, truncated, tuple(description)
222
223     def _execute_datasette_query(self, sql, params):
224         "Datasette special queries for getting tables info"
225         if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
226             row = Row()
227             row['count(*)'] = 0
228             return [row]
229         elif sql == 'select sql from sqlite_master where name = :n and type="table"':
230             try:
231                 table = self.h5file.get_node(params['n'])
232                 row = Row()
233                 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
234                 return [row]
235             except:
236                 return []
237         else:
238             raise Exception("SQLite queries cannot be executed with this connector")
239
240 class Row(list):
241     def __init__(self, values=None):
242         self.labels = []
243         self.values = []
244         if values:
245             for idx in values:
246                 self.__setitem__(idx, values[idx])
247
248     def __setitem__(self, idx, value):
249         if type(idx) is str:
250             if idx in self.labels:
251                 self.values[self.labels.index(idx)] = value
252             else:
253                 self.labels.append(idx)
254                 self.values.append(value)
255         else:
256             self.values[idx] = value
257
258     def __getitem__(self, idx):
259         if type(idx) is str:
260             return self.values[self.labels.index(idx)]
261         else:
262             return self.values[idx]
263
264     def __iter__(self):
265         return self.values.__iter__()