forked from GoogleCloudPlatform/professional-services
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hive_table_model.py
executable file
·283 lines (232 loc) · 9.93 KB
/
hive_table_model.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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# Copyright 2019 Google Inc.
#
# 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.
"""Module to wrap Hive table as a model."""
import logging
from collections import OrderedDict
from uuid import uuid4
import hashlib
logger = logging.getLogger('Hive2BigQuery')
class HiveTableModel(object):
"""Wrapper for resource describing a Hive table.
Bundles information of different properties of the source Hive table such
as schema, location of the table, input format, partition column etc.
Attributes:
table_details (dict): Hive table details such as database name,
table name, schema, input format of the table, partition
information and a boolean indicating whether the table data format
is supported by BigQuery.
inc_col_details (dict): Incremental column(if any) and it's data type.
destination_details (dict): Dictionary containing destination data
format of BigQuery, one of [Avro,ORC,Parquet] and BigQuery table name.
create_statement (str): CREATE TABLE statement for Hive staging table.
tracking_table_name (str): Cloud SQL tracking table name.
is_first_run (boolean): A boolean indicating whether the table is being
migrated for the first time.
flat_schema (dict): Flattened schema of the table.
"""
def __init__(self, **kwargs):
logger.debug('Initializing HiveTableModel Object')
self._table_details = kwargs['table_details']
self._inc_col_details = {"name": kwargs['inc_col'], "type": None,
"options": kwargs['inc_col_options']}
self._destination_details = {
"data_format": kwargs['destination_data_format'],
"bq_table": kwargs['bq_table_name']}
self.create_statement = kwargs['create_statement']
encode_string = "{}_{}_{}".format(self.db_name, self.table_name,
self._destination_details['bq_table'])
self._tracking_table_name = "hive_bq_" + hashlib.md5(
encode_string.encode('utf-8')).hexdigest()
self._is_first_run = True
self._flat_schema = None
def __str__(self):
"""Iterates over the attributes dictionary of HiveTableModel object
and returns a string which contains all the attribute values."""
model = 'Hive Table Model\n'
for key, value in self.__dict__.items():
model += key + ' : ' + str(value) + '\n'
return model
@property
def db_name(self):
return self._table_details['database_name']
@property
def table_name(self):
return self._table_details['table_name']
@property
def schema(self):
return self._table_details['schema']
@property
def input_format(self):
return self._table_details['input_format']
@property
def partition_info(self):
return self._table_details['partition_info']
@property
def is_table_type_supported(self):
return self._table_details['is_table_type_supported']
@property
def n_cols(self):
return len(self.schema)
@property
def is_partitioned(self):
if self._table_details['partition_info']:
return True
return False
@property
def flat_schema(self):
if self._flat_schema is None:
self._flat_schema = self.flatten_schema()
return self._flat_schema
@property
def is_inc_col_present(self):
if self._inc_col_details['name']:
return 1
return 0
# @is_inc_col_present.setter
# def is_inc_col_present(self, value):
# logger.debug("Setting value is_inc_col_present to %s", value)
# if value in [True, False]:
# self._inc_col_details['type'] = value
# else:
# logger.debug(
# "Can't set is_inc_col_present to other than True/False")
@property
def inc_col(self):
return self._inc_col_details['name']
@inc_col.setter
def inc_col(self, value):
logger.debug("Setting value inc_col to %s", value)
self._inc_col_details['name'] = value
@property
def inc_col_type(self):
return self._inc_col_details['type']
@inc_col_type.setter
def inc_col_type(self, value):
logger.debug("Setting value inc_col_type to %s", value)
self._inc_col_details['type'] = value
@property
def int_type_col(self):
return self._inc_col_details['options']['int']
@property
def timestamp_type_col(self):
return self._inc_col_details['options']['timestamp']
@property
def staging_table_name(self):
return 'stage__{}__{}'.format(self.table_name, str(uuid4()).replace("-","_"))
@property
def destination_data_format(self):
return self._destination_details['data_format']
@property
def bq_table_name(self):
return self._destination_details['bq_table']
@property
def tracking_table_name(self):
return self._tracking_table_name
@tracking_table_name.setter
def tracking_table_name(self, value):
logger.debug("Setting value tracking_table_name to %s", value)
self._tracking_table_name = value
@property
def is_first_run(self):
return self._is_first_run
@is_first_run.setter
def is_first_run(self, value):
logger.debug("Setting value is_first_run to %s", value)
if value in [True, False]:
self._is_first_run = value
else:
logger.debug("Can't set is_first_run to other than True/False")
def flatten_schema(self):
"""Returns Hive table schema in flat structure.
Nested data types in Hive schema are represented using '<'. For
example, array of integers is represented as 'array<int>'. Similarly,
maps and structs are represented too. To compare the data types in
Hive and BigQuery, this schema needs to be flattened out and then the
internal data type can be compared.
For example col_name(map<string,array<int>>) in Hive is flattened as
{
"col_name" : "map",
"col_name__key" : "string",
"col_name__value" : "array_int"
}
Uses string extraction to flatten the schema.
Returns:
dict: A dictionary mapping flattened columns and their data types.
"""
def recursively_flatten(name, item_type):
"""Iterates through the nested fields and gets the data types.
Args:
name (str): Flattened column name.
item_type (str): Flattened column type.
"""
columns.append(name)
if '<' in item_type:
col_type = item_type.split('<')[0]
# If type is array, recursively flatten the nested structure.
if col_type == 'array':
col_types.append('array')
recursively_flatten(name,
'<'.join(item_type.split('<')[1:])[:-1])
# If type is map, recursively flatten the value in the map.
elif col_type == 'map':
col_types.append('map')
columns.append(name + '__key')
col_types.append('string')
recursively_flatten(name + '__value', ','.join(
'<'.join(item_type.split('<')[1:])[:-1].split(',')[1:]))
elif col_type == "uniontype":
col_types.append('union')
# If type is struct, recursively flatten all the fields inside.
elif col_type == 'struct':
col_types.append('struct')
struct_info = '<'.join(item_type.split('<')[1:])[:-1]
rand = []
struct_split = struct_info.split(',')
for i, struct_item in enumerate(struct_split):
if struct_item.count('<') == struct_item.count('>'):
rand.append(struct_item)
else:
struct_split[i + 1] = struct_item + ',' + \
struct_split[i + 1]
for item in rand:
recursively_flatten(name + '__' + item.split(':')[0],
':'.join(item.split(':')[1:]))
else:
col_types.append(item_type)
columns = []
col_types = []
for name, col_type in self.schema.items():
recursively_flatten(name, col_type)
list_tuple = zip(columns, col_types)
col_dict = OrderedDict()
for item in list_tuple:
if item[0] in col_dict.keys():
col_dict[str(item[0])].append(str(item[1]))
else:
col_dict[str(item[0])] = [str(item[1])]
for key, value in col_dict.items():
if len(value) >= 2:
collapse_string = "array_" * value.count('array') + \
[item for item in value if item != 'array'][0]
col_dict[key] = collapse_string
else:
col_dict[key] = value[0]
for key, value in col_dict.items():
if 'decimal' in value:
col_dict[key] = 'decimal'
elif 'varchar' in value:
col_dict[key] = 'varchar'
elif 'char' in value:
col_dict[key] = 'char'
return col_dict