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 rows = self._execute_datasette_query(sql, params)
84 description = (('value',))
85 return rows, truncated, description
87 table = self.h5file.get_node(parsed_sql['from'])
89 fields = parsed_sql['select']
95 # Use 'where' statement or get all the rows
96 def _cast_param(field, pname):
97 # Cast value to the column type
98 if type(table) is tables.table.Table:
99 coltype = table.coltypes[field]
101 coltype = table.dtype.name
103 if coltype == 'string':
105 elif coltype.startswith('int'):
107 elif coltype.startswith('float'):
110 params[pname] = fcast(params[pname])
112 def _translate_where(where):
113 # Translate SQL to PyTables expression
116 operator = list(where)[0]
118 if operator in ['and', 'or']:
119 subexpr = [_translate_where(e) for e in where[operator]]
120 subexpr = filter(lambda e: e, subexpr)
121 subexpr = ["({})".format(e) for e in subexpr]
122 expr = " {} ".format(_operators[operator]).join(subexpr)
123 elif operator == 'exists':
125 elif where == {'eq': ['rowid', 'p0']}:
126 start = int(params['p0'])
128 elif where == {'gt': ['rowid', 'p0']}:
129 start = int(params['p0']) + 1
131 left, right = where[operator]
133 _cast_param(right, left)
134 elif right in params:
135 _cast_param(left, right)
137 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
141 if 'where' in parsed_sql:
142 if type(parsed_sql['where']) is dict:
143 query = _translate_where(parsed_sql['where'])
145 query = parsed_sql['where']
147 # Limit number of rows
149 if 'limit' in parsed_sql:
150 limit = int(parsed_sql['limit'])
153 if page_size and max_returned_rows and truncate:
154 if max_returned_rows == page_size:
155 max_returned_rows += 1
159 table_rows = table.where(query, params, start, end)
161 table_rows = table.iterrows(start, end)
164 if len(fields) == 1 and type(fields[0]['value']) is dict and \
165 fields[0]['value'].get('count') == '*':
166 rows.append(Row({'count(*)': int(table.nrows)}))
168 if type(table) is tables.table.Table:
170 for table_row in table_rows:
172 if limit and count > limit:
174 if truncate and max_returned_rows and count > max_returned_rows:
179 field_name = field['value']
180 if type(field_name) is dict and 'distinct' in field_name:
181 field_name = field_name['distinct']
182 if field_name == 'rowid':
183 row['rowid'] = int(table_row.nrow)
184 elif field_name == '*':
185 for col in table.colnames:
186 value = table_row[col]
187 if type(value) is bytes:
188 value = value.decode('utf-8')
191 row[field_name] = table_row[field_name]
197 for table_row in table_rows:
199 if limit and count > limit:
201 if truncate and max_returned_rows and count > max_returned_rows:
207 field_name = field['value']
208 if type(field_name) is dict and 'distinct' in field_name:
209 field_name = field_name['distinct']
210 if field_name == 'rowid':
214 if type(value) is bytes:
215 value = value.decode('utf-8')
216 elif not type(value) in (int, float, complex):
221 # Prepare query description
222 for field in [f['value'] for f in fields]:
224 if type(table) is tables.table.Table:
225 for col in table.colnames:
226 description.append((col,))
228 description.append(('value',))
230 description.append((field,))
233 return rows, truncated, tuple(description)
235 def _execute_datasette_query(self, sql, params):
236 "Datasette special queries for getting tables info"
237 if sql == "SELECT count(*) from sqlite_master WHERE type = 'view' and name=:n":
241 elif sql == 'select sql from sqlite_master where name = :n and type="table"':
243 table = self.h5file.get_node(params['n'])
245 row['sql'] = 'CREATE TABLE {} ()'.format(params['n'])
250 raise Exception("SQLite queries cannot be executed with this connector")
253 def __init__(self, values=None):
258 self.__setitem__(idx, values[idx])
260 def __setitem__(self, idx, value):
262 if idx in self.labels:
263 self.values[self.labels.index(idx)] = value
265 self.labels.append(idx)
266 self.values.append(value)
268 self.values[idx] = value
270 def __getitem__(self, idx):
272 return self.values[self.labels.index(idx)]
274 return self.values[idx]
277 return self.values.__iter__()