]> git.jsancho.org Git - datasette-pytables.git/blob - datasette_pytables/__init__.py
Test for custom query
[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):
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 = [_translate_where(e) for e in where[operator]]
111                 subexpr = filter(lambda e: e, subexpr)
112                 subexpr = ["({})".format(e) for e in subexpr]
113                 expr = " {} ".format(_operators[operator]).join(subexpr)
114             elif operator == 'exists':
115                 pass
116             elif where == {'eq': ['rowid', 'p0']}:
117                 nonlocal start, end
118                 start = int(params['p0'])
119                 end = start + 1
120             else:
121                 left, right = where[operator]
122                 if left in params:
123                     _cast_param(right, left)
124                 elif right in params:
125                     _cast_param(left, right)
126
127                 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
128
129             return expr
130
131         if 'where' in parsed_sql:
132             if type(parsed_sql['where']) is dict:
133                 query = _translate_where(parsed_sql['where'])
134             else:
135                 query = parsed_sql['where']
136
137         # Limit number of rows
138         if 'limit' in parsed_sql:
139             max_rows = int(parsed_sql['limit'])
140             if end - start > max_rows:
141                 end = start + max_rows
142
143         # Execute query
144         if query:
145             table_rows = table.where(query, params, start, end)
146         else:
147             table_rows = table.iterrows(start, end)
148
149         # Prepare rows
150         if len(fields) == 1 and type(fields[0]['value']) is dict and \
151            fields[0]['value'].get('count') == '*':
152             rows.append(Row({'count(*)': int(table.nrows)}))
153         else:
154             if type(table) is tables.table.Table:
155                 for table_row in table_rows:
156                     row = Row()
157                     for field in fields:
158                         field_name = field['value']
159                         if type(field_name) is dict and 'distinct' in field_name:
160                             field_name = field_name['distinct']
161                         if field_name == 'rowid':
162                             row['rowid'] = int(table_row.nrow)
163                         elif field_name == '*':
164                             for col in table.colnames:
165                                 value = table_row[col]
166                                 if type(value) is bytes:
167                                     value = value.decode('utf-8')
168                                 row[col] = value
169                         else:
170                             row[field_name] = table_row[field_name]
171                     rows.append(row)
172             else:
173                 # Any kind of array
174                 rowid = start - 1
175                 for table_row in table_rows:
176                     row = Row()
177                     rowid += 1
178                     for field in fields:
179                         field_name = field['value']
180                         if type(field_name) is dict and 'distinct' in field_name:
181                             field_name = field_name['distinct']
182                         if field_name == 'rowid':
183                             row['rowid'] = rowid
184                         else:
185                             value = table_row
186                             if type(value) is bytes:
187                                 value = value.decode('utf-8')
188                             row['value'] = value
189                     rows.append(row)
190
191         # Prepare query description
192         for field in [f['value'] for f in fields]:
193             if field == '*':
194                 if type(table) is tables.table.Table:
195                     for col in table.colnames:
196                         description.append((col,))
197                 else:
198                     description.append(('value',))
199             else:
200                 description.append((field,))
201
202         # Return the rows
203         if truncate:
204             return rows, truncated, tuple(description)
205         else:
206             return rows
207
208 class Row(OrderedDict):
209     def __getitem__(self, label):
210         if type(label) is int:
211             return super(OrderedDict, self).__getitem__(list(self.keys())[label])
212         else:
213             return super(OrderedDict, self).__getitem__(label)
214
215     def __iter__(self):
216         return self.values().__iter__()