]> git.jsancho.org Git - datasette-pytables.git/blob - datasette_pytables/__init__.py
Basic execute method for queries
[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         else:
47             if not token.is_whitespace:
48                 parsed_sql[current_keyword] += str(token)
49     return parsed_sql
50
51 class Connection:
52     def __init__(self, path):
53         self.path = path
54         self.h5file = tables.open_file(path)
55
56     def execute(self, sql, params=None, truncate=False):
57         rows = []
58         truncated = False
59         description = []
60
61         parsed_sql = _parse_sql(sql)
62         table = self.h5file.get_node(parsed_sql['from'][1:-1])
63         table_rows = []
64         fields = parsed_sql['select'].split(',')
65
66         # Use 'where' statement or get all the rows
67         if 'where' in parsed_sql:
68             pass
69         else:
70             table_rows = table.iterrows()
71
72         if len(fields) == 1 and fields[0] == 'count(*)':
73             rows.append(Row({'count(*)': table.nrows}))
74         else:
75             for table_row in table_rows:
76                 row = Row()
77                 for field in fields:
78                     if field == 'rowid':
79                         row[field] = table_row.nrow
80                     elif field == '*':
81                         for col in table.colnames:
82                             row[col] = table_row[col]
83                     else:
84                         row[field] = table_row[field]
85                 rows.append(row)
86
87         description = ((col,) for col in table.colnames)
88
89         if truncate:
90             return rows, truncated, description
91         else:
92             return rows
93
94 class Row(OrderedDict):
95     def __getitem__(self, label):
96         if type(label) is int:
97             return super(OrderedDict, self).__getitem__(list(self.keys())[label])