]> git.jsancho.org Git - datasette-pytables.git/blob - datasette_pytables/__init__.py
Truncate query results according to page_size limit
[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         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         # Truncate if needed
144         if page_size and truncate:
145             if end - start > page_size:
146                 end = start + page_size
147                 truncated = True
148
149         # Execute query
150         if query:
151             table_rows = table.where(query, params, start, end)
152         else:
153             table_rows = table.iterrows(start, end)
154
155         # Prepare rows
156         if len(fields) == 1 and type(fields[0]['value']) is dict and \
157            fields[0]['value'].get('count') == '*':
158             rows.append(Row({'count(*)': int(table.nrows)}))
159         else:
160             if type(table) is tables.table.Table:
161                 for table_row in table_rows:
162                     row = Row()
163                     for field in fields:
164                         field_name = field['value']
165                         if type(field_name) is dict and 'distinct' in field_name:
166                             field_name = field_name['distinct']
167                         if field_name == 'rowid':
168                             row['rowid'] = int(table_row.nrow)
169                         elif field_name == '*':
170                             for col in table.colnames:
171                                 value = table_row[col]
172                                 if type(value) is bytes:
173                                     value = value.decode('utf-8')
174                                 row[col] = value
175                         else:
176                             row[field_name] = table_row[field_name]
177                     rows.append(row)
178             else:
179                 # Any kind of array
180                 rowid = start - 1
181                 for table_row in table_rows:
182                     row = Row()
183                     rowid += 1
184                     for field in fields:
185                         field_name = field['value']
186                         if type(field_name) is dict and 'distinct' in field_name:
187                             field_name = field_name['distinct']
188                         if field_name == 'rowid':
189                             row['rowid'] = rowid
190                         else:
191                             value = table_row
192                             if type(value) is bytes:
193                                 value = value.decode('utf-8')
194                             row['value'] = value
195                     rows.append(row)
196
197         # Prepare query description
198         for field in [f['value'] for f in fields]:
199             if field == '*':
200                 if type(table) is tables.table.Table:
201                     for col in table.colnames:
202                         description.append((col,))
203                 else:
204                     description.append(('value',))
205             else:
206                 description.append((field,))
207
208         # Return the rows
209         if truncate:
210             return rows, truncated, tuple(description)
211         else:
212             return rows
213
214 class Row(OrderedDict):
215     def __getitem__(self, label):
216         if type(label) is int:
217             return super(OrderedDict, self).__getitem__(list(self.keys())[label])
218         else:
219             return super(OrderedDict, self).__getitem__(label)
220
221     def __iter__(self):
222         return self.values().__iter__()