/
snowflake_v2.py
1708 lines (1522 loc) · 66 KB
/
snowflake_v2.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 json
import logging
import os
import os.path
import platform
from dataclasses import dataclass
from functools import partial
from typing import Callable, Dict, Iterable, List, Optional, Union
import pandas as pd
from snowflake.connector import SnowflakeConnection
from datahub.configuration.pattern_utils import is_schema_allowed
from datahub.emitter.mce_builder import (
make_data_platform_urn,
make_dataset_urn_with_platform_instance,
make_schema_field_urn,
make_tag_urn,
)
from datahub.emitter.mcp import MetadataChangeProposalWrapper
from datahub.ingestion.api.common import PipelineContext
from datahub.ingestion.api.decorators import (
SupportStatus,
capability,
config_class,
platform_name,
support_status,
)
from datahub.ingestion.api.incremental_lineage_helper import auto_incremental_lineage
from datahub.ingestion.api.source import (
CapabilityReport,
MetadataWorkUnitProcessor,
Source,
SourceCapability,
SourceReport,
TestableSource,
TestConnectionReport,
)
from datahub.ingestion.api.workunit import MetadataWorkUnit
from datahub.ingestion.glossary.classification_mixin import ClassificationHandler
from datahub.ingestion.source.common.subtypes import (
DatasetContainerSubTypes,
DatasetSubTypes,
)
from datahub.ingestion.source.snowflake.constants import (
GENERIC_PERMISSION_ERROR_KEY,
SNOWFLAKE_DATABASE,
SnowflakeEdition,
SnowflakeObjectDomain,
)
from datahub.ingestion.source.snowflake.snowflake_config import (
SnowflakeV2Config,
TagOption,
)
from datahub.ingestion.source.snowflake.snowflake_lineage_v2 import (
SnowflakeLineageExtractor,
)
from datahub.ingestion.source.snowflake.snowflake_profiler import SnowflakeProfiler
from datahub.ingestion.source.snowflake.snowflake_report import SnowflakeV2Report
from datahub.ingestion.source.snowflake.snowflake_schema import (
SnowflakeColumn,
SnowflakeDatabase,
SnowflakeDataDictionary,
SnowflakeFK,
SnowflakePK,
SnowflakeQuery,
SnowflakeSchema,
SnowflakeTable,
SnowflakeTag,
SnowflakeView,
)
from datahub.ingestion.source.snowflake.snowflake_shares import SnowflakeSharesHandler
from datahub.ingestion.source.snowflake.snowflake_tag import SnowflakeTagExtractor
from datahub.ingestion.source.snowflake.snowflake_usage_v2 import (
SnowflakeUsageExtractor,
)
from datahub.ingestion.source.snowflake.snowflake_utils import (
SnowflakeCommonMixin,
SnowflakeConnectionMixin,
SnowflakePermissionError,
SnowflakeQueryMixin,
)
from datahub.ingestion.source.sql.sql_utils import (
add_table_to_schema_container,
gen_database_container,
gen_database_key,
gen_schema_container,
gen_schema_key,
get_dataplatform_instance_aspect,
get_domain_wu,
)
from datahub.ingestion.source.state.profiling_state_handler import ProfilingHandler
from datahub.ingestion.source.state.redundant_run_skip_handler import (
RedundantLineageRunSkipHandler,
RedundantUsageRunSkipHandler,
)
from datahub.ingestion.source.state.stale_entity_removal_handler import (
StaleEntityRemovalHandler,
)
from datahub.ingestion.source.state.stateful_ingestion_base import (
StatefulIngestionSourceBase,
)
from datahub.ingestion.source_report.ingestion_stage import (
LINEAGE_EXTRACTION,
METADATA_EXTRACTION,
PROFILING,
)
from datahub.metadata.com.linkedin.pegasus2avro.common import (
GlobalTags,
Status,
SubTypes,
TagAssociation,
TimeStamp,
)
from datahub.metadata.com.linkedin.pegasus2avro.dataset import (
DatasetProperties,
ViewProperties,
)
from datahub.metadata.com.linkedin.pegasus2avro.schema import (
ArrayType,
BooleanType,
BytesType,
DateType,
ForeignKeyConstraint,
MySqlDDL,
NullType,
NumberType,
RecordType,
SchemaField,
SchemaFieldDataType,
SchemaMetadata,
StringType,
TimeType,
)
from datahub.metadata.com.linkedin.pegasus2avro.tag import TagProperties
from datahub.sql_parsing.sql_parsing_aggregator import SqlParsingAggregator
from datahub.utilities.perf_timer import PerfTimer
from datahub.utilities.registries.domain_registry import DomainRegistry
logger: logging.Logger = logging.getLogger(__name__)
# https://docs.snowflake.com/en/sql-reference/intro-summary-data-types.html
SNOWFLAKE_FIELD_TYPE_MAPPINGS = {
"DATE": DateType,
"BIGINT": NumberType,
"BINARY": BytesType,
# 'BIT': BIT,
"BOOLEAN": BooleanType,
"CHAR": NullType,
"CHARACTER": NullType,
"DATETIME": TimeType,
"DEC": NumberType,
"DECIMAL": NumberType,
"DOUBLE": NumberType,
"FIXED": NumberType,
"FLOAT": NumberType,
"INT": NumberType,
"INTEGER": NumberType,
"NUMBER": NumberType,
# 'OBJECT': ?
"REAL": NumberType,
"BYTEINT": NumberType,
"SMALLINT": NumberType,
"STRING": StringType,
"TEXT": StringType,
"TIME": TimeType,
"TIMESTAMP": TimeType,
"TIMESTAMP_TZ": TimeType,
"TIMESTAMP_LTZ": TimeType,
"TIMESTAMP_NTZ": TimeType,
"TINYINT": NumberType,
"VARBINARY": BytesType,
"VARCHAR": StringType,
"VARIANT": RecordType,
"OBJECT": NullType,
"ARRAY": ArrayType,
"GEOGRAPHY": NullType,
}
@platform_name("Snowflake", doc_order=1)
@config_class(SnowflakeV2Config)
@support_status(SupportStatus.CERTIFIED)
@capability(SourceCapability.PLATFORM_INSTANCE, "Enabled by default")
@capability(SourceCapability.DOMAINS, "Supported via the `domain` config field")
@capability(SourceCapability.CONTAINERS, "Enabled by default")
@capability(SourceCapability.SCHEMA_METADATA, "Enabled by default")
@capability(
SourceCapability.DATA_PROFILING,
"Optionally enabled via configuration `profiling.enabled`",
)
@capability(SourceCapability.DESCRIPTIONS, "Enabled by default")
@capability(
SourceCapability.LINEAGE_COARSE,
"Enabled by default, can be disabled via configuration `include_table_lineage` and `include_view_lineage`",
)
@capability(
SourceCapability.LINEAGE_FINE,
"Enabled by default, can be disabled via configuration `include_column_lineage`",
)
@capability(
SourceCapability.USAGE_STATS,
"Enabled by default, can be disabled via configuration `include_usage_stats`",
)
@capability(
SourceCapability.DELETION_DETECTION,
"Optionally enabled via `stateful_ingestion.remove_stale_metadata`",
supported=True,
)
@capability(
SourceCapability.TAGS,
"Optionally enabled via `extract_tags`",
supported=True,
)
class SnowflakeV2Source(
SnowflakeQueryMixin,
SnowflakeConnectionMixin,
SnowflakeCommonMixin,
StatefulIngestionSourceBase,
TestableSource,
):
def __init__(self, ctx: PipelineContext, config: SnowflakeV2Config):
super().__init__(config, ctx)
self.config: SnowflakeV2Config = config
self.report: SnowflakeV2Report = SnowflakeV2Report()
self.logger = logger
self.snowsight_base_url: Optional[str] = None
self.connection: Optional[SnowflakeConnection] = None
self.domain_registry: Optional[DomainRegistry] = None
if self.config.domain:
self.domain_registry = DomainRegistry(
cached_domains=[k for k in self.config.domain], graph=self.ctx.graph
)
# For database, schema, tables, views, etc
self.data_dictionary = SnowflakeDataDictionary()
self.lineage_extractor: Optional[SnowflakeLineageExtractor] = None
self.aggregator: Optional[SqlParsingAggregator] = None
if self.config.include_table_lineage:
self.aggregator = SqlParsingAggregator(
platform=self.platform,
platform_instance=self.config.platform_instance,
env=self.config.env,
graph=self.ctx.graph,
generate_usage_statistics=False,
generate_operations=False,
)
self.report.sql_aggregator = self.aggregator.report
redundant_lineage_run_skip_handler: Optional[
RedundantLineageRunSkipHandler
] = None
if self.config.enable_stateful_lineage_ingestion:
redundant_lineage_run_skip_handler = RedundantLineageRunSkipHandler(
source=self,
config=self.config,
pipeline_name=self.ctx.pipeline_name,
run_id=self.ctx.run_id,
)
self.lineage_extractor = SnowflakeLineageExtractor(
config,
self.report,
dataset_urn_builder=self.gen_dataset_urn,
redundant_run_skip_handler=redundant_lineage_run_skip_handler,
sql_aggregator=self.aggregator,
)
self.usage_extractor: Optional[SnowflakeUsageExtractor] = None
if self.config.include_usage_stats or self.config.include_operational_stats:
redundant_usage_run_skip_handler: Optional[
RedundantUsageRunSkipHandler
] = None
if self.config.enable_stateful_usage_ingestion:
redundant_usage_run_skip_handler = RedundantUsageRunSkipHandler(
source=self,
config=self.config,
pipeline_name=self.ctx.pipeline_name,
run_id=self.ctx.run_id,
)
self.usage_extractor = SnowflakeUsageExtractor(
config,
self.report,
dataset_urn_builder=self.gen_dataset_urn,
redundant_run_skip_handler=redundant_usage_run_skip_handler,
)
self.tag_extractor = SnowflakeTagExtractor(
config, self.data_dictionary, self.report
)
self.profiling_state_handler: Optional[ProfilingHandler] = None
if self.config.enable_stateful_profiling:
self.profiling_state_handler = ProfilingHandler(
source=self,
config=self.config,
pipeline_name=self.ctx.pipeline_name,
run_id=self.ctx.run_id,
)
if config.is_profiling_enabled():
# For profiling
self.profiler = SnowflakeProfiler(
config, self.report, self.profiling_state_handler
)
if self.config.classification.enabled:
self.classification_handler = ClassificationHandler(
self.config, self.report
)
# Caches tables for a single database. Consider moving to disk or S3 when possible.
self.db_tables: Dict[str, List[SnowflakeTable]] = {}
self.add_config_to_report()
@classmethod
def create(cls, config_dict: dict, ctx: PipelineContext) -> "Source":
config = SnowflakeV2Config.parse_obj(config_dict)
return cls(ctx, config)
@staticmethod
def test_connection(config_dict: dict) -> TestConnectionReport:
test_report = TestConnectionReport()
try:
connection_conf = SnowflakeV2Config.parse_obj_allow_extras(config_dict)
connection: SnowflakeConnection = connection_conf.get_connection()
assert connection
test_report.basic_connectivity = CapabilityReport(capable=True)
test_report.capability_report = SnowflakeV2Source.check_capabilities(
connection, connection_conf
)
connection.close()
except Exception as e:
logger.error(f"Failed to test connection due to {e}", exc_info=e)
if test_report.basic_connectivity is None:
test_report.basic_connectivity = CapabilityReport(
capable=False, failure_reason=f"{e}"
)
else:
test_report.internal_failure = True
test_report.internal_failure_reason = f"{e}"
return test_report
@staticmethod
def check_capabilities(
conn: SnowflakeConnection, connection_conf: SnowflakeV2Config
) -> Dict[Union[SourceCapability, str], CapabilityReport]:
# Currently only overall capabilities are reported.
# Resource level variations in capabilities are not considered.
@dataclass
class SnowflakePrivilege:
privilege: str
object_name: str
object_type: str
def query(query):
logger.info("Query : {}".format(query))
resp = conn.cursor().execute(query)
return resp
_report: Dict[Union[SourceCapability, str], CapabilityReport] = dict()
privileges: List[SnowflakePrivilege] = []
capabilities: List[SourceCapability] = [c.capability for c in SnowflakeV2Source.get_capabilities() if c.capability not in (SourceCapability.PLATFORM_INSTANCE, SourceCapability.DOMAINS, SourceCapability.DELETION_DETECTION)] # type: ignore
cur = query("select current_role()")
current_role = [row[0] for row in cur][0]
cur = query("select current_secondary_roles()")
secondary_roles_str = json.loads([row[0] for row in cur][0])["roles"]
secondary_roles = (
[] if secondary_roles_str == "" else secondary_roles_str.split(",")
)
roles = [current_role] + secondary_roles
# PUBLIC role is automatically granted to every role
if "PUBLIC" not in roles:
roles.append("PUBLIC")
i = 0
while i < len(roles):
role = roles[i]
i = i + 1
# for some roles, quoting is necessary. for example test-role
cur = query(f'show grants to role "{role}"')
for row in cur:
privilege = SnowflakePrivilege(
privilege=row[1], object_type=row[2], object_name=row[3]
)
privileges.append(privilege)
if privilege.object_type in (
"DATABASE",
"SCHEMA",
) and privilege.privilege in ("OWNERSHIP", "USAGE"):
_report[SourceCapability.CONTAINERS] = CapabilityReport(
capable=True
)
_report[SourceCapability.TAGS] = CapabilityReport(capable=True)
elif privilege.object_type in (
"TABLE",
"VIEW",
"MATERIALIZED_VIEW",
):
_report[SourceCapability.SCHEMA_METADATA] = CapabilityReport(
capable=True
)
_report[SourceCapability.DESCRIPTIONS] = CapabilityReport(
capable=True
)
# Table level profiling is supported without SELECT access
# if privilege.privilege in ("SELECT", "OWNERSHIP"):
_report[SourceCapability.DATA_PROFILING] = CapabilityReport(
capable=True
)
if privilege.object_name.startswith("SNOWFLAKE.ACCOUNT_USAGE."):
# if access to "snowflake" shared database, access to all account_usage views is automatically granted
# Finer access control is not yet supported for shares
# https://community.snowflake.com/s/article/Error-Granting-individual-privileges-on-imported-database-is-not-allowed-Use-GRANT-IMPORTED-PRIVILEGES-instead
_report[SourceCapability.LINEAGE_COARSE] = CapabilityReport(
capable=True
)
_report[SourceCapability.LINEAGE_FINE] = CapabilityReport(
capable=True
)
_report[SourceCapability.USAGE_STATS] = CapabilityReport(
capable=True
)
_report[SourceCapability.TAGS] = CapabilityReport(capable=True)
# If all capabilities supported, no need to continue
if set(capabilities) == set(_report.keys()):
break
# Due to this, entire role hierarchy is considered
if (
privilege.object_type == "ROLE"
and privilege.privilege == "USAGE"
and privilege.object_name not in roles
):
roles.append(privilege.object_name)
cur = query("select current_warehouse()")
current_warehouse = [row[0] for row in cur][0]
default_failure_messages = {
SourceCapability.SCHEMA_METADATA: "Either no tables exist or current role does not have permissions to access them",
SourceCapability.DESCRIPTIONS: "Either no tables exist or current role does not have permissions to access them",
SourceCapability.DATA_PROFILING: "Either no tables exist or current role does not have permissions to access them",
SourceCapability.CONTAINERS: "Current role does not have permissions to use any database",
SourceCapability.LINEAGE_COARSE: "Current role does not have permissions to snowflake account usage views",
SourceCapability.LINEAGE_FINE: "Current role does not have permissions to snowflake account usage views",
SourceCapability.USAGE_STATS: "Current role does not have permissions to snowflake account usage views",
SourceCapability.TAGS: "Either no tags have been applied to objects, or the current role does not have permission to access the objects or to snowflake account usage views ",
}
for c in capabilities: # type:ignore
# These capabilities do not work without active warehouse
if current_warehouse is None and c in (
SourceCapability.SCHEMA_METADATA,
SourceCapability.DESCRIPTIONS,
SourceCapability.DATA_PROFILING,
SourceCapability.LINEAGE_COARSE,
SourceCapability.LINEAGE_FINE,
SourceCapability.USAGE_STATS,
SourceCapability.TAGS,
):
failure_message = (
f"Current role {current_role} does not have permissions to use warehouse {connection_conf.warehouse}. Please check the grants associated with this role."
if connection_conf.warehouse is not None
else "No default warehouse set for user. Either set default warehouse for user or configure warehouse in recipe"
)
_report[c] = CapabilityReport(
capable=False,
failure_reason=failure_message,
)
if c in _report.keys():
continue
# If some capabilities are missing, then mark them as not capable
_report[c] = CapabilityReport(
capable=False,
failure_reason=default_failure_messages[c],
)
return _report
def get_workunit_processors(self) -> List[Optional[MetadataWorkUnitProcessor]]:
return [
*super().get_workunit_processors(),
partial(
auto_incremental_lineage,
self.ctx.graph,
self.config.incremental_lineage,
),
StaleEntityRemovalHandler.create(
self, self.config, self.ctx
).workunit_processor,
]
def get_workunits_internal(self) -> Iterable[MetadataWorkUnit]:
self._snowflake_clear_ocsp_cache()
self.connection = self.create_connection()
if self.connection is None:
return
self.inspect_session_metadata()
if self.config.include_external_url:
self.snowsight_base_url = self.get_snowsight_base_url()
if self.report.default_warehouse is None:
self.report_warehouse_failure()
return
self.data_dictionary.set_connection(self.connection)
databases: List[SnowflakeDatabase] = []
for database in self.get_databases() or []:
self.report.report_entity_scanned(database.name, "database")
if not self.config.database_pattern.allowed(database.name):
self.report.report_dropped(f"{database.name}.*")
else:
databases.append(database)
if len(databases) == 0:
return
for snowflake_db in databases:
try:
self.report.set_ingestion_stage(snowflake_db.name, METADATA_EXTRACTION)
yield from self._process_database(snowflake_db)
except SnowflakePermissionError as e:
# FIXME - This may break stateful ingestion if new tables than previous run are emitted above
# and stateful ingestion is enabled
self.report_error(GENERIC_PERMISSION_ERROR_KEY, str(e))
return
self.connection.close()
self.report_cache_info()
# TODO: The checkpoint state for stale entity detection can be committed here.
if self.config.shares:
yield from SnowflakeSharesHandler(
self.config, self.report, self.gen_dataset_urn
).get_shares_workunits(databases)
discovered_tables: List[str] = [
self.get_dataset_identifier(table_name, schema.name, db.name)
for db in databases
for schema in db.schemas
for table_name in schema.tables
]
discovered_views: List[str] = [
self.get_dataset_identifier(table_name, schema.name, db.name)
for db in databases
for schema in db.schemas
for table_name in schema.views
]
if len(discovered_tables) == 0 and len(discovered_views) == 0:
self.report_error(
GENERIC_PERMISSION_ERROR_KEY,
"No tables/views found. Please check permissions.",
)
return
discovered_datasets = discovered_tables + discovered_views
if self.config.include_table_lineage and self.lineage_extractor:
self.report.set_ingestion_stage("*", LINEAGE_EXTRACTION)
yield from self.lineage_extractor.get_workunits(
discovered_tables=discovered_tables,
discovered_views=discovered_views,
)
if (
self.config.include_usage_stats or self.config.include_operational_stats
) and self.usage_extractor:
yield from self.usage_extractor.get_usage_workunits(discovered_datasets)
def report_cache_info(self) -> None:
lru_cache_functions: List[Callable] = [
self.data_dictionary.get_tables_for_database,
self.data_dictionary.get_views_for_database,
self.data_dictionary.get_columns_for_schema,
self.data_dictionary.get_pk_constraints_for_schema,
self.data_dictionary.get_fk_constraints_for_schema,
]
for func in lru_cache_functions:
self.report.lru_cache_info[func.__name__] = func.cache_info()._asdict() # type: ignore
def report_warehouse_failure(self) -> None:
if self.config.warehouse is not None:
self.report_error(
GENERIC_PERMISSION_ERROR_KEY,
f"Current role does not have permissions to use warehouse {self.config.warehouse}. Please update permissions.",
)
else:
self.report_error(
"no-active-warehouse",
"No default warehouse set for user. Either set default warehouse for user or configure warehouse in recipe.",
)
def get_databases(self) -> Optional[List[SnowflakeDatabase]]:
try:
# `show databases` is required only to get one of the databases
# whose information_schema can be queried to start with.
databases = self.data_dictionary.show_databases()
except Exception as e:
logger.debug(f"Failed to list databases due to error {e}", exc_info=e)
self.report_error(
"list-databases",
f"Failed to list databases due to error {e}",
)
return None
else:
ischema_databases: List[
SnowflakeDatabase
] = self.get_databases_from_ischema(databases)
if len(ischema_databases) == 0:
self.report_error(
GENERIC_PERMISSION_ERROR_KEY,
"No databases found. Please check permissions.",
)
return ischema_databases
def get_databases_from_ischema(
self, databases: List[SnowflakeDatabase]
) -> List[SnowflakeDatabase]:
ischema_databases: List[SnowflakeDatabase] = []
for database in databases:
try:
ischema_databases = self.data_dictionary.get_databases(database.name)
break
except Exception:
# query fails if "USAGE" access is not granted for database
# This is okay, because `show databases` query lists all databases irrespective of permission,
# if role has `MANAGE GRANTS` privilege. (not advisable)
logger.debug(
f"Failed to list databases {database.name} information_schema"
)
# SNOWFLAKE database always shows up even if permissions are missing
if database == SNOWFLAKE_DATABASE:
continue
logger.info(
f"The role {self.report.role} has `MANAGE GRANTS` privilege. This is not advisable and also not required."
)
return ischema_databases
def _process_database(
self, snowflake_db: SnowflakeDatabase
) -> Iterable[MetadataWorkUnit]:
db_name = snowflake_db.name
try:
self.query(SnowflakeQuery.use_database(db_name))
except Exception as e:
if isinstance(e, SnowflakePermissionError):
# This may happen if REFERENCE_USAGE permissions are set
# We can not run show queries on database in such case.
# This need not be a failure case.
self.report_warning(
"Insufficient privileges to operate on database, skipping. Please grant USAGE permissions on database to extract its metadata.",
db_name,
)
else:
logger.debug(
f"Failed to use database {db_name} due to error {e}",
exc_info=e,
)
self.report_warning(
"Failed to get schemas for database",
db_name,
)
return
if self.config.extract_tags != TagOption.skip:
snowflake_db.tags = self.tag_extractor.get_tags_on_object(
domain="database", db_name=db_name
)
if self.config.include_technical_schema:
yield from self.gen_database_containers(snowflake_db)
self.fetch_schemas_for_database(snowflake_db, db_name)
if self.config.include_technical_schema and snowflake_db.tags:
for tag in snowflake_db.tags:
yield from self._process_tag(tag)
self.db_tables = {}
for snowflake_schema in snowflake_db.schemas:
yield from self._process_schema(snowflake_schema, db_name)
if self.config.is_profiling_enabled() and self.db_tables:
self.report.set_ingestion_stage(snowflake_db.name, PROFILING)
yield from self.profiler.get_workunits(snowflake_db, self.db_tables)
def fetch_schemas_for_database(
self, snowflake_db: SnowflakeDatabase, db_name: str
) -> None:
schemas: List[SnowflakeSchema] = []
try:
for schema in self.data_dictionary.get_schemas_for_database(db_name):
self.report.report_entity_scanned(schema.name, "schema")
if not is_schema_allowed(
self.config.schema_pattern,
schema.name,
db_name,
self.config.match_fully_qualified_names,
):
self.report.report_dropped(f"{db_name}.{schema.name}.*")
else:
schemas.append(schema)
except Exception as e:
if isinstance(e, SnowflakePermissionError):
error_msg = f"Failed to get schemas for database {db_name}. Please check permissions."
# Ideal implementation would use PEP 678 – Enriching Exceptions with Notes
raise SnowflakePermissionError(error_msg) from e.__cause__
else:
logger.debug(
f"Failed to get schemas for database {db_name} due to error {e}",
exc_info=e,
)
self.report_warning(
"Failed to get schemas for database",
db_name,
)
if not schemas:
self.report_warning(
"No schemas found in database. If schemas exist, please grant USAGE permissions on them.",
db_name,
)
else:
snowflake_db.schemas = schemas
def _process_schema(
self, snowflake_schema: SnowflakeSchema, db_name: str
) -> Iterable[MetadataWorkUnit]:
schema_name = snowflake_schema.name
if self.config.extract_tags != TagOption.skip:
snowflake_schema.tags = self.tag_extractor.get_tags_on_object(
schema_name=schema_name, db_name=db_name, domain="schema"
)
if self.config.include_technical_schema:
yield from self.gen_schema_containers(snowflake_schema, db_name)
if self.config.include_tables:
tables = self.fetch_tables_for_schema(
snowflake_schema, db_name, schema_name
)
self.db_tables[schema_name] = tables
if self.config.include_technical_schema:
for table in tables:
yield from self._process_table(table, schema_name, db_name)
if self.config.include_views:
views = self.fetch_views_for_schema(snowflake_schema, db_name, schema_name)
if (
self.aggregator
and self.config.include_view_lineage
and self.config.parse_view_ddl
):
for view in views:
view_identifier = self.get_dataset_identifier(
view.name, schema_name, db_name
)
if view.view_definition:
self.aggregator.add_view_definition(
view_urn=self.gen_dataset_urn(view_identifier),
view_definition=view.view_definition,
default_db=db_name,
default_schema=schema_name,
)
if self.config.include_technical_schema:
for view in views:
yield from self._process_view(view, schema_name, db_name)
if self.config.include_technical_schema and snowflake_schema.tags:
for tag in snowflake_schema.tags:
yield from self._process_tag(tag)
if not snowflake_schema.views and not snowflake_schema.tables:
self.report_warning(
"No tables/views found in schema. If tables exist, please grant REFERENCES or SELECT permissions on them.",
f"{db_name}.{schema_name}",
)
def fetch_views_for_schema(
self, snowflake_schema: SnowflakeSchema, db_name: str, schema_name: str
) -> List[SnowflakeView]:
try:
views: List[SnowflakeView] = []
for view in self.get_views_for_schema(schema_name, db_name):
view_name = self.get_dataset_identifier(view.name, schema_name, db_name)
self.report.report_entity_scanned(view_name, "view")
if not self.config.view_pattern.allowed(view_name):
self.report.report_dropped(view_name)
else:
views.append(view)
snowflake_schema.views = [view.name for view in views]
return views
except Exception as e:
if isinstance(e, SnowflakePermissionError):
# Ideal implementation would use PEP 678 – Enriching Exceptions with Notes
error_msg = f"Failed to get views for schema {db_name}.{schema_name}. Please check permissions."
raise SnowflakePermissionError(error_msg) from e.__cause__
else:
logger.debug(
f"Failed to get views for schema {db_name}.{schema_name} due to error {e}",
exc_info=e,
)
self.report_warning(
"Failed to get views for schema",
f"{db_name}.{schema_name}",
)
return []
def fetch_tables_for_schema(
self, snowflake_schema: SnowflakeSchema, db_name: str, schema_name: str
) -> List[SnowflakeTable]:
try:
tables: List[SnowflakeTable] = []
for table in self.get_tables_for_schema(schema_name, db_name):
table_identifier = self.get_dataset_identifier(
table.name, schema_name, db_name
)
self.report.report_entity_scanned(table_identifier)
if not self.config.table_pattern.allowed(table_identifier):
self.report.report_dropped(table_identifier)
else:
tables.append(table)
snowflake_schema.tables = [table.name for table in tables]
return tables
except Exception as e:
if isinstance(e, SnowflakePermissionError):
# Ideal implementation would use PEP 678 – Enriching Exceptions with Notes
error_msg = f"Failed to get tables for schema {db_name}.{schema_name}. Please check permissions."
raise SnowflakePermissionError(error_msg) from e.__cause__
else:
logger.debug(
f"Failed to get tables for schema {db_name}.{schema_name} due to error {e}",
exc_info=e,
)
self.report_warning(
"Failed to get tables for schema",
f"{db_name}.{schema_name}",
)
return []
def _process_table(
self,
table: SnowflakeTable,
schema_name: str,
db_name: str,
) -> Iterable[MetadataWorkUnit]:
table_identifier = self.get_dataset_identifier(table.name, schema_name, db_name)
self.fetch_columns_for_table(table, schema_name, db_name, table_identifier)
self.fetch_pk_for_table(table, schema_name, db_name, table_identifier)
self.fetch_foreign_keys_for_table(table, schema_name, db_name, table_identifier)
dataset_name = self.get_dataset_identifier(table.name, schema_name, db_name)
self.fetch_sample_data_for_classification(
table, schema_name, db_name, dataset_name
)
if self.config.extract_tags != TagOption.skip:
table.tags = self.tag_extractor.get_tags_on_object(
table_name=table.name,
schema_name=schema_name,
db_name=db_name,
domain="table",
)
if self.config.include_technical_schema:
if table.tags:
for tag in table.tags:
yield from self._process_tag(tag)
for column_name in table.column_tags:
for tag in table.column_tags[column_name]:
yield from self._process_tag(tag)
yield from self.gen_dataset_workunits(table, schema_name, db_name)
def fetch_sample_data_for_classification(
self, table: SnowflakeTable, schema_name: str, db_name: str, dataset_name: str
) -> None:
if (
table.columns
and self.config.classification.enabled
and self.classification_handler.is_classification_enabled_for_table(
dataset_name
)
):
try:
table.sample_data = self.get_sample_values_for_table(
table.name, schema_name, db_name
)
except Exception as e:
logger.debug(
f"Failed to get sample values for dataset {dataset_name} due to error {e}",
exc_info=e,
)
if isinstance(e, SnowflakePermissionError):
self.report_warning(
"Failed to get sample values for dataset. Please grant SELECT permissions on dataset.",
dataset_name,
)
else:
self.report_warning(
"Failed to get sample values for dataset",
dataset_name,
)
def fetch_foreign_keys_for_table(
self,
table: SnowflakeTable,
schema_name: str,
db_name: str,
table_identifier: str,
) -> None:
try:
table.foreign_keys = self.get_fk_constraints_for_table(
table.name, schema_name, db_name
)
except Exception as e:
logger.debug(
f"Failed to get foreign key for table {table_identifier} due to error {e}",
exc_info=e,
)
self.report_warning("Failed to get foreign key for table", table_identifier)
def fetch_pk_for_table(
self,
table: SnowflakeTable,
schema_name: str,
db_name: str,
table_identifier: str,
) -> None:
try:
table.pk = self.get_pk_constraints_for_table(
table.name, schema_name, db_name
)
except Exception as e:
logger.debug(
f"Failed to get primary key for table {table_identifier} due to error {e}",
exc_info=e,
)
self.report_warning("Failed to get primary key for table", table_identifier)
def fetch_columns_for_table(
self,
table: SnowflakeTable,
schema_name: str,
db_name: str,
table_identifier: str,
) -> None:
try:
table.columns = self.get_columns_for_table(table.name, schema_name, db_name)
table.column_count = len(table.columns)
if self.config.extract_tags != TagOption.skip:
table.column_tags = self.tag_extractor.get_column_tags_for_table(
table.name, schema_name, db_name
)
except Exception as e:
logger.debug(
f"Failed to get columns for table {table_identifier} due to error {e}",
exc_info=e,