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)
41 if type(parsed['select']) is not list:
42 parsed['select'] = [parsed['select']]
58 def __init__(self, path):
60 self.h5file = tables.open_file(path)
62 def execute(self, sql, params=None, truncate=False):
69 parsed_sql = _parse_sql(sql, params)
70 table = self.h5file.get_node(parsed_sql['from'])
72 fields = parsed_sql['select']
78 # Use 'where' statement or get all the rows
79 def _cast_param(field, pname):
80 # Cast value to the column type
81 coltype = table.coltypes[field]
83 if coltype == 'string':
85 elif coltype.startswith('int'):
87 elif coltype.startswith('float'):
90 params[pname] = fcast(params[pname])
92 def _translate_where(where):
93 # Translate SQL to PyTables expression
95 operator = list(where)[0]
97 if operator in ['and', 'or']:
98 subexpr = ["({})".format(_translate_where(q)) for q in where[operator]]
99 expr = " {} ".format(_operators[operator]).join(subexpr)
100 elif where == {'eq': ['rowid', 'p0']}:
102 start = int(params['p0'])
105 left, right = where[operator]
107 _cast_param(right, left)
108 elif right in params:
109 _cast_param(left, right)
111 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
115 if 'where' in parsed_sql:
117 query = _translate_where(parsed_sql['where'])
119 # Probably it's a PyTables query
120 query = str(parsed_sql['where'])[6:] # without where keyword
122 # Limit number of rows
123 if 'limit' in parsed_sql:
124 max_rows = int(parsed_sql['limit'])
125 if end - start > max_rows:
126 end = start + max_rows
130 table_rows = table.where(query, params, start, end)
132 table_rows = table.iterrows(start, end)
135 if len(fields) == 1 and type(fields[0]['value']) is dict and \
136 fields[0]['value'].get('count') == '*':
137 rows.append(Row({'count(*)': int(table.nrows)}))
139 for table_row in table_rows:
142 if field['value'] == 'rowid':
143 row['rowid'] = int(table_row.nrow)
144 elif field['value'] == '*':
145 for col in table.colnames:
146 value = table_row[col]
147 if type(value) is bytes:
148 value = value.decode('utf-8')
151 row[field['value']] = table_row[field['value']]
154 # Prepare query description
155 for field in [f['value'] for f in fields]:
157 for col in table.colnames:
158 description.append((col,))
160 description.append((field,))
164 return rows, truncated, tuple(description)
168 class Row(OrderedDict):
169 def __getitem__(self, label):
170 if type(label) is int:
171 return super(OrderedDict, self).__getitem__(list(self.keys())[label])
173 return super(OrderedDict, self).__getitem__(label)
176 return self.values().__iter__()