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):
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 coltype = table.coltypes[field]
99 if coltype == 'string':
101 elif coltype.startswith('int'):
103 elif coltype.startswith('float'):
106 params[pname] = fcast(params[pname])
108 def _translate_where(where):
109 # Translate SQL to PyTables expression
111 operator = list(where)[0]
113 if operator in ['and', 'or']:
114 subexpr = [_translate_where(e) for e in where[operator]]
115 subexpr = filter(lambda e: e, subexpr)
116 subexpr = ["({})".format(e) for e in subexpr]
117 expr = " {} ".format(_operators[operator]).join(subexpr)
118 elif operator == 'exists':
120 elif where == {'eq': ['rowid', 'p0']}:
122 start = int(params['p0'])
125 left, right = where[operator]
127 _cast_param(right, left)
128 elif right in params:
129 _cast_param(left, right)
131 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
135 if 'where' in parsed_sql:
136 if type(parsed_sql['where']) is dict:
137 query = _translate_where(parsed_sql['where'])
139 query = parsed_sql['where']
141 # Limit number of rows
142 if 'limit' in parsed_sql:
143 max_rows = int(parsed_sql['limit'])
144 if end - start > max_rows:
145 end = start + max_rows
148 if page_size and truncate:
149 if end - start > page_size:
150 end = start + page_size
155 table_rows = table.where(query, params, start, end)
157 table_rows = table.iterrows(start, end)
160 if len(fields) == 1 and type(fields[0]['value']) is dict and \
161 fields[0]['value'].get('count') == '*':
162 rows.append(Row({'count(*)': int(table.nrows)}))
164 if type(table) is tables.table.Table:
165 for table_row in table_rows:
168 field_name = field['value']
169 if type(field_name) is dict and 'distinct' in field_name:
170 field_name = field_name['distinct']
171 if field_name == 'rowid':
172 row['rowid'] = int(table_row.nrow)
173 elif field_name == '*':
174 for col in table.colnames:
175 value = table_row[col]
176 if type(value) is bytes:
177 value = value.decode('utf-8')
180 row[field_name] = table_row[field_name]
185 for table_row in table_rows:
189 field_name = field['value']
190 if type(field_name) is dict and 'distinct' in field_name:
191 field_name = field_name['distinct']
192 if field_name == 'rowid':
196 if type(value) is bytes:
197 value = value.decode('utf-8')
201 # Prepare query description
202 for field in [f['value'] for f in fields]:
204 if type(table) is tables.table.Table:
205 for col in table.colnames:
206 description.append((col,))
208 description.append(('value',))
210 description.append((field,))
214 return rows, truncated, tuple(description)
218 def _execute_datasette_query(self, sql, params):
219 "Datasette special queries for getting tables info"
220 if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
224 elif sql == 'select sql from sqlite_master where name = :n and type="table"':
226 table = self.h5file.get_node(params['n'])
228 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
233 raise Exception("SQLite queries cannot be executed with this connector")
235 class Row(OrderedDict):
236 def __getitem__(self, label):
237 if type(label) is int:
238 return super(OrderedDict, self).__getitem__(list(self.keys())[label])
240 return super(OrderedDict, self).__getitem__(label)
243 return self.values().__iter__()