-
Notifications
You must be signed in to change notification settings - Fork 108
/
api.py
245 lines (209 loc) · 7.07 KB
/
api.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import ibis
from ibis.backends.impala import Backend as ImpalaBackend
from ibis.backends.impala.client import ImpalaConnection
from typing import Literal
from ibis.backends.impala import udf
from ibis.backends.impala.compiler import rewrites
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
import ibis.expr.schema as sch
import numpy as np
import fsspec
def do_connect(
# Override do_connect to add use_http_transport and http_path params
self,
host: str = "localhost",
port: int = 10000,
database: str = "default",
timeout: int = 45,
use_ssl: bool = False,
ca_cert: str = None,
user: str = None,
password: str = None,
auth_mechanism: Literal["NOSASL", "PLAIN", "GSSAPI", "LDAP"] = "PLAIN",
kerberos_service_name: str = "impala",
pool_size: int = 8,
hdfs_client: fsspec.spec.AbstractFileSystem = None,
use_http_transport: bool = False,
http_path: str = "",
):
self._temp_objects = set()
self._hdfs = hdfs_client
params = {
"host": host,
"port": port,
"database": database,
"timeout": timeout,
"use_ssl": use_ssl,
"ca_cert": ca_cert,
"user": user,
"password": password,
"auth_mechanism": auth_mechanism,
"kerberos_service_name": kerberos_service_name,
"use_http_transport": use_http_transport,
"http_path": http_path,
}
self.con = ImpalaConnection(pool_size=pool_size, **params)
self._ensure_temp_db_exists()
def parse_type(t):
"""Returns the Ibis datatype from source type."""
t = t.lower()
if t in udf._impala_to_ibis_type:
return udf._impala_to_ibis_type[t]
else:
if "varchar" in t or "char" in t:
return "string"
elif "decimal" in t:
result = dt.dtype(t)
if result:
return t
else:
return ValueError(t)
elif "struct" in t or "array" in t or "map" in t:
# Supports parsing through structs/arrays in schema in #444
if "bigint" in t:
t = t.replace(":bigint", ":int64")
elif "tinyint" in t:
t = t.replace(":tinyint", ":int8")
elif "smallint" in t:
t = t.replace(":smallint", ":int16")
else:
t = t.replace(":int", ":int32")
if "varchar" in t:
t = t.replace(":varchar", ":string")
else:
t = t.replace(":char", ":string")
return t
elif "binary" in t:
return "binary"
else:
raise Exception(t)
def get_schema(self, table_name, database=None):
"""
Return a Schema object for the indicated table and database
Parameters
----------
table_name : string
May be fully qualified
database : string, default None
Returns
-------
schema : ibis Schema
"""
qualified_name = self._fully_qualified_name(table_name, database)
query = "DESCRIBE {}".format(qualified_name)
pairs = []
for row in self.con.fetchall(query):
# Add check for empty row for Hive partitioned tables in #375
if row[0] == "":
break
pairs.append(row[:2])
names, types = zip(*pairs)
ibis_types = [parse_type(type.lower()) for type in types]
ibis_fields = dict(zip(names, ibis_types))
return sch.Schema(ibis_fields)
def _chunks_to_pandas_array(chunks):
total_length = 0
have_nulls = False
for c in chunks:
total_length += len(c)
have_nulls = have_nulls or c.nulls.any()
type_ = chunks[0].data_type
numpy_type = ibis.backends.impala._HS2_TTypeId_to_dtype[type_]
def fill_nonnull(target, chunks):
pos = 0
for c in chunks:
target[pos : pos + len(c)] = c.values
pos += len(c.values)
def fill(target, chunks, na_rep):
pos = 0
for c in chunks:
nulls = c.nulls.copy()
nulls.bytereverse()
bits = np.frombuffer(nulls.tobytes(), dtype="u1")
mask = np.unpackbits(bits).view(np.bool_)
k = len(c)
dest = target[pos : pos + k]
dest[:] = c.values
dest[mask[:k]] = na_rep
pos += k
if have_nulls:
# Updating NaN to None for consistency across DBs as per #406
if numpy_type in ("bool", "datetime64[ns]"):
target = np.empty(total_length, dtype="O")
na_rep = None
elif numpy_type.startswith("int"):
target = np.empty(total_length, dtype="f8")
na_rep = np.nan
elif numpy_type in ("object"):
target = np.empty(total_length, dtype=object)
na_rep = None
else:
target = np.empty(total_length, dtype=numpy_type)
na_rep = np.nan
fill(target, chunks, na_rep)
else:
target = np.empty(total_length, dtype=numpy_type)
fill_nonnull(target, chunks)
return target
@rewrites(ops.IfNull)
def _if_null(op):
return ops.Coalesce((op.arg, op.ifnull_expr))
def _get_schema_using_query(self, query):
# Removing LIMIT 0 around query since it returns no results in Hive
cur = self.raw_sql(f"SELECT * FROM ({query}) t0 LIMIT 1")
cur.fetchall()
ibis_fields = self._adapt_types(cur.description)
cur.release()
return sch.Schema(ibis_fields)
udf.parse_type = parse_type
ibis.backends.impala._chunks_to_pandas_array = _chunks_to_pandas_array
ImpalaBackend.get_schema = get_schema
ImpalaBackend._get_schema_using_query = _get_schema_using_query
ImpalaBackend.do_connect = do_connect
def impala_connect(
host: str = "localhost",
port: int = 10000,
database: str = "default",
timeout: int = 45,
use_ssl: bool = False,
ca_cert: str = None,
user: str = None,
password: str = None,
auth_mechanism: Literal["NOSASL", "PLAIN", "GSSAPI", "LDAP"] = "PLAIN",
kerberos_service_name: str = "impala",
pool_size: int = 8,
hdfs_client: fsspec.spec.AbstractFileSystem = None,
use_http_transport: bool = False,
http_path: str = "",
):
backend = ibis.impala.connect(
host=host,
port=port,
database=database,
timeout=timeout,
use_ssl=use_ssl,
ca_cert=ca_cert,
user=user,
password=password,
auth_mechanism=auth_mechanism,
kerberos_service_name=kerberos_service_name,
pool_size=pool_size,
hdfs_client=hdfs_client,
use_http_transport=use_http_transport,
http_path=http_path,
)
return backend