-
Notifications
You must be signed in to change notification settings - Fork 4
/
lineage.py
427 lines (357 loc) · 13.8 KB
/
lineage.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
from typing import Dict, List, Optional, Tuple
from pydantic.dataclasses import Field, dataclass
from metaphor.common.entity_id import (
parts_to_dataset_entity_id,
to_entity_id_from_virtual_view_logical_id,
)
from metaphor.common.sql.table_level_lineage.table_level_lineage import (
extract_table_level_lineage,
)
from metaphor.common.utils import unique_list
from metaphor.models.metadata_change_event import (
EntityUpstream,
FieldMapping,
SourceField,
VirtualView,
VirtualViewLogicalID,
VirtualViewQuery,
VirtualViewSchema,
VirtualViewSchemaField,
VirtualViewType,
)
from metaphor.quick_sight.data_source_utils import (
DATA_SOURCE_PLATFORM_MAP,
get_account,
get_database,
)
from metaphor.quick_sight.models import (
DataSet,
DataSetColumn,
DataSetLogicalTable,
DataSetPhysicalTable,
DataSource,
ResourceType,
TransformOperation,
TypeCustomSql,
TypeRelationalTable,
)
@dataclass
class ColumnReference:
upstream_id: Optional[str]
name: str
@dataclass
class Column:
output: DataSetColumn
upstream: List[ColumnReference] = Field(default_factory=list)
expression: Optional[str] = None
TypeColumnMap = Dict[str, Column]
def _get_source_from_custom_sql(
resources: Dict[str, ResourceType],
custom_sql: TypeCustomSql,
) -> Tuple[Optional[List[str]], Optional[VirtualViewQuery]]:
data_source = resources.get(custom_sql.DataSourceArn)
if (
data_source is None
or not isinstance(data_source, DataSource)
or data_source.Type is None
):
return None, None
data_platform = DATA_SOURCE_PLATFORM_MAP.get(data_source.Type)
if not data_platform:
return None, None
database = get_database(data_source)
account = get_account(data_source)
query = custom_sql.SqlQuery
tll = extract_table_level_lineage(
query,
platform=data_platform,
account=account,
query_id="",
default_database=database,
)
return unique_list([source.id for source in tll.sources]), VirtualViewQuery(
default_database=database,
query=custom_sql.SqlQuery,
source_dataset_account=account,
source_platform=data_platform,
)
def _process_transformation(
columns: TypeColumnMap,
transformations: List[TransformOperation],
) -> None:
for transformation in transformations:
if transformation.CreateColumnsOperation:
for column in transformation.CreateColumnsOperation.Columns:
columns[column.ColumnName] = Column(
upstream=[],
expression=column.Expression,
output=DataSetColumn(Name=column.ColumnName),
)
elif transformation.ProjectOperation:
for key in list(columns.keys()):
if key not in transformation.ProjectOperation.ProjectedColumns:
columns.pop(key)
elif transformation.RenameColumnOperation:
before = transformation.RenameColumnOperation.ColumnName
after = transformation.RenameColumnOperation.NewColumnName
columns[after] = columns[before]
columns.pop(before)
class LineageProcessor:
def __init__(
self,
resources: Dict[str, ResourceType],
virtual_views: Dict[str, VirtualView],
data_set: DataSet,
):
self._resources = resources
self._virtual_views = virtual_views
self._data_set = data_set
def run(self) -> str:
if (
not self._data_set.LogicalTableMap
or not self._data_set.PhysicalTableMap
or not self._data_set.OutputColumns
):
return ""
tables: Dict[str, TypeColumnMap] = {}
self._process_physical_table_map(tables, self._data_set.PhysicalTableMap)
output_table_id = self._process_logical_table_map(
tables, self._data_set.LogicalTableMap
)
return output_table_id
def _get_source_from_relation_table(
self,
relation_table: TypeRelationalTable,
) -> Optional[str]:
data_source = self._resources.get(relation_table.DataSourceArn)
if (
data_source is None
or not isinstance(data_source, DataSource)
or data_source.Type is None
):
return None
data_platform = DATA_SOURCE_PLATFORM_MAP.get(data_source.Type)
if not data_platform:
return None
database = get_database(data_source)
account = get_account(data_source)
source_entity_id = str(
parts_to_dataset_entity_id(
platform=data_platform,
account=account,
database=relation_table.Catalog or database,
schema=relation_table.Schema,
table=relation_table.Name,
)
)
return source_entity_id
def _init_virtual_view(self, table_id: str) -> VirtualView:
view = VirtualView(
logical_id=VirtualViewLogicalID(
name=table_id,
type=VirtualViewType.QUICK_SIGHT,
),
is_non_prod=True,
)
self._virtual_views[table_id] = view
return view
def _process_physical_table_map(
self,
tables: Dict[str, TypeColumnMap],
physical_table_map: Dict[str, DataSetPhysicalTable],
) -> None:
for table_id, physical_table in physical_table_map.items():
column_lineage: TypeColumnMap = {}
if physical_table.CustomSql:
source_entities, query = _get_source_from_custom_sql(
self._resources, physical_table.CustomSql
)
# CLL of custom sql is not supported
for column in physical_table.CustomSql.Columns:
if column.Name is None:
continue
column_lineage[column.Name] = Column(output=column)
view = self._init_virtual_view(table_id)
view.entity_upstream = extract_virtual_view_upstream(
column_lineage, source_entities or []
)
view.schema = extract_virtual_view_schema(column_lineage, query)
elif physical_table.RelationalTable:
source_dataset_id = self._get_source_from_relation_table(
physical_table.RelationalTable
)
columns = physical_table.RelationalTable.InputColumns
for column in columns:
if column.Name is None:
continue
column_lineage[column.Name] = Column(
upstream=[
ColumnReference(
upstream_id=source_dataset_id, name=column.Name
)
],
output=column,
)
view = self._init_virtual_view(table_id)
view.entity_upstream = extract_virtual_view_upstream(
column_lineage, [source_dataset_id] if source_dataset_id else []
)
view.schema = extract_virtual_view_schema(column_lineage)
elif physical_table.S3Source:
for column in physical_table.S3Source.InputColumns:
if column.Name is None:
continue
column_lineage[column.Name] = Column(output=column)
view = self._init_virtual_view(table_id)
view.schema = extract_virtual_view_schema(column_lineage)
tables[table_id] = column_lineage
return None
@staticmethod
def _entity_id(arn_or_table_id: str) -> str:
return str(
to_entity_id_from_virtual_view_logical_id(
VirtualViewLogicalID(
name=arn_or_table_id, type=VirtualViewType.QUICK_SIGHT
)
)
)
@staticmethod
def _replace_upstream_id(
upstream_table: TypeColumnMap,
upstream_id: str,
):
column_lineage: TypeColumnMap = {}
for key, value in upstream_table.items():
if value.output.Name is None:
continue
column_lineage[key] = Column(
output=value.output,
upstream=[
ColumnReference(upstream_id=upstream_id, name=value.output.Name)
],
)
return column_lineage
def _process_logical_table_map(
self,
tables: Dict[str, TypeColumnMap],
logical_table_map: Dict[str, DataSetLogicalTable],
) -> str:
logical_tables = list(logical_table_map.items())
output_table_id = ""
column_lineage: Dict[str, Column]
# Walk through the dependence tree, the last table (root) will be the output table
while logical_tables:
unresolved = []
for table_id, logical_table in logical_tables:
column_lineage = {}
source = logical_table.Source
source_entities: List[str] = []
if source.DataSetArn:
arn = source.DataSetArn
upstream_data_set = self._resources.get(arn)
if upstream_data_set is None:
continue
assert isinstance(upstream_data_set, DataSet)
upstream_id = self._entity_id(arn)
source_entities.append(upstream_id)
for column in upstream_data_set.OutputColumns or []:
if column.Name is None:
continue
column_lineage[column.Name] = Column(
upstream=[
ColumnReference(
upstream_id=upstream_id,
name=column.Name,
)
],
output=column,
)
elif source.PhysicalTableId:
upstream_table = tables.get(source.PhysicalTableId)
upstream_id = self._entity_id(source.PhysicalTableId)
source_entities.append(upstream_id)
if upstream_table:
column_lineage.update(
**self._replace_upstream_id(upstream_table, upstream_id)
)
else:
assert False, "should not happen"
elif source.JoinInstruction:
left_table_id = source.JoinInstruction.LeftOperand
right_table_id = source.JoinInstruction.RightOperand
source_entities.append(self._entity_id(left_table_id))
source_entities.append(self._entity_id(right_table_id))
left_table = tables.get(left_table_id)
right_table = tables.get(right_table_id)
if left_table and right_table:
column_lineage.update(
**self._replace_upstream_id(
left_table, self._entity_id(left_table_id)
)
)
column_lineage.update(
**self._replace_upstream_id(
right_table, self._entity_id(right_table_id)
)
)
if not column_lineage:
unresolved.append((table_id, logical_table))
continue
_process_transformation(
column_lineage, logical_table.DataTransforms or []
)
view = self._init_virtual_view(table_id)
view.entity_upstream = extract_virtual_view_upstream(
column_lineage, source_entities
)
view.schema = extract_virtual_view_schema(column_lineage)
tables[table_id] = column_lineage
output_table_id = table_id
logical_tables = unresolved
# Return root table_id
return output_table_id
def extract_virtual_view_schema(
column_lineage: TypeColumnMap,
query: Optional[VirtualViewQuery] = None,
) -> Optional[VirtualViewSchema]:
if not column_lineage:
return None
fields: List[VirtualViewSchemaField] = []
for column in column_lineage.values():
if column.output.Name is None:
continue
fields.append(
VirtualViewSchemaField(
field_name=column.output.Name,
field_path=column.output.Name.lower(),
description=column.output.Description,
type=column.output.Type,
formula=column.expression,
optional_type=("FORMULA" if column.expression else None),
)
)
return (
VirtualViewSchema(
fields=sorted(fields, key=lambda f: f.field_path), query=query
)
if fields
else None
)
def extract_virtual_view_upstream(
column_lineage: Dict[str, Column], source_entities: List[str]
) -> EntityUpstream:
field_mappings: List[FieldMapping] = []
for column_name, upstream_column in column_lineage.items():
field_mappings.append(
FieldMapping(
destination=column_name.lower(),
sources=[
SourceField(source_entity_id=x.upstream_id, field=x.name.lower())
for x in upstream_column.upstream
],
)
)
return EntityUpstream(
source_entities=source_entities if source_entities else None,
field_mappings=field_mappings if field_mappings else None,
)