-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
sqlglot_lineage.py
1329 lines (1109 loc) · 46.4 KB
/
sqlglot_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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import contextlib
import enum
import functools
import itertools
import logging
import pathlib
from collections import defaultdict
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
import pydantic.dataclasses
import sqlglot
import sqlglot.errors
import sqlglot.lineage
import sqlglot.optimizer.annotate_types
import sqlglot.optimizer.optimizer
import sqlglot.optimizer.qualify
from pydantic import BaseModel
from typing_extensions import TypedDict
from datahub.configuration.pydantic_migration_helpers import PYDANTIC_VERSION_2
from datahub.emitter.mce_builder import (
DEFAULT_ENV,
make_dataset_urn_with_platform_instance,
)
from datahub.ingestion.api.closeable import Closeable
from datahub.ingestion.graph.client import DataHubGraph
from datahub.ingestion.source.bigquery_v2.bigquery_audit import BigqueryTableIdentifier
from datahub.metadata.schema_classes import (
ArrayTypeClass,
BooleanTypeClass,
DateTypeClass,
NumberTypeClass,
OperationTypeClass,
SchemaFieldDataTypeClass,
SchemaMetadataClass,
StringTypeClass,
TimeTypeClass,
)
from datahub.utilities.file_backed_collections import ConnectionWrapper, FileBackedDict
from datahub.utilities.urns.field_paths import get_simple_field_path_from_v2_field_path
logger = logging.getLogger(__name__)
Urn = str
# A lightweight table schema: column -> type mapping.
SchemaInfo = Dict[str, str]
SQL_PARSE_RESULT_CACHE_SIZE = 1000
RULES_BEFORE_TYPE_ANNOTATION: tuple = tuple(
filter(
# Skip pushdown_predicates because it sometimes throws exceptions, and we
# don't actually need it for anything.
lambda func: func.__name__ not in {"pushdown_predicates"},
itertools.takewhile(
lambda func: func != sqlglot.optimizer.annotate_types.annotate_types,
sqlglot.optimizer.optimizer.RULES,
),
)
)
# Quick check that the rules were loaded correctly.
assert 0 < len(RULES_BEFORE_TYPE_ANNOTATION) < len(sqlglot.optimizer.optimizer.RULES)
class GraphQLSchemaField(TypedDict):
fieldPath: str
nativeDataType: str
class GraphQLSchemaMetadata(TypedDict):
fields: List[GraphQLSchemaField]
class QueryType(enum.Enum):
CREATE = "CREATE"
SELECT = "SELECT"
INSERT = "INSERT"
UPDATE = "UPDATE"
DELETE = "DELETE"
MERGE = "MERGE"
UNKNOWN = "UNKNOWN"
def to_operation_type(self) -> Optional[str]:
if self == QueryType.CREATE:
return OperationTypeClass.CREATE
elif self == QueryType.INSERT:
return OperationTypeClass.INSERT
elif self == QueryType.UPDATE:
return OperationTypeClass.UPDATE
elif self == QueryType.DELETE:
return OperationTypeClass.DELETE
elif self == QueryType.MERGE:
return OperationTypeClass.UPDATE
elif self == QueryType.SELECT:
return None
else:
return OperationTypeClass.UNKNOWN
def get_query_type_of_sql(expression: sqlglot.exp.Expression) -> QueryType:
# UPGRADE: Once we use Python 3.10, replace this with a match expression.
mapping = {
sqlglot.exp.Create: QueryType.CREATE,
sqlglot.exp.Select: QueryType.SELECT,
sqlglot.exp.Insert: QueryType.INSERT,
sqlglot.exp.Update: QueryType.UPDATE,
sqlglot.exp.Delete: QueryType.DELETE,
sqlglot.exp.Merge: QueryType.MERGE,
sqlglot.exp.Subqueryable: QueryType.SELECT, # unions, etc. are also selects
}
for cls, query_type in mapping.items():
if isinstance(expression, cls):
return query_type
return QueryType.UNKNOWN
class _ParserBaseModel(
BaseModel,
arbitrary_types_allowed=True,
json_encoders={
SchemaFieldDataTypeClass: lambda v: v.to_obj(),
},
):
def json(self, *args: Any, **kwargs: Any) -> str:
if PYDANTIC_VERSION_2:
return super().model_dump_json(*args, **kwargs) # type: ignore
else:
return super().json(*args, **kwargs)
@functools.total_ordering
class _FrozenModel(_ParserBaseModel, frozen=True):
def __lt__(self, other: "_FrozenModel") -> bool:
# TODO: The __fields__ attribute is deprecated in Pydantic v2.
for field in self.__fields__:
self_v = getattr(self, field)
other_v = getattr(other, field)
if self_v != other_v:
return self_v < other_v
return False
class _TableName(_FrozenModel):
database: Optional[str] = None
db_schema: Optional[str] = None
table: str
def as_sqlglot_table(self) -> sqlglot.exp.Table:
return sqlglot.exp.Table(
catalog=sqlglot.exp.Identifier(this=self.database)
if self.database
else None,
db=sqlglot.exp.Identifier(this=self.db_schema) if self.db_schema else None,
this=sqlglot.exp.Identifier(this=self.table),
)
def qualified(
self,
dialect: sqlglot.Dialect,
default_db: Optional[str] = None,
default_schema: Optional[str] = None,
) -> "_TableName":
database = self.database or default_db
db_schema = self.db_schema or default_schema
return _TableName(
database=database,
db_schema=db_schema,
table=self.table,
)
@classmethod
def from_sqlglot_table(
cls,
table: sqlglot.exp.Table,
default_db: Optional[str] = None,
default_schema: Optional[str] = None,
) -> "_TableName":
return cls(
database=table.catalog or default_db,
db_schema=table.db or default_schema,
table=table.this.name,
)
class _ColumnRef(_FrozenModel):
table: _TableName
column: str
class ColumnRef(_FrozenModel):
table: Urn
column: str
class _DownstreamColumnRef(_ParserBaseModel):
table: Optional[_TableName] = None
column: str
column_type: Optional[sqlglot.exp.DataType] = None
class DownstreamColumnRef(_ParserBaseModel):
table: Optional[Urn] = None
column: str
column_type: Optional[SchemaFieldDataTypeClass] = None
native_column_type: Optional[str] = None
@pydantic.validator("column_type", pre=True)
def _load_column_type(
cls, v: Optional[Union[dict, SchemaFieldDataTypeClass]]
) -> Optional[SchemaFieldDataTypeClass]:
if v is None:
return None
if isinstance(v, SchemaFieldDataTypeClass):
return v
return SchemaFieldDataTypeClass.from_obj(v)
class _ColumnLineageInfo(_ParserBaseModel):
downstream: _DownstreamColumnRef
upstreams: List[_ColumnRef]
logic: Optional[str] = None
class ColumnLineageInfo(_ParserBaseModel):
downstream: DownstreamColumnRef
upstreams: List[ColumnRef]
# Logic for this column, as a SQL expression.
logic: Optional[str] = pydantic.Field(default=None, exclude=True)
class SqlParsingDebugInfo(_ParserBaseModel):
confidence: float = 0.0
tables_discovered: int = 0
table_schemas_resolved: int = 0
table_error: Optional[Exception] = None
column_error: Optional[Exception] = None
@property
def error(self) -> Optional[Exception]:
return self.table_error or self.column_error
class SqlParsingResult(_ParserBaseModel):
query_type: QueryType = QueryType.UNKNOWN
in_tables: List[Urn]
out_tables: List[Urn]
column_lineage: Optional[List[ColumnLineageInfo]] = None
# TODO include formatted original sql logic
# TODO include list of referenced columns
debug_info: SqlParsingDebugInfo = pydantic.Field(
default_factory=lambda: SqlParsingDebugInfo(),
exclude=True,
)
@classmethod
def make_from_error(cls, error: Exception) -> "SqlParsingResult":
return cls(
in_tables=[],
out_tables=[],
debug_info=SqlParsingDebugInfo(
table_error=error,
),
)
def _parse_statement(
sql: sqlglot.exp.ExpOrStr, dialect: sqlglot.Dialect
) -> sqlglot.Expression:
statement: sqlglot.Expression = sqlglot.maybe_parse(
sql, dialect=dialect, error_level=sqlglot.ErrorLevel.RAISE
)
return statement
def _table_level_lineage(
statement: sqlglot.Expression, dialect: sqlglot.Dialect
) -> Tuple[Set[_TableName], Set[_TableName]]:
# Generate table-level lineage.
modified = {
_TableName.from_sqlglot_table(expr.this)
for expr in statement.find_all(
sqlglot.exp.Create,
sqlglot.exp.Insert,
sqlglot.exp.Update,
sqlglot.exp.Delete,
sqlglot.exp.Merge,
)
# In some cases like "MERGE ... then INSERT (col1, col2) VALUES (col1, col2)",
# the `this` on the INSERT part isn't a table.
if isinstance(expr.this, sqlglot.exp.Table)
} | {
# For CREATE DDL statements, the table name is nested inside
# a Schema object.
_TableName.from_sqlglot_table(expr.this.this)
for expr in statement.find_all(sqlglot.exp.Create)
if isinstance(expr.this, sqlglot.exp.Schema)
and isinstance(expr.this.this, sqlglot.exp.Table)
}
tables = (
{
_TableName.from_sqlglot_table(table)
for table in statement.find_all(sqlglot.exp.Table)
}
# ignore references created in this query
- modified
# ignore CTEs created in this statement
- {
_TableName(database=None, db_schema=None, table=cte.alias_or_name)
for cte in statement.find_all(sqlglot.exp.CTE)
}
)
# TODO: If a CTAS has "LIMIT 0", it's not really lineage, just copying the schema.
# Update statements implicitly read from the table being updated, so add those back in.
if isinstance(statement, sqlglot.exp.Update):
tables = tables | modified
return tables, modified
TABLE_CASE_SENSITIVE_PLATFORMS = {"bigquery"}
class SchemaResolver(Closeable):
def __init__(
self,
*,
platform: str,
platform_instance: Optional[str] = None,
env: str = DEFAULT_ENV,
graph: Optional[DataHubGraph] = None,
_cache_filename: Optional[pathlib.Path] = None,
):
# TODO handle platforms when prefixed with urn:li:dataPlatform:
self.platform = platform
self.platform_instance = platform_instance
self.env = env
self.graph = graph
# Init cache, potentially restoring from a previous run.
shared_conn = None
if _cache_filename:
shared_conn = ConnectionWrapper(filename=_cache_filename)
self._schema_cache: FileBackedDict[Optional[SchemaInfo]] = FileBackedDict(
shared_connection=shared_conn,
)
def get_urns(self) -> Set[str]:
return set(self._schema_cache.keys())
def get_urn_for_table(self, table: _TableName, lower: bool = False) -> str:
# TODO: Validate that this is the correct 2/3 layer hierarchy for the platform.
table_name = ".".join(
filter(None, [table.database, table.db_schema, table.table])
)
platform_instance = self.platform_instance
if lower:
table_name = table_name.lower()
platform_instance = platform_instance.lower() if platform_instance else None
if self.platform == "bigquery":
# Normalize shard numbers and other BigQuery weirdness.
with contextlib.suppress(IndexError):
table_name = BigqueryTableIdentifier.from_string_name(
table_name
).get_table_name()
urn = make_dataset_urn_with_platform_instance(
platform=self.platform,
platform_instance=platform_instance,
env=self.env,
name=table_name,
)
return urn
def resolve_table(self, table: _TableName) -> Tuple[str, Optional[SchemaInfo]]:
urn = self.get_urn_for_table(table)
schema_info = self._resolve_schema_info(urn)
if schema_info:
return urn, schema_info
urn_lower = self.get_urn_for_table(table, lower=True)
if urn_lower != urn:
schema_info = self._resolve_schema_info(urn_lower)
if schema_info:
return urn_lower, schema_info
if self.platform in TABLE_CASE_SENSITIVE_PLATFORMS:
return urn, None
else:
return urn_lower, None
def _resolve_schema_info(self, urn: str) -> Optional[SchemaInfo]:
if urn in self._schema_cache:
return self._schema_cache[urn]
# TODO: For bigquery partitioned tables, add the pseudo-column _PARTITIONTIME
# or _PARTITIONDATE where appropriate.
if self.graph:
schema_info = self._fetch_schema_info(self.graph, urn)
if schema_info:
self._save_to_cache(urn, schema_info)
return schema_info
self._save_to_cache(urn, None)
return None
def add_schema_metadata(
self, urn: str, schema_metadata: SchemaMetadataClass
) -> None:
schema_info = self._convert_schema_aspect_to_info(schema_metadata)
self._save_to_cache(urn, schema_info)
def add_raw_schema_info(self, urn: str, schema_info: SchemaInfo) -> None:
self._save_to_cache(urn, schema_info)
def add_graphql_schema_metadata(
self, urn: str, schema_metadata: GraphQLSchemaMetadata
) -> None:
schema_info = self.convert_graphql_schema_metadata_to_info(schema_metadata)
self._save_to_cache(urn, schema_info)
def _save_to_cache(self, urn: str, schema_info: Optional[SchemaInfo]) -> None:
self._schema_cache[urn] = schema_info
def _fetch_schema_info(self, graph: DataHubGraph, urn: str) -> Optional[SchemaInfo]:
aspect = graph.get_aspect(urn, SchemaMetadataClass)
if not aspect:
return None
return self._convert_schema_aspect_to_info(aspect)
@classmethod
def _convert_schema_aspect_to_info(
cls, schema_metadata: SchemaMetadataClass
) -> SchemaInfo:
return {
get_simple_field_path_from_v2_field_path(col.fieldPath): (
# The actual types are more of a "nice to have".
col.nativeDataType
or "str"
)
for col in schema_metadata.fields
# TODO: We can't generate lineage to columns nested within structs yet.
if "." not in get_simple_field_path_from_v2_field_path(col.fieldPath)
}
@classmethod
def convert_graphql_schema_metadata_to_info(
cls, schema: GraphQLSchemaMetadata
) -> SchemaInfo:
return {
get_simple_field_path_from_v2_field_path(field["fieldPath"]): (
# The actual types are more of a "nice to have".
field["nativeDataType"]
or "str"
)
for field in schema["fields"]
# TODO: We can't generate lineage to columns nested within structs yet.
if "." not in get_simple_field_path_from_v2_field_path(field["fieldPath"])
}
def close(self) -> None:
self._schema_cache.close()
# TODO: Once PEP 604 is supported (Python 3.10), we can unify these into a
# single type. See https://peps.python.org/pep-0604/#isinstance-and-issubclass.
_SupportedColumnLineageTypes = Union[
# Note that Select and Union inherit from Subqueryable.
sqlglot.exp.Subqueryable,
# For actual subqueries, the statement type might also be DerivedTable.
sqlglot.exp.DerivedTable,
]
_SupportedColumnLineageTypesTuple = (sqlglot.exp.Subqueryable, sqlglot.exp.DerivedTable)
DIALECTS_WITH_CASE_INSENSITIVE_COLS = {
# Column identifiers are case-insensitive in BigQuery, so we need to
# do a normalization step beforehand to make sure it's resolved correctly.
"bigquery",
# Our snowflake source lowercases column identifiers, so we are forced
# to do fuzzy (case-insensitive) resolution instead of exact resolution.
"snowflake",
# Teradata column names are case-insensitive.
# A name, even when enclosed in double quotation marks, is not case sensitive. For example, CUSTOMER and Customer are the same.
# See more below:
# https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/acreldb/n0ejgx4895bofnn14rlguktfx5r3.htm
"teradata",
}
DIALECTS_WITH_DEFAULT_UPPERCASE_COLS = {
# In some dialects, column identifiers are effectively case insensitive
# because they are automatically converted to uppercase. Most other systems
# automatically lowercase unquoted identifiers.
"snowflake",
}
class UnsupportedStatementTypeError(TypeError):
pass
class SqlUnderstandingError(Exception):
# Usually hit when we need schema info for a given statement but don't have it.
pass
# TODO: Break this up into smaller functions.
def _column_level_lineage( # noqa: C901
statement: sqlglot.exp.Expression,
dialect: sqlglot.Dialect,
table_schemas: Dict[_TableName, SchemaInfo],
output_table: Optional[_TableName],
default_db: Optional[str],
default_schema: Optional[str],
) -> List[_ColumnLineageInfo]:
is_create_ddl = _is_create_table_ddl(statement)
if (
not isinstance(
statement,
_SupportedColumnLineageTypesTuple,
)
and not is_create_ddl
):
raise UnsupportedStatementTypeError(
f"Can only generate column-level lineage for select-like inner statements, not {type(statement)}"
)
column_lineage: List[_ColumnLineageInfo] = []
use_case_insensitive_cols = _is_dialect_instance(
dialect, DIALECTS_WITH_CASE_INSENSITIVE_COLS
)
sqlglot_db_schema = sqlglot.MappingSchema(
dialect=dialect,
# We do our own normalization, so don't let sqlglot do it.
normalize=False,
)
table_schema_normalized_mapping: Dict[_TableName, Dict[str, str]] = defaultdict(
dict
)
for table, table_schema in table_schemas.items():
normalized_table_schema: SchemaInfo = {}
for col, col_type in table_schema.items():
if use_case_insensitive_cols:
col_normalized = (
# This is required to match Sqlglot's behavior.
col.upper()
if _is_dialect_instance(
dialect, DIALECTS_WITH_DEFAULT_UPPERCASE_COLS
)
else col.lower()
)
else:
col_normalized = col
table_schema_normalized_mapping[table][col_normalized] = col
normalized_table_schema[col_normalized] = col_type
sqlglot_db_schema.add_table(
table.as_sqlglot_table(),
column_mapping=normalized_table_schema,
)
if use_case_insensitive_cols:
def _sqlglot_force_column_normalizer(
node: sqlglot.exp.Expression,
) -> sqlglot.exp.Expression:
if isinstance(node, sqlglot.exp.Column):
node.this.set("quoted", False)
return node
# logger.debug(
# "Prior to case normalization sql %s",
# statement.sql(pretty=True, dialect=dialect),
# )
statement = statement.transform(_sqlglot_force_column_normalizer, copy=False)
# logger.debug(
# "Sql after casing normalization %s",
# statement.sql(pretty=True, dialect=dialect),
# )
def _schema_aware_fuzzy_column_resolve(
table: Optional[_TableName], sqlglot_column: str
) -> str:
default_col_name = (
sqlglot_column.lower() if use_case_insensitive_cols else sqlglot_column
)
if table:
return table_schema_normalized_mapping[table].get(
sqlglot_column, default_col_name
)
else:
return default_col_name
# Optimize the statement + qualify column references.
logger.debug(
"Prior to column qualification sql %s",
statement.sql(pretty=True, dialect=dialect),
)
try:
# Second time running qualify, this time with:
# - the select instead of the full outer statement
# - schema info
# - column qualification enabled
# - running the full pre-type annotation optimizer
# logger.debug("Schema: %s", sqlglot_db_schema.mapping)
statement = sqlglot.optimizer.optimizer.optimize(
statement,
dialect=dialect,
schema=sqlglot_db_schema,
qualify_columns=True,
validate_qualify_columns=False,
identify=True,
# sqlglot calls the db -> schema -> table hierarchy "catalog", "db", "table".
catalog=default_db,
db=default_schema,
rules=RULES_BEFORE_TYPE_ANNOTATION,
)
except (sqlglot.errors.OptimizeError, ValueError) as e:
raise SqlUnderstandingError(
f"sqlglot failed to map columns to their source tables; likely missing/outdated table schema info: {e}"
) from e
logger.debug("Qualified sql %s", statement.sql(pretty=True, dialect=dialect))
# Handle the create DDL case.
if is_create_ddl:
assert (
output_table is not None
), "output_table must be set for create DDL statements"
create_schema: sqlglot.exp.Schema = statement.this
sqlglot_columns = create_schema.expressions
for column_def in sqlglot_columns:
if not isinstance(column_def, sqlglot.exp.ColumnDef):
# Ignore things like constraints.
continue
output_col = _schema_aware_fuzzy_column_resolve(
output_table, column_def.name
)
output_col_type = column_def.args.get("kind")
column_lineage.append(
_ColumnLineageInfo(
downstream=_DownstreamColumnRef(
table=output_table,
column=output_col,
column_type=output_col_type,
),
upstreams=[],
)
)
return column_lineage
# Try to figure out the types of the output columns.
try:
statement = sqlglot.optimizer.annotate_types.annotate_types(
statement, schema=sqlglot_db_schema
)
except (sqlglot.errors.OptimizeError, sqlglot.errors.ParseError) as e:
# This is not a fatal error, so we can continue.
logger.debug("sqlglot failed to annotate or parse types: %s", e)
try:
assert isinstance(statement, _SupportedColumnLineageTypesTuple)
# List output columns.
output_columns = [
(select_col.alias_or_name, select_col) for select_col in statement.selects
]
logger.debug("output columns: %s", [col[0] for col in output_columns])
for output_col, original_col_expression in output_columns:
if output_col == "*":
# If schema information is available, the * will be expanded to the actual columns.
# Otherwise, we can't process it.
continue
if _is_dialect_instance(dialect, "bigquery") and output_col.lower() in {
"_partitiontime",
"_partitiondate",
}:
# These are not real columns, just a way to filter by partition.
# TODO: We should add these columns to the schema info instead.
# Once that's done, we should actually generate lineage for these
# if they appear in the output.
continue
lineage_node = sqlglot.lineage.lineage(
output_col,
statement,
dialect=dialect,
schema=sqlglot_db_schema,
)
# pathlib.Path("sqlglot.html").write_text(
# str(lineage_node.to_html(dialect=dialect))
# )
# Generate SELECT lineage.
# Using a set here to deduplicate upstreams.
direct_raw_col_upstreams: Set[_ColumnRef] = set()
for node in lineage_node.walk():
if node.downstream:
# We only want the leaf nodes.
pass
elif isinstance(node.expression, sqlglot.exp.Table):
table_ref = _TableName.from_sqlglot_table(node.expression)
# Parse the column name out of the node name.
# Sqlglot calls .sql(), so we have to do the inverse.
normalized_col = sqlglot.parse_one(node.name).this.name
if node.subfield:
normalized_col = f"{normalized_col}.{node.subfield}"
direct_raw_col_upstreams.add(
_ColumnRef(table=table_ref, column=normalized_col)
)
else:
# This branch doesn't matter. For example, a count(*) column would go here, and
# we don't get any column-level lineage for that.
pass
# column_logic = lineage_node.source
if output_col.startswith("_col_"):
# This is the format sqlglot uses for unnamed columns e.g. 'count(id)' -> 'count(id) AS _col_0'
# This is a bit jank since we're relying on sqlglot internals, but it seems to be
# the best way to do it.
output_col = original_col_expression.this.sql(dialect=dialect)
output_col = _schema_aware_fuzzy_column_resolve(output_table, output_col)
# Guess the output column type.
output_col_type = None
if original_col_expression.type:
output_col_type = original_col_expression.type
# Fuzzy resolve upstream columns.
direct_resolved_col_upstreams = {
_ColumnRef(
table=edge.table,
column=_schema_aware_fuzzy_column_resolve(edge.table, edge.column),
)
for edge in direct_raw_col_upstreams
}
if not direct_resolved_col_upstreams:
logger.debug(f' "{output_col}" has no upstreams')
column_lineage.append(
_ColumnLineageInfo(
downstream=_DownstreamColumnRef(
table=output_table,
column=output_col,
column_type=output_col_type,
),
upstreams=sorted(direct_resolved_col_upstreams),
# logic=column_logic.sql(pretty=True, dialect=dialect),
)
)
# TODO: Also extract referenced columns (aka auxillary / non-SELECT lineage)
except (sqlglot.errors.OptimizeError, ValueError) as e:
raise SqlUnderstandingError(
f"sqlglot failed to compute some lineage: {e}"
) from e
return column_lineage
def _extract_select_from_create(
statement: sqlglot.exp.Create,
) -> sqlglot.exp.Expression:
# TODO: Validate that this properly includes WITH clauses in all dialects.
inner = statement.expression
if inner:
return inner
else:
return statement
_UPDATE_ARGS_NOT_SUPPORTED_BY_SELECT: Set[str] = set(
sqlglot.exp.Update.arg_types.keys()
) - set(sqlglot.exp.Select.arg_types.keys())
_UPDATE_FROM_TABLE_ARGS_TO_MOVE = {"joins", "laterals", "pivot"}
def _extract_select_from_update(
statement: sqlglot.exp.Update,
) -> sqlglot.exp.Select:
statement = statement.copy()
# The "SET" expressions need to be converted.
# For the update command, it'll be a list of EQ expressions, but the select
# should contain aliased columns.
new_expressions = []
for expr in statement.expressions:
if isinstance(expr, sqlglot.exp.EQ) and isinstance(
expr.left, sqlglot.exp.Column
):
new_expressions.append(
sqlglot.exp.Alias(
this=expr.right,
alias=expr.left.this,
)
)
else:
# If we don't know how to convert it, just leave it as-is. If this causes issues,
# they'll get caught later.
new_expressions.append(expr)
# Special translation for the `from` clause.
extra_args = {}
original_from = statement.args.get("from")
if original_from and isinstance(original_from.this, sqlglot.exp.Table):
# Move joins, laterals, and pivots from the Update->From->Table->field
# to the top-level Select->field.
for k in _UPDATE_FROM_TABLE_ARGS_TO_MOVE:
if k in original_from.this.args:
# Mutate the from table clause in-place.
extra_args[k] = original_from.this.args.pop(k)
select_statement = sqlglot.exp.Select(
**{
**{
k: v
for k, v in statement.args.items()
if k not in _UPDATE_ARGS_NOT_SUPPORTED_BY_SELECT
},
**extra_args,
"expressions": new_expressions,
}
)
# Update statements always implicitly have the updated table in context.
# TODO: Retain table name alias, if one was present.
if select_statement.args.get("from"):
select_statement = select_statement.join(
statement.this, append=True, join_kind="cross"
)
else:
select_statement = select_statement.from_(statement.this)
return select_statement
def _is_create_table_ddl(statement: sqlglot.exp.Expression) -> bool:
return isinstance(statement, sqlglot.exp.Create) and isinstance(
statement.this, sqlglot.exp.Schema
)
def _try_extract_select(
statement: sqlglot.exp.Expression,
) -> sqlglot.exp.Expression:
# Try to extract the core select logic from a more complex statement.
# If it fails, just return the original statement.
if isinstance(statement, sqlglot.exp.Merge):
# TODO Need to map column renames in the expressions part of the statement.
# Likely need to use the named_selects attr.
statement = statement.args["using"]
if isinstance(statement, sqlglot.exp.Table):
# If we're querying a table directly, wrap it in a SELECT.
statement = sqlglot.exp.Select().select("*").from_(statement)
elif isinstance(statement, sqlglot.exp.Insert):
# TODO Need to map column renames in the expressions part of the statement.
statement = statement.expression
elif isinstance(statement, sqlglot.exp.Update):
# Assumption: the output table is already captured in the modified tables list.
statement = _extract_select_from_update(statement)
elif isinstance(statement, sqlglot.exp.Create):
# TODO May need to map column renames.
# Assumption: the output table is already captured in the modified tables list.
statement = _extract_select_from_create(statement)
if isinstance(statement, sqlglot.exp.Subquery):
statement = statement.unnest()
return statement
def _translate_sqlglot_type(
sqlglot_type: sqlglot.exp.DataType.Type,
) -> Optional[SchemaFieldDataTypeClass]:
TypeClass: Any
if sqlglot_type in sqlglot.exp.DataType.TEXT_TYPES:
TypeClass = StringTypeClass
elif sqlglot_type in sqlglot.exp.DataType.NUMERIC_TYPES or sqlglot_type in {
sqlglot.exp.DataType.Type.DECIMAL,
}:
TypeClass = NumberTypeClass
elif sqlglot_type in {
sqlglot.exp.DataType.Type.BOOLEAN,
sqlglot.exp.DataType.Type.BIT,
}:
TypeClass = BooleanTypeClass
elif sqlglot_type in {
sqlglot.exp.DataType.Type.DATE,
}:
TypeClass = DateTypeClass
elif sqlglot_type in sqlglot.exp.DataType.TEMPORAL_TYPES:
TypeClass = TimeTypeClass
elif sqlglot_type in {
sqlglot.exp.DataType.Type.ARRAY,
}:
TypeClass = ArrayTypeClass
elif sqlglot_type in {
sqlglot.exp.DataType.Type.UNKNOWN,
sqlglot.exp.DataType.Type.NULL,
}:
return None
else:
logger.debug("Unknown sqlglot type: %s", sqlglot_type)
return None
return SchemaFieldDataTypeClass(type=TypeClass())
def _translate_internal_column_lineage(
table_name_urn_mapping: Dict[_TableName, str],
raw_column_lineage: _ColumnLineageInfo,
dialect: sqlglot.Dialect,
) -> ColumnLineageInfo:
downstream_urn = None
if raw_column_lineage.downstream.table:
downstream_urn = table_name_urn_mapping[raw_column_lineage.downstream.table]
return ColumnLineageInfo(
downstream=DownstreamColumnRef(
table=downstream_urn,
column=raw_column_lineage.downstream.column,
column_type=_translate_sqlglot_type(
raw_column_lineage.downstream.column_type.this
)
if raw_column_lineage.downstream.column_type
else None,
native_column_type=raw_column_lineage.downstream.column_type.sql(
dialect=dialect
)
if raw_column_lineage.downstream.column_type
and raw_column_lineage.downstream.column_type.this
!= sqlglot.exp.DataType.Type.UNKNOWN
else None,
),
upstreams=[
ColumnRef(
table=table_name_urn_mapping[upstream.table],
column=upstream.column,
)
for upstream in raw_column_lineage.upstreams
],
logic=raw_column_lineage.logic,
)
def _get_dialect_str(platform: str) -> str:
# TODO: convert datahub platform names to sqlglot dialect
if platform == "presto-on-hive":
return "hive"
elif platform == "mssql":
return "tsql"
elif platform == "athena":
return "trino"
elif platform == "mysql":
# In sqlglot v20+, MySQL is now case-sensitive by default, which is the
# default behavior on Linux. However, MySQL's default case sensitivity
# actually depends on the underlying OS.
# For us, it's simpler to just assume that it's case-insensitive, and
# let the fuzzy resolution logic handle it.
return "mysql, normalization_strategy = lowercase"
else:
return platform