1 from collections import OrderedDict
2 from moz_sql_parser import parse
6 _connector_type = 'pytables'
9 "Open file and return tables info"
12 h5file = tables.open_file(path)
14 for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
16 if isinstance(table, tables.table.Table):
17 colnames = table.colnames
19 h5tables[table._v_pathname] = {
20 'name': table._v_pathname,
23 'count': int(table.nrows),
27 'foreign_keys': {'incoming': [], 'outgoing': []},
31 return h5tables, views, _connector_type
33 def _parse_sql(sql, params):
35 sql = re.sub('(?i)from \[(.*)]', 'from "\g<1>"', sql)
38 sql = sql.replace(":" + param, param)
43 # Propably it's a PyTables expression
44 for token in ['group by', 'order by', 'limit']:
45 res = re.search('(?i)where (.*)' + token, sql)
47 modified_sql = re.sub('(?i)where (.*)(' + token + ')', '\g<2>', sql)
48 parsed = parse(modified_sql)
49 parsed['where'] = res.group(1)
52 # Always a list of fields
53 if type(parsed['select']) is not list:
54 parsed['select'] = [parsed['select']]
70 def __init__(self, path):
72 self.h5file = tables.open_file(path)
74 def execute(self, sql, params=None, truncate=False):
81 parsed_sql = _parse_sql(sql, params)
82 table = self.h5file.get_node(parsed_sql['from'])
84 fields = parsed_sql['select']
90 # Use 'where' statement or get all the rows
91 def _cast_param(field, pname):
92 # Cast value to the column type
93 coltype = table.coltypes[field]
95 if coltype == 'string':
97 elif coltype.startswith('int'):
99 elif coltype.startswith('float'):
102 params[pname] = fcast(params[pname])
104 def _translate_where(where):
105 # Translate SQL to PyTables expression
107 operator = list(where)[0]
109 if operator in ['and', 'or']:
110 subexpr = ["({})".format(_translate_where(q)) for q in where[operator]]
111 expr = " {} ".format(_operators[operator]).join(subexpr)
112 elif where == {'eq': ['rowid', 'p0']}:
114 start = int(params['p0'])
117 left, right = where[operator]
119 _cast_param(right, left)
120 elif right in params:
121 _cast_param(left, right)
123 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
127 if 'where' in parsed_sql:
128 if type(parsed_sql['where']) is dict:
129 query = _translate_where(parsed_sql['where'])
131 query = parsed_sql['where']
133 # Limit number of rows
134 if 'limit' in parsed_sql:
135 max_rows = int(parsed_sql['limit'])
136 if end - start > max_rows:
137 end = start + max_rows
141 table_rows = table.where(query, params, start, end)
143 table_rows = table.iterrows(start, end)
146 if len(fields) == 1 and type(fields[0]['value']) is dict and \
147 fields[0]['value'].get('count') == '*':
148 rows.append(Row({'count(*)': int(table.nrows)}))
150 for table_row in table_rows:
153 if field['value'] == 'rowid':
154 row['rowid'] = int(table_row.nrow)
155 elif field['value'] == '*':
156 for col in table.colnames:
157 value = table_row[col]
158 if type(value) is bytes:
159 value = value.decode('utf-8')
162 row[field['value']] = table_row[field['value']]
165 # Prepare query description
166 for field in [f['value'] for f in fields]:
168 for col in table.colnames:
169 description.append((col,))
171 description.append((field,))
175 return rows, truncated, tuple(description)
179 class Row(OrderedDict):
180 def __getitem__(self, label):
181 if type(label) is int:
182 return super(OrderedDict, self).__getitem__(list(self.keys())[label])
184 return super(OrderedDict, self).__getitem__(label)
187 return self.values().__iter__()