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