]> git.jsancho.org Git - datasette-pytables.git/blob - datasette_pytables/__init__.py
Replace sqlparse with Mozilla SQL Parser
[datasette-pytables.git] / datasette_pytables / __init__.py
1 from collections import OrderedDict
2 from moz_sql_parser import parse
3 import re
4 import tables
5
6 _connector_type = 'pytables'
7
8 def inspect(path):
9     "Open file and return tables info"
10     h5tables = {}
11     views = []
12     h5file = tables.open_file(path)
13
14     for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
15         colnames = []
16         if isinstance(table, tables.table.Table):
17             colnames = table.colnames
18
19         h5tables[table._v_pathname] = {
20             'name': table._v_pathname,
21             'columns': colnames,
22             'primary_keys': [],
23             'count': int(table.nrows),
24             'label_column': None,
25             'hidden': False,
26             'fts_table': None,
27             'foreign_keys': {'incoming': [], 'outgoing': []},
28         }
29
30     h5file.close()
31     return h5tables, views, _connector_type
32
33 def _parse_sql(sql, params):
34     # Table name
35     sql = re.sub('(?i)from \[(.*)]', 'from "\g<1>"', sql)
36     # Params
37     for param in params:
38         sql = sql.replace(":" + param, param)
39
40     parsed = parse(sql)
41     if type(parsed['select']) is not list:
42         parsed['select'] = [parsed['select']]
43
44     return parsed
45
46 _operators = {
47     'eq': '==',
48     'neq': '!=',
49     'gt': '>',
50     'gte': '>=',
51     'lt': '<',
52     'lte': '<=',
53     'and': '&',
54     'or': '|',
55 }
56
57 class Connection:
58     def __init__(self, path):
59         self.path = path
60         self.h5file = tables.open_file(path)
61
62     def execute(self, sql, params=None, truncate=False):
63         if params is None:
64             params = {}
65         rows = []
66         truncated = False
67         description = []
68
69         parsed_sql = _parse_sql(sql, params)
70         table = self.h5file.get_node(parsed_sql['from'])
71         table_rows = []
72         fields = parsed_sql['select']
73
74         query = ''
75         start = 0
76         end = table.nrows
77
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]
82             fcast = None
83             if coltype == 'string':
84                 fcast = str
85             elif coltype.startswith('int'):
86                 fcast = int
87             elif coltype.startswith('float'):
88                 fcast = float
89             if fcast:
90                 params[pname] = fcast(params[pname])
91
92         def _translate_where(where):
93             # Translate SQL to PyTables expression
94             expr = ''
95             operator = list(where)[0]
96
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']}:
101                 nonlocal start, end
102                 start = int(params['p0'])
103                 end = start + 1
104             else:
105                 left, right = where[operator]
106                 if left in params:
107                     _cast_param(right, left)
108                 elif right in params:
109                     _cast_param(left, right)
110
111                 expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)
112
113             return expr
114
115         if 'where' in parsed_sql:
116             try:
117                 query = _translate_where(parsed_sql['where'])
118             except:
119                 # Probably it's a PyTables query
120                 query = str(parsed_sql['where'])[6:]    # without where keyword
121
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
127
128         # Execute query
129         if query:
130             table_rows = table.where(query, params, start, end)
131         else:
132             table_rows = table.iterrows(start, end)
133
134         # Prepare rows
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)}))
138         else:
139             for table_row in table_rows:
140                 row = Row()
141                 for field in fields:
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')
149                             row[col] = value
150                     else:
151                         row[field['value']] = table_row[field['value']]
152                 rows.append(row)
153
154         # Prepare query description
155         for field in [f['value'] for f in fields]:
156             if field == '*':
157                 for col in table.colnames:
158                     description.append((col,))
159             else:
160                 description.append((field,))
161
162         # Return the rows
163         if truncate:
164             return rows, truncated, tuple(description)
165         else:
166             return rows
167
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])
172         else:
173             return super(OrderedDict, self).__getitem__(label)
174
175     def __iter__(self):
176         return self.values().__iter__()