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 table_names(self):
32 for node in self.conn.h5file
33 if not(isinstance(node, tables.group.Group))
36 def table_count(self, table_name):
37 table = self.conn.h5file.get_node(table_name)
38 return int(table.nrows)
40 def table_info(self, table_name):
41 table = self.conn.h5file.get_node(table_name)
43 if isinstance(table, tables.table.Table):
44 colnames = table.colnames
52 for idx, colname in enumerate(colnames)
55 def hidden_table_names(self):
58 def detect_spatialite(self):
64 def detect_fts(self, table_name):
67 def foreign_keys(self, table_name):
70 def table_exists(self, table_name):
72 self.conn.h5file.get_node(table_name)
77 def table_definition(self, table_type, table_name):
78 table = self.conn.h5file.get_node(table_name)
80 if isinstance(table, tables.table.Table):
81 colnames = table.colnames
83 return 'CREATE TABLE {} ({})'.format(
88 def indices_definition(self, table_name):
96 custom_time_limit=None,
104 parsed_sql = parse_sql(sql, params)
106 while isinstance(parsed_sql['from'], dict):
107 # Pytables does not support subqueries
108 parsed_sql['from'] = parsed_sql['from']['value']['from']
110 table = self.conn.h5file.get_node(parsed_sql['from'])
112 fields = parsed_sql['select']
114 if type(table) is tables.table.Table:
115 colnames = table.colnames
121 # Use 'where' statement or get all the rows
122 def _cast_param(field, pname):
123 # Cast value to the column type
124 coltype = table.dtype.name
125 if type(table) is tables.table.Table:
126 coltype = table.coltypes[field]
128 if coltype == 'string':
130 elif coltype.startswith('int'):
132 elif coltype.startswith('float'):
135 params[pname] = fcast(params[pname])
137 def _translate_where(where):
138 # Translate SQL to PyTables expression
141 operator = list(where)[0]
143 if operator in ['and', 'or']:
144 subexpr = [_translate_where(e) for e in where[operator]]
145 subexpr = filter(lambda e: e, subexpr)
146 subexpr = ["({})".format(e) for e in subexpr]
147 expr = " {} ".format(self.operators[operator]).join(subexpr)
148 elif operator == 'exists':
150 elif where == {'eq': ['rowid', 'p0']}:
151 start = int(params['p0'])
153 elif where == {'gt': ['rowid', 'p0']}:
154 start = int(params['p0']) + 1
156 left, right = where[operator]
158 if isinstance(left, dict):
159 left = "(" + _translate_where(left) + ")"
161 _cast_param(right, left)
163 if isinstance(right, dict):
164 right = "(" + _translate_where(right) + ")"
165 elif right in params:
166 _cast_param(left, right)
168 expr = "{left} {operator} {right}".format(
170 operator=self.operators.get(operator, operator),
176 if 'where' in parsed_sql:
177 if type(parsed_sql['where']) is dict:
178 query = _translate_where(parsed_sql['where'])
180 query = parsed_sql['where']
184 if 'orderby' in parsed_sql:
185 orderby = parsed_sql['orderby']
186 if type(orderby) is list:
188 orderby = orderby['value']
189 if orderby == 'rowid':
192 # Limit number of rows
194 if 'limit' in parsed_sql:
195 limit = int(parsed_sql['limit'])
198 if page_size and max_returned_rows and truncate:
199 if max_returned_rows == page_size:
200 max_returned_rows += 1
204 if not ' glob ' in query:
205 table_rows = table.where(query, params, start, end)
207 table_rows = table.itersorted(orderby, start=start, stop=end)
209 table_rows = table.iterrows(start, end)
212 def normalize_field_value(value):
213 if type(value) is bytes:
214 return value.decode('utf-8')
215 elif not type(value) in (int, float, complex):
220 def make_get_rowid():
221 if type(table) is tables.table.Table:
232 def make_get_row_value():
233 if type(table) is tables.table.Table:
234 def get_row_value(row, field):
237 def get_row_value(row, field):
242 get_rowid = make_get_rowid()
243 get_row_value = make_get_row_value()
245 for table_row in table_rows:
247 if limit is not None and count > limit:
249 if truncate and max_returned_rows and count > max_returned_rows:
255 if isinstance(field, dict):
256 field_name = field['value']
257 if isinstance(field_name, dict) and 'distinct' in field_name:
258 field_name = field_name['distinct']
259 if field_name == 'rowid':
260 row['rowid'] = get_rowid(table_row)
261 elif field_name == '*':
263 row[col] = normalize_field_value(get_row_value(table_row, col))
264 elif isinstance(field_name, dict):
265 if field_name.get('count') == '*':
266 row['count(*)'] = int(table.nrows)
267 elif field_name.get('json_type'):
268 field_name = field_name.get('json_type')
269 row['json_type(' + field_name + ')'] = table.coltypes[field_name]
271 raise Exception("Function not recognized")
273 row[field_name] = normalize_field_value(get_row_value(table_row, field_name))
276 # Prepare query description
277 for field in [f['value'] if isinstance(f, dict) else f for f in fields]:
280 description += ((col,),)
282 description += ((field,),)
284 return results, truncated, description