Support PyTables expressions using the new parser
[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)
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):
75         if params is None:
76             params = {}
77         rows = []
78         truncated = False
79         description = []
80
81         parsed_sql = _parse_sql(sql, params)
82         table = self.h5file.get_node(parsed_sql['from'])
83         table_rows = []
84         fields = parsed_sql['select']
85
86         query = ''
87         start = 0
88         end = table.nrows
89
90         # Use 'where' statement or get all the rows
91         def _cast_param(field, pname):
92             # Cast value to the column type
93             coltype = table.coltypes[field]
94             fcast = None
95             if coltype == 'string':
96                 fcast = str
97             elif coltype.startswith('int'):
98                 fcast = int
99             elif coltype.startswith('float'):
100                 fcast = float
101             if fcast:
102                 params[pname] = fcast(params[pname])
103
104         def _translate_where(where):
105             # Translate SQL to PyTables expression
106             expr = ''
107             operator = list(where)[0]
108
109             if operator in ['and', 'or']:
110                 subexpr = ["({})".format(_translate_where(q)) for q in where[operator]]
111                 expr = " {} ".format(_operators[operator]).join(subexpr)
112             elif where == {'eq': ['rowid', 'p0']}:
113                 nonlocal start, end
114                 start = int(params['p0'])
115                 end = start + 1
116             else:
117                 left, right = where[operator]
118                 if left in params:
119                     _cast_param(right, left)
120                 elif right in params:
121                     _cast_param(left, right)
122
123                 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
124
125             return expr
126
127         if 'where' in parsed_sql:
128             if type(parsed_sql['where']) is dict:
129                 query = _translate_where(parsed_sql['where'])
130             else:
131                 query = parsed_sql['where']
132
133         # Limit number of rows
134         if 'limit' in parsed_sql:
135             max_rows = int(parsed_sql['limit'])
136             if end - start > max_rows:
137                 end = start + max_rows
138
139         # Execute query
140         if query:
141             table_rows = table.where(query, params, start, end)
142         else:
143             table_rows = table.iterrows(start, end)
144
145         # Prepare rows
146         if len(fields) == 1 and type(fields[0]['value']) is dict and \
147            fields[0]['value'].get('count') == '*':
148             rows.append(Row({'count(*)': int(table.nrows)}))
149         else:
150             for table_row in table_rows:
151                 row = Row()
152                 for field in fields:
153                     if field['value'] == 'rowid':
154                         row['rowid'] = int(table_row.nrow)
155                     elif field['value'] == '*':
156                         for col in table.colnames:
157                             value = table_row[col]
158                             if type(value) is bytes:
159                                 value = value.decode('utf-8')
160                             row[col] = value
161                     else:
162                         row[field['value']] = table_row[field['value']]
163                 rows.append(row)
164
165         # Prepare query description
166         for field in [f['value'] for f in fields]:
167             if field == '*':
168                 for col in table.colnames:
169                     description.append((col,))
170             else:
171                 description.append((field,))
172
173         # Return the rows
174         if truncate:
175             return rows, truncated, tuple(description)
176         else:
177             return rows
178
179 class Row(OrderedDict):
180     def __getitem__(self, label):
181         if type(label) is int:
182             return super(OrderedDict, self).__getitem__(list(self.keys())[label])
183         else:
184             return super(OrderedDict, self).__getitem__(label)
185
186     def __iter__(self):
187         return self.values().__iter__()