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 = [_translate_where(e) for e in where[operator]]
111 subexpr = filter(lambda e: e, subexpr)
112 subexpr = ["({})".format(e) for e in subexpr]
113 expr = " {} ".format(_operators[operator]).join(subexpr)
114 elif operator == 'exists':
116 elif where == {'eq': ['rowid', 'p0']}:
118 start = int(params['p0'])
121 left, right = where[operator]
123 _cast_param(right, left)
124 elif right in params:
125 _cast_param(left, right)
127 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
131 if 'where' in parsed_sql:
132 if type(parsed_sql['where']) is dict:
133 query = _translate_where(parsed_sql['where'])
135 query = parsed_sql['where']
137 # Limit number of rows
138 if 'limit' in parsed_sql:
139 max_rows = int(parsed_sql['limit'])
140 if end - start > max_rows:
141 end = start + max_rows
145 table_rows = table.where(query, params, start, end)
147 table_rows = table.iterrows(start, end)
150 if len(fields) == 1 and type(fields[0]['value']) is dict and \
151 fields[0]['value'].get('count') == '*':
152 rows.append(Row({'count(*)': int(table.nrows)}))
154 if type(table) is tables.table.Table:
155 for table_row in table_rows:
158 field_name = field['value']
159 if type(field_name) is dict and 'distinct' in field_name:
160 field_name = field_name['distinct']
161 if field_name == 'rowid':
162 row['rowid'] = int(table_row.nrow)
163 elif field_name == '*':
164 for col in table.colnames:
165 value = table_row[col]
166 if type(value) is bytes:
167 value = value.decode('utf-8')
170 row[field_name] = table_row[field_name]
175 for table_row in table_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':
186 if type(value) is bytes:
187 value = value.decode('utf-8')
191 # Prepare query description
192 for field in [f['value'] for f in fields]:
194 if type(table) is tables.table.Table:
195 for col in table.colnames:
196 description.append((col,))
198 description.append(('value',))
200 description.append((field,))
204 return rows, truncated, tuple(description)
208 class Row(OrderedDict):
209 def __getitem__(self, label):
210 if type(label) is int:
211 return super(OrderedDict, self).__getitem__(list(self.keys())[label])
213 return super(OrderedDict, self).__getitem__(label)
216 return self.values().__iter__()