50180fdc5c35c1d6ae93d817080dabd6d824ed9d
[datasette-pytables.git] / datasette_pytables / __init__.py
1 import tables
2 import sqlparse
3 from collections import OrderedDict
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': 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 class Connection:
54     def __init__(self, path):
55         self.path = path
56         self.h5file = tables.open_file(path)
57
58     def execute(self, sql, params=None, truncate=False):
59         rows = []
60         truncated = False
61         description = []
62
63         parsed_sql = _parse_sql(sql)
64         table = self.h5file.get_node(parsed_sql['from'][1:-1])
65         table_rows = []
66         fields = parsed_sql['select'].split(',')
67
68         # Use 'where' statement or get all the rows
69         if 'where' in parsed_sql:
70             query = ''
71             start = 0
72             end = table.nrows
73             for condition in parsed_sql['where'].get_sublists():
74                 if str(condition) == '"rowid"=:p0':
75                     start = int(params['p0'])
76                     end = start + 1
77             if query:
78                 table_rows = table.where(query, start, end)
79             else:
80                 table_rows = table.iterrows(start, end)
81         else:
82             table_rows = table.iterrows()
83
84         # Prepare rows
85         if len(fields) == 1 and fields[0] == 'count(*)':
86             rows.append(Row({fields[0]: table.nrows}))
87         else:
88             for table_row in table_rows:
89                 row = Row()
90                 for field in fields:
91                     if field == 'rowid':
92                         row[field] = table_row.nrow
93                     elif field == '*':
94                         for col in table.colnames:
95                             value = table_row[col]
96                             if type(value) is bytes:
97                                 value = value.decode('utf-8')
98                             row[col] = value
99                     else:
100                         row[field] = table_row[field]
101                 rows.append(row)
102
103         # Prepare query description
104         for field in fields:
105             if field == '*':
106                 for col in table.colnames:
107                     description.append((col,))
108             else:
109                 description.append((field,))
110
111         if truncate:
112             return rows, truncated, tuple(description)
113         else:
114             return rows
115
116 class Row(OrderedDict):
117     def __getitem__(self, label):
118         if type(label) is int:
119             return super(OrderedDict, self).__getitem__(list(self.keys())[label])
120         else:
121             return super(OrderedDict, self).__getitem__(label)
122
123     def __iter__(self):
124         return self.values().__iter__()