forked from ibis-project/ibis
/
client.py
210 lines (156 loc) · 5.72 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
try:
import pathlib
except ImportError:
# py2 compat
import pathlib2 as pathlib
import ibis
import ibis.expr.types as ir
import ibis.expr.operations as ops
from ibis.pandas.execution import execute
from ibis.pandas.core import data_preload
from ibis.pandas.client import pandas_dtypes_to_ibis_schema
import ibis.file.execution # noqa
import ibis.file.api # noqa
import pandas as pd
class HDFTable(ops.DatabaseTable):
pass
class CSVTable(ops.DatabaseTable):
pass
class Client(ibis.client.Client):
def __init__(self, root):
super(Client, self).__init__()
self.root = pathlib.Path(str(root))
self.dictionary = {}
def database(self, name=None, path=None):
if name is None:
return Database('root', self, path=path)
if name not in self.list_databases(path):
raise AttributeError(name)
if path is None:
path = self.root
new_name = "{}.{}".format(name, self.extension)
if (self.root / name).is_dir():
path = path / name
elif not str(path).endswith(new_name):
path = path / new_name
return Database(name, self, path=path)
def table(self, name, path):
raise NotImplementedError
def execute(self, expr, params=None, **kwargs):
assert isinstance(expr, ir.Expr)
return execute(expr, params=params)
def list_tables(self, path=None):
raise NotImplementedError
def list_databases(self, path=None):
raise NotImplementedError
class HDFClient(Client):
extension = 'h5'
def table(self, name, path):
if name not in self.list_tables(path):
raise AttributeError(name)
# get the schema
with pd.HDFStore(str(path), mode='r') as store:
df = store.select(name, start=0, stop=0)
schema = pandas_dtypes_to_ibis_schema(df, {})
t = HDFTable(name, schema, self).to_expr()
self.dictionary[name] = path
return t
def list_tables(self, path=None):
# tables are individual tables within a file
if path is None:
path = self.root
if (path.is_file() and str(path).endswith(self.extension)):
with pd.HDFStore(str(path), mode='r') as store:
# strip leading /
return [k[1:] for k in store.keys()]
return []
def list_databases(self, path=None):
# databases are dir & a .h5 file
if path is None:
path = self.root
tables = []
if path.is_dir():
for d in path.iterdir():
if d.is_dir():
tables.append(d.name)
elif d.is_file():
if str(d).endswith(self.extension):
tables.append(d.stem)
elif path.is_file():
# by definition we are at the db level at this point
pass
return tables
class CSVClient(Client):
extension = 'csv'
def table(self, name, path=None):
if name not in self.list_tables(path):
raise AttributeError(name)
if path is None:
path = self.root
# get the schema
f = path / "{}.{}".format(name, self.extension)
df = pd.read_csv(str(f), header=0, nrows=10)
schema = pandas_dtypes_to_ibis_schema(df, {})
t = CSVTable(name, schema, self).to_expr()
self.dictionary[name] = f
return t
def list_tables(self, path=None):
# tables are files in a dir
if path is None:
path = self.root
tables = []
if path.is_dir():
for d in path.iterdir():
if d.is_file():
if str(d).endswith(self.extension):
tables.append(d.stem)
elif path.is_file():
if str(path).endswith(self.extension):
tables.append(path.stem)
return tables
def list_databases(self, path=None):
# databases are dir
if path is None:
path = self.root
tables = []
if path.is_dir():
for d in path.iterdir():
if d.is_dir():
tables.append(d.name)
return tables
class Database(ibis.client.Database):
def __init__(self, name, client, path=None):
super(Database, self).__init__(name, client)
self.path = path
def __str__(self):
return '{0.__class__.__name__}({0.name})'.format(self)
def __dir__(self):
dbs = self.list_databases(path=self.path)
tables = self.list_tables(path=self.path)
return sorted(list(set(dbs).union(set(tables))))
def __getattr__(self, name):
try:
return object.__getattribute__(self, name)
except AttributeError:
try:
return self.table(name, path=self.path)
except AttributeError:
return self.database(name, path=self.path)
def table(self, name, path):
return self.client.table(name, path=path)
def database(self, name=None, path=None):
return self.client.database(name=name, path=path)
def list_databases(self, path=None):
if path is None:
path = self.path
return sorted(self.client.list_databases(path=path))
def list_tables(self, path=None):
if path is None:
path = self.path
return sorted(self.client.list_tables(path=path))
@data_preload.register(HDFTable, (pathlib.Path, str))
def hdf_data_preload_uri_client(table, path, scope=None, **kwargs):
return pd.read_hdf(str(path), table.name, mode='r')
@data_preload.register(CSVTable, (pathlib.Path, str))
def csv_data_preload_uri_client(table, path, scope=None, **kwargs):
return pd.read_csv(str(path), header=0)