1 from collections import OrderedDict
2 from moz_sql_parser import parse
6 _connector_type = 'pytables'
9 "Open file and return tables info"
12 h5file = tables.open_file(path)
14 for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
16 if isinstance(table, tables.table.Table):
17 colnames = table.colnames
19 h5tables[table._v_pathname] = {
20 'name': table._v_pathname,
23 'count': int(table.nrows),
27 'foreign_keys': {'incoming': [], 'outgoing': []},
31 return h5tables, views, _connector_type
33 def _parse_sql(sql, params):
35 sql = re.sub('(?i)from \[(.*)]', 'from "\g<1>"', sql)
38 sql = sql.replace(":" + param, param)
43 # Propably it's a PyTables expression
44 for token in ['group by', 'order by', 'limit', '']:
45 res = re.search('(?i)where (.*)' + token, sql)
47 modified_sql = re.sub('(?i)where (.*)(' + token + ')', '\g<2>', sql)
48 parsed = parse(modified_sql)
49 parsed['where'] = res.group(1).strip()
52 # Always a list of fields
53 if type(parsed['select']) is not list:
54 parsed['select'] = [parsed['select']]
70 def __init__(self, path):
72 self.h5file = tables.open_file(path)
74 def execute(self, sql, params=None, truncate=False, page_size=None, max_returned_rows=None):
81 parsed_sql = _parse_sql(sql, params)
83 if parsed_sql['from'] == 'sqlite_master':
84 return self._execute_datasette_query(sql, params)
86 table = self.h5file.get_node(parsed_sql['from'])
88 fields = parsed_sql['select']
94 # Use 'where' statement or get all the rows
95 def _cast_param(field, pname):
96 # Cast value to the column type
97 if type(table) is tables.table.Table:
98 coltype = table.coltypes[field]
100 coltype = table.dtype.name
102 if coltype == 'string':
104 elif coltype.startswith('int'):
106 elif coltype.startswith('float'):
109 params[pname] = fcast(params[pname])
111 def _translate_where(where):
112 # Translate SQL to PyTables expression
115 operator = list(where)[0]
117 if operator in ['and', 'or']:
118 subexpr = [_translate_where(e) for e in where[operator]]
119 subexpr = filter(lambda e: e, subexpr)
120 subexpr = ["({})".format(e) for e in subexpr]
121 expr = " {} ".format(_operators[operator]).join(subexpr)
122 elif operator == 'exists':
124 elif where == {'eq': ['rowid', 'p0']}:
125 start = int(params['p0'])
127 elif where == {'gt': ['rowid', 'p0']}:
128 start = int(params['p0']) + 1
130 left, right = where[operator]
132 _cast_param(right, left)
133 elif right in params:
134 _cast_param(left, right)
136 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
140 if 'where' in parsed_sql:
141 if type(parsed_sql['where']) is dict:
142 query = _translate_where(parsed_sql['where'])
144 query = parsed_sql['where']
146 # Limit number of rows
147 if 'limit' in parsed_sql:
148 max_rows = int(parsed_sql['limit'])
149 if end - start > max_rows:
150 end = start + max_rows
153 if page_size and max_returned_rows and truncate:
154 if max_returned_rows == page_size:
155 max_returned_rows += 1
156 if end - start > max_returned_rows:
157 end = start + max_returned_rows
162 table_rows = table.where(query, params, start, end)
164 table_rows = table.iterrows(start, end)
167 if len(fields) == 1 and type(fields[0]['value']) is dict and \
168 fields[0]['value'].get('count') == '*':
169 rows.append(Row({'count(*)': int(table.nrows)}))
171 if type(table) is tables.table.Table:
172 for table_row in table_rows:
175 field_name = field['value']
176 if type(field_name) is dict and 'distinct' in field_name:
177 field_name = field_name['distinct']
178 if field_name == 'rowid':
179 row['rowid'] = int(table_row.nrow)
180 elif field_name == '*':
181 for col in table.colnames:
182 value = table_row[col]
183 if type(value) is bytes:
184 value = value.decode('utf-8')
187 row[field_name] = table_row[field_name]
192 for table_row in table_rows:
196 field_name = field['value']
197 if type(field_name) is dict and 'distinct' in field_name:
198 field_name = field_name['distinct']
199 if field_name == 'rowid':
203 if type(value) is bytes:
204 value = value.decode('utf-8')
208 # Prepare query description
209 for field in [f['value'] for f in fields]:
211 if type(table) is tables.table.Table:
212 for col in table.colnames:
213 description.append((col,))
215 description.append(('value',))
217 description.append((field,))
221 return rows, truncated, tuple(description)
225 def _execute_datasette_query(self, sql, params):
226 "Datasette special queries for getting tables info"
227 if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
231 elif sql == 'select sql from sqlite_master where name = :n and type="table"':
233 table = self.h5file.get_node(params['n'])
235 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
240 raise Exception("SQLite queries cannot be executed with this connector")
243 def __init__(self, values=None):
248 self.__setitem__(idx, values[idx])
250 def __setitem__(self, idx, value):
252 if idx in self.labels:
253 self.values[self.labels.index(idx)] = value
255 self.labels.append(idx)
256 self.values.append(value)
258 self.values[idx] = value
260 def __getitem__(self, idx):
262 return self.values[self.labels.index(idx)]
264 return self.values[idx]
267 return self.values.__iter__()