-
Notifications
You must be signed in to change notification settings - Fork 91
/
glue.py
381 lines (337 loc) · 13.6 KB
/
glue.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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
import re
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from typing import Sequence
import boto3
from mypy_boto3_glue import GlueClient
from mypy_boto3_glue.type_defs import ColumnTypeDef
from mypy_boto3_glue.type_defs import GetTableResponseTypeDef
from mypy_boto3_glue.type_defs import PartitionInputTypeDef
from mypy_boto3_glue.type_defs import SerDeInfoTypeDef
from mypy_boto3_glue.type_defs import StorageDescriptorTypeDef
from mypy_boto3_glue.type_defs import TableInputTypeDef
from . import BasePlugin
from ..utils import TargetConfig
from dbt.adapters.base.column import Column
from dbt.adapters.duckdb.secrets import Secret
class UnsupportedFormatType(Exception):
"""UnsupportedFormatType exception."""
class UnsupportedType(Exception):
"""UnsupportedType exception."""
class UndetectedType(Exception):
"""UndetectedType exception."""
def _dbt2glue(dtype: str, ignore_null: bool = False) -> str: # pragma: no cover
"""DuckDB to Glue data types conversion."""
data_type = dtype.split("(")[0]
if data_type.lower() in ["int1", "tinyint"]:
return "tinyint"
if data_type.lower() in ["int2", "smallint", "short", "utinyint"]:
return "smallint"
if data_type.lower() in ["int4", "int", "integer", "signed", "usmallint"]:
return "int"
if data_type.lower() in ["int8", "long", "bigint", "signed", "uinteger"]:
return "bigint"
if data_type.lower() in ["hugeint", "ubigint"]:
raise UnsupportedType(
"There is no support for hugeint or ubigint, please consider bigint or uinteger."
)
if data_type.lower() in ["float4", "float", "real"]:
return "float"
if data_type.lower() in ["float8", "numeric", "decimal", "double"]:
return "double"
if data_type.lower() in ["boolean", "bool", "logical"]:
return "boolean"
if data_type.lower() in ["varchar", "char", "bpchar", "text", "string", "uuid"]:
return "string"
if data_type.lower() in [
"timestamp",
"datetime",
"timestamptz",
"timestamp with time zone",
]:
return "timestamp"
if data_type.lower() in ["date"]:
return "date"
if data_type.lower() in ["blob", "bytea", "binary", "varbinary"]:
return "binary"
if data_type.lower() in ["struct"]:
struct_fields = re.findall(r"(\w+)\s+(\w+)", dtype[dtype.find("(") + 1 : dtype.rfind(")")])
glue_fields = []
for field_name, field_type in struct_fields:
glue_field_type = _dbt2glue(field_type)
glue_fields.append(f"{field_name}:{glue_field_type}")
struct_schema = f"struct<{','.join(glue_fields)}>"
if dtype.strip().endswith("[]"):
return f"array<{struct_schema}>"
return struct_schema
if data_type is None:
if ignore_null:
return ""
raise UndetectedType("We can not infer the data type from an entire null object column")
raise UnsupportedType(f"Unsupported type: {dtype}")
def _get_parquet_table_def(
table: str, s3_parent: str, columns: Sequence["ColumnTypeDef"]
) -> "TableInputTypeDef":
"""Create table definition for Glue table. See https://docs.aws.amazon.com/glue/latest/webapi/API_CreateTable.html#API_CreateTable_RequestSyntax"""
table_def = TableInputTypeDef(
Name=table,
TableType="EXTERNAL_TABLE",
Parameters={"classification": "parquet"},
StorageDescriptor=StorageDescriptorTypeDef(
Columns=columns,
Location=s3_parent,
InputFormat="org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat",
OutputFormat="org.apache.hadoop.hive.ql.io.parquet.MapredParquetOutputFormat",
Compressed=False,
NumberOfBuckets=-1,
SerdeInfo=SerDeInfoTypeDef(
SerializationLibrary="org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe",
Parameters={"serialization.format": "1"},
),
BucketColumns=[],
StoredAsSubDirectories=False,
SortColumns=[],
),
)
return table_def
def _get_csv_table_def(
table: str, s3_parent: str, columns: Sequence["ColumnTypeDef"], delimiter: str = ","
) -> "TableInputTypeDef":
"""Create table definition for Glue table. See https://docs.aws.amazon.com/glue/latest/webapi/API_CreateTable.html#API_CreateTable_RequestSyntax"""
table_def = TableInputTypeDef(
Name=table,
TableType="EXTERNAL_TABLE",
Parameters={"classification": "csv"},
StorageDescriptor=StorageDescriptorTypeDef(
Columns=columns,
Location=s3_parent,
InputFormat="org.apache.hadoop.mapred.TextInputFormat",
OutputFormat="org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
Compressed=False,
NumberOfBuckets=-1,
SerdeInfo=SerDeInfoTypeDef(
SerializationLibrary="org.apache.hadoop.hive.serde2.OpenCSVSerde",
Parameters={"separatorChar": delimiter},
),
BucketColumns=[],
StoredAsSubDirectories=False,
SortColumns=[],
),
)
return table_def
def _convert_columns(column_list: Sequence[Column]) -> Sequence["ColumnTypeDef"]:
"""Convert dbt schema into Glue compliable Schema"""
column_types = []
for column in column_list:
column_types.append(ColumnTypeDef(Name=column.name, Type=_dbt2glue(column.dtype)))
return column_types
def _create_table(
client: "GlueClient",
database: str,
table_def: "TableInputTypeDef",
partition_columns: List[Dict[str, str]],
) -> None:
client.create_table(DatabaseName=database, TableInput=table_def)
# Create partition if relevant
if partition_columns != []:
partition_input, partition_values = _parse_partition_columns(partition_columns, table_def)
client.create_partition(
DatabaseName=database, TableName=table_def["Name"], PartitionInput=partition_input
)
def _update_table(
client: "GlueClient",
database: str,
table_def: "TableInputTypeDef",
partition_columns: List[Dict[str, str]],
) -> None:
client.update_table(DatabaseName=database, TableInput=table_def)
# Update or create partition if relevant
if partition_columns != []:
partition_input, partition_values = _parse_partition_columns(partition_columns, table_def)
try:
client.get_partition(
DatabaseName=database,
TableName=table_def["Name"],
PartitionValues=partition_values,
)
client.update_partition(
DatabaseName=database,
TableName=table_def["Name"],
PartitionValueList=partition_values,
PartitionInput=partition_input,
)
except client.exceptions.EntityNotFoundException:
client.create_partition(
DatabaseName=database, TableName=table_def["Name"], PartitionInput=partition_input
)
def _get_table(
client: "GlueClient", database: str, table: str
) -> Optional["GetTableResponseTypeDef"]:
try:
return client.get_table(DatabaseName=database, Name=table)
except client.exceptions.EntityNotFoundException: # pragma: no cover
return None
def _get_column_type_def(
table_def: "GetTableResponseTypeDef",
) -> Optional[Sequence["ColumnTypeDef"]]:
"""Get columns definition from Glue Table Definition"""
raw = table_def.get("Table", {}).get("StorageDescriptor", {}).get("Columns")
if raw:
converted = []
for column in raw:
converted.append(ColumnTypeDef(Name=column["Name"], Type=column["Type"]))
return converted
else:
return None
def _add_partition_columns(
table_def: TableInputTypeDef, partition_columns: List[Dict[str, str]]
) -> TableInputTypeDef:
partition_keys = []
if "PartitionKeys" not in table_def:
table_def["PartitionKeys"] = []
for column in partition_columns:
partition_column = ColumnTypeDef(Name=column["Name"], Type=column["Type"])
partition_keys.append(partition_column)
table_def["PartitionKeys"] = partition_keys
# Remove columns from StorageDescriptor if they match with partition columns to avoid duplicate columns
for p_column in partition_columns:
table_def["StorageDescriptor"]["Columns"] = [
column # type: ignore
for column in table_def["StorageDescriptor"]["Columns"]
if not (column["Name"] == p_column["Name"] and column["Type"] == p_column["Type"])
]
return table_def
def _parse_partition_columns(
partition_columns: List[Dict[str, str]], table_def: TableInputTypeDef
):
partition_input, partition_values = None, None
if partition_columns:
partition_values = [column["Value"] for column in partition_columns]
partition_location = table_def["StorageDescriptor"]["Location"]
partition_components = [partition_location]
for c in partition_columns:
partition_components.append("=".join((c["Name"], c["Value"])))
partition_location = "/".join(partition_components)
partition_input = PartitionInputTypeDef()
partition_input["Values"] = partition_values
partition_input["StorageDescriptor"] = table_def["StorageDescriptor"]
partition_input["StorageDescriptor"]["Location"] = partition_location
return partition_input, partition_values
def _get_table_def(
table: str,
s3_parent: str,
columns: Sequence["ColumnTypeDef"],
file_format: str,
delimiter: str,
):
if file_format == "csv":
table_def = _get_csv_table_def(
table=table,
s3_parent=s3_parent,
columns=columns,
delimiter=delimiter,
)
elif file_format == "parquet":
table_def = _get_parquet_table_def(table=table, s3_parent=s3_parent, columns=columns)
else:
raise UnsupportedFormatType("Format %s is not supported in Glue registrar." % file_format)
return table_def
def _get_glue_client(
settings: Dict[str, Any], secrets: Optional[List[Dict[str, Any]]]
) -> "GlueClient":
client = None
if secrets is not None:
for secret in secrets:
if isinstance(secret, Secret) and "config" == str(secret.provider).lower():
secret_kwargs = secret.secret_kwargs or {}
client = boto3.client(
"glue",
aws_access_key_id=secret_kwargs.get("key_id"),
aws_secret_access_key=secret_kwargs.get("secret"),
aws_session_token=secret_kwargs.get("session_token"),
region_name=secret_kwargs.get("region"),
)
break
if client is None:
if settings:
client = boto3.client(
"glue",
aws_access_key_id=settings.get("s3_access_key_id"),
aws_secret_access_key=settings.get("s3_secret_access_key"),
aws_session_token=settings.get("s3_session_token"),
region_name=settings.get("s3_region"),
)
else:
client = boto3.client("glue")
return client
def create_or_update_table(
client: GlueClient,
database: str,
table: str,
column_list: Sequence[Column],
s3_path: str,
file_format: str,
delimiter: str,
partition_columns: List[Dict[str, str]] = [],
) -> None:
# Set s3 original path if partitioning is used, else use parent path
if partition_columns != []:
s3_parent = s3_path
if partition_columns == []:
s3_parent = "/".join(s3_path.split("/")[:-1])
# Existing table in AWS Glue catalog
glue_table = _get_table(client=client, database=database, table=table)
columns = _convert_columns(column_list)
table_def = _get_table_def(
table=table,
s3_parent=s3_parent,
columns=columns,
file_format=file_format,
delimiter=delimiter,
)
# Add partition columns
if partition_columns != []:
table_def = _add_partition_columns(table_def, partition_columns)
if glue_table:
# Existing columns in AWS Glue catalog
glue_columns = _get_column_type_def(glue_table)
# Create new version only if columns are changed
if glue_columns != columns:
_update_table(
client=client,
database=database,
table_def=table_def,
partition_columns=partition_columns,
)
else:
_create_table(
client=client,
database=database,
table_def=table_def,
partition_columns=partition_columns,
)
class Plugin(BasePlugin):
def initialize(self, config: Dict[str, Any]):
secrets: Optional[List[Dict[str, Any]]] = (
self.creds.secrets if self.creds is not None else None
)
self.client = _get_glue_client(config, secrets)
self.database = config.get("glue_database", "default")
self.delimiter = config.get("delimiter", ",")
def store(self, target_config: TargetConfig):
assert target_config.location is not None
assert target_config.relation.identifier is not None
table: str = target_config.relation.identifier
partition_columns = target_config.config.get("partition_columns", [])
create_or_update_table(
self.client,
self.database,
table,
target_config.column_list,
target_config.location.path,
target_config.location.format,
self.delimiter,
partition_columns,
)