]> git.jsancho.org Git - datasette-pytables.git/blob - datasette_pytables/__init__.py
c4087730d24699c52968cb34b1de0955635b24a0
[datasette-pytables.git] / datasette_pytables / __init__.py
1 import tables
2 import datasette_connectors as dc
3 from .utils import parse_sql
4
5
6 class PyTablesConnection(dc.Connection):
7     def __init__(self, path, connector):
8         super().__init__(path, connector)
9         self.h5file = tables.open_file(path)
10
11
12 class PyTablesConnector(dc.Connector):
13     connector_type = 'pytables'
14     connection_class = PyTablesConnection
15
16     operators = {
17         'eq': '==',
18         'neq': '!=',
19         'gt': '>',
20         'gte': '>=',
21         'lt': '<',
22         'lte': '<=',
23         'and': '&',
24         'or': '|',
25         'binary_and': '&',
26         'binary_or': '|',
27     }
28
29     def table_names(self):
30         return [
31             node._v_pathname
32             for node in self.conn.h5file
33             if not(isinstance(node, tables.group.Group))
34         ]
35
36     def table_count(self, table_name):
37         table = self.conn.h5file.get_node(table_name)
38         return int(table.nrows)
39
40     def table_info(self, table_name):
41         table = self.conn.h5file.get_node(table_name)
42         colnames = ['value']
43         if isinstance(table, tables.table.Table):
44             colnames = table.colnames
45
46         return [
47             {
48                 'idx': idx,
49                 'name': colname,
50                 'primary_key': False,
51             }
52             for idx, colname in enumerate(colnames)
53         ]
54
55     def hidden_table_names(self):
56         return []
57
58     def detect_spatialite(self):
59         return False
60
61     def view_names(self):
62         return []
63
64     def detect_fts(self, table_name):
65         return False
66
67     def foreign_keys(self, table_name):
68         return []
69
70     def table_exists(self, table_name):
71         try:
72             self.conn.h5file.get_node(table_name)
73             return True
74         except:
75             return False
76
77     def table_definition(self, table_type, table_name):
78         table = self.conn.h5file.get_node(table_name)
79         colnames = ['value']
80         if isinstance(table, tables.table.Table):
81             colnames = table.colnames
82
83         return 'CREATE TABLE {} ({})'.format(
84             table_name,
85             ', '.join(colnames),
86         )
87
88     def indices_definition(self, table_name):
89         return []
90
91     def execute(
92         self,
93         sql,
94         params=None,
95         truncate=False,
96         custom_time_limit=None,
97         page_size=None,
98         log_sql_errors=True,
99     ):
100         results = []
101         truncated = False
102         description = ()
103
104         parsed_sql = parse_sql(sql, params)
105
106         while isinstance(parsed_sql['from'], dict):
107             # Pytables does not support subqueries
108             parsed_sql['from'] = parsed_sql['from']['value']['from']
109
110         table = self.conn.h5file.get_node(parsed_sql['from'])
111         table_rows = []
112         fields = parsed_sql['select']
113         colnames = ['value']
114         if type(table) is tables.table.Table:
115             colnames = table.colnames
116
117         query = ''
118         start = 0
119         end = table.nrows
120
121         # Use 'where' statement or get all the rows
122         def _cast_param(field, pname):
123             # Cast value to the column type
124             coltype = table.dtype.name
125             if type(table) is tables.table.Table:
126                 coltype = table.coltypes[field]
127             fcast = None
128             if coltype == 'string':
129                 fcast = str
130             elif coltype.startswith('int'):
131                 fcast = int
132             elif coltype.startswith('float'):
133                 fcast = float
134             if fcast:
135                 params[pname] = fcast(params[pname])
136
137         def _translate_where(where):
138             # Translate SQL to PyTables expression
139             nonlocal start, end
140             expr = ''
141             operator = list(where)[0]
142
143             if operator in ['and', 'or']:
144                 subexpr = [_translate_where(e) for e in where[operator]]
145                 subexpr = filter(lambda e: e, subexpr)
146                 subexpr = ["({})".format(e) for e in subexpr]
147                 expr = " {} ".format(self.operators[operator]).join(subexpr)
148             elif operator == 'exists':
149                 pass
150             elif where == {'eq': ['rowid', 'p0']}:
151                 start = int(params['p0'])
152                 end = start + 1
153             elif where == {'gt': ['rowid', 'p0']}:
154                 start = int(params['p0']) + 1
155             else:
156                 left, right = where[operator]
157
158                 if isinstance(left, dict):
159                     left = "(" + _translate_where(left) + ")"
160                 elif left in params:
161                     _cast_param(right, left)
162
163                 if isinstance(right, dict):
164                     right = "(" + _translate_where(right) + ")"
165                 elif right in params:
166                     _cast_param(left, right)
167
168                 expr = "{left} {operator} {right}".format(
169                     left=left,
170                     operator=self.operators.get(operator, operator),
171                     right=right,
172                 )
173
174             return expr
175
176         if 'where' in parsed_sql:
177             if type(parsed_sql['where']) is dict:
178                 query = _translate_where(parsed_sql['where'])
179             else:
180                 query = parsed_sql['where']
181
182         # Sort by column
183         orderby = ''
184         if 'orderby' in parsed_sql:
185             orderby = parsed_sql['orderby']
186             if type(orderby) is list:
187                 orderby = orderby[0]
188             orderby = orderby['value']
189             if orderby == 'rowid':
190                 orderby = ''
191
192         # Limit number of rows
193         limit = None
194         if 'limit' in parsed_sql:
195             limit = int(parsed_sql['limit'])
196
197         # Truncate if needed
198         if page_size and max_returned_rows and truncate:
199             if max_returned_rows == page_size:
200                 max_returned_rows += 1
201
202         # Execute query
203         if query:
204             if not ' glob ' in query:
205                 table_rows = table.where(query, params, start, end)
206         elif orderby:
207             table_rows = table.itersorted(orderby, start=start, stop=end)
208         else:
209             table_rows = table.iterrows(start, end)
210
211         # Prepare rows
212         def normalize_field_value(value):
213             if type(value) is bytes:
214                 return value.decode('utf-8')
215             elif not type(value) in (int, float, complex):
216                 return str(value)
217             else:
218                 return value
219
220         def make_get_rowid():
221             if type(table) is tables.table.Table:
222                 def get_rowid(row):
223                     return int(row.nrow)
224             else:
225                 rowid = start - 1
226                 def get_rowid(row):
227                     nonlocal rowid
228                     rowid += 1
229                     return rowid
230             return get_rowid
231
232         def make_get_row_value():
233             if type(table) is tables.table.Table:
234                 def get_row_value(row, field):
235                     return row[field]
236             else:
237                 def get_row_value(row, field):
238                     return row
239             return get_row_value
240
241         # Get results
242         get_rowid = make_get_rowid()
243         get_row_value = make_get_row_value()
244         count = 0
245         for table_row in table_rows:
246             count += 1
247             if limit is not None and count > limit:
248                 break
249             if truncate and max_returned_rows and count > max_returned_rows:
250                 truncated = True
251                 break
252             row = {}
253             for field in fields:
254                 field_name = field
255                 if isinstance(field, dict):
256                     field_name = field['value']
257                 if isinstance(field_name, dict) and 'distinct' in field_name:
258                     field_name = field_name['distinct']
259                 if field_name == 'rowid':
260                     row['rowid'] = get_rowid(table_row)
261                 elif field_name == '*':
262                     for col in colnames:
263                         row[col] = normalize_field_value(get_row_value(table_row, col))
264                 elif isinstance(field_name, dict):
265                     if field_name.get('count') == '*':
266                         row['count(*)'] = int(table.nrows)
267                     elif field_name.get('json_type'):
268                         field_name = field_name.get('json_type')
269                         row['json_type(' + field_name + ')'] = table.coltypes[field_name]
270                     else:
271                         raise Exception("Function not recognized")
272                 else:
273                     row[field_name] = normalize_field_value(get_row_value(table_row, field_name))
274             results.append(row)
275
276         # Prepare query description
277         for field in [f['value'] if isinstance(f, dict) else f for f in fields]:
278             if field == '*':
279                 for col in colnames:
280                     description += ((col,),)
281             else:
282                 description += ((field,),)
283
284         return results, truncated, description