1 from moz_sql_parser import parse
5 import datasette_connectors as dc
8 class PyTablesConnection(dc.Connection):
9 def __init__(self, path, connector):
10 super().__init__(path, connector)
11 self.h5file = tables.open_file(path)
14 class PyTablesConnector(dc.Connector):
15 connector_type = 'pytables'
16 connection_class = PyTablesConnection
18 def table_names(self):
21 for node in self.conn.h5file
22 if not(isinstance(node, tables.group.Group))
25 def table_count(self, table_name):
26 table = self.conn.h5file.get_node(table_name)
27 return int(table.nrows)
29 def table_info(self, table_name):
30 table = self.conn.h5file.get_node(table_name)
32 if isinstance(table, tables.table.Table):
33 colnames = table.colnames
41 for idx, colname in enumerate(colnames)
44 def hidden_table_names(self):
47 def detect_spatialite(self):
53 def detect_fts(self, table_name):
58 "Open file and return tables info"
61 h5file = tables.open_file(path)
63 for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
65 if isinstance(table, tables.table.Table):
66 colnames = table.colnames
68 h5tables[table._v_pathname] = {
69 'name': table._v_pathname,
72 'count': int(table.nrows),
76 'foreign_keys': {'incoming': [], 'outgoing': []},
80 return h5tables, views, _connector_type
82 def _parse_sql(sql, params):
84 sql = re.sub(r'(?i)from \[(.*)]', r'from "\g<1>"', sql)
87 sql = sql.replace(":" + param, param)
92 # Propably it's a PyTables expression
93 for token in ['group by', 'order by', 'limit', '']:
94 res = re.search('(?i)where (.*)' + token, sql)
96 modified_sql = re.sub('(?i)where (.*)(' + token + ')', r'\g<2>', sql)
97 parsed = parse(modified_sql)
98 parsed['where'] = res.group(1).strip()
101 # Always a list of fields
102 if type(parsed['select']) is not list:
103 parsed['select'] = [parsed['select']]
119 def __init__(self, path):
121 self.h5file = tables.open_file(path)
123 def execute(self, sql, params=None, truncate=False, page_size=None, max_returned_rows=None):
130 parsed_sql = _parse_sql(sql, params)
132 if parsed_sql['from'] == 'sqlite_master':
133 rows = self._execute_datasette_query(sql, params)
134 description = (('value',),)
135 return rows, truncated, description
137 table = self.h5file.get_node(parsed_sql['from'])
139 fields = parsed_sql['select']
141 if type(table) is tables.table.Table:
142 colnames = table.colnames
148 # Use 'where' statement or get all the rows
149 def _cast_param(field, pname):
150 # Cast value to the column type
151 coltype = table.dtype.name
152 if type(table) is tables.table.Table:
153 coltype = table.coltypes[field]
155 if coltype == 'string':
157 elif coltype.startswith('int'):
159 elif coltype.startswith('float'):
162 params[pname] = fcast(params[pname])
164 def _translate_where(where):
165 # Translate SQL to PyTables expression
168 operator = list(where)[0]
170 if operator in ['and', 'or']:
171 subexpr = [_translate_where(e) for e in where[operator]]
172 subexpr = filter(lambda e: e, subexpr)
173 subexpr = ["({})".format(e) for e in subexpr]
174 expr = " {} ".format(_operators[operator]).join(subexpr)
175 elif operator == 'exists':
177 elif where == {'eq': ['rowid', 'p0']}:
178 start = int(params['p0'])
180 elif where == {'gt': ['rowid', 'p0']}:
181 start = int(params['p0']) + 1
183 left, right = where[operator]
185 _cast_param(right, left)
186 elif right in params:
187 _cast_param(left, right)
189 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
193 if 'where' in parsed_sql:
194 if type(parsed_sql['where']) is dict:
195 query = _translate_where(parsed_sql['where'])
197 query = parsed_sql['where']
201 if 'orderby' in parsed_sql:
202 orderby = parsed_sql['orderby']
203 if type(orderby) is list:
205 orderby = orderby['value']
206 if orderby == 'rowid':
209 # Limit number of rows
211 if 'limit' in parsed_sql:
212 limit = int(parsed_sql['limit'])
215 if page_size and max_returned_rows and truncate:
216 if max_returned_rows == page_size:
217 max_returned_rows += 1
221 table_rows = table.where(query, params, start, end)
223 table_rows = table.itersorted(orderby, start=start, stop=end)
225 table_rows = table.iterrows(start, end)
228 def normalize_field_value(value):
229 if type(value) is bytes:
230 return value.decode('utf-8')
231 elif not type(value) in (int, float, complex):
236 def make_get_rowid():
237 if type(table) is tables.table.Table:
248 def make_get_row_value():
249 if type(table) is tables.table.Table:
250 def get_row_value(row, field):
253 def get_row_value(row, field):
257 if len(fields) == 1 and type(fields[0]['value']) is dict and \
258 fields[0]['value'].get('count') == '*':
259 rows.append(Row({'count(*)': int(table.nrows)}))
261 get_rowid = make_get_rowid()
262 get_row_value = make_get_row_value()
264 for table_row in table_rows:
266 if limit and count > limit:
268 if truncate and max_returned_rows and count > max_returned_rows:
273 field_name = field['value']
274 if type(field_name) is dict and 'distinct' in field_name:
275 field_name = field_name['distinct']
276 if field_name == 'rowid':
277 row['rowid'] = get_rowid(table_row)
278 elif field_name == '*':
280 row[col] = normalize_field_value(get_row_value(table_row, col))
282 row[field_name] = normalize_field_value(get_row_value(table_row, field_name))
285 # Prepare query description
286 for field in [f['value'] for f in fields]:
289 description.append((col,))
291 description.append((field,))
294 return rows, truncated, tuple(description)
296 def _execute_datasette_query(self, sql, params):
297 "Datasette special queries for getting tables info"
298 if sql == 'select sql from sqlite_master where name = :n and type=:t':
299 if params['t'] == 'view':
303 table = self.h5file.get_node(params['n'])
305 if type(table) is tables.table.Table:
306 colnames = table.colnames
308 row['sql'] = 'CREATE TABLE {} ({})'.format(params['n'], ", ".join(colnames))
313 raise Exception("SQLite queries cannot be executed with this connector: %s, %s" % (sql, params))
317 def __init__(self, values=None):
322 self.__setitem__(idx, values[idx])
324 def __setitem__(self, idx, value):
326 if idx in self.labels:
327 self.values[self.labels.index(idx)] = value
329 self.labels.append(idx)
330 self.values.append(value)
332 self.values[idx] = value
334 def __getitem__(self, idx):
336 return self.values[self.labels.index(idx)]
338 return self.values[idx]
341 return self.values.__iter__()