dvt-core 1.11.0b4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dvt-core might be problematic. Click here for more details.

Files changed (261) hide show
  1. dvt/__init__.py +7 -0
  2. dvt/_pydantic_shim.py +26 -0
  3. dvt/adapters/__init__.py +16 -0
  4. dvt/adapters/multi_adapter_manager.py +268 -0
  5. dvt/artifacts/__init__.py +0 -0
  6. dvt/artifacts/exceptions/__init__.py +1 -0
  7. dvt/artifacts/exceptions/schemas.py +31 -0
  8. dvt/artifacts/resources/__init__.py +116 -0
  9. dvt/artifacts/resources/base.py +68 -0
  10. dvt/artifacts/resources/types.py +93 -0
  11. dvt/artifacts/resources/v1/analysis.py +10 -0
  12. dvt/artifacts/resources/v1/catalog.py +23 -0
  13. dvt/artifacts/resources/v1/components.py +275 -0
  14. dvt/artifacts/resources/v1/config.py +282 -0
  15. dvt/artifacts/resources/v1/documentation.py +11 -0
  16. dvt/artifacts/resources/v1/exposure.py +52 -0
  17. dvt/artifacts/resources/v1/function.py +53 -0
  18. dvt/artifacts/resources/v1/generic_test.py +32 -0
  19. dvt/artifacts/resources/v1/group.py +22 -0
  20. dvt/artifacts/resources/v1/hook.py +11 -0
  21. dvt/artifacts/resources/v1/macro.py +30 -0
  22. dvt/artifacts/resources/v1/metric.py +173 -0
  23. dvt/artifacts/resources/v1/model.py +146 -0
  24. dvt/artifacts/resources/v1/owner.py +10 -0
  25. dvt/artifacts/resources/v1/saved_query.py +112 -0
  26. dvt/artifacts/resources/v1/seed.py +42 -0
  27. dvt/artifacts/resources/v1/semantic_layer_components.py +72 -0
  28. dvt/artifacts/resources/v1/semantic_model.py +315 -0
  29. dvt/artifacts/resources/v1/singular_test.py +14 -0
  30. dvt/artifacts/resources/v1/snapshot.py +92 -0
  31. dvt/artifacts/resources/v1/source_definition.py +85 -0
  32. dvt/artifacts/resources/v1/sql_operation.py +10 -0
  33. dvt/artifacts/resources/v1/unit_test_definition.py +78 -0
  34. dvt/artifacts/schemas/__init__.py +0 -0
  35. dvt/artifacts/schemas/base.py +191 -0
  36. dvt/artifacts/schemas/batch_results.py +24 -0
  37. dvt/artifacts/schemas/catalog/__init__.py +12 -0
  38. dvt/artifacts/schemas/catalog/v1/__init__.py +0 -0
  39. dvt/artifacts/schemas/catalog/v1/catalog.py +60 -0
  40. dvt/artifacts/schemas/freshness/__init__.py +1 -0
  41. dvt/artifacts/schemas/freshness/v3/__init__.py +0 -0
  42. dvt/artifacts/schemas/freshness/v3/freshness.py +159 -0
  43. dvt/artifacts/schemas/manifest/__init__.py +2 -0
  44. dvt/artifacts/schemas/manifest/v12/__init__.py +0 -0
  45. dvt/artifacts/schemas/manifest/v12/manifest.py +212 -0
  46. dvt/artifacts/schemas/results.py +148 -0
  47. dvt/artifacts/schemas/run/__init__.py +2 -0
  48. dvt/artifacts/schemas/run/v5/__init__.py +0 -0
  49. dvt/artifacts/schemas/run/v5/run.py +184 -0
  50. dvt/artifacts/schemas/upgrades/__init__.py +4 -0
  51. dvt/artifacts/schemas/upgrades/upgrade_manifest.py +174 -0
  52. dvt/artifacts/schemas/upgrades/upgrade_manifest_dbt_version.py +2 -0
  53. dvt/artifacts/utils/validation.py +153 -0
  54. dvt/cli/__init__.py +1 -0
  55. dvt/cli/context.py +16 -0
  56. dvt/cli/exceptions.py +56 -0
  57. dvt/cli/flags.py +558 -0
  58. dvt/cli/main.py +971 -0
  59. dvt/cli/option_types.py +121 -0
  60. dvt/cli/options.py +79 -0
  61. dvt/cli/params.py +803 -0
  62. dvt/cli/requires.py +478 -0
  63. dvt/cli/resolvers.py +32 -0
  64. dvt/cli/types.py +40 -0
  65. dvt/clients/__init__.py +0 -0
  66. dvt/clients/checked_load.py +82 -0
  67. dvt/clients/git.py +164 -0
  68. dvt/clients/jinja.py +206 -0
  69. dvt/clients/jinja_static.py +245 -0
  70. dvt/clients/registry.py +192 -0
  71. dvt/clients/yaml_helper.py +68 -0
  72. dvt/compilation.py +833 -0
  73. dvt/compute/__init__.py +26 -0
  74. dvt/compute/base.py +288 -0
  75. dvt/compute/engines/__init__.py +13 -0
  76. dvt/compute/engines/duckdb_engine.py +368 -0
  77. dvt/compute/engines/spark_engine.py +273 -0
  78. dvt/compute/query_analyzer.py +212 -0
  79. dvt/compute/router.py +483 -0
  80. dvt/config/__init__.py +4 -0
  81. dvt/config/catalogs.py +95 -0
  82. dvt/config/compute_config.py +406 -0
  83. dvt/config/profile.py +411 -0
  84. dvt/config/profiles_v2.py +464 -0
  85. dvt/config/project.py +893 -0
  86. dvt/config/renderer.py +232 -0
  87. dvt/config/runtime.py +491 -0
  88. dvt/config/selectors.py +209 -0
  89. dvt/config/utils.py +78 -0
  90. dvt/connectors/.gitignore +6 -0
  91. dvt/connectors/README.md +306 -0
  92. dvt/connectors/catalog.yml +217 -0
  93. dvt/connectors/download_connectors.py +300 -0
  94. dvt/constants.py +29 -0
  95. dvt/context/__init__.py +0 -0
  96. dvt/context/base.py +746 -0
  97. dvt/context/configured.py +136 -0
  98. dvt/context/context_config.py +350 -0
  99. dvt/context/docs.py +82 -0
  100. dvt/context/exceptions_jinja.py +179 -0
  101. dvt/context/macro_resolver.py +195 -0
  102. dvt/context/macros.py +171 -0
  103. dvt/context/manifest.py +73 -0
  104. dvt/context/providers.py +2198 -0
  105. dvt/context/query_header.py +14 -0
  106. dvt/context/secret.py +59 -0
  107. dvt/context/target.py +74 -0
  108. dvt/contracts/__init__.py +0 -0
  109. dvt/contracts/files.py +413 -0
  110. dvt/contracts/graph/__init__.py +0 -0
  111. dvt/contracts/graph/manifest.py +1904 -0
  112. dvt/contracts/graph/metrics.py +98 -0
  113. dvt/contracts/graph/model_config.py +71 -0
  114. dvt/contracts/graph/node_args.py +42 -0
  115. dvt/contracts/graph/nodes.py +1806 -0
  116. dvt/contracts/graph/semantic_manifest.py +233 -0
  117. dvt/contracts/graph/unparsed.py +812 -0
  118. dvt/contracts/project.py +417 -0
  119. dvt/contracts/results.py +53 -0
  120. dvt/contracts/selection.py +23 -0
  121. dvt/contracts/sql.py +86 -0
  122. dvt/contracts/state.py +69 -0
  123. dvt/contracts/util.py +46 -0
  124. dvt/deprecations.py +347 -0
  125. dvt/deps/__init__.py +0 -0
  126. dvt/deps/base.py +153 -0
  127. dvt/deps/git.py +196 -0
  128. dvt/deps/local.py +80 -0
  129. dvt/deps/registry.py +131 -0
  130. dvt/deps/resolver.py +149 -0
  131. dvt/deps/tarball.py +121 -0
  132. dvt/docs/source/_ext/dbt_click.py +118 -0
  133. dvt/docs/source/conf.py +32 -0
  134. dvt/env_vars.py +64 -0
  135. dvt/event_time/event_time.py +40 -0
  136. dvt/event_time/sample_window.py +60 -0
  137. dvt/events/__init__.py +16 -0
  138. dvt/events/base_types.py +37 -0
  139. dvt/events/core_types_pb2.py +2 -0
  140. dvt/events/logging.py +109 -0
  141. dvt/events/types.py +2534 -0
  142. dvt/exceptions.py +1487 -0
  143. dvt/flags.py +89 -0
  144. dvt/graph/__init__.py +11 -0
  145. dvt/graph/cli.py +248 -0
  146. dvt/graph/graph.py +172 -0
  147. dvt/graph/queue.py +213 -0
  148. dvt/graph/selector.py +375 -0
  149. dvt/graph/selector_methods.py +976 -0
  150. dvt/graph/selector_spec.py +223 -0
  151. dvt/graph/thread_pool.py +18 -0
  152. dvt/hooks.py +21 -0
  153. dvt/include/README.md +49 -0
  154. dvt/include/__init__.py +3 -0
  155. dvt/include/global_project.py +4 -0
  156. dvt/include/starter_project/.gitignore +4 -0
  157. dvt/include/starter_project/README.md +15 -0
  158. dvt/include/starter_project/__init__.py +3 -0
  159. dvt/include/starter_project/analyses/.gitkeep +0 -0
  160. dvt/include/starter_project/dvt_project.yml +36 -0
  161. dvt/include/starter_project/macros/.gitkeep +0 -0
  162. dvt/include/starter_project/models/example/my_first_dbt_model.sql +27 -0
  163. dvt/include/starter_project/models/example/my_second_dbt_model.sql +6 -0
  164. dvt/include/starter_project/models/example/schema.yml +21 -0
  165. dvt/include/starter_project/seeds/.gitkeep +0 -0
  166. dvt/include/starter_project/snapshots/.gitkeep +0 -0
  167. dvt/include/starter_project/tests/.gitkeep +0 -0
  168. dvt/internal_deprecations.py +27 -0
  169. dvt/jsonschemas/__init__.py +3 -0
  170. dvt/jsonschemas/jsonschemas.py +309 -0
  171. dvt/jsonschemas/project/0.0.110.json +4717 -0
  172. dvt/jsonschemas/project/0.0.85.json +2015 -0
  173. dvt/jsonschemas/resources/0.0.110.json +2636 -0
  174. dvt/jsonschemas/resources/0.0.85.json +2536 -0
  175. dvt/jsonschemas/resources/latest.json +6773 -0
  176. dvt/links.py +4 -0
  177. dvt/materializations/__init__.py +0 -0
  178. dvt/materializations/incremental/__init__.py +0 -0
  179. dvt/materializations/incremental/microbatch.py +235 -0
  180. dvt/mp_context.py +8 -0
  181. dvt/node_types.py +37 -0
  182. dvt/parser/__init__.py +23 -0
  183. dvt/parser/analysis.py +21 -0
  184. dvt/parser/base.py +549 -0
  185. dvt/parser/common.py +267 -0
  186. dvt/parser/docs.py +52 -0
  187. dvt/parser/fixtures.py +51 -0
  188. dvt/parser/functions.py +30 -0
  189. dvt/parser/generic_test.py +100 -0
  190. dvt/parser/generic_test_builders.py +334 -0
  191. dvt/parser/hooks.py +119 -0
  192. dvt/parser/macros.py +137 -0
  193. dvt/parser/manifest.py +2204 -0
  194. dvt/parser/models.py +574 -0
  195. dvt/parser/partial.py +1179 -0
  196. dvt/parser/read_files.py +445 -0
  197. dvt/parser/schema_generic_tests.py +423 -0
  198. dvt/parser/schema_renderer.py +111 -0
  199. dvt/parser/schema_yaml_readers.py +936 -0
  200. dvt/parser/schemas.py +1467 -0
  201. dvt/parser/search.py +149 -0
  202. dvt/parser/seeds.py +28 -0
  203. dvt/parser/singular_test.py +20 -0
  204. dvt/parser/snapshots.py +44 -0
  205. dvt/parser/sources.py +557 -0
  206. dvt/parser/sql.py +63 -0
  207. dvt/parser/unit_tests.py +622 -0
  208. dvt/plugins/__init__.py +20 -0
  209. dvt/plugins/contracts.py +10 -0
  210. dvt/plugins/exceptions.py +2 -0
  211. dvt/plugins/manager.py +164 -0
  212. dvt/plugins/manifest.py +21 -0
  213. dvt/profiler.py +20 -0
  214. dvt/py.typed +1 -0
  215. dvt/runners/__init__.py +2 -0
  216. dvt/runners/exposure_runner.py +7 -0
  217. dvt/runners/no_op_runner.py +46 -0
  218. dvt/runners/saved_query_runner.py +7 -0
  219. dvt/selected_resources.py +8 -0
  220. dvt/task/__init__.py +0 -0
  221. dvt/task/base.py +504 -0
  222. dvt/task/build.py +197 -0
  223. dvt/task/clean.py +57 -0
  224. dvt/task/clone.py +162 -0
  225. dvt/task/compile.py +151 -0
  226. dvt/task/compute.py +366 -0
  227. dvt/task/debug.py +650 -0
  228. dvt/task/deps.py +280 -0
  229. dvt/task/docs/__init__.py +3 -0
  230. dvt/task/docs/generate.py +408 -0
  231. dvt/task/docs/index.html +250 -0
  232. dvt/task/docs/serve.py +28 -0
  233. dvt/task/freshness.py +323 -0
  234. dvt/task/function.py +122 -0
  235. dvt/task/group_lookup.py +46 -0
  236. dvt/task/init.py +374 -0
  237. dvt/task/list.py +237 -0
  238. dvt/task/printer.py +176 -0
  239. dvt/task/profiles.py +256 -0
  240. dvt/task/retry.py +175 -0
  241. dvt/task/run.py +1146 -0
  242. dvt/task/run_operation.py +142 -0
  243. dvt/task/runnable.py +802 -0
  244. dvt/task/seed.py +104 -0
  245. dvt/task/show.py +150 -0
  246. dvt/task/snapshot.py +57 -0
  247. dvt/task/sql.py +111 -0
  248. dvt/task/test.py +464 -0
  249. dvt/tests/fixtures/__init__.py +1 -0
  250. dvt/tests/fixtures/project.py +620 -0
  251. dvt/tests/util.py +651 -0
  252. dvt/tracking.py +529 -0
  253. dvt/utils/__init__.py +3 -0
  254. dvt/utils/artifact_upload.py +151 -0
  255. dvt/utils/utils.py +408 -0
  256. dvt/version.py +249 -0
  257. dvt_core-1.11.0b4.dist-info/METADATA +252 -0
  258. dvt_core-1.11.0b4.dist-info/RECORD +261 -0
  259. dvt_core-1.11.0b4.dist-info/WHEEL +5 -0
  260. dvt_core-1.11.0b4.dist-info/entry_points.txt +2 -0
  261. dvt_core-1.11.0b4.dist-info/top_level.txt +1 -0
dvt/parser/schemas.py ADDED
@@ -0,0 +1,1467 @@
1
+ import datetime
2
+ import pathlib
3
+ import re
4
+ import time
5
+ from abc import ABCMeta, abstractmethod
6
+ from dataclasses import dataclass, field
7
+ from typing import (
8
+ Any,
9
+ Callable,
10
+ Dict,
11
+ Generic,
12
+ Iterable,
13
+ List,
14
+ Optional,
15
+ Tuple,
16
+ Type,
17
+ TypeVar,
18
+ )
19
+
20
+ from dvt.artifacts.resources import CustomGranularity, RefArgs, TimeSpine
21
+ from dvt.clients.checked_load import (
22
+ checked_load,
23
+ issue_deprecation_warnings_for_failures,
24
+ )
25
+ from dvt.clients.jinja_static import statically_parse_ref_or_source
26
+ from dvt.clients.yaml_helper import load_yaml_text
27
+ from dvt.config import RuntimeConfig
28
+ from dvt.context.configured import SchemaYamlVars, generate_schema_yml_context
29
+ from dvt.context.context_config import ContextConfig
30
+ from dvt.contracts.files import SchemaSourceFile, SourceFile
31
+ from dvt.contracts.graph.manifest import Manifest
32
+ from dvt.contracts.graph.nodes import (
33
+ FunctionNode,
34
+ Macro,
35
+ ModelNode,
36
+ ParsedFunctionPatch,
37
+ ParsedMacroPatch,
38
+ ParsedNodePatch,
39
+ ParsedSingularTestPatch,
40
+ UnpatchedSourceDefinition,
41
+ )
42
+ from dvt.contracts.graph.unparsed import (
43
+ HasColumnDocs,
44
+ HasColumnTests,
45
+ SourcePatch,
46
+ UnparsedAnalysisUpdate,
47
+ UnparsedFunctionUpdate,
48
+ UnparsedMacroUpdate,
49
+ UnparsedModelUpdate,
50
+ UnparsedNodeUpdate,
51
+ UnparsedSingularTestUpdate,
52
+ UnparsedSourceDefinition,
53
+ )
54
+ from dvt.events.types import (
55
+ InvalidMacroAnnotation,
56
+ MacroNotFoundForPatch,
57
+ NoNodeForYamlKey,
58
+ UnsupportedConstraintMaterialization,
59
+ ValidationWarning,
60
+ WrongResourceSchemaFile,
61
+ )
62
+ from dvt.exceptions import (
63
+ DbtInternalError,
64
+ DuplicateMacroPatchNameError,
65
+ DuplicatePatchPathError,
66
+ DuplicateSourcePatchNameError,
67
+ InvalidAccessTypeError,
68
+ JSONValidationError,
69
+ ParsingError,
70
+ YamlLoadError,
71
+ YamlParseDictError,
72
+ YamlParseListError,
73
+ )
74
+ from dvt.flags import get_flags
75
+ from dvt.node_types import AccessType, NodeType
76
+ from dvt.parser.base import SimpleParser
77
+ from dvt.parser.common import (
78
+ ParserRef,
79
+ TargetBlock,
80
+ TestBlock,
81
+ VersionedTestBlock,
82
+ YamlBlock,
83
+ schema_file_keys_to_resource_types,
84
+ trimmed,
85
+ )
86
+ from dvt.parser.schema_generic_tests import SchemaGenericTestParser
87
+ from dvt.parser.schema_renderer import SchemaYamlRenderer
88
+ from dvt.parser.search import FileBlock
89
+ from dvt.utils import coerce_dict_str
90
+
91
+ from dbt_common.contracts.constraints import ConstraintType, ModelLevelConstraint
92
+ from dbt_common.dataclass_schema import ValidationError, dbtClassMixin
93
+ from dbt_common.events import EventLevel
94
+ from dbt_common.events.functions import fire_event, warn_or_error
95
+ from dbt_common.events.types import Note
96
+ from dbt_common.exceptions import DbtValidationError
97
+ from dbt_common.utils import deep_merge
98
+
99
+ # ===============================================================================
100
+ # Schema Parser classes
101
+ #
102
+ # The SchemaParser is a subclass of the SimpleParser from base.py, as is
103
+ # the SchemaGenericTestParser. The schema sub-parsers are all subclasses of
104
+ # the YamlReader parsing class. Most of the action in creating SourceDefinition
105
+ # nodes actually happens in the SourcePatcher class, in sources.py, which is
106
+ # called as a late-stage parsing step in manifest.py.
107
+ #
108
+ # The "patch" parsers read yaml config and properties and apply them to
109
+ # nodes that were already created from sql files.
110
+ #
111
+ # The SchemaParser and SourcePatcher both use the SchemaGenericTestParser
112
+ # (in schema_generic_tests.py) to create generic test nodes.
113
+ #
114
+ # YamlReader
115
+ # MetricParser (metrics) [schema_yaml_readers.py]
116
+ # ExposureParser (exposures) [schema_yaml_readers.py]
117
+ # GroupParser (groups) [schema_yaml_readers.py]
118
+ # SourceParser (sources)
119
+ # PatchParser
120
+ # MacroPatchParser (macros)
121
+ # NodePatchParser
122
+ # ModelPatchParser (models)
123
+ # AnalysisPatchParser (analyses)
124
+ # TestablePatchParser (seeds, snapshots)
125
+ #
126
+ # ===============================================================================
127
+
128
+
129
+ def yaml_from_file(
130
+ source_file: SchemaSourceFile, validate: bool = False
131
+ ) -> Optional[Dict[str, Any]]:
132
+ """If loading the yaml fails, raise an exception."""
133
+ try:
134
+ # source_file.contents can sometimes be None
135
+ to_load = source_file.contents or ""
136
+
137
+ if validate:
138
+ contents, failures = checked_load(to_load)
139
+ issue_deprecation_warnings_for_failures(
140
+ failures=failures, file=source_file.path.original_file_path
141
+ )
142
+ if contents is not None:
143
+ from dvt.jsonschemas.jsonschemas import (
144
+ jsonschema_validate,
145
+ resources_schema,
146
+ )
147
+
148
+ # Validate the yaml against the jsonschema to raise deprecation warnings
149
+ # for invalid fields.
150
+ jsonschema_validate(
151
+ schema=resources_schema(),
152
+ json=contents,
153
+ file_path=source_file.path.original_file_path,
154
+ )
155
+ else:
156
+ contents = load_yaml_text(to_load, source_file.path)
157
+
158
+ if contents is None:
159
+ return contents
160
+
161
+ if not isinstance(contents, dict):
162
+ raise DbtValidationError(
163
+ f"Contents of file '{source_file.original_file_path}' are not valid. Dictionary expected."
164
+ )
165
+
166
+ # When loaded_at_field is defined as None or null, it shows up in
167
+ # the dict but when it is not defined, it does not show up in the dict
168
+ # We need to capture this to be able to override source level settings later.
169
+ for source in contents.get("sources", []):
170
+ for table in source.get("tables", []):
171
+ if "loaded_at_field" in table or (
172
+ "config" in table
173
+ and table["config"] is not None
174
+ and table["config"].get("loaded_at_field")
175
+ ):
176
+ table["loaded_at_field_present"] = True
177
+
178
+ return contents
179
+ except DbtValidationError as e:
180
+ raise YamlLoadError(
181
+ project_name=source_file.project_name, path=source_file.path.relative_path, exc=e
182
+ )
183
+
184
+
185
+ # This is the main schema file parser, but almost everything happens in the
186
+ # the schema sub-parsers.
187
+ class SchemaParser(SimpleParser[YamlBlock, ModelNode]):
188
+ def __init__(
189
+ self,
190
+ project: RuntimeConfig,
191
+ manifest: Manifest,
192
+ root_project: RuntimeConfig,
193
+ ) -> None:
194
+ super().__init__(project, manifest, root_project)
195
+
196
+ self.generic_test_parser = SchemaGenericTestParser(project, manifest, root_project)
197
+
198
+ self.schema_yaml_vars = SchemaYamlVars()
199
+ self.render_ctx = generate_schema_yml_context(
200
+ self.root_project, self.project.project_name, self.schema_yaml_vars
201
+ )
202
+
203
+ # This is unnecessary, but mypy was requiring it. Clean up parser code so
204
+ # we don't have to do this.
205
+ def parse_from_dict(self, dct):
206
+ pass
207
+
208
+ @classmethod
209
+ def get_compiled_path(cls, block: FileBlock) -> str:
210
+ # should this raise an error?
211
+ return block.path.relative_path
212
+
213
+ @property
214
+ def resource_type(self) -> NodeType:
215
+ return NodeType.Test
216
+
217
+ def parse_file(self, block: FileBlock, dct: Optional[Dict] = None) -> None:
218
+ assert isinstance(block.file, SchemaSourceFile)
219
+
220
+ # If partially parsing, dct should be from pp_dict, otherwise
221
+ # dict_from_yaml
222
+ if dct:
223
+ # contains the FileBlock and the data (dictionary)
224
+ yaml_block = YamlBlock.from_file_block(block, dct)
225
+ parser: YamlReader
226
+
227
+ # There are 9 different yaml lists which are parsed by different parsers:
228
+ # Model, Seed, Snapshot, Source, Macro, Analysis, Exposure, Metric, Group
229
+
230
+ # ModelPatchParser.parse()
231
+ if "models" in dct:
232
+ # the models are already in the manifest as nodes when we reach this code,
233
+ # even if they are disabled in the schema file
234
+ model_parse_result = ModelPatchParser(self, yaml_block, "models").parse()
235
+ for versioned_test_block in model_parse_result.versioned_test_blocks:
236
+ self.generic_test_parser.parse_versioned_tests(versioned_test_block)
237
+
238
+ # PatchParser.parse()
239
+ if "seeds" in dct:
240
+ seed_parse_result = TestablePatchParser(self, yaml_block, "seeds").parse()
241
+ for test_block in seed_parse_result.test_blocks:
242
+ self.generic_test_parser.parse_tests(test_block)
243
+
244
+ # PatchParser.parse()
245
+ if "snapshots" in dct:
246
+ self._add_yaml_snapshot_nodes_to_manifest(dct["snapshots"], block)
247
+ snapshot_parse_result = TestablePatchParser(self, yaml_block, "snapshots").parse()
248
+ for test_block in snapshot_parse_result.test_blocks:
249
+ self.generic_test_parser.parse_tests(test_block)
250
+
251
+ # This parser uses SourceParser.parse() which doesn't return
252
+ # any test blocks. Source tests are handled at a later point
253
+ # in the process.
254
+ if "sources" in dct:
255
+ parser = SourceParser(self, yaml_block, "sources")
256
+ parser.parse()
257
+
258
+ # PatchParser.parse() (but never test_blocks)
259
+ if "macros" in dct:
260
+ parser = MacroPatchParser(self, yaml_block, "macros")
261
+ parser.parse()
262
+
263
+ if "data_tests" in dct:
264
+ parser = SingularTestPatchParser(self, yaml_block, "data_tests")
265
+ try:
266
+ parser.parse()
267
+ except ParsingError as e:
268
+ fire_event(
269
+ Note(
270
+ msg=f"Unable to parse 'data_tests' section of file '{block.path.original_file_path}'\n{e}",
271
+ ),
272
+ EventLevel.WARN,
273
+ )
274
+
275
+ # PatchParser.parse() (but never test_blocks)
276
+ if "analyses" in dct:
277
+ parser = AnalysisPatchParser(self, yaml_block, "analyses")
278
+ parser.parse()
279
+
280
+ # ExposureParser.parse()
281
+ if "exposures" in dct:
282
+ from dvt.parser.schema_yaml_readers import ExposureParser
283
+
284
+ exp_parser = ExposureParser(self, yaml_block)
285
+ exp_parser.parse()
286
+
287
+ # FunctionPatchParser.parse()
288
+ if "functions" in dct:
289
+ function_parser = FunctionPatchParser(self, yaml_block, "functions")
290
+ function_parser.parse()
291
+
292
+ # MetricParser.parse()
293
+ if "metrics" in dct:
294
+ from dvt.parser.schema_yaml_readers import MetricParser
295
+
296
+ metric_parser = MetricParser(self, yaml_block)
297
+ metric_parser.parse()
298
+
299
+ # GroupParser.parse()
300
+ if "groups" in dct:
301
+ from dvt.parser.schema_yaml_readers import GroupParser
302
+
303
+ group_parser = GroupParser(self, yaml_block)
304
+ group_parser.parse()
305
+
306
+ if "semantic_models" in dct:
307
+ from dvt.parser.schema_yaml_readers import SemanticModelParser
308
+
309
+ semantic_model_parser = SemanticModelParser(self, yaml_block)
310
+ semantic_model_parser.parse()
311
+
312
+ if "unit_tests" in dct:
313
+ from dvt.parser.unit_tests import UnitTestParser
314
+
315
+ unit_test_parser = UnitTestParser(self, yaml_block)
316
+ unit_test_parser.parse()
317
+
318
+ if "saved_queries" in dct:
319
+ from dvt.parser.schema_yaml_readers import SavedQueryParser
320
+
321
+ saved_query_parser = SavedQueryParser(self, yaml_block)
322
+ saved_query_parser.parse()
323
+
324
+ def _add_yaml_snapshot_nodes_to_manifest(
325
+ self, snapshots: List[Dict[str, Any]], block: FileBlock
326
+ ) -> None:
327
+ """We support the creation of simple snapshots in yaml, without an
328
+ accompanying SQL definition. For such snapshots, the user must supply
329
+ a 'relation' property to indicate the target of the snapshot. This
330
+ function looks for such snapshots and adds a node to manifest for each
331
+ one we find, since they were not added during SQL parsing."""
332
+
333
+ rebuild_refs = False
334
+ for snapshot in snapshots:
335
+ if "relation" in snapshot:
336
+ from dvt.parser import SnapshotParser
337
+
338
+ if "name" not in snapshot:
339
+ raise ParsingError("A snapshot must define the 'name' property. ")
340
+
341
+ # Reuse the logic of SnapshotParser as far as possible to create
342
+ # a new node we can add to the manifest.
343
+ parser = SnapshotParser(self.project, self.manifest, self.root_project)
344
+ fqn = parser.get_fqn_prefix(block.path.relative_path)
345
+ fqn.append(snapshot["name"])
346
+
347
+ compiled_path = str(
348
+ pathlib.PurePath("").joinpath(
349
+ block.path.relative_path, snapshot["name"] + ".sql"
350
+ )
351
+ )
352
+ snapshot_node = parser._create_parsetime_node(
353
+ block,
354
+ compiled_path,
355
+ parser.initial_config(fqn),
356
+ fqn,
357
+ snapshot["name"],
358
+ )
359
+
360
+ # Parse the expected ref() or source() expression given by
361
+ # 'relation' so that we know what we are snapshotting.
362
+ source_or_ref = statically_parse_ref_or_source(snapshot["relation"])
363
+ if isinstance(source_or_ref, RefArgs):
364
+ snapshot_node.refs.append(source_or_ref)
365
+ else:
366
+ snapshot_node.sources.append(source_or_ref)
367
+
368
+ # Implement the snapshot SQL as a simple select *
369
+ snapshot_node.raw_code = "select * from {{ " + snapshot["relation"] + " }}"
370
+
371
+ # Add our new node to the manifest, and note that ref lookup collections
372
+ # will need to be rebuilt. This adds the node unique_id to the "snapshots"
373
+ # list in the SchemaSourceFile.
374
+ self.manifest.add_node(block.file, snapshot_node)
375
+ rebuild_refs = True
376
+
377
+ if rebuild_refs:
378
+ self.manifest.rebuild_ref_lookup()
379
+
380
+
381
+ Parsed = TypeVar(
382
+ "Parsed", UnpatchedSourceDefinition, ParsedNodePatch, ParsedMacroPatch, ParsedSingularTestPatch
383
+ )
384
+ NodeTarget = TypeVar(
385
+ "NodeTarget",
386
+ UnparsedNodeUpdate,
387
+ UnparsedAnalysisUpdate,
388
+ UnparsedModelUpdate,
389
+ UnparsedFunctionUpdate,
390
+ )
391
+ NonSourceTarget = TypeVar(
392
+ "NonSourceTarget",
393
+ UnparsedNodeUpdate,
394
+ UnparsedAnalysisUpdate,
395
+ UnparsedMacroUpdate,
396
+ UnparsedModelUpdate,
397
+ UnparsedFunctionUpdate,
398
+ UnparsedSingularTestUpdate,
399
+ )
400
+
401
+
402
+ @dataclass
403
+ class ParseResult:
404
+ test_blocks: List[TestBlock] = field(default_factory=list)
405
+ versioned_test_blocks: List[VersionedTestBlock] = field(default_factory=list)
406
+
407
+
408
+ # abstract base class (ABCMeta)
409
+ # Many subclasses: MetricParser, ExposureParser, GroupParser, SourceParser,
410
+ # PatchParser, SemanticModelParser, SavedQueryParser, UnitTestParser
411
+ class YamlReader(metaclass=ABCMeta):
412
+ def __init__(self, schema_parser: SchemaParser, yaml: YamlBlock, key: str) -> None:
413
+ self.schema_parser: SchemaParser = schema_parser
414
+ # key: models, seeds, snapshots, sources, macros,
415
+ # analyses, exposures, unit_tests
416
+ self.key: str = key
417
+ self.yaml: YamlBlock = yaml
418
+ self.schema_yaml_vars: SchemaYamlVars = SchemaYamlVars()
419
+ self.render_ctx = generate_schema_yml_context(
420
+ self.schema_parser.root_project,
421
+ self.schema_parser.project.project_name,
422
+ self.schema_yaml_vars,
423
+ )
424
+ self.renderer: SchemaYamlRenderer = SchemaYamlRenderer(self.render_ctx, self.key)
425
+
426
+ @property
427
+ def manifest(self) -> Manifest:
428
+ return self.schema_parser.manifest
429
+
430
+ @property
431
+ def project(self) -> RuntimeConfig:
432
+ return self.schema_parser.project
433
+
434
+ @property
435
+ def default_database(self) -> str:
436
+ return self.schema_parser.default_database
437
+
438
+ @property
439
+ def root_project(self) -> RuntimeConfig:
440
+ return self.schema_parser.root_project
441
+
442
+ # for the different schema subparsers ('models', 'source', etc)
443
+ # get the list of dicts pointed to by the key in the yaml config,
444
+ # ensure that the dicts have string keys
445
+ def get_key_dicts(self) -> Iterable[Dict[str, Any]]:
446
+ data = self.yaml.data.get(self.key, [])
447
+ if not isinstance(data, list):
448
+ raise ParsingError(
449
+ "{} must be a list, got {} instead: ({})".format(
450
+ self.key, type(data), trimmed(str(data))
451
+ )
452
+ )
453
+ path = self.yaml.path.original_file_path
454
+
455
+ # for each dict in the data (which is a list of dicts)
456
+ for entry in data:
457
+
458
+ # check that entry is a dict and that all dict values
459
+ # are strings
460
+ if coerce_dict_str(entry) is None:
461
+ raise YamlParseListError(path, self.key, data, "expected a dict with string keys")
462
+
463
+ if "name" not in entry and "model" not in entry:
464
+ raise ParsingError("Entry did not contain a name")
465
+
466
+ unrendered_config = {}
467
+ if "config" in entry:
468
+ unrendered_config = entry["config"]
469
+
470
+ unrendered_version_configs = {}
471
+ if "versions" in entry:
472
+ for version in entry["versions"]:
473
+ if "v" in version:
474
+ unrendered_version_configs[version["v"]] = version.get("config", {})
475
+
476
+ # For sources
477
+ unrendered_database = entry.get("database", None)
478
+ unrendered_schema = entry.get("schema", None)
479
+
480
+ # Render the data (except for tests, data_tests and descriptions).
481
+ # See the SchemaYamlRenderer
482
+ entry = self.render_entry(entry)
483
+
484
+ schema_file = self.yaml.file
485
+ assert isinstance(schema_file, SchemaSourceFile)
486
+
487
+ if unrendered_config:
488
+ schema_file.add_unrendered_config(unrendered_config, self.key, entry["name"])
489
+
490
+ for version, unrendered_version_config in unrendered_version_configs.items():
491
+ schema_file.add_unrendered_config(
492
+ unrendered_version_config, self.key, entry["name"], version
493
+ )
494
+
495
+ if unrendered_database:
496
+ schema_file.add_unrendered_database(self.key, entry["name"], unrendered_database)
497
+ if unrendered_schema:
498
+ schema_file.add_unrendered_schema(self.key, entry["name"], unrendered_schema)
499
+
500
+ if self.schema_yaml_vars.env_vars:
501
+ self.schema_parser.manifest.env_vars.update(self.schema_yaml_vars.env_vars)
502
+ for var in self.schema_yaml_vars.env_vars.keys():
503
+ schema_file.add_env_var(var, self.key, entry["name"])
504
+ self.schema_yaml_vars.env_vars = {}
505
+
506
+ yield entry
507
+
508
+ def render_entry(self, dct):
509
+ try:
510
+ # This does a deep_map which will fail if there are circular references
511
+ dct = self.renderer.render_data(dct)
512
+ except ParsingError as exc:
513
+ raise ParsingError(
514
+ f"Failed to render {self.yaml.file.path.original_file_path} from "
515
+ f"project {self.project.project_name}: {exc}"
516
+ ) from exc
517
+ return dct
518
+
519
+ @abstractmethod
520
+ def parse(self) -> Optional[ParseResult]:
521
+ raise NotImplementedError("parse is abstract")
522
+
523
+
524
+ T = TypeVar("T", bound=dbtClassMixin)
525
+
526
+
527
+ # This parses the 'sources' keys in yaml files.
528
+ class SourceParser(YamlReader):
529
+ def _target_from_dict(self, cls: Type[T], data: Dict[str, Any]) -> T:
530
+ path = self.yaml.path.original_file_path
531
+ try:
532
+ cls.validate(data)
533
+ return cls.from_dict(data)
534
+ except (ValidationError, JSONValidationError) as exc:
535
+ raise YamlParseDictError(path, self.key, data, exc)
536
+
537
+ # This parse method takes the yaml dictionaries in 'sources' keys and uses them
538
+ # to create UnparsedSourceDefinition objects. They are then turned
539
+ # into UnpatchedSourceDefinition objects in 'add_source_definitions'
540
+ # or SourcePatch objects in 'add_source_patch'
541
+ def parse(self) -> ParseResult:
542
+ # get a verified list of dicts for the key handled by this parser
543
+ for data in self.get_key_dicts():
544
+ data = self.project.credentials.translate_aliases(data, recurse=True)
545
+
546
+ is_override = "overrides" in data
547
+ if is_override:
548
+ data["path"] = self.yaml.path.original_file_path
549
+ patch = self._target_from_dict(SourcePatch, data)
550
+ assert isinstance(self.yaml.file, SchemaSourceFile)
551
+ source_file = self.yaml.file
552
+ # source patches must be unique
553
+ key = (patch.overrides, patch.name)
554
+ if key in self.manifest.source_patches:
555
+ raise DuplicateSourcePatchNameError(patch, self.manifest.source_patches[key])
556
+ self.manifest.source_patches[key] = patch
557
+ source_file.source_patches.append(key)
558
+ else:
559
+ source = self._target_from_dict(UnparsedSourceDefinition, data)
560
+ # Store unrendered_database and unrendered_schema for state:modified comparisons
561
+ if isinstance(self.yaml.file, SchemaSourceFile):
562
+ source.unrendered_database = self.yaml.file.get_unrendered_database(
563
+ "sources", source.name
564
+ )
565
+ source.unrendered_schema = self.yaml.file.get_unrendered_schema(
566
+ "sources", source.name
567
+ )
568
+
569
+ self.add_source_definitions(source)
570
+ return ParseResult()
571
+
572
+ def add_source_definitions(self, source: UnparsedSourceDefinition) -> None:
573
+ package_name = self.project.project_name
574
+ original_file_path = self.yaml.path.original_file_path
575
+ fqn_path = self.yaml.path.relative_path
576
+ for table in source.tables:
577
+ unique_id = ".".join([NodeType.Source, package_name, source.name, table.name])
578
+
579
+ # the FQN is project name / path elements /source_name /table_name
580
+ fqn = self.schema_parser.get_fqn_prefix(fqn_path)
581
+ fqn.extend([source.name, table.name])
582
+
583
+ source_def = UnpatchedSourceDefinition(
584
+ source=source,
585
+ table=table,
586
+ path=original_file_path,
587
+ original_file_path=original_file_path,
588
+ package_name=package_name,
589
+ unique_id=unique_id,
590
+ resource_type=NodeType.Source,
591
+ fqn=fqn,
592
+ name=f"{source.name}_{table.name}",
593
+ )
594
+ assert isinstance(self.yaml.file, SchemaSourceFile)
595
+ source_file: SchemaSourceFile = self.yaml.file
596
+ self.manifest.add_source(source_file, source_def)
597
+
598
+
599
+ # This class has two subclasses: NodePatchParser and MacroPatchParser
600
+ class PatchParser(YamlReader, Generic[NonSourceTarget, Parsed]):
601
+ @abstractmethod
602
+ def _target_type(self) -> Type[NonSourceTarget]:
603
+ raise NotImplementedError("_target_type not implemented")
604
+
605
+ @abstractmethod
606
+ def get_block(self, node: NonSourceTarget) -> TargetBlock:
607
+ raise NotImplementedError("get_block is abstract")
608
+
609
+ @abstractmethod
610
+ def parse_patch(self, block: TargetBlock[NonSourceTarget], refs: ParserRef) -> None:
611
+ raise NotImplementedError("parse_patch is abstract")
612
+
613
+ def parse(self) -> ParseResult:
614
+ node: NonSourceTarget
615
+ # This will always be empty if the node a macro or analysis
616
+ test_blocks: List[TestBlock] = []
617
+ # This will always be empty if the node is _not_ a model
618
+ versioned_test_blocks: List[VersionedTestBlock] = []
619
+
620
+ # get list of 'node' objects
621
+ # UnparsedNodeUpdate (TestablePatchParser, models, seeds, snapshots)
622
+ # = HasColumnTests, HasTests
623
+ # UnparsedAnalysisUpdate (UnparsedAnalysisParser, analyses)
624
+ # = HasColumnDocs, HasDocs
625
+ # UnparsedMacroUpdate (MacroPatchParser, 'macros')
626
+ # = HasDocs
627
+ # correspond to this parser's 'key'
628
+ for node in self.get_unparsed_target():
629
+ # node_block is a TargetBlock (Macro or Analysis)
630
+ # or a TestBlock (all of the others)
631
+ node_block = self.get_block(node)
632
+ if isinstance(node_block, TestBlock):
633
+ # TestablePatchParser = seeds, snapshots
634
+ test_blocks.append(node_block)
635
+ if isinstance(node_block, VersionedTestBlock):
636
+ # models
637
+ versioned_test_blocks.append(node_block)
638
+ if isinstance(node, (HasColumnDocs, HasColumnTests)):
639
+ # UnparsedNodeUpdate and UnparsedAnalysisUpdate
640
+ refs: ParserRef = ParserRef.from_target(node)
641
+ else:
642
+ refs = ParserRef()
643
+
644
+ # There's no unique_id on the node yet so cannot add to disabled dict
645
+ self.parse_patch(node_block, refs)
646
+
647
+ return ParseResult(test_blocks, versioned_test_blocks)
648
+
649
+ def get_unparsed_target(self) -> Iterable[NonSourceTarget]:
650
+ path = self.yaml.path.original_file_path
651
+
652
+ # get verified list of dicts for the 'key' that this
653
+ # parser handles
654
+ key_dicts = self.get_key_dicts()
655
+ for data in key_dicts:
656
+ # add extra data to each dict. This updates the dicts
657
+ # in the parser yaml
658
+ data.update(
659
+ {
660
+ "original_file_path": path,
661
+ "yaml_key": self.key,
662
+ "package_name": self.project.project_name,
663
+ }
664
+ )
665
+ try:
666
+ # target_type: UnparsedNodeUpdate, UnparsedAnalysisUpdate,
667
+ # or UnparsedMacroUpdate, UnparsedFunctionUpdate
668
+ self._target_type().validate(data)
669
+ if self.key != "macros":
670
+ # macros don't have the 'config' key support yet
671
+ self.normalize_meta_attribute(data, path)
672
+ self.normalize_docs_attribute(data, path)
673
+ self.normalize_group_attribute(data, path)
674
+ self.normalize_contract_attribute(data, path)
675
+ self.normalize_access_attribute(data, path)
676
+ # `tests` has been deprecated, convert to `data_tests` here if present
677
+ self.validate_data_tests(data)
678
+ node = self._target_type().from_dict(data)
679
+ except (ValidationError, JSONValidationError) as exc:
680
+ raise YamlParseDictError(path, self.key, data, exc)
681
+ else:
682
+ yield node
683
+
684
+ # We want to raise an error if some attributes are in two places, and move them
685
+ # from toplevel to config if necessary
686
+ def normalize_attribute(self, data, path, attribute) -> None:
687
+ if attribute in data:
688
+ if "config" in data and attribute in data["config"]:
689
+ raise ParsingError(
690
+ f"""
691
+ In {path}: found {attribute} dictionary in 'config' dictionary and as top-level key.
692
+ Remove the top-level key and define it under 'config' dictionary only.
693
+ """.strip()
694
+ )
695
+ else:
696
+ if "config" not in data:
697
+ data["config"] = {}
698
+ data["config"][attribute] = data.pop(attribute)
699
+
700
+ def normalize_meta_attribute(self, data, path) -> None:
701
+ return self.normalize_attribute(data, path, "meta")
702
+
703
+ def normalize_docs_attribute(self, data, path) -> None:
704
+ return self.normalize_attribute(data, path, "docs")
705
+
706
+ def normalize_group_attribute(self, data, path) -> None:
707
+ return self.normalize_attribute(data, path, "group")
708
+
709
+ def normalize_contract_attribute(self, data, path) -> None:
710
+ return self.normalize_attribute(data, path, "contract")
711
+
712
+ def normalize_access_attribute(self, data, path) -> None:
713
+ return self.normalize_attribute(data, path, "access")
714
+
715
+ @property
716
+ def is_root_project(self) -> bool:
717
+ if self.root_project.project_name == self.project.project_name:
718
+ return True
719
+ return False
720
+
721
+ def validate_data_tests(self, data) -> None:
722
+ # Rename 'tests' -> 'data_tests' at both model-level and column-level
723
+ # Raise a validation error if the user has defined both names
724
+ def validate_and_rename(data, is_root_project: bool) -> None:
725
+ if data.get("tests"):
726
+ if "tests" in data and "data_tests" in data:
727
+ raise ValidationError(
728
+ "Invalid test config: cannot have both 'tests' and 'data_tests' defined"
729
+ )
730
+ data["data_tests"] = data.pop("tests")
731
+
732
+ # model-level tests
733
+ validate_and_rename(data, self.is_root_project)
734
+
735
+ # column-level tests
736
+ if data.get("columns"):
737
+ for column in data["columns"]:
738
+ validate_and_rename(column, self.is_root_project)
739
+
740
+ # versioned models
741
+ if data.get("versions"):
742
+ for version in data["versions"]:
743
+ validate_and_rename(version, self.is_root_project)
744
+ if version.get("columns"):
745
+ for column in version["columns"]:
746
+ validate_and_rename(column, self.is_root_project)
747
+
748
+ def patch_node_config(self, node, patch) -> None:
749
+ if "access" in patch.config:
750
+ if AccessType.is_valid(patch.config["access"]):
751
+ patch.config["access"] = AccessType(patch.config["access"])
752
+ else:
753
+ raise InvalidAccessTypeError(
754
+ unique_id=node.unique_id,
755
+ field_value=patch.config["access"],
756
+ )
757
+ # Get the ContextConfig that's used in calculating the config
758
+ # This must match the model resource_type that's being patched
759
+ config = ContextConfig(
760
+ self.schema_parser.root_project,
761
+ node.fqn,
762
+ node.resource_type,
763
+ self.schema_parser.project.project_name,
764
+ )
765
+ # We need to re-apply the config_call_dict after the patch config
766
+ config._config_call_dict = node.config_call_dict
767
+ config._unrendered_config_call_dict = node.unrendered_config_call_dict
768
+ self.schema_parser.update_parsed_node_config(
769
+ node,
770
+ config,
771
+ patch_config_dict=patch.config,
772
+ patch_file_id=patch.file_id,
773
+ )
774
+
775
+
776
+ # Subclasses of NodePatchParser: TestablePatchParser, ModelPatchParser, AnalysisPatchParser, FunctionPatchParser
777
+ # so models, seeds, snapshots, analyses, functions
778
+ class NodePatchParser(PatchParser[NodeTarget, ParsedNodePatch], Generic[NodeTarget]):
779
+ def _get_node_patch(self, block: TargetBlock[NodeTarget], refs: ParserRef) -> ParsedNodePatch:
780
+ # We're not passing the ParsedNodePatch around anymore, so we
781
+ # could possibly skip creating one. Leaving here for now for
782
+ # code consistency.
783
+ deprecation_date: Optional[datetime.datetime] = None
784
+ time_spine: Optional[TimeSpine] = None
785
+
786
+ if isinstance(block.target, UnparsedModelUpdate):
787
+ deprecation_date = block.target.deprecation_date
788
+ time_spine = (
789
+ TimeSpine(
790
+ standard_granularity_column=block.target.time_spine.standard_granularity_column,
791
+ custom_granularities=[
792
+ CustomGranularity(
793
+ name=custom_granularity.name,
794
+ column_name=custom_granularity.column_name,
795
+ )
796
+ for custom_granularity in block.target.time_spine.custom_granularities
797
+ ],
798
+ )
799
+ if block.target.time_spine
800
+ else None
801
+ )
802
+
803
+ return ParsedNodePatch(
804
+ name=block.target.name,
805
+ original_file_path=block.target.original_file_path,
806
+ yaml_key=block.target.yaml_key,
807
+ package_name=block.target.package_name,
808
+ description=block.target.description,
809
+ columns=refs.column_info,
810
+ meta=block.target.meta,
811
+ docs=block.target.docs,
812
+ config=block.target.config,
813
+ access=block.target.access,
814
+ version=None,
815
+ latest_version=None,
816
+ constraints=block.target.constraints,
817
+ deprecation_date=deprecation_date,
818
+ time_spine=time_spine,
819
+ )
820
+
821
+ def parse_patch(self, block: TargetBlock[NodeTarget], refs: ParserRef) -> None:
822
+ patch = self._get_node_patch(block, refs)
823
+
824
+ assert isinstance(self.yaml.file, SchemaSourceFile)
825
+ source_file: SchemaSourceFile = self.yaml.file
826
+
827
+ # TODO: I'd like to refactor this out but the early return makes doing so a bit messy
828
+ if patch.yaml_key in ["models", "seeds", "snapshots"]:
829
+ unique_id = self.manifest.ref_lookup.get_unique_id(
830
+ patch.name, self.project.project_name, None
831
+ ) or self.manifest.ref_lookup.get_unique_id(patch.name, None, None)
832
+
833
+ if unique_id:
834
+ resource_type = NodeType(unique_id.split(".")[0])
835
+ if resource_type.pluralize() != patch.yaml_key:
836
+ warn_or_error(
837
+ WrongResourceSchemaFile(
838
+ patch_name=patch.name,
839
+ resource_type=resource_type,
840
+ plural_resource_type=resource_type.pluralize(),
841
+ yaml_key=patch.yaml_key,
842
+ file_path=patch.original_file_path,
843
+ )
844
+ )
845
+ return
846
+ elif patch.yaml_key == "functions":
847
+ unique_id = self.manifest.function_lookup.get_unique_id(patch.name, None)
848
+ elif patch.yaml_key == "analyses":
849
+ unique_id = self.manifest.analysis_lookup.get_unique_id(patch.name, None, None)
850
+ else:
851
+ raise DbtInternalError(
852
+ f"Unexpected yaml_key {patch.yaml_key} for patch in "
853
+ f"file {source_file.path.original_file_path}"
854
+ )
855
+ # handle disabled nodes
856
+ if unique_id is None:
857
+ # Node might be disabled. Following call returns list of matching disabled nodes
858
+ resource_type = schema_file_keys_to_resource_types[patch.yaml_key]
859
+ found_nodes = self.manifest.disabled_lookup.find(
860
+ patch.name, patch.package_name, resource_types=[resource_type]
861
+ )
862
+ if found_nodes:
863
+ if len(found_nodes) > 1 and patch.config.get("enabled"):
864
+ # There are multiple disabled nodes for this model and the schema file wants to enable one.
865
+ # We have no way to know which one to enable.
866
+ resource_type = found_nodes[0].unique_id.split(".")[0]
867
+ msg = (
868
+ f"Found {len(found_nodes)} matching disabled nodes for "
869
+ f"{resource_type} '{patch.name}'. Multiple nodes for the same "
870
+ "unique id cannot be enabled in the schema file. They must be enabled "
871
+ "in `dbt_project.yml` or in the sql files."
872
+ )
873
+ raise ParsingError(msg)
874
+
875
+ # all nodes in the disabled dict have the same unique_id so just grab the first one
876
+ # to append with the unique id
877
+ source_file.append_patch(patch.yaml_key, found_nodes[0].unique_id)
878
+ for node in found_nodes:
879
+ node.patch_path = source_file.file_id
880
+ # re-calculate the node config with the patch config. Always do this
881
+ # for the case when no config is set to ensure the default of true gets captured
882
+ if patch.config:
883
+ self.patch_node_config(node, patch)
884
+
885
+ self.patch_node_properties(node, patch)
886
+ else:
887
+ warn_or_error(
888
+ NoNodeForYamlKey(
889
+ patch_name=patch.name,
890
+ yaml_key=patch.yaml_key,
891
+ file_path=source_file.path.original_file_path,
892
+ )
893
+ )
894
+ return # we only return early if no disabled early nodes are found. Why don't we return after patching the disabled nodes?
895
+
896
+ if patch.yaml_key == "functions":
897
+ node = self.manifest.functions.get(unique_id)
898
+ else:
899
+ node = self.manifest.nodes.get(unique_id)
900
+
901
+ if node:
902
+ # patches can't be overwritten
903
+ if node.patch_path:
904
+ package_name, existing_file_path = node.patch_path.split("://")
905
+ raise DuplicatePatchPathError(patch, existing_file_path)
906
+
907
+ source_file.append_patch(patch.yaml_key, node.unique_id)
908
+ # re-calculate the node config with the patch config. Always do this
909
+ # for the case when no config is set to ensure the default of true gets captured
910
+ if patch.config:
911
+ self.patch_node_config(node, patch)
912
+
913
+ self.patch_node_properties(node, patch)
914
+
915
+ def patch_node_properties(self, node, patch: "ParsedNodePatch") -> None:
916
+ """Given a ParsedNodePatch, add the new information to the node."""
917
+ # explicitly pick out the parts to update so we don't inadvertently
918
+ # step on the model name or anything
919
+ # Note: config should already be updated
920
+ node.patch_path = patch.file_id
921
+ # update created_at so process_docs will run in partial parsing
922
+ node.created_at = time.time()
923
+ node.description = patch.description
924
+ node.columns = patch.columns
925
+ node.name = patch.name
926
+
927
+ if not isinstance(node, ModelNode):
928
+ for attr in ["latest_version", "access", "version", "constraints"]:
929
+ if getattr(patch, attr):
930
+ warn_or_error(
931
+ ValidationWarning(
932
+ field_name=attr,
933
+ resource_type=node.resource_type.value,
934
+ node_name=patch.name,
935
+ )
936
+ )
937
+
938
+
939
+ # TestablePatchParser = seeds, snapshots
940
+ class TestablePatchParser(NodePatchParser[UnparsedNodeUpdate]):
941
+ __test__ = False
942
+
943
+ def get_block(self, node: UnparsedNodeUpdate) -> TestBlock:
944
+ return TestBlock.from_yaml_block(self.yaml, node)
945
+
946
+ def _target_type(self) -> Type[UnparsedNodeUpdate]:
947
+ return UnparsedNodeUpdate
948
+
949
+
950
+ class ModelPatchParser(NodePatchParser[UnparsedModelUpdate]):
951
+ def get_block(self, node: UnparsedModelUpdate) -> VersionedTestBlock:
952
+ return VersionedTestBlock.from_yaml_block(self.yaml, node)
953
+
954
+ def parse_patch(self, block: TargetBlock[UnparsedModelUpdate], refs: ParserRef) -> None:
955
+ target = block.target
956
+ if NodeType.Model.pluralize() != target.yaml_key:
957
+ warn_or_error(
958
+ WrongResourceSchemaFile(
959
+ patch_name=target.name,
960
+ resource_type=NodeType.Model,
961
+ plural_resource_type=NodeType.Model.pluralize(),
962
+ yaml_key=target.yaml_key,
963
+ file_path=target.original_file_path,
964
+ )
965
+ )
966
+ return
967
+
968
+ versions = target.versions
969
+ if not versions:
970
+ super().parse_patch(block, refs)
971
+ else:
972
+ assert isinstance(self.yaml.file, SchemaSourceFile)
973
+ source_file: SchemaSourceFile = self.yaml.file
974
+ latest_version = (
975
+ target.latest_version if target.latest_version is not None else max(versions).v
976
+ )
977
+ for unparsed_version in versions:
978
+ versioned_model_name = (
979
+ unparsed_version.defined_in or f"{block.name}_{unparsed_version.formatted_v}"
980
+ )
981
+ # ref lookup without version - version is not set yet
982
+ versioned_model_unique_id = self.manifest.ref_lookup.get_unique_id(
983
+ versioned_model_name, target.package_name, None
984
+ )
985
+
986
+ versioned_model_node: Optional[ModelNode] = None
987
+ add_node_nofile_fn: Callable
988
+
989
+ # If this is the latest version, it's allowed to define itself in a model file name that doesn't have a suffix
990
+ if versioned_model_unique_id is None and unparsed_version.v == latest_version:
991
+ versioned_model_unique_id = self.manifest.ref_lookup.get_unique_id(
992
+ block.name, target.package_name, None
993
+ )
994
+
995
+ if versioned_model_unique_id is None:
996
+ # Node might be disabled. Following call returns list of matching disabled nodes
997
+ found_nodes = self.manifest.disabled_lookup.find(
998
+ versioned_model_name, None, resource_types=[NodeType.Model]
999
+ )
1000
+ if found_nodes:
1001
+ if len(found_nodes) > 1 and target.config.get("enabled"):
1002
+ # There are multiple disabled nodes for this model and the schema file wants to enable one.
1003
+ # We have no way to know which one to enable.
1004
+ resource_type = found_nodes[0].unique_id.split(".")[0]
1005
+ msg = (
1006
+ f"Found {len(found_nodes)} matching disabled nodes for "
1007
+ f"{resource_type} '{target.name}'. Multiple nodes for the same "
1008
+ "unique id cannot be enabled in the schema file. They must be enabled "
1009
+ "in `dbt_project.yml` or in the sql files."
1010
+ )
1011
+ raise ParsingError(msg)
1012
+ # We know that there's only one node in the disabled list because
1013
+ # otherwise we would have raised the error above
1014
+ found_node = found_nodes[0]
1015
+ self.manifest.disabled.pop(found_node.unique_id)
1016
+ assert isinstance(found_node, ModelNode)
1017
+ versioned_model_node = found_node
1018
+ add_node_nofile_fn = self.manifest.add_disabled_nofile
1019
+ else:
1020
+ found_node = self.manifest.nodes.pop(versioned_model_unique_id)
1021
+ assert isinstance(found_node, ModelNode)
1022
+ versioned_model_node = found_node
1023
+ add_node_nofile_fn = self.manifest.add_node_nofile
1024
+
1025
+ if versioned_model_node is None:
1026
+ warn_or_error(
1027
+ NoNodeForYamlKey(
1028
+ patch_name=versioned_model_name,
1029
+ yaml_key=target.yaml_key,
1030
+ file_path=source_file.path.original_file_path,
1031
+ )
1032
+ )
1033
+ continue
1034
+
1035
+ # update versioned node unique_id
1036
+ versioned_model_node_unique_id_old = versioned_model_node.unique_id
1037
+ versioned_model_node.unique_id = (
1038
+ f"model.{target.package_name}.{target.name}.{unparsed_version.formatted_v}"
1039
+ )
1040
+ # update source file.nodes with new unique_id
1041
+ model_source_file = self.manifest.files[versioned_model_node.file_id]
1042
+ assert isinstance(model_source_file, SourceFile)
1043
+ # because of incomplete test setup, check before removing
1044
+ if versioned_model_node_unique_id_old in model_source_file.nodes:
1045
+ model_source_file.nodes.remove(versioned_model_node_unique_id_old)
1046
+ model_source_file.nodes.append(versioned_model_node.unique_id)
1047
+
1048
+ # update versioned node fqn
1049
+ versioned_model_node.fqn[-1] = target.name
1050
+ versioned_model_node.fqn.append(unparsed_version.formatted_v)
1051
+
1052
+ # add versioned node back to nodes/disabled
1053
+ add_node_nofile_fn(versioned_model_node)
1054
+
1055
+ # flatten columns based on include/exclude
1056
+ version_refs: ParserRef = ParserRef.from_versioned_target(
1057
+ block.target, unparsed_version.v
1058
+ )
1059
+
1060
+ versioned_model_patch = ParsedNodePatch(
1061
+ name=target.name,
1062
+ original_file_path=target.original_file_path,
1063
+ yaml_key=target.yaml_key,
1064
+ package_name=target.package_name,
1065
+ description=unparsed_version.description or target.description,
1066
+ columns=version_refs.column_info,
1067
+ meta=target.meta,
1068
+ docs=unparsed_version.docs or target.docs,
1069
+ config=deep_merge(target.config, unparsed_version.config),
1070
+ access=unparsed_version.access or target.access,
1071
+ version=unparsed_version.v,
1072
+ latest_version=latest_version,
1073
+ constraints=unparsed_version.constraints or target.constraints,
1074
+ deprecation_date=unparsed_version.deprecation_date,
1075
+ )
1076
+ # Node patched before config because config patching depends on model name,
1077
+ # which may have been updated in the version patch
1078
+ # versioned_model_node.patch(versioned_model_patch)
1079
+ self.patch_node_properties(versioned_model_node, versioned_model_patch)
1080
+
1081
+ # Includes alias recomputation
1082
+ self.patch_node_config(versioned_model_node, versioned_model_patch)
1083
+
1084
+ # Need to reapply setting constraints and contract checksum here, because
1085
+ # they depend on node.contract.enabled, which wouldn't be set when
1086
+ # patch_node_properties was called if it wasn't set in the model file.
1087
+ self.patch_constraints(versioned_model_node, versioned_model_patch.constraints)
1088
+ versioned_model_node.build_contract_checksum()
1089
+ source_file.append_patch(
1090
+ versioned_model_patch.yaml_key, versioned_model_node.unique_id
1091
+ )
1092
+ self.manifest.rebuild_ref_lookup()
1093
+ self.manifest.rebuild_disabled_lookup()
1094
+
1095
+ def _target_type(self) -> Type[UnparsedModelUpdate]:
1096
+ return UnparsedModelUpdate
1097
+
1098
+ def patch_node_properties(self, node, patch: "ParsedNodePatch") -> None:
1099
+ super().patch_node_properties(node, patch)
1100
+
1101
+ # Remaining patch properties are only relevant to ModelNode objects
1102
+ if not isinstance(node, ModelNode):
1103
+ return
1104
+
1105
+ node.version = patch.version
1106
+ node.latest_version = patch.latest_version
1107
+ node.deprecation_date = patch.deprecation_date
1108
+ if patch.access:
1109
+ if AccessType.is_valid(patch.access):
1110
+ node.access = AccessType(patch.access)
1111
+ else:
1112
+ raise InvalidAccessTypeError(
1113
+ unique_id=node.unique_id,
1114
+ field_value=patch.access,
1115
+ )
1116
+ # These two will have to be reapplied after config is built for versioned models
1117
+ self.patch_constraints(node, patch.constraints)
1118
+ self.patch_time_spine(node, patch.time_spine)
1119
+ node.build_contract_checksum()
1120
+
1121
+ def patch_constraints(self, node: ModelNode, constraints: List[Dict[str, Any]]) -> None:
1122
+ contract_config = node.config.get("contract")
1123
+ if contract_config.enforced is True:
1124
+ self._validate_constraint_prerequisites(node)
1125
+
1126
+ if any(
1127
+ c for c in constraints if "type" not in c or not ConstraintType.is_valid(c["type"])
1128
+ ):
1129
+ raise ParsingError(
1130
+ f"Invalid constraint type on model {node.name}: "
1131
+ f"Type must be one of {[ct.value for ct in ConstraintType]}"
1132
+ )
1133
+
1134
+ self._validate_pk_constraints(node, constraints)
1135
+ node.constraints = [ModelLevelConstraint.from_dict(c) for c in constraints]
1136
+ self._process_constraints_refs_and_sources(node)
1137
+
1138
+ def _process_constraints_refs_and_sources(self, model_node: ModelNode) -> None:
1139
+ """
1140
+ Populate model_node.refs and model_node.sources based on foreign-key constraint references,
1141
+ whether defined at the model-level or column-level.
1142
+ """
1143
+ for constraint in model_node.all_constraints:
1144
+ if constraint.type == ConstraintType.foreign_key and constraint.to:
1145
+ try:
1146
+ ref_or_source = statically_parse_ref_or_source(constraint.to)
1147
+ except ParsingError:
1148
+ raise ParsingError(
1149
+ f"Invalid 'ref' or 'source' syntax on foreign key constraint 'to' on model {model_node.name}: {constraint.to}."
1150
+ )
1151
+
1152
+ if isinstance(ref_or_source, RefArgs):
1153
+ model_node.refs.append(ref_or_source)
1154
+ else:
1155
+ model_node.sources.append(ref_or_source)
1156
+
1157
+ def patch_time_spine(self, node: ModelNode, time_spine: Optional[TimeSpine]) -> None:
1158
+ node.time_spine = time_spine
1159
+
1160
+ def _validate_pk_constraints(
1161
+ self, model_node: ModelNode, constraints: List[Dict[str, Any]]
1162
+ ) -> None:
1163
+ errors = []
1164
+ # check for primary key constraints defined at the column level
1165
+ pk_col: List[str] = []
1166
+ for col in model_node.columns.values():
1167
+ for constraint in col.constraints:
1168
+ if constraint.type == ConstraintType.primary_key:
1169
+ pk_col.append(col.name)
1170
+
1171
+ if len(pk_col) > 1:
1172
+ errors.append(
1173
+ f"Found {len(pk_col)} columns ({pk_col}) with primary key constraints defined. "
1174
+ "Primary keys for multiple columns must be defined as a model level constraint."
1175
+ )
1176
+
1177
+ if len(pk_col) > 0 and (
1178
+ any(
1179
+ constraint.type == ConstraintType.primary_key
1180
+ for constraint in model_node.constraints
1181
+ )
1182
+ or any(constraint["type"] == ConstraintType.primary_key for constraint in constraints)
1183
+ ):
1184
+ errors.append(
1185
+ "Primary key constraints defined at the model level and the columns level. "
1186
+ "Primary keys can be defined at the model level or the column level, not both."
1187
+ )
1188
+
1189
+ if errors:
1190
+ raise ParsingError(
1191
+ f"Primary key constraint error: ({model_node.original_file_path})\n"
1192
+ + "\n".join(errors)
1193
+ )
1194
+
1195
+ def _validate_constraint_prerequisites(self, model_node: ModelNode) -> None:
1196
+ column_warn_unsupported = [
1197
+ constraint.warn_unsupported
1198
+ for column in model_node.columns.values()
1199
+ for constraint in column.constraints
1200
+ ]
1201
+ model_warn_unsupported = [
1202
+ constraint.warn_unsupported for constraint in model_node.constraints
1203
+ ]
1204
+ warn_unsupported = column_warn_unsupported + model_warn_unsupported
1205
+
1206
+ # if any constraint has `warn_unsupported` as True then send the warning
1207
+ if any(warn_unsupported) and not model_node.materialization_enforces_constraints:
1208
+ warn_or_error(
1209
+ UnsupportedConstraintMaterialization(materialized=model_node.config.materialized),
1210
+ node=model_node,
1211
+ )
1212
+
1213
+ errors = []
1214
+ if not model_node.columns:
1215
+ errors.append(
1216
+ "Constraints must be defined in a `yml` schema configuration file like `schema.yml`."
1217
+ )
1218
+
1219
+ if str(model_node.language) != "sql":
1220
+ errors.append(f"Language Error: Expected 'sql' but found '{model_node.language}'")
1221
+
1222
+ if errors:
1223
+ raise ParsingError(
1224
+ f"Contract enforcement failed for: ({model_node.original_file_path})\n"
1225
+ + "\n".join(errors)
1226
+ )
1227
+
1228
+
1229
+ class AnalysisPatchParser(NodePatchParser[UnparsedAnalysisUpdate]):
1230
+ def get_block(self, node: UnparsedAnalysisUpdate) -> TargetBlock:
1231
+ return TargetBlock.from_yaml_block(self.yaml, node)
1232
+
1233
+ def _target_type(self) -> Type[UnparsedAnalysisUpdate]:
1234
+ return UnparsedAnalysisUpdate
1235
+
1236
+
1237
+ class SingularTestPatchParser(PatchParser[UnparsedSingularTestUpdate, ParsedSingularTestPatch]):
1238
+ def get_block(self, node: UnparsedSingularTestUpdate) -> TargetBlock:
1239
+ return TargetBlock.from_yaml_block(self.yaml, node)
1240
+
1241
+ def _target_type(self) -> Type[UnparsedSingularTestUpdate]:
1242
+ return UnparsedSingularTestUpdate
1243
+
1244
+ def parse_patch(self, block: TargetBlock[UnparsedSingularTestUpdate], refs: ParserRef) -> None:
1245
+ patch = ParsedSingularTestPatch(
1246
+ name=block.target.name,
1247
+ description=block.target.description,
1248
+ meta=block.target.meta,
1249
+ docs=block.target.docs,
1250
+ config=block.target.config,
1251
+ original_file_path=block.target.original_file_path,
1252
+ yaml_key=block.target.yaml_key,
1253
+ package_name=block.target.package_name,
1254
+ )
1255
+
1256
+ assert isinstance(self.yaml.file, SchemaSourceFile)
1257
+ source_file: SchemaSourceFile = self.yaml.file
1258
+
1259
+ unique_id = self.manifest.singular_test_lookup.get_unique_id(
1260
+ block.name, block.target.package_name
1261
+ )
1262
+ if not unique_id:
1263
+ warn_or_error(
1264
+ NoNodeForYamlKey(
1265
+ patch_name=patch.name,
1266
+ yaml_key=patch.yaml_key,
1267
+ file_path=source_file.path.original_file_path,
1268
+ )
1269
+ )
1270
+ return
1271
+
1272
+ node = self.manifest.nodes.get(unique_id)
1273
+ assert node is not None
1274
+
1275
+ source_file.append_patch(patch.yaml_key, unique_id)
1276
+ if patch.config:
1277
+ self.patch_node_config(node, patch)
1278
+
1279
+ node.patch_path = patch.file_id
1280
+ node.description = patch.description
1281
+ node.created_at = time.time()
1282
+
1283
+
1284
+ class FunctionPatchParser(NodePatchParser[UnparsedFunctionUpdate]):
1285
+ def get_block(self, node: UnparsedFunctionUpdate) -> TargetBlock:
1286
+ return TargetBlock.from_yaml_block(self.yaml, node)
1287
+
1288
+ def _target_type(self) -> Type[UnparsedFunctionUpdate]:
1289
+ return UnparsedFunctionUpdate
1290
+
1291
+ def patch_node_properties(self, node, patch: "ParsedNodePatch") -> None:
1292
+ super().patch_node_properties(node, patch)
1293
+
1294
+ assert isinstance(patch, ParsedFunctionPatch)
1295
+ assert isinstance(node, FunctionNode)
1296
+
1297
+ node.arguments = patch.arguments
1298
+ node.returns = patch.returns
1299
+
1300
+ def _get_node_patch(self, block: TargetBlock[NodeTarget], refs: ParserRef) -> ParsedNodePatch:
1301
+ target = block.target
1302
+ assert isinstance(target, UnparsedFunctionUpdate)
1303
+
1304
+ return ParsedFunctionPatch(
1305
+ name=target.name,
1306
+ original_file_path=target.original_file_path,
1307
+ yaml_key=target.yaml_key,
1308
+ package_name=target.package_name,
1309
+ description=target.description,
1310
+ columns=refs.column_info,
1311
+ meta=target.meta,
1312
+ docs=target.docs,
1313
+ config=target.config,
1314
+ access=target.access,
1315
+ version=None,
1316
+ latest_version=None,
1317
+ constraints=target.constraints,
1318
+ deprecation_date=None,
1319
+ time_spine=None,
1320
+ arguments=target.arguments,
1321
+ returns=target.returns,
1322
+ )
1323
+
1324
+
1325
+ class MacroPatchParser(PatchParser[UnparsedMacroUpdate, ParsedMacroPatch]):
1326
+ def get_block(self, node: UnparsedMacroUpdate) -> TargetBlock:
1327
+ return TargetBlock.from_yaml_block(self.yaml, node)
1328
+
1329
+ def _target_type(self) -> Type[UnparsedMacroUpdate]:
1330
+ return UnparsedMacroUpdate
1331
+
1332
+ def parse_patch(self, block: TargetBlock[UnparsedMacroUpdate], refs: ParserRef) -> None:
1333
+ patch = ParsedMacroPatch(
1334
+ name=block.target.name,
1335
+ original_file_path=block.target.original_file_path,
1336
+ yaml_key=block.target.yaml_key,
1337
+ package_name=block.target.package_name,
1338
+ arguments=block.target.arguments,
1339
+ description=block.target.description,
1340
+ meta=block.target.meta,
1341
+ docs=block.target.docs,
1342
+ config=block.target.config,
1343
+ )
1344
+ assert isinstance(self.yaml.file, SchemaSourceFile)
1345
+ source_file = self.yaml.file
1346
+ # macros are fully namespaced
1347
+ unique_id = f"macro.{patch.package_name}.{patch.name}"
1348
+ macro = self.manifest.macros.get(unique_id)
1349
+ if not macro:
1350
+ warn_or_error(MacroNotFoundForPatch(patch_name=patch.name))
1351
+ return
1352
+ if macro.patch_path:
1353
+ package_name, existing_file_path = macro.patch_path.split("://")
1354
+ raise DuplicateMacroPatchNameError(patch, existing_file_path)
1355
+ source_file.macro_patches[patch.name] = unique_id
1356
+
1357
+ # former macro.patch code
1358
+ macro.patch_path = patch.file_id
1359
+ macro.description = patch.description
1360
+ macro.created_at = time.time()
1361
+ macro.meta = patch.meta
1362
+ macro.docs = patch.docs
1363
+
1364
+ if getattr(get_flags(), "validate_macro_args", False):
1365
+ self._check_patch_arguments(macro, patch)
1366
+ macro.arguments = patch.arguments if patch.arguments else macro.arguments
1367
+ else:
1368
+ macro.arguments = patch.arguments
1369
+
1370
+ def _check_patch_arguments(self, macro: Macro, patch: ParsedMacroPatch) -> None:
1371
+ if not patch.arguments:
1372
+ return
1373
+
1374
+ for macro_arg, patch_arg in zip(macro.arguments, patch.arguments):
1375
+ if patch_arg.name != macro_arg.name:
1376
+ msg = f"Argument {patch_arg.name} in yaml for macro {macro.name} does not match the jinja definition."
1377
+ self._fire_macro_arg_warning(msg, macro)
1378
+
1379
+ if len(patch.arguments) != len(macro.arguments):
1380
+ msg = f"The number of arguments in the yaml for macro {macro.name} does not match the jinja definition."
1381
+ self._fire_macro_arg_warning(msg, macro)
1382
+
1383
+ for patch_arg in patch.arguments:
1384
+ arg_type = patch_arg.type
1385
+ if arg_type is not None and arg_type.strip() != "" and not is_valid_type(arg_type):
1386
+ msg = f"Argument {patch_arg.name} in the yaml for macro {macro.name} has an invalid type."
1387
+ self._fire_macro_arg_warning(msg, macro)
1388
+
1389
+ def _fire_macro_arg_warning(self, msg: str, macro: Macro) -> None:
1390
+ warn_or_error(
1391
+ InvalidMacroAnnotation(
1392
+ msg=msg, macro_unique_id=macro.unique_id, macro_file_path=macro.original_file_path
1393
+ )
1394
+ )
1395
+
1396
+
1397
+ # valid type names, along with the number of parameters they require
1398
+ macro_types: Dict[str, int] = {
1399
+ "str": 0,
1400
+ "string": 0,
1401
+ "bool": 0,
1402
+ "int": 0,
1403
+ "integer": 0,
1404
+ "float": 0,
1405
+ "any": 0,
1406
+ "list": 1,
1407
+ "dict": 2,
1408
+ "optional": 1,
1409
+ "relation": 0,
1410
+ "column": 0,
1411
+ }
1412
+
1413
+
1414
+ def is_valid_type(buffer: str) -> bool:
1415
+ buffer = buffer.replace(" ", "").replace("\t", "")
1416
+ type_desc, remainder = match_type_desc(buffer)
1417
+ return type_desc is not None and remainder == ""
1418
+
1419
+
1420
+ def match_type_desc(buffer: str) -> Tuple[Optional[str], str]:
1421
+ """A matching buffer is a type name followed by an argument list with
1422
+ the correct number of arguments."""
1423
+ type_name, remainder = match_type_name(buffer)
1424
+ if type_name is None:
1425
+ return None, buffer
1426
+ attr_list, remainder = match_arg_list(remainder, macro_types[type_name])
1427
+ if attr_list is None:
1428
+ return None, buffer
1429
+ return type_name + attr_list, remainder
1430
+
1431
+
1432
+ alpha_pattern = re.compile(r"[a-z]+")
1433
+
1434
+
1435
+ def match_type_name(buffer: str) -> Tuple[Optional[str], str]:
1436
+ """A matching buffer starts with one of the valid type names from macro_types"""
1437
+ match = alpha_pattern.match(buffer)
1438
+ if match is not None and buffer[: match.end(0)] in macro_types:
1439
+ return buffer[: match.end(0)], buffer[match.end(0) :]
1440
+ else:
1441
+ return None, buffer
1442
+
1443
+
1444
+ def match_arg_list(buffer: str, arg_count: int) -> Tuple[Optional[str], str]:
1445
+ """A matching buffer must begin with '[', followed by exactly arg_count type
1446
+ specs, followed by ']'"""
1447
+
1448
+ if arg_count == 0:
1449
+ return "", buffer
1450
+
1451
+ if not buffer.startswith("["):
1452
+ return None, buffer
1453
+
1454
+ remainder = buffer[1:]
1455
+ for i in range(arg_count):
1456
+ type_desc, remainder = match_type_desc(remainder)
1457
+ if type_desc is None:
1458
+ return None, buffer
1459
+ if i != arg_count - 1:
1460
+ if not remainder.startswith(","):
1461
+ return None, buffer
1462
+ remainder = remainder[1:]
1463
+
1464
+ if not remainder.startswith("]"):
1465
+ return None, buffer
1466
+ else:
1467
+ return "", remainder[1:]