1 from moz_sql_parser import parse
5 _connector_type = 'pytables'
8 "Open file and return tables info"
11 h5file = tables.open_file(path)
13 for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
15 if isinstance(table, tables.table.Table):
16 colnames = table.colnames
18 h5tables[table._v_pathname] = {
19 'name': table._v_pathname,
22 'count': int(table.nrows),
26 'foreign_keys': {'incoming': [], 'outgoing': []},
30 return h5tables, views, _connector_type
32 def _parse_sql(sql, params):
34 sql = re.sub('(?i)from \[(.*)]', 'from "\g<1>"', sql)
37 sql = sql.replace(":" + param, param)
42 # Propably it's a PyTables expression
43 for token in ['group by', 'order by', 'limit', '']:
44 res = re.search('(?i)where (.*)' + token, sql)
46 modified_sql = re.sub('(?i)where (.*)(' + token + ')', '\g<2>', sql)
47 parsed = parse(modified_sql)
48 parsed['where'] = res.group(1).strip()
51 # Always a list of fields
52 if type(parsed['select']) is not list:
53 parsed['select'] = [parsed['select']]
69 def __init__(self, path):
71 self.h5file = tables.open_file(path)
73 def execute(self, sql, params=None, truncate=False, page_size=None, max_returned_rows=None):
80 parsed_sql = _parse_sql(sql, params)
82 if parsed_sql['from'] == 'sqlite_master':
83 return self._execute_datasette_query(sql, params)
85 table = self.h5file.get_node(parsed_sql['from'])
87 fields = parsed_sql['select']
93 # Use 'where' statement or get all the rows
94 def _cast_param(field, pname):
95 # Cast value to the column type
96 if type(table) is tables.table.Table:
97 coltype = table.coltypes[field]
99 coltype = table.dtype.name
101 if coltype == 'string':
103 elif coltype.startswith('int'):
105 elif coltype.startswith('float'):
108 params[pname] = fcast(params[pname])
110 def _translate_where(where):
111 # Translate SQL to PyTables expression
114 operator = list(where)[0]
116 if operator in ['and', 'or']:
117 subexpr = [_translate_where(e) for e in where[operator]]
118 subexpr = filter(lambda e: e, subexpr)
119 subexpr = ["({})".format(e) for e in subexpr]
120 expr = " {} ".format(_operators[operator]).join(subexpr)
121 elif operator == 'exists':
123 elif where == {'eq': ['rowid', 'p0']}:
124 start = int(params['p0'])
126 elif where == {'gt': ['rowid', 'p0']}:
127 start = int(params['p0']) + 1
129 left, right = where[operator]
131 _cast_param(right, left)
132 elif right in params:
133 _cast_param(left, right)
135 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
139 if 'where' in parsed_sql:
140 if type(parsed_sql['where']) is dict:
141 query = _translate_where(parsed_sql['where'])
143 query = parsed_sql['where']
145 # Limit number of rows
146 if 'limit' in parsed_sql:
147 max_rows = int(parsed_sql['limit'])
148 if end - start > max_rows:
149 end = start + max_rows
152 if page_size and max_returned_rows and truncate:
153 if max_returned_rows == page_size:
154 max_returned_rows += 1
155 if end - start > max_returned_rows:
156 end = start + max_returned_rows
161 table_rows = table.where(query, params, start, end)
163 table_rows = table.iterrows(start, end)
166 if len(fields) == 1 and type(fields[0]['value']) is dict and \
167 fields[0]['value'].get('count') == '*':
168 rows.append(Row({'count(*)': int(table.nrows)}))
170 if type(table) is tables.table.Table:
171 for table_row in table_rows:
174 field_name = field['value']
175 if type(field_name) is dict and 'distinct' in field_name:
176 field_name = field_name['distinct']
177 if field_name == 'rowid':
178 row['rowid'] = int(table_row.nrow)
179 elif field_name == '*':
180 for col in table.colnames:
181 value = table_row[col]
182 if type(value) is bytes:
183 value = value.decode('utf-8')
186 row[field_name] = table_row[field_name]
191 for table_row in table_rows:
195 field_name = field['value']
196 if type(field_name) is dict and 'distinct' in field_name:
197 field_name = field_name['distinct']
198 if field_name == 'rowid':
202 if type(value) is bytes:
203 value = value.decode('utf-8')
207 # Prepare query description
208 for field in [f['value'] for f in fields]:
210 if type(table) is tables.table.Table:
211 for col in table.colnames:
212 description.append((col,))
214 description.append(('value',))
216 description.append((field,))
220 return rows, truncated, tuple(description)
224 def _execute_datasette_query(self, sql, params):
225 "Datasette special queries for getting tables info"
226 if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
230 elif sql == 'select sql from sqlite_master where name = :n and type="table"':
232 table = self.h5file.get_node(params['n'])
234 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
239 raise Exception("SQLite queries cannot be executed with this connector")
242 def __init__(self, values=None):
247 self.__setitem__(idx, values[idx])
249 def __setitem__(self, idx, value):
251 if idx in self.labels:
252 self.values[self.labels.index(idx)] = value
254 self.labels.append(idx)
255 self.values.append(value)
257 self.values[idx] = value
259 def __getitem__(self, idx):
261 return self.values[self.labels.index(idx)]
263 return self.values[idx]
266 return self.values.__iter__()