Use max_returned_rows in conjuction with page_size for truncating
[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             coltype = table.coltypes[field]
98             fcast = None
99             if coltype == 'string':
100                 fcast = str
101             elif coltype.startswith('int'):
102                 fcast = int
103             elif coltype.startswith('float'):
104                 fcast = float
105             if fcast:
106                 params[pname] = fcast(params[pname])
107
108         def _translate_where(where):
109             # Translate SQL to PyTables expression
110             expr = ''
111             operator = list(where)[0]
112
113             if operator in ['and', 'or']:
114                 subexpr = [_translate_where(e) for e in where[operator]]
115                 subexpr = filter(lambda e: e, subexpr)
116                 subexpr = ["({})".format(e) for e in subexpr]
117                 expr = " {} ".format(_operators[operator]).join(subexpr)
118             elif operator == 'exists':
119                 pass
120             elif where == {'eq': ['rowid', 'p0']}:
121                 nonlocal start, end
122                 start = int(params['p0'])
123                 end = start + 1
124             else:
125                 left, right = where[operator]
126                 if left in params:
127                     _cast_param(right, left)
128                 elif right in params:
129                     _cast_param(left, right)
130
131                 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
132
133             return expr
134
135         if 'where' in parsed_sql:
136             if type(parsed_sql['where']) is dict:
137                 query = _translate_where(parsed_sql['where'])
138             else:
139                 query = parsed_sql['where']
140
141         # Limit number of rows
142         if 'limit' in parsed_sql:
143             max_rows = int(parsed_sql['limit'])
144             if end - start > max_rows:
145                 end = start + max_rows
146
147         # Truncate if needed
148         if page_size and max_returned_rows and truncate:
149             if max_returned_rows == page_size:
150                 max_returned_rows += 1
151             if end - start > max_returned_rows:
152                 end = start + max_returned_rows
153                 truncated = True
154
155         # Execute query
156         if query:
157             table_rows = table.where(query, params, start, end)
158         else:
159             table_rows = table.iterrows(start, end)
160
161         # Prepare rows
162         if len(fields) == 1 and type(fields[0]['value']) is dict and \
163            fields[0]['value'].get('count') == '*':
164             rows.append(Row({'count(*)': int(table.nrows)}))
165         else:
166             if type(table) is tables.table.Table:
167                 for table_row in table_rows:
168                     row = Row()
169                     for field in fields:
170                         field_name = field['value']
171                         if type(field_name) is dict and 'distinct' in field_name:
172                             field_name = field_name['distinct']
173                         if field_name == 'rowid':
174                             row['rowid'] = int(table_row.nrow)
175                         elif field_name == '*':
176                             for col in table.colnames:
177                                 value = table_row[col]
178                                 if type(value) is bytes:
179                                     value = value.decode('utf-8')
180                                 row[col] = value
181                         else:
182                             row[field_name] = table_row[field_name]
183                     rows.append(row)
184             else:
185                 # Any kind of array
186                 rowid = start - 1
187                 for table_row in table_rows:
188                     row = Row()
189                     rowid += 1
190                     for field in fields:
191                         field_name = field['value']
192                         if type(field_name) is dict and 'distinct' in field_name:
193                             field_name = field_name['distinct']
194                         if field_name == 'rowid':
195                             row['rowid'] = rowid
196                         else:
197                             value = table_row
198                             if type(value) is bytes:
199                                 value = value.decode('utf-8')
200                             row['value'] = value
201                     rows.append(row)
202
203         # Prepare query description
204         for field in [f['value'] for f in fields]:
205             if field == '*':
206                 if type(table) is tables.table.Table:
207                     for col in table.colnames:
208                         description.append((col,))
209                 else:
210                     description.append(('value',))
211             else:
212                 description.append((field,))
213
214         # Return the rows
215         if truncate:
216             return rows, truncated, tuple(description)
217         else:
218             return rows
219
220     def _execute_datasette_query(self, sql, params):
221         "Datasette special queries for getting tables info"
222         if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
223             row = Row()
224             row['count(*)'] = 0
225             return [row]
226         elif sql == 'select sql from sqlite_master where name = :n and type="table"':
227             try:
228                 table = self.h5file.get_node(params['n'])
229                 row = Row()
230                 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
231                 return [row]
232             except:
233                 return []
234         else:
235             raise Exception("SQLite queries cannot be executed with this connector")
236
237 class Row(list):
238     def __init__(self, values=None):
239         self.labels = []
240         self.values = []
241         if values:
242             for idx in values:
243                 self.__setitem__(idx, values[idx])
244
245     def __setitem__(self, idx, value):
246         if type(idx) is str:
247             if idx in self.labels:
248                 self.values[self.labels.index(idx)] = value
249             else:
250                 self.labels.append(idx)
251                 self.values.append(value)
252         else:
253             self.values[idx] = value
254
255     def __getitem__(self, idx):
256         if type(idx) is str:
257             return self.values[self.labels.index(idx)]
258         else:
259             return self.values[idx]
260
261     def __iter__(self):
262         return self.values.__iter__()