Check limit to return the appropiate number of rows
[datasette-pytables.git] / datasette_pytables / __init__.py
1 from collections import OrderedDict
2 import sqlparse
3 import tables
4
5 _connector_type = 'pytables'
6
7 def inspect(path):
8     "Open file and return tables info"
9     h5tables = {}
10     views = []
11     h5file = tables.open_file(path)
12
13     for table in filter(lambda node: not(isinstance(node, tables.group.Group)), h5file):
14         colnames = []
15         if isinstance(table, tables.table.Table):
16             colnames = table.colnames
17
18         h5tables[table._v_pathname] = {
19             'name': table._v_pathname,
20             'columns': colnames,
21             'primary_keys': [],
22             'count': int(table.nrows),
23             'label_column': None,
24             'hidden': False,
25             'fts_table': None,
26             'foreign_keys': {'incoming': [], 'outgoing': []},
27         }
28
29     h5file.close()
30     return h5tables, views, _connector_type
31
32 def _parse_sql(sql):
33     parsed = sqlparse.parse(sql)
34     stmt = parsed[0]
35     parsed_sql = {}
36     current_keyword = ""
37     for token in stmt.tokens:
38         if token.is_keyword:
39             if current_keyword in parsed_sql and parsed_sql[current_keyword] == '':
40                 # Check composed keywords like 'order by'
41                 del parsed_sql[current_keyword]
42                 current_keyword += " " + str(token)
43             else:
44                 current_keyword = str(token)
45             parsed_sql[current_keyword] = ""
46         elif type(token) is sqlparse.sql.Where:
47             parsed_sql['where'] = token
48         else:
49             if not token.is_whitespace:
50                 parsed_sql[current_keyword] += str(token)
51     return parsed_sql
52
53 _operators = {
54     '=': '==',
55 }
56
57 def _translate_condition(table, condition, params):
58     field = condition.left.get_real_name()
59
60     operator = list(filter(lambda t: t.ttype == sqlparse.tokens.Comparison, condition.tokens))[0]
61     if operator.value in _operators:
62         operator = _operators[operator.value]
63     else:
64         operator = operator.value
65
66     value = condition.right.value
67     if value.startswith(':'):
68         # Value is a parameters
69         value = value[1:]
70         if value in params:
71             # Cast value to the column type
72             coltype = table.coltypes[field]
73             if coltype == 'string':
74                 params[value] = str(params[value])
75             elif coltype.startswith('int'):
76                 params[value] = int(params[value])
77             elif coltype.startswith('float'):
78                 params[value] = float(params[value])
79
80     translated = "{left} {operator} {right}".format(left=field, operator=operator, right=value)
81     return translated, params
82
83 class Connection:
84     def __init__(self, path):
85         self.path = path
86         self.h5file = tables.open_file(path)
87
88     def execute(self, sql, params=None, truncate=False):
89         if params is None:
90             params = {}
91         rows = []
92         truncated = False
93         description = []
94
95         parsed_sql = _parse_sql(sql)
96         table = self.h5file.get_node(parsed_sql['from'][1:-1])
97         table_rows = []
98         fields = parsed_sql['select'].split(',')
99
100         query = ''
101         start = 0
102         end = table.nrows
103
104         # Use 'where' statement or get all the rows
105         if 'where' in parsed_sql:
106             try:
107                 conditions = []
108                 for condition in parsed_sql['where'].get_sublists():
109                     if str(condition) == '"rowid"=:p0':
110                         start = int(params['p0'])
111                         end = start + 1
112                     else:
113                         translated, params = _translate_condition(table, condition, params)
114                         conditions.append(translated)
115                 if conditions:
116                     query = ') & ('.join(conditions)
117                     query = '(' + query + ')'
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 fields[0] == 'count(*)':
136             rows.append(Row({fields[0]: int(table.nrows)}))
137         else:
138             for table_row in table_rows:
139                 row = Row()
140                 for field in fields:
141                     if field == 'rowid':
142                         row[field] = int(table_row.nrow)
143                     elif field == '*':
144                         for col in table.colnames:
145                             value = table_row[col]
146                             if type(value) is bytes:
147                                 value = value.decode('utf-8')
148                             row[col] = value
149                     else:
150                         row[field] = table_row[field]
151                 rows.append(row)
152
153         # Prepare query description
154         for field in fields:
155             if field == '*':
156                 for col in table.colnames:
157                     description.append((col,))
158             else:
159                 description.append((field,))
160
161         # Return the rows
162         if truncate:
163             return rows, truncated, tuple(description)
164         else:
165             return rows
166
167 class Row(OrderedDict):
168     def __getitem__(self, label):
169         if type(label) is int:
170             return super(OrderedDict, self).__getitem__(list(self.keys())[label])
171         else:
172             return super(OrderedDict, self).__getitem__(label)
173
174     def __iter__(self):
175         return self.values().__iter__()