2 import datasette_connectors as dc
3 from .utils import parse_sql
6 class PyTablesConnection(dc.Connection):
7 def __init__(self, path, connector):
8 super().__init__(path, connector)
9 self.h5file = tables.open_file(path)
12 class PyTablesConnector(dc.Connector):
13 connector_type = 'pytables'
14 connection_class = PyTablesConnection
29 def _serialize_table_name(self, table_name):
30 return table_name.replace('/', '%')
32 def _deserialize_table_name(self, table_name):
33 return table_name.replace('%', '/')
35 def table_names(self):
37 self._serialize_table_name(node._v_pathname)
38 for node in self.conn.h5file
39 if not(isinstance(node, tables.group.Group))
42 def table_count(self, table_name):
43 table = self.conn.h5file.get_node(self._deserialize_table_name(table_name))
44 return int(table.nrows)
46 def table_info(self, table_name):
47 table = self.conn.h5file.get_node(self._deserialize_table_name(table_name))
51 'type': table.dtype.name,
54 if isinstance(table, tables.table.Table):
58 'type': table.coltypes[colname],
60 for colname in table.colnames
66 'name': column['name'],
67 'type': column['type'],
69 'default_value': None,
72 for cid, column in enumerate(columns)
75 def hidden_table_names(self):
78 def detect_spatialite(self):
84 def detect_fts(self, table_name):
87 def foreign_keys(self, table_name):
90 def table_exists(self, table_name):
92 self.conn.h5file.get_node(self._deserialize_table_name(table_name))
97 def table_definition(self, table_type, table_name):
98 table_name = self._deserialize_table_name(table_name)
99 table = self.conn.h5file.get_node(table_name)
101 if isinstance(table, tables.table.Table):
102 colnames = table.colnames
104 return 'CREATE TABLE {} ({})'.format(
109 def indices_definition(self, table_name):
117 custom_time_limit=None,
125 parsed_sql = parse_sql(sql, params)
127 while isinstance(parsed_sql['from'], dict):
128 # Pytables does not support subqueries
129 parsed_sql['from'] = parsed_sql['from']['value']['from']
131 table = self.conn.h5file.get_node(self._deserialize_table_name(parsed_sql['from']))
133 fields = parsed_sql['select']
135 if type(table) is tables.table.Table:
136 colnames = table.colnames
142 def _get_field_type(field):
143 coltype = table.dtype.name
144 if type(table) is tables.table.Table:
145 coltype = table.coltypes[field]
148 # Use 'where' statement or get all the rows
149 def _cast_param(field, pname):
150 # Cast value to the column type
151 coltype = _get_field_type(field)
153 if coltype == 'string':
155 elif coltype.startswith('int'):
157 elif coltype.startswith('float'):
160 params[pname] = fcast(params[pname])
162 def _translate_where(where):
163 # Translate SQL to PyTables expression
166 operator = list(where)[0]
168 if operator in ['and', 'or']:
169 subexpr = [_translate_where(e) for e in where[operator]]
170 subexpr = filter(lambda e: e, subexpr)
171 subexpr = ["({})".format(e) for e in subexpr]
172 expr = " {} ".format(self.operators[operator]).join(subexpr)
173 elif operator == 'exists':
175 elif where == {'eq': ['rowid', 'p0']}:
176 start = int(params['p0'])
178 elif where == {'gt': ['rowid', 'p0']}:
179 start = int(params['p0']) + 1
181 left, right = where[operator]
183 if isinstance(left, dict):
184 left = "(" + _translate_where(left) + ")"
186 _cast_param(right, left)
188 if isinstance(right, dict):
189 right = "(" + _translate_where(right) + ")"
190 elif right in params:
191 _cast_param(left, right)
193 expr = "{left} {operator} {right}".format(
195 operator=self.operators.get(operator, operator),
201 if 'where' in parsed_sql:
202 if type(parsed_sql['where']) is dict:
203 query = _translate_where(parsed_sql['where'])
205 query = parsed_sql['where']
209 if 'orderby' in parsed_sql:
210 orderby = parsed_sql['orderby']
211 if type(orderby) is list:
213 orderby = orderby['value']
214 if orderby == 'rowid':
217 # Limit number of rows
219 if 'limit' in parsed_sql:
220 limit = int(parsed_sql['limit'])
224 if 'offset' in parsed_sql:
225 offset = int(parsed_sql['offset'])
228 if page_size and max_returned_rows and truncate:
229 if max_returned_rows == page_size:
230 max_returned_rows += 1
234 if not ' glob ' in query:
235 table_rows = table.where(query, params, start, end)
237 table_rows = table.itersorted(orderby, start=start, stop=end)
239 table_rows = table.iterrows(start, end)
242 def normalize_field_value(value):
243 if type(value) is bytes:
244 return value.decode('utf-8')
245 elif not type(value) in (int, float, complex):
250 def make_get_rowid():
251 if type(table) is tables.table.Table:
262 def make_get_row_value():
263 if type(table) is tables.table.Table:
264 def get_row_value(row, field):
267 def get_row_value(row, field):
272 get_rowid = make_get_rowid()
273 get_row_value = make_get_row_value()
275 table_rows = table_rows[offset:]
277 for table_row in table_rows:
279 if limit is not None and count > limit:
281 if truncate and max_returned_rows and count > max_returned_rows:
287 if isinstance(field, dict):
288 field_name = field['value']
289 if isinstance(field_name, dict) and 'distinct' in field_name:
290 field_name = field_name['distinct']
291 if field_name == 'rowid':
292 row['rowid'] = get_rowid(table_row)
293 elif field_name == '*':
295 row[col] = normalize_field_value(get_row_value(table_row, col))
296 elif isinstance(field_name, dict):
297 if field_name.get('count') == '*':
298 row['count(*)'] = int(table.nrows)
299 elif field_name.get('json_type'):
300 field_name = field_name.get('json_type')
301 row['json_type(' + field_name + ')'] = _get_field_type(field_name)
303 raise Exception("Function not recognized")
305 row[field_name] = normalize_field_value(get_row_value(table_row, field_name))
308 # Prepare query description
309 for field in [f['value'] if isinstance(f, dict) else f for f in fields]:
312 description += ((col,),)
314 description += ((field,),)
316 return results, truncated, description