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