-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
nodes.py
1710 lines (1396 loc) · 56.6 KB
/
nodes.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 hashlib
import os
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import (
Any,
Dict,
Iterator,
List,
Literal,
Optional,
Sequence,
Tuple,
Type,
Union,
get_args,
)
from mashumaro.types import SerializableType
from dbt.adapters.base import ConstraintSupport
from dbt.adapters.factory import get_adapter_constraint_support
from dbt.artifacts.resources import Analysis as AnalysisResource
from dbt.artifacts.resources import (
BaseResource,
ColumnInfo,
CompiledResource,
DependsOn,
Docs,
)
from dbt.artifacts.resources import Documentation as DocumentationResource
from dbt.artifacts.resources import Exposure as ExposureResource
from dbt.artifacts.resources import FileHash
from dbt.artifacts.resources import GenericTest as GenericTestResource
from dbt.artifacts.resources import GraphResource
from dbt.artifacts.resources import Group as GroupResource
from dbt.artifacts.resources import HasRelationMetadata as HasRelationMetadataResource
from dbt.artifacts.resources import HookNode as HookNodeResource
from dbt.artifacts.resources import InjectedCTE
from dbt.artifacts.resources import Macro as MacroResource
from dbt.artifacts.resources import MacroArgument
from dbt.artifacts.resources import Metric as MetricResource
from dbt.artifacts.resources import MetricInputMeasure
from dbt.artifacts.resources import Model as ModelResource
from dbt.artifacts.resources import (
ModelConfig,
NodeConfig,
NodeVersion,
ParsedResource,
ParsedResourceMandatory,
)
from dbt.artifacts.resources import Quoting as QuotingResource
from dbt.artifacts.resources import SavedQuery as SavedQueryResource
from dbt.artifacts.resources import Seed as SeedResource
from dbt.artifacts.resources import SemanticModel as SemanticModelResource
from dbt.artifacts.resources import SingularTest as SingularTestResource
from dbt.artifacts.resources import Snapshot as SnapshotResource
from dbt.artifacts.resources import SourceDefinition as SourceDefinitionResource
from dbt.artifacts.resources import SqlOperation as SqlOperationResource
from dbt.artifacts.resources import TimeSpine
from dbt.artifacts.resources import UnitTestDefinition as UnitTestDefinitionResource
from dbt.artifacts.schemas.batch_results import BatchResults
from dbt.contracts.graph.model_config import UnitTestNodeConfig
from dbt.contracts.graph.node_args import ModelNodeArgs
from dbt.contracts.graph.unparsed import (
HasYamlMetadata,
TestDef,
UnitTestOverrides,
UnparsedColumn,
UnparsedSourceDefinition,
UnparsedSourceTableDefinition,
)
from dbt.events.types import (
SeedExceedsLimitAndPathChanged,
SeedExceedsLimitChecksumChanged,
SeedExceedsLimitSamePath,
SeedIncreased,
UnversionedBreakingChange,
)
from dbt.exceptions import ContractBreakingChangeError, ParsingError, ValidationError
from dbt.flags import get_flags
from dbt.node_types import (
REFABLE_NODE_TYPES,
VERSIONED_NODE_TYPES,
AccessType,
NodeType,
)
from dbt_common.clients.system import write_file
from dbt_common.contracts.constraints import (
ColumnLevelConstraint,
ConstraintType,
ModelLevelConstraint,
)
from dbt_common.events.contextvars import set_log_contextvars
from dbt_common.events.functions import warn_or_error
# =====================================================================
# This contains the classes for all of the nodes and node-like objects
# in the manifest. In the "nodes" dictionary of the manifest we find
# all of the objects in the ManifestNode union below. In addition the
# manifest contains "macros", "sources", "metrics", "exposures", "docs",
# and "disabled" dictionaries.
#
# The SeedNode is a ManifestNode, but can't be compiled because it has
# no SQL.
#
# All objects defined in this file should have BaseNode as a parent
# class.
#
# The two objects which do not show up in the DAG are Macro and
# Documentation.
# =====================================================================
# ==================================================
# Various parent classes and node attribute classes
# ==================================================
@dataclass
class BaseNode(BaseResource):
"""All nodes or node-like objects in this file should have this as a base class"""
# In an ideal world this would be a class property. However, chaining @classmethod and
# @property was deprecated in python 3.11 and removed in 3.13. There are more
# complicated ways of making a class property, however a class method suits our
# purposes well enough
@classmethod
def resource_class(cls) -> Type[BaseResource]:
"""Should be overriden by any class inheriting BaseNode"""
raise NotImplementedError
@property
def search_name(self):
return self.name
@property
def file_id(self):
return f"{self.package_name}://{self.original_file_path}"
@property
def is_refable(self):
return self.resource_type in REFABLE_NODE_TYPES
@property
def should_store_failures(self):
return False
# will this node map to an object in the database?
@property
def is_relational(self):
return self.resource_type in REFABLE_NODE_TYPES
@property
def is_versioned(self):
return self.resource_type in VERSIONED_NODE_TYPES and self.version is not None
@property
def is_ephemeral(self):
return self.config.materialized == "ephemeral"
@property
def is_ephemeral_model(self):
return self.is_refable and self.is_ephemeral
def get_materialization(self):
return self.config.materialized
@classmethod
def from_resource(cls, resource_instance: BaseResource):
assert isinstance(resource_instance, cls.resource_class())
return cls.from_dict(resource_instance.to_dict())
def to_resource(self):
return self.resource_class().from_dict(self.to_dict())
@dataclass
class GraphNode(GraphResource, BaseNode):
"""Nodes in the DAG. Macro and Documentation don't have fqn."""
def same_fqn(self, other) -> bool:
return self.fqn == other.fqn
@dataclass
class HasRelationMetadata(HasRelationMetadataResource):
@classmethod
def __pre_deserialize__(cls, data):
data = super().__pre_deserialize__(data)
if "database" not in data:
data["database"] = None
return data
@property
def quoting_dict(self) -> Dict[str, bool]:
if hasattr(self, "quoting"):
return self.quoting.to_dict(omit_none=True)
else:
return {}
@dataclass
class ParsedNodeMandatory(ParsedResourceMandatory, GraphNode, HasRelationMetadata):
pass
# This needs to be in all ManifestNodes and also in SourceDefinition,
# because of "source freshness". Should not be in artifacts, because we
# don't write out _event_status.
@dataclass
class NodeInfoMixin:
_event_status: Dict[str, Any] = field(default_factory=dict)
@property
def node_info(self):
node_info = {
"node_path": getattr(self, "path", None),
"node_name": getattr(self, "name", None),
"unique_id": getattr(self, "unique_id", None),
"resource_type": str(getattr(self, "resource_type", "")),
"materialized": self.config.get("materialized"),
"node_status": str(self._event_status.get("node_status")),
"node_started_at": self._event_status.get("started_at"),
"node_finished_at": self._event_status.get("finished_at"),
"meta": getattr(self, "meta", {}),
"node_relation": {
"database": getattr(self, "database", None),
"schema": getattr(self, "schema", None),
"alias": getattr(self, "alias", None),
"relation_name": getattr(self, "relation_name", None),
},
}
return node_info
def update_event_status(self, **kwargs):
for k, v in kwargs.items():
self._event_status[k] = v
set_log_contextvars(node_info=self.node_info)
def clear_event_status(self):
self._event_status = dict()
@dataclass
class ParsedNode(ParsedResource, NodeInfoMixin, ParsedNodeMandatory, SerializableType):
def get_target_write_path(
self, target_path: str, subdirectory: str, split_suffix: Optional[str] = None
):
# This is called for both the "compiled" subdirectory of "target" and the "run" subdirectory
if os.path.basename(self.path) == os.path.basename(self.original_file_path):
# One-to-one relationship of nodes to files.
path = self.original_file_path
else:
# Many-to-one relationship of nodes to files.
path = os.path.join(self.original_file_path, self.path)
if split_suffix:
pathlib_path = Path(path)
path = str(
pathlib_path.parent
/ pathlib_path.stem
/ (pathlib_path.stem + f"_{split_suffix}" + pathlib_path.suffix)
)
target_write_path = os.path.join(target_path, subdirectory, self.package_name, path)
return target_write_path
def write_node(self, project_root: str, compiled_path, compiled_code: str):
if os.path.isabs(compiled_path):
full_path = compiled_path
else:
full_path = os.path.join(project_root, compiled_path)
write_file(full_path, compiled_code)
def _serialize(self):
return self.to_dict()
def __post_serialize__(self, dct: Dict, context: Optional[Dict] = None):
dct = super().__post_serialize__(dct, context)
if "_event_status" in dct:
del dct["_event_status"]
return dct
@classmethod
def _deserialize(cls, dct: Dict[str, int]):
# The serialized ParsedNodes do not differ from each other
# in fields that would allow 'from_dict' to distinguis
# between them.
resource_type = dct["resource_type"]
if resource_type == "model":
return ModelNode.from_dict(dct)
elif resource_type == "analysis":
return AnalysisNode.from_dict(dct)
elif resource_type == "seed":
return SeedNode.from_dict(dct)
elif resource_type == "sql":
return SqlNode.from_dict(dct)
elif resource_type == "test":
if "test_metadata" in dct:
return GenericTestNode.from_dict(dct)
else:
return SingularTestNode.from_dict(dct)
elif resource_type == "operation":
return HookNode.from_dict(dct)
elif resource_type == "seed":
return SeedNode.from_dict(dct)
elif resource_type == "snapshot":
return SnapshotNode.from_dict(dct)
else:
return cls.from_dict(dct)
def _persist_column_docs(self) -> bool:
if hasattr(self.config, "persist_docs"):
assert isinstance(self.config, NodeConfig)
return bool(self.config.persist_docs.get("columns"))
return False
def _persist_relation_docs(self) -> bool:
if hasattr(self.config, "persist_docs"):
assert isinstance(self.config, NodeConfig)
return bool(self.config.persist_docs.get("relation"))
return False
def same_persisted_description(self, other) -> bool:
# the check on configs will handle the case where we have different
# persist settings, so we only have to care about the cases where they
# are the same..
if self._persist_relation_docs():
if self.description != other.description:
return False
if self._persist_column_docs():
# assert other._persist_column_docs()
column_descriptions = {k: v.description for k, v in self.columns.items()}
other_column_descriptions = {k: v.description for k, v in other.columns.items()}
if column_descriptions != other_column_descriptions:
return False
return True
def same_body(self, other) -> bool:
return self.raw_code == other.raw_code
def same_database_representation(self, other) -> bool:
# compare the config representation, not the node's config value. This
# compares the configured value, rather than the ultimate value (so
# generate_*_name and unset values derived from the target are
# ignored)
keys = ("database", "schema", "alias")
for key in keys:
mine = self.unrendered_config.get(key)
others = other.unrendered_config.get(key)
if mine != others:
return False
return True
def same_config(self, old) -> bool:
return self.config.same_contents(
self.unrendered_config,
old.unrendered_config,
)
def build_contract_checksum(self):
pass
def same_contract(self, old, adapter_type=None) -> bool:
# This would only apply to seeds
return True
def same_contents(self, old, adapter_type) -> bool:
if old is None:
return False
# Need to ensure that same_contract is called because it
# could throw an error
same_contract = self.same_contract(old, adapter_type)
return (
self.same_body(old)
and self.same_config(old)
and self.same_persisted_description(old)
and self.same_fqn(old)
and self.same_database_representation(old)
and same_contract
and True
)
@property
def is_external_node(self):
return False
@dataclass
class CompiledNode(CompiledResource, ParsedNode):
"""Contains attributes necessary for SQL files and nodes with refs, sources, etc,
so all ManifestNodes except SeedNode."""
@property
def empty(self):
return not self.raw_code.strip()
def set_cte(self, cte_id: str, sql: str):
"""This is the equivalent of what self.extra_ctes[cte_id] = sql would
do if extra_ctes were an OrderedDict
"""
for cte in self.extra_ctes:
# Because it's possible that multiple threads are compiling the
# node at the same time, we don't want to overwrite already compiled
# sql in the extra_ctes with empty sql.
if cte.id == cte_id:
break
else:
self.extra_ctes.append(InjectedCTE(id=cte_id, sql=sql))
@property
def depends_on_nodes(self):
return self.depends_on.nodes
@property
def depends_on_macros(self):
return self.depends_on.macros
# ====================================
# CompiledNode subclasses
# ====================================
@dataclass
class AnalysisNode(AnalysisResource, CompiledNode):
@classmethod
def resource_class(cls) -> Type[AnalysisResource]:
return AnalysisResource
@dataclass
class HookNode(HookNodeResource, CompiledNode):
@classmethod
def resource_class(cls) -> Type[HookNodeResource]:
return HookNodeResource
@dataclass
class ModelNode(ModelResource, CompiledNode):
batch_info: Optional[BatchResults] = None
@classmethod
def resource_class(cls) -> Type[ModelResource]:
return ModelResource
@classmethod
def from_args(cls, args: ModelNodeArgs) -> "ModelNode":
unique_id = args.unique_id
# build unrendered config -- for usage in ParsedNode.same_contents
unrendered_config = {}
unrendered_config["alias"] = args.identifier
unrendered_config["schema"] = args.schema
if args.database:
unrendered_config["database"] = args.database
return cls(
resource_type=NodeType.Model,
name=args.name,
package_name=args.package_name,
unique_id=unique_id,
fqn=args.fqn,
version=args.version,
latest_version=args.latest_version,
relation_name=args.relation_name,
database=args.database,
schema=args.schema,
alias=args.identifier,
deprecation_date=args.deprecation_date,
checksum=FileHash.from_contents(f"{unique_id},{args.generated_at}"),
access=AccessType(args.access),
original_file_path="",
path="",
unrendered_config=unrendered_config,
depends_on=DependsOn(nodes=args.depends_on_nodes),
config=ModelConfig(enabled=args.enabled),
)
@property
def is_external_node(self) -> bool:
return not self.original_file_path and not self.path
@property
def is_latest_version(self) -> bool:
return self.version is not None and self.version == self.latest_version
@property
def is_past_deprecation_date(self) -> bool:
return (
self.deprecation_date is not None
and self.deprecation_date < datetime.now().astimezone()
)
@property
def search_name(self):
if self.version is None:
return self.name
else:
return f"{self.name}.v{self.version}"
@property
def materialization_enforces_constraints(self) -> bool:
return self.config.materialized in ["table", "incremental"]
@property
def all_constraints(self) -> List[Union[ModelLevelConstraint, ColumnLevelConstraint]]:
constraints: List[Union[ModelLevelConstraint, ColumnLevelConstraint]] = []
for model_level_constraint in self.constraints:
constraints.append(model_level_constraint)
for column in self.columns.values():
for column_level_constraint in column.constraints:
constraints.append(column_level_constraint)
return constraints
def infer_primary_key(self, data_tests: List["GenericTestNode"]) -> List[str]:
"""
Infers the columns that can be used as primary key of a model in the following order:
1. Columns with primary key constraints
2. Columns with unique and not_null data tests
3. Columns with enabled unique or dbt_utils.unique_combination_of_columns data tests
4. Columns with disabled unique or dbt_utils.unique_combination_of_columns data tests
"""
for constraint in self.constraints:
if constraint.type == ConstraintType.primary_key:
return constraint.columns
for column, column_info in self.columns.items():
for column_constraint in column_info.constraints:
if column_constraint.type == ConstraintType.primary_key:
return [column]
columns_with_enabled_unique_tests = set()
columns_with_disabled_unique_tests = set()
columns_with_not_null_tests = set()
for test in data_tests:
columns = []
if "column_name" in test.test_metadata.kwargs:
columns = [test.test_metadata.kwargs["column_name"]]
elif "combination_of_columns" in test.test_metadata.kwargs:
columns = test.test_metadata.kwargs["combination_of_columns"]
for column in columns:
if test.test_metadata.name in ["unique", "unique_combination_of_columns"]:
if test.config.enabled:
columns_with_enabled_unique_tests.add(column)
else:
columns_with_disabled_unique_tests.add(column)
elif test.test_metadata.name == "not_null":
columns_with_not_null_tests.add(column)
columns_with_unique_and_not_null_tests = []
for column in columns_with_not_null_tests:
if (
column in columns_with_enabled_unique_tests
or column in columns_with_disabled_unique_tests
):
columns_with_unique_and_not_null_tests.append(column)
if columns_with_unique_and_not_null_tests:
return columns_with_unique_and_not_null_tests
if columns_with_enabled_unique_tests:
return list(columns_with_enabled_unique_tests)
if columns_with_disabled_unique_tests:
return list(columns_with_disabled_unique_tests)
return []
def same_contents(self, old, adapter_type) -> bool:
return super().same_contents(old, adapter_type) and self.same_ref_representation(old)
def same_ref_representation(self, old) -> bool:
return (
# Changing the latest_version may break downstream unpinned refs
self.latest_version == old.latest_version
# Changes to access or deprecation_date may lead to ref-related parsing errors
and self.access == old.access
and self.deprecation_date == old.deprecation_date
)
def build_contract_checksum(self):
# We don't need to construct the checksum if the model does not
# have contract enforced, because it won't be used.
# This needs to be executed after contract config is set
# Avoid rebuilding the checksum if it has already been set.
if self.contract.checksum is not None:
return
if self.contract.enforced is True:
contract_state = ""
# We need to sort the columns so that order doesn't matter
# columns is a str: ColumnInfo dictionary
sorted_columns = sorted(self.columns.values(), key=lambda col: col.name)
for column in sorted_columns:
contract_state += f"|{column.name}"
contract_state += str(column.data_type)
contract_state += str(column.constraints)
if self.materialization_enforces_constraints:
contract_state += self.config.materialized
contract_state += str(self.constraints)
data = contract_state.encode("utf-8")
self.contract.checksum = hashlib.new("sha256", data).hexdigest()
def same_contract_removed(self) -> bool:
"""
self: the removed (deleted, renamed, or disabled) model node
"""
# If the contract wasn't previously enforced, no contract change has occurred
if self.contract.enforced is False:
return True
# Removed node is past its deprecation_date, so deletion does not constitute a contract change
if self.is_past_deprecation_date:
return True
# Disabled, deleted, or renamed node with previously enforced contract.
if not self.config.enabled:
breaking_change = f"Contracted model '{self.unique_id}' was disabled."
else:
breaking_change = f"Contracted model '{self.unique_id}' was deleted or renamed."
if self.version is None:
warn_or_error(
UnversionedBreakingChange(
breaking_changes=[breaking_change],
model_name=self.name,
model_file_path=self.original_file_path,
),
node=self,
)
return False
else:
raise (
ContractBreakingChangeError(
breaking_changes=[breaking_change],
node=self,
)
)
def same_contract(self, old, adapter_type=None) -> bool:
# If the contract wasn't previously enforced:
if old.contract.enforced is False and self.contract.enforced is False:
# No change -- same_contract: True
return True
if old.contract.enforced is False and self.contract.enforced is True:
# Now it's enforced. This is a change, but not a breaking change -- same_contract: False
return False
# Otherwise: The contract was previously enforced, and we need to check for changes.
# Happy path: The contract is still being enforced, and the checksums are identical.
if self.contract.enforced is True and self.contract.checksum == old.contract.checksum:
# No change -- same_contract: True
return True
# Otherwise: There has been a change.
# We need to determine if it is a **breaking** change.
# These are the categories of breaking changes:
contract_enforced_disabled: bool = False
columns_removed: List[str] = []
column_type_changes: List[Dict[str, str]] = []
enforced_column_constraint_removed: List[Dict[str, str]] = (
[]
) # column_name, constraint_type
enforced_model_constraint_removed: List[Dict[str, Any]] = [] # constraint_type, columns
materialization_changed: List[str] = []
if old.contract.enforced is True and self.contract.enforced is False:
# Breaking change: the contract was previously enforced, and it no longer is
contract_enforced_disabled = True
constraint_support = get_adapter_constraint_support(adapter_type)
column_constraints_exist = False
# Next, compare each column from the previous contract (old.columns)
for old_key, old_value in sorted(old.columns.items()):
# Has this column been removed?
if old_key not in self.columns.keys():
columns_removed.append(old_value.name)
# Has this column's data type changed?
elif old_value.data_type != self.columns[old_key].data_type:
column_type_changes.append(
{
"column_name": str(old_value.name),
"previous_column_type": str(old_value.data_type),
"current_column_type": str(self.columns[old_key].data_type),
}
)
# track if there are any column level constraints for the materialization check late
if old_value.constraints:
column_constraints_exist = True
# Have enforced columns level constraints changed?
# Constraints are only enforced for table and incremental materializations.
# We only really care if the old node was one of those materializations for breaking changes
if (
old_key in self.columns.keys()
and old_value.constraints != self.columns[old_key].constraints
and old.materialization_enforces_constraints
):
for old_constraint in old_value.constraints:
if (
old_constraint not in self.columns[old_key].constraints
and constraint_support[old_constraint.type] == ConstraintSupport.ENFORCED
):
enforced_column_constraint_removed.append(
{
"column_name": old_key,
"constraint_name": old_constraint.name,
"constraint_type": ConstraintType(old_constraint.type),
}
)
# Now compare the model level constraints
if old.constraints != self.constraints and old.materialization_enforces_constraints:
for old_constraint in old.constraints:
if (
old_constraint not in self.constraints
and constraint_support[old_constraint.type] == ConstraintSupport.ENFORCED
):
enforced_model_constraint_removed.append(
{
"constraint_name": old_constraint.name,
"constraint_type": ConstraintType(old_constraint.type),
"columns": old_constraint.columns,
}
)
# Check for relevant materialization changes.
if (
old.materialization_enforces_constraints
and not self.materialization_enforces_constraints
and (old.constraints or column_constraints_exist)
):
materialization_changed = [old.config.materialized, self.config.materialized]
# If a column has been added, it will be missing in the old.columns, and present in self.columns
# That's a change (caught by the different checksums), but not a breaking change
# Did we find any changes that we consider breaking? If there's an enforced contract, that's
# a warning unless the model is versioned, then it's an error.
if (
contract_enforced_disabled
or columns_removed
or column_type_changes
or enforced_model_constraint_removed
or enforced_column_constraint_removed
or materialization_changed
):
breaking_changes = []
if contract_enforced_disabled:
breaking_changes.append(
"Contract enforcement was removed: Previously, this model had an enforced contract. It is no longer configured to enforce its contract, and this is a breaking change."
)
if columns_removed:
columns_removed_str = "\n - ".join(columns_removed)
breaking_changes.append(f"Columns were removed: \n - {columns_removed_str}")
if column_type_changes:
column_type_changes_str = "\n - ".join(
[
f"{c['column_name']} ({c['previous_column_type']} -> {c['current_column_type']})"
for c in column_type_changes
]
)
breaking_changes.append(
f"Columns with data_type changes: \n - {column_type_changes_str}"
)
if enforced_column_constraint_removed:
column_constraint_changes_str = "\n - ".join(
[
f"'{c['constraint_name'] if c['constraint_name'] is not None else c['constraint_type']}' constraint on column {c['column_name']}"
for c in enforced_column_constraint_removed
]
)
breaking_changes.append(
f"Enforced column level constraints were removed: \n - {column_constraint_changes_str}"
)
if enforced_model_constraint_removed:
model_constraint_changes_str = "\n - ".join(
[
f"'{c['constraint_name'] if c['constraint_name'] is not None else c['constraint_type']}' constraint on columns {c['columns']}"
for c in enforced_model_constraint_removed
]
)
breaking_changes.append(
f"Enforced model level constraints were removed: \n - {model_constraint_changes_str}"
)
if materialization_changed:
materialization_changes_str = (
f"{materialization_changed[0]} -> {materialization_changed[1]}"
)
breaking_changes.append(
f"Materialization changed with enforced constraints: \n - {materialization_changes_str}"
)
if self.version is None:
warn_or_error(
UnversionedBreakingChange(
contract_enforced_disabled=contract_enforced_disabled,
columns_removed=columns_removed,
column_type_changes=column_type_changes,
enforced_column_constraint_removed=enforced_column_constraint_removed,
enforced_model_constraint_removed=enforced_model_constraint_removed,
breaking_changes=breaking_changes,
model_name=self.name,
model_file_path=self.original_file_path,
),
node=self,
)
else:
raise (
ContractBreakingChangeError(
breaking_changes=breaking_changes,
node=self,
)
)
# Otherwise, the contract has changed -- same_contract: False
return False
@dataclass
class SqlNode(SqlOperationResource, CompiledNode):
@classmethod
def resource_class(cls) -> Type[SqlOperationResource]:
return SqlOperationResource
# ====================================
# Seed node
# ====================================
@dataclass
class SeedNode(SeedResource, ParsedNode): # No SQLDefaults!
@classmethod
def resource_class(cls) -> Type[SeedResource]:
return SeedResource
def same_seeds(self, other: "SeedNode") -> bool:
# for seeds, we check the hashes. If the hashes are different types,
# no match. If the hashes are both the same 'path', log a warning and
# assume they are the same
# if the current checksum is a path, we want to log a warning.
result = self.checksum == other.checksum
if self.checksum.name == "path":
msg: str
if other.checksum.name != "path":
warn_or_error(
SeedIncreased(package_name=self.package_name, name=self.name), node=self
)
elif result:
warn_or_error(
SeedExceedsLimitSamePath(package_name=self.package_name, name=self.name),
node=self,
)
elif not result:
warn_or_error(
SeedExceedsLimitAndPathChanged(package_name=self.package_name, name=self.name),
node=self,
)
else:
warn_or_error(
SeedExceedsLimitChecksumChanged(
package_name=self.package_name,
name=self.name,
checksum_name=other.checksum.name,
),
node=self,
)
return result
@property
def empty(self):
"""Seeds are never empty"""
return False
def _disallow_implicit_dependencies(self):
"""Disallow seeds to take implicit upstream dependencies via pre/post hooks"""
# Seeds are root nodes in the DAG. They cannot depend on other nodes.
# However, it's possible to define pre- and post-hooks on seeds, and for those
# hooks to include {{ ref(...) }}. This worked in previous versions, but it
# was never officially documented or supported behavior. Let's raise an explicit error,
# which will surface during parsing if the user has written code such that we attempt
# to capture & record a ref/source/metric call on the SeedNode.
# For more details: https://github.com/dbt-labs/dbt-core/issues/6806
hooks = [f'- pre_hook: "{hook.sql}"' for hook in self.config.pre_hook] + [
f'- post_hook: "{hook.sql}"' for hook in self.config.post_hook
]
hook_list = "\n".join(hooks)
message = f"""
Seeds cannot depend on other nodes. dbt detected a seed with a pre- or post-hook
that calls 'ref', 'source', or 'metric', either directly or indirectly via other macros.
Error raised for '{self.unique_id}', which has these hooks defined: \n{hook_list}
"""
raise ParsingError(message)
@property
def refs(self):
self._disallow_implicit_dependencies()
@property
def sources(self):
self._disallow_implicit_dependencies()
@property
def metrics(self):
self._disallow_implicit_dependencies()
def same_body(self, other) -> bool:
return self.same_seeds(other)
@property
def depends_on_nodes(self):
return []
@property
def depends_on_macros(self) -> List[str]:
return self.depends_on.macros
@property
def extra_ctes(self):
return []
@property
def extra_ctes_injected(self):
return False
@property
def language(self):
return "sql"
# @property
# def compiled_code(self):
# return None
# ====================================
# Singular Test node
# ====================================
class TestShouldStoreFailures:
@property
def should_store_failures(self):
if self.config.store_failures:
return self.config.store_failures
return get_flags().STORE_FAILURES
@property
def is_relational(self):
if self.should_store_failures:
return True
return False
@dataclass
class SingularTestNode(SingularTestResource, TestShouldStoreFailures, CompiledNode):
@classmethod
def resource_class(cls) -> Type[SingularTestResource]:
return SingularTestResource
@property
def test_node_type(self):
return "singular"
# ====================================
# Generic Test node
# ====================================
@dataclass
class GenericTestNode(GenericTestResource, TestShouldStoreFailures, CompiledNode):
@classmethod
def resource_class(cls) -> Type[GenericTestResource]:
return GenericTestResource
def same_contents(self, other, adapter_type: Optional[str]) -> bool:
if other is None:
return False
return self.same_config(other) and self.same_fqn(other) and True
@property