-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
providers.py
1600 lines (1309 loc) · 55 KB
/
providers.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 abc
import os
from typing import (
Callable,
Any,
Dict,
Optional,
Union,
List,
TypeVar,
Type,
Iterable,
Mapping,
)
from typing_extensions import Protocol
from dbt.adapters.base.column import Column
from dbt.adapters.factory import get_adapter, get_adapter_package_names, get_adapter_type_names
from dbt.clients import agate_helper
from dbt.clients.jinja import get_rendered, MacroGenerator, MacroStack
from dbt.config import RuntimeConfig, Project
from dbt.constants import SECRET_ENV_PREFIX, DEFAULT_ENV_PLACEHOLDER
from dbt.context.base import contextmember, contextproperty, Var
from dbt.context.configured import FQNLookup
from dbt.context.context_config import ContextConfig
from dbt.context.exceptions_jinja import wrapped_exports
from dbt.context.macro_resolver import MacroResolver, TestMacroNamespace
from dbt.context.macros import MacroNamespaceBuilder, MacroNamespace
from dbt.context.manifest import ManifestContext
from dbt.contracts.connection import AdapterResponse
from dbt.contracts.graph.manifest import Manifest, Disabled
from dbt.contracts.graph.nodes import (
Macro,
Exposure,
Metric,
SeedNode,
SourceDefinition,
Resource,
ManifestNode,
)
from dbt.contracts.graph.metrics import MetricReference, ResolvedMetricReference
from dbt.events.functions import get_metadata_vars
from dbt.exceptions import (
CompilationError,
ConflictingConfigKeysError,
SecretEnvVarLocationError,
EnvVarMissingError,
DbtInternalError,
InlineModelConfigError,
NumberSourceArgsError,
PersistDocsValueTypeError,
LoadAgateTableNotSeedError,
LoadAgateTableValueError,
MacroDispatchArgError,
MacrosSourcesUnWriteableError,
MetricArgsError,
MissingConfigError,
OperationsCannotRefEphemeralNodesError,
PackageNotInDepsError,
ParsingError,
RefBadContextError,
RefArgsError,
DbtRuntimeError,
TargetNotFoundError,
DbtValidationError,
)
from dbt.config import IsFQNResource
from dbt.node_types import NodeType, ModelLanguage
from dbt.utils import merge, AttrDict, MultiDict, args_to_dict
from dbt import selected_resources
import agate
_MISSING = object()
# base classes
class RelationProxy:
def __init__(self, adapter):
self._quoting_config = adapter.config.quoting
self._relation_type = adapter.Relation
def __getattr__(self, key):
return getattr(self._relation_type, key)
def create_from_source(self, *args, **kwargs):
# bypass our create when creating from source so as not to mess up
# the source quoting
return self._relation_type.create_from_source(*args, **kwargs)
def create(self, *args, **kwargs):
kwargs["quote_policy"] = merge(self._quoting_config, kwargs.pop("quote_policy", {}))
return self._relation_type.create(*args, **kwargs)
class BaseDatabaseWrapper:
"""
Wrapper for runtime database interaction. Applies the runtime quote policy
via a relation proxy.
"""
def __init__(self, adapter, namespace: MacroNamespace):
self._adapter = adapter
self.Relation = RelationProxy(adapter)
self._namespace = namespace
def __getattr__(self, name):
raise NotImplementedError("subclasses need to implement this")
@property
def config(self):
return self._adapter.config
def type(self):
return self._adapter.type()
def commit(self):
return self._adapter.commit_if_has_connection()
def _get_adapter_macro_prefixes(self) -> List[str]:
# order matters for dispatch:
# 1. current adapter
# 2. any parent adapters (dependencies)
# 3. 'default'
search_prefixes = get_adapter_type_names(self._adapter.type()) + ["default"]
return search_prefixes
def dispatch(
self,
macro_name: str,
macro_namespace: Optional[str] = None,
packages: Optional[List[str]] = None, # eventually remove since it's fully deprecated
) -> MacroGenerator:
search_packages: List[Optional[str]]
if "." in macro_name:
suggest_macro_namespace, suggest_macro_name = macro_name.split(".", 1)
msg = (
f'In adapter.dispatch, got a macro name of "{macro_name}", '
f'but "." is not a valid macro name component. Did you mean '
f'`adapter.dispatch("{suggest_macro_name}", '
f'macro_namespace="{suggest_macro_namespace}")`?'
)
raise CompilationError(msg)
if packages is not None:
raise MacroDispatchArgError(macro_name)
namespace = macro_namespace
if namespace is None:
search_packages = [None]
elif isinstance(namespace, str):
search_packages = self._adapter.config.get_macro_search_order(namespace)
if not search_packages and namespace in self._adapter.config.dependencies:
search_packages = [self.config.project_name, namespace]
else:
# Not a string and not None so must be a list
raise CompilationError(
f"In adapter.dispatch, got a list macro_namespace argument "
f'("{macro_namespace}"), but macro_namespace should be None or a string.'
)
attempts = []
for package_name in search_packages:
for prefix in self._get_adapter_macro_prefixes():
search_name = f"{prefix}__{macro_name}"
try:
# this uses the namespace from the context
macro = self._namespace.get_from_package(package_name, search_name)
except CompilationError:
# Only raise CompilationError if macro is not found in
# any package
macro = None
if package_name is None:
attempts.append(search_name)
else:
attempts.append(f"{package_name}.{search_name}")
if macro is not None:
return macro
searched = ", ".join(repr(a) for a in attempts)
msg = f"In dispatch: No macro named '{macro_name}' found\n Searched for: {searched}"
raise CompilationError(msg)
class BaseResolver(metaclass=abc.ABCMeta):
def __init__(self, db_wrapper, model, config, manifest):
self.db_wrapper = db_wrapper
self.model = model
self.config = config
self.manifest = manifest
@property
def current_project(self):
return self.config.project_name
@property
def Relation(self):
return self.db_wrapper.Relation
@abc.abstractmethod
def __call__(self, *args: str) -> Union[str, RelationProxy, MetricReference]:
pass
class BaseRefResolver(BaseResolver):
@abc.abstractmethod
def resolve(self, name: str, package: Optional[str] = None) -> RelationProxy:
...
def _repack_args(self, name: str, package: Optional[str]) -> List[str]:
if package is None:
return [name]
else:
return [package, name]
def validate_args(self, name: str, package: Optional[str]):
if not isinstance(name, str):
raise CompilationError(
f"The name argument to ref() must be a string, got {type(name)}"
)
if package is not None and not isinstance(package, str):
raise CompilationError(
f"The package argument to ref() must be a string or None, got {type(package)}"
)
def __call__(self, *args: str) -> RelationProxy:
name: str
package: Optional[str] = None
if len(args) == 1:
name = args[0]
elif len(args) == 2:
package, name = args
else:
raise RefArgsError(node=self.model, args=args)
self.validate_args(name, package)
return self.resolve(name, package)
class BaseSourceResolver(BaseResolver):
@abc.abstractmethod
def resolve(self, source_name: str, table_name: str):
pass
def validate_args(self, source_name: str, table_name: str):
if not isinstance(source_name, str):
raise CompilationError(
f"The source name (first) argument to source() must be a "
f"string, got {type(source_name)}"
)
if not isinstance(table_name, str):
raise CompilationError(
f"The table name (second) argument to source() must be a "
f"string, got {type(table_name)}"
)
def __call__(self, *args: str) -> RelationProxy:
if len(args) != 2:
raise NumberSourceArgsError(args, node=self.model)
self.validate_args(args[0], args[1])
return self.resolve(args[0], args[1])
class BaseMetricResolver(BaseResolver):
def resolve(self, name: str, package: Optional[str] = None) -> MetricReference:
...
def _repack_args(self, name: str, package: Optional[str]) -> List[str]:
if package is None:
return [name]
else:
return [package, name]
def validate_args(self, name: str, package: Optional[str]):
if not isinstance(name, str):
raise CompilationError(
f"The name argument to metric() must be a string, got {type(name)}"
)
if package is not None and not isinstance(package, str):
raise CompilationError(
f"The package argument to metric() must be a string or None, got {type(package)}"
)
def __call__(self, *args: str) -> MetricReference:
name: str
package: Optional[str] = None
if len(args) == 1:
name = args[0]
elif len(args) == 2:
package, name = args
else:
raise MetricArgsError(node=self.model, args=args)
self.validate_args(name, package)
return self.resolve(name, package)
class Config(Protocol):
def __init__(self, model, context_config: Optional[ContextConfig]):
...
# Implementation of "config(..)" calls in models
class ParseConfigObject(Config):
def __init__(self, model, context_config: Optional[ContextConfig]):
self.model = model
self.context_config = context_config
def _transform_config(self, config):
for oldkey in ("pre_hook", "post_hook"):
if oldkey in config:
newkey = oldkey.replace("_", "-")
if newkey in config:
raise ConflictingConfigKeysError(oldkey, newkey, node=self.model)
config[newkey] = config.pop(oldkey)
return config
def __call__(self, *args, **kwargs):
if len(args) == 1 and len(kwargs) == 0:
opts = args[0]
elif len(args) == 0 and len(kwargs) > 0:
opts = kwargs
else:
raise InlineModelConfigError(node=self.model)
opts = self._transform_config(opts)
# it's ok to have a parse context with no context config, but you must
# not call it!
if self.context_config is None:
raise DbtRuntimeError("At parse time, did not receive a context config")
self.context_config.add_config_call(opts)
return ""
def set(self, name, value):
return self.__call__({name: value})
def require(self, name, validator=None):
return ""
def get(self, name, default=None, validator=None):
return ""
def persist_relation_docs(self) -> bool:
return False
def persist_column_docs(self) -> bool:
return False
class RuntimeConfigObject(Config):
def __init__(self, model, context_config: Optional[ContextConfig] = None):
self.model = model
# we never use or get a config, only the parser cares
def __call__(self, *args, **kwargs):
return ""
def set(self, name, value):
return self.__call__({name: value})
def _validate(self, validator, value):
validator(value)
def _lookup(self, name, default=_MISSING):
# if this is a macro, there might be no `model.config`.
if not hasattr(self.model, "config"):
result = default
else:
result = self.model.config.get(name, default)
if result is _MISSING:
raise MissingConfigError(unique_id=self.model.unique_id, name=name)
return result
def require(self, name, validator=None):
to_return = self._lookup(name)
if validator is not None:
self._validate(validator, to_return)
return to_return
def get(self, name, default=None, validator=None):
to_return = self._lookup(name, default)
if validator is not None and default is not None:
self._validate(validator, to_return)
return to_return
def persist_relation_docs(self) -> bool:
persist_docs = self.get("persist_docs", default={})
if not isinstance(persist_docs, dict):
raise PersistDocsValueTypeError(persist_docs)
return persist_docs.get("relation", False)
def persist_column_docs(self) -> bool:
persist_docs = self.get("persist_docs", default={})
if not isinstance(persist_docs, dict):
raise PersistDocsValueTypeError(persist_docs)
return persist_docs.get("columns", False)
# `adapter` implementations
class ParseDatabaseWrapper(BaseDatabaseWrapper):
"""The parser subclass of the database wrapper applies any explicit
parse-time overrides.
"""
def __getattr__(self, name):
override = name in self._adapter._available_ and name in self._adapter._parse_replacements_
if override:
return self._adapter._parse_replacements_[name]
elif name in self._adapter._available_:
return getattr(self._adapter, name)
else:
raise AttributeError(
"'{}' object has no attribute '{}'".format(self.__class__.__name__, name)
)
class RuntimeDatabaseWrapper(BaseDatabaseWrapper):
"""The runtime database wrapper exposes everything the adapter marks
available.
"""
def __getattr__(self, name):
if name in self._adapter._available_:
return getattr(self._adapter, name)
else:
raise AttributeError(
"'{}' object has no attribute '{}'".format(self.__class__.__name__, name)
)
# `ref` implementations
class ParseRefResolver(BaseRefResolver):
def resolve(self, name: str, package: Optional[str] = None) -> RelationProxy:
self.model.refs.append(self._repack_args(name, package))
return self.Relation.create_from(self.config, self.model)
ResolveRef = Union[Disabled, ManifestNode]
class RuntimeRefResolver(BaseRefResolver):
def resolve(self, target_name: str, target_package: Optional[str] = None) -> RelationProxy:
target_model = self.manifest.resolve_ref(
target_name,
target_package,
self.current_project,
self.model.package_name,
)
if target_model is None or isinstance(target_model, Disabled):
raise TargetNotFoundError(
node=self.model,
target_name=target_name,
target_kind="node",
target_package=target_package,
disabled=isinstance(target_model, Disabled),
)
self.validate(target_model, target_name, target_package)
return self.create_relation(target_model, target_name)
def create_relation(self, target_model: ManifestNode, name: str) -> RelationProxy:
if target_model.is_ephemeral_model:
self.model.set_cte(target_model.unique_id, None)
return self.Relation.create_ephemeral_from_node(self.config, target_model)
else:
return self.Relation.create_from(self.config, target_model)
def validate(
self, resolved: ManifestNode, target_name: str, target_package: Optional[str]
) -> None:
if resolved.unique_id not in self.model.depends_on.nodes:
args = self._repack_args(target_name, target_package)
raise RefBadContextError(node=self.model, args=args)
class OperationRefResolver(RuntimeRefResolver):
def validate(
self,
resolved: ManifestNode,
target_name: str,
target_package: Optional[str],
) -> None:
pass
def create_relation(self, target_model: ManifestNode, name: str) -> RelationProxy:
if target_model.is_ephemeral_model:
# In operations, we can't ref() ephemeral nodes, because
# Macros do not support set_cte
raise OperationsCannotRefEphemeralNodesError(target_model.name, node=self.model)
else:
return super().create_relation(target_model, name)
# `source` implementations
class ParseSourceResolver(BaseSourceResolver):
def resolve(self, source_name: str, table_name: str):
# When you call source(), this is what happens at parse time
self.model.sources.append([source_name, table_name])
return self.Relation.create_from(self.config, self.model)
class RuntimeSourceResolver(BaseSourceResolver):
def resolve(self, source_name: str, table_name: str):
target_source = self.manifest.resolve_source(
source_name,
table_name,
self.current_project,
self.model.package_name,
)
if target_source is None or isinstance(target_source, Disabled):
raise TargetNotFoundError(
node=self.model,
target_name=f"{source_name}.{table_name}",
target_kind="source",
disabled=(isinstance(target_source, Disabled)),
)
return self.Relation.create_from_source(target_source)
# metric` implementations
class ParseMetricResolver(BaseMetricResolver):
def resolve(self, name: str, package: Optional[str] = None) -> MetricReference:
self.model.metrics.append(self._repack_args(name, package))
return MetricReference(name, package)
class RuntimeMetricResolver(BaseMetricResolver):
def resolve(self, target_name: str, target_package: Optional[str] = None) -> MetricReference:
target_metric = self.manifest.resolve_metric(
target_name,
target_package,
self.current_project,
self.model.package_name,
)
if target_metric is None or isinstance(target_metric, Disabled):
raise TargetNotFoundError(
node=self.model,
target_name=target_name,
target_kind="metric",
target_package=target_package,
)
return ResolvedMetricReference(target_metric, self.manifest, self.Relation)
# `var` implementations.
class ModelConfiguredVar(Var):
def __init__(
self,
context: Dict[str, Any],
config: RuntimeConfig,
node: Resource,
) -> None:
self._node: Resource
self._config: RuntimeConfig = config
super().__init__(context, config.cli_vars, node=node)
def packages_for_node(self) -> Iterable[Project]:
dependencies = self._config.load_dependencies()
package_name = self._node.package_name
if package_name != self._config.project_name:
if package_name not in dependencies:
# I don't think this is actually reachable
raise PackageNotInDepsError(package_name, node=self._node)
yield dependencies[package_name]
yield self._config
def _generate_merged(self) -> Mapping[str, Any]:
search_node: IsFQNResource
if isinstance(self._node, IsFQNResource):
search_node = self._node
else:
search_node = FQNLookup(self._node.package_name)
adapter_type = self._config.credentials.type
merged = MultiDict()
for project in self.packages_for_node():
merged.add(project.vars.vars_for(search_node, adapter_type))
merged.add(self._cli_vars)
return merged
class ParseVar(ModelConfiguredVar):
def get_missing_var(self, var_name):
# in the parser, just always return None.
return None
class RuntimeVar(ModelConfiguredVar):
pass
# Providers
class Provider(Protocol):
execute: bool
Config: Type[Config]
DatabaseWrapper: Type[BaseDatabaseWrapper]
Var: Type[ModelConfiguredVar]
ref: Type[BaseRefResolver]
source: Type[BaseSourceResolver]
metric: Type[BaseMetricResolver]
class ParseProvider(Provider):
execute = False
Config = ParseConfigObject
DatabaseWrapper = ParseDatabaseWrapper
Var = ParseVar
ref = ParseRefResolver
source = ParseSourceResolver
metric = ParseMetricResolver
class GenerateNameProvider(Provider):
execute = False
Config = RuntimeConfigObject
DatabaseWrapper = ParseDatabaseWrapper
Var = RuntimeVar
ref = ParseRefResolver
source = ParseSourceResolver
metric = ParseMetricResolver
class RuntimeProvider(Provider):
execute = True
Config = RuntimeConfigObject
DatabaseWrapper = RuntimeDatabaseWrapper
Var = RuntimeVar
ref = RuntimeRefResolver
source = RuntimeSourceResolver
metric = RuntimeMetricResolver
class OperationProvider(RuntimeProvider):
ref = OperationRefResolver
T = TypeVar("T")
# Base context collection, used for parsing configs.
class ProviderContext(ManifestContext):
# subclasses are MacroContext, ModelContext, TestContext
def __init__(
self,
model,
config: RuntimeConfig,
manifest: Manifest,
provider: Provider,
context_config: Optional[ContextConfig],
) -> None:
if provider is None:
raise DbtInternalError(f"Invalid provider given to context: {provider}")
# mypy appeasement - we know it'll be a RuntimeConfig
self.config: RuntimeConfig
self.model: Union[Macro, ManifestNode] = model
super().__init__(config, manifest, model.package_name)
self.sql_results: Dict[str, AttrDict] = {}
self.context_config: Optional[ContextConfig] = context_config
self.provider: Provider = provider
self.adapter = get_adapter(self.config)
# The macro namespace is used in creating the DatabaseWrapper
self.db_wrapper = self.provider.DatabaseWrapper(self.adapter, self.namespace)
# This overrides the method in ManifestContext, and provides
# a model, which the ManifestContext builder does not
def _get_namespace_builder(self):
internal_packages = get_adapter_package_names(self.config.credentials.type)
return MacroNamespaceBuilder(
self.config.project_name,
self.search_package,
self.macro_stack,
internal_packages,
self.model,
)
@contextproperty
def dbt_metadata_envs(self) -> Dict[str, str]:
return get_metadata_vars()
@contextproperty
def invocation_args_dict(self):
return args_to_dict(self.config.args)
@contextproperty
def _sql_results(self) -> Dict[str, AttrDict]:
return self.sql_results
@contextmember
def load_result(self, name: str) -> Optional[AttrDict]:
return self.sql_results.get(name)
@contextmember
def store_result(
self, name: str, response: Any, agate_table: Optional[agate.Table] = None
) -> str:
if agate_table is None:
agate_table = agate_helper.empty_table()
self.sql_results[name] = AttrDict(
{
"response": response,
"data": agate_helper.as_matrix(agate_table),
"table": agate_table,
}
)
return ""
@contextmember
def store_raw_result(
self,
name: str,
message=Optional[str],
code=Optional[str],
rows_affected=Optional[str],
agate_table: Optional[agate.Table] = None,
) -> str:
response = AdapterResponse(_message=message, code=code, rows_affected=rows_affected)
return self.store_result(name, response, agate_table)
@contextproperty
def validation(self):
def validate_any(*args) -> Callable[[T], None]:
def inner(value: T) -> None:
for arg in args:
if isinstance(arg, type) and isinstance(value, arg):
return
elif value == arg:
return
raise DbtValidationError(
'Expected value "{}" to be one of {}'.format(value, ",".join(map(str, args)))
)
return inner
return AttrDict(
{
"any": validate_any,
}
)
@contextmember
def write(self, payload: str) -> str:
# macros/source defs aren't 'writeable'.
if isinstance(self.model, (Macro, SourceDefinition)):
raise MacrosSourcesUnWriteableError(node=self.model)
self.model.build_path = self.model.write_node(self.config.target_path, "run", payload)
return ""
@contextmember
def render(self, string: str) -> str:
return get_rendered(string, self._ctx, self.model)
@contextmember
def try_or_compiler_error(
self, message_if_exception: str, func: Callable, *args, **kwargs
) -> Any:
try:
return func(*args, **kwargs)
except Exception:
raise CompilationError(message_if_exception, self.model)
@contextmember
def load_agate_table(self) -> agate.Table:
if not isinstance(self.model, SeedNode):
raise LoadAgateTableNotSeedError(self.model.resource_type, node=self.model)
assert self.model.root_path
path = os.path.join(self.model.root_path, self.model.original_file_path)
column_types = self.model.config.column_types
try:
table = agate_helper.from_csv(path, text_columns=column_types)
except ValueError as e:
raise LoadAgateTableValueError(e, node=self.model)
table.original_abspath = os.path.abspath(path)
return table
@contextproperty
def ref(self) -> Callable:
"""The most important function in dbt is `ref()`; it's impossible to
build even moderately complex models without it. `ref()` is how you
reference one model within another. This is a very common behavior, as
typically models are built to be "stacked" on top of one another. Here
is how this looks in practice:
> model_a.sql:
select *
from public.raw_data
> model_b.sql:
select *
from {{ref('model_a')}}
`ref()` is, under the hood, actually doing two important things. First,
it is interpolating the schema into your model file to allow you to
change your deployment schema via configuration. Second, it is using
these references between models to automatically build the dependency
graph. This will enable dbt to deploy models in the correct order when
using dbt run.
The `ref` function returns a Relation object.
## Advanced ref usage
There is also a two-argument variant of the `ref` function. With this
variant, you can pass both a package name and model name to `ref` to
avoid ambiguity. This functionality is not commonly required for
typical dbt usage.
> model.sql:
select * from {{ ref('package_name', 'model_name') }}"
"""
return self.provider.ref(self.db_wrapper, self.model, self.config, self.manifest)
@contextproperty
def source(self) -> Callable:
return self.provider.source(self.db_wrapper, self.model, self.config, self.manifest)
@contextproperty
def metric(self) -> Callable:
return self.provider.metric(self.db_wrapper, self.model, self.config, self.manifest)
@contextproperty("config")
def ctx_config(self) -> Config:
"""The `config` variable exists to handle end-user configuration for
custom materializations. Configs like `unique_key` can be implemented
using the `config` variable in your own materializations.
For example, code in the `incremental` materialization like this:
{% materialization incremental, default -%}
{%- set unique_key = config.get('unique_key') -%}
...
is responsible for handling model code that looks like this:
{{
config(
materialized='incremental',
unique_key='id'
)
}}
## config.get
name: The name of the configuration variable (required)
default: The default value to use if this configuration is not provided
(optional)
The `config.get` function is used to get configurations for a model
from the end-user. Configs defined in this way are optional, and a
default value can be provided.
Example usage:
{% materialization incremental, default -%}
-- Example w/ no default. unique_key will be None if the user does not provide this configuration
{%- set unique_key = config.get('unique_key') -%}
-- Example w/ default value. Default to 'id' if 'unique_key' not provided
{%- set unique_key = config.get('unique_key', default='id') -%}
...
## config.require
name: The name of the configuration variable (required)
The `config.require` function is used to get configurations for a model
from the end-user. Configs defined using this function are required,
and failure to provide them will result in a compilation error.
Example usage:
{% materialization incremental, default -%}
{%- set unique_key = config.require('unique_key') -%}
...
""" # noqa
return self.provider.Config(self.model, self.context_config)
@contextproperty
def execute(self) -> bool:
"""`execute` is a Jinja variable that returns True when dbt is in
"execute" mode.
When you execute a dbt compile or dbt run command, dbt:
- Reads all of the files in your project and generates a "manifest"
comprised of models, tests, and other graph nodes present in your
project. During this phase, dbt uses the `ref` statements it finds
to generate the DAG for your project. *No SQL is run during this
phase*, and `execute == False`.
- Compiles (and runs) each node (eg. building models, or running
tests). SQL is run during this phase, and `execute == True`.
Any Jinja that relies on a result being returned from the database will
error during the parse phase. For example, this SQL will return an
error:
> models/order_payment_methods.sql:
{% set payment_method_query %}
select distinct
payment_method
from {{ ref('raw_payments') }}
order by 1
{% endset %}
{% set results = run_query(relation_query) %}
{# Return the first column #}
{% set payment_methods = results.columns[0].values() %}
The error returned by dbt will look as follows:
Encountered an error:
Compilation Error in model order_payment_methods (models/order_payment_methods.sql)
'None' has no attribute 'table'
This is because Line #11 assumes that a table has been returned, when,
during the parse phase, this query hasn't been run.
To work around this, wrap any problematic Jinja in an
`{% if execute %}` statement:
> models/order_payment_methods.sql:
{% set payment_method_query %}
select distinct
payment_method
from {{ ref('raw_payments') }}
order by 1
{% endset %}
{% set results = run_query(relation_query) %}
{% if execute %}
{# Return the first column #}
{% set payment_methods = results.columns[0].values() %}
{% else %}
{% set payment_methods = [] %}
{% endif %}
""" # noqa
return self.provider.execute
@contextproperty
def exceptions(self) -> Dict[str, Any]:
"""The exceptions namespace can be used to raise warnings and errors in
dbt userspace.
## raise_compiler_error
The `exceptions.raise_compiler_error` method will raise a compiler
error with the provided message. This is typically only useful in
macros or materializations when invalid arguments are provided by the
calling model. Note that throwing an exception will cause a model to
fail, so please use this variable with care!
Example usage:
> exceptions.sql:
{% if number < 0 or number > 100 %}
{{ exceptions.raise_compiler_error("Invalid `number`. Got: " ~ number) }}
{% endif %}
## warn
The `exceptions.warn` method will raise a compiler warning with the
provided message. If the `--warn-error` flag is provided to dbt, then
this warning will be elevated to an exception, which is raised.
Example usage:
> warn.sql:
{% if number < 0 or number > 100 %}