forked from dbt-labs/dbt-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exceptions.py
2375 lines (1771 loc) · 73.8 KB
/
exceptions.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 builtins
import json
import re
from typing import Any, Dict, List, Mapping, NoReturn, Optional, Union
# from dbt.contracts.graph import ManifestNode # or ParsedNode?
from dbt.dataclass_schema import ValidationError
from dbt.events.functions import warn_or_error
from dbt.events.helpers import env_secrets, scrub_secrets
from dbt.events.types import JinjaLogWarning
from dbt.events.contextvars import get_node_info
from dbt.node_types import NodeType
from dbt.ui import line_wrap_message
import dbt.dataclass_schema
class MacroReturn(builtins.BaseException):
"""
Hack of all hacks
This is not actually an exception.
It's how we return a value from a macro.
"""
def __init__(self, value):
self.value = value
class Exception(builtins.Exception):
CODE = -32000
MESSAGE = "Server Error"
def data(self):
# if overriding, make sure the result is json-serializable.
return {
"type": self.__class__.__name__,
"message": str(self),
}
class InternalException(Exception):
def __init__(self, msg: str):
self.stack: List = []
self.msg = scrub_secrets(msg, env_secrets())
@property
def type(self):
return "Internal"
def process_stack(self):
lines = []
stack = self.stack
first = True
if len(stack) > 1:
lines.append("")
for item in stack:
msg = "called by"
if first:
msg = "in"
first = False
lines.append(f"> {msg}")
return lines
def __str__(self):
if hasattr(self.msg, "split"):
split_msg = self.msg.split("\n")
else:
split_msg = str(self.msg).split("\n")
lines = ["{}".format(self.type + " Error")] + split_msg
lines += self.process_stack()
return lines[0] + "\n" + "\n".join([" " + line for line in lines[1:]])
class RuntimeException(RuntimeError, Exception):
CODE = 10001
MESSAGE = "Runtime error"
def __init__(self, msg: str, node=None):
self.stack: List = []
self.node = node
self.msg = scrub_secrets(msg, env_secrets())
def add_node(self, node=None):
if node is not None and node is not self.node:
if self.node is not None:
self.stack.append(self.node)
self.node = node
@property
def type(self):
return "Runtime"
def node_to_string(self, node):
if node is None:
return "<Unknown>"
if not hasattr(node, "name"):
# we probably failed to parse a block, so we can't know the name
return f"{node.resource_type} ({node.original_file_path})"
if hasattr(node, "contents"):
# handle FileBlocks. They aren't really nodes but we want to render
# out the path we know at least. This indicates an error during
# block parsing.
return f"{node.path.original_file_path}"
return f"{node.resource_type} {node.name} ({node.original_file_path})"
def process_stack(self):
lines = []
stack = self.stack + [self.node]
first = True
if len(stack) > 1:
lines.append("")
for item in stack:
msg = "called by"
if first:
msg = "in"
first = False
lines.append(f"> {msg} {self.node_to_string(item)}")
return lines
def validator_error_message(self, exc: builtins.Exception):
"""Given a dbt.dataclass_schema.ValidationError (which is basically a
jsonschema.ValidationError), return the relevant parts as a string
"""
if not isinstance(exc, dbt.dataclass_schema.ValidationError):
return str(exc)
path = "[%s]" % "][".join(map(repr, exc.relative_path))
return f"at path {path}: {exc.message}"
def __str__(self, prefix: str = "! "):
node_string = ""
if self.node is not None:
node_string = f" in {self.node_to_string(self.node)}"
if hasattr(self.msg, "split"):
split_msg = self.msg.split("\n")
else:
split_msg = str(self.msg).split("\n")
lines = ["{}{}".format(self.type + " Error", node_string)] + split_msg
lines += self.process_stack()
return lines[0] + "\n" + "\n".join([" " + line for line in lines[1:]])
def data(self):
result = Exception.data(self)
if self.node is None:
return result
result.update(
{
"raw_code": self.node.raw_code,
# the node isn't always compiled, but if it is, include that!
"compiled_code": getattr(self.node, "compiled_code", None),
}
)
return result
class RPCFailureResult(RuntimeException):
CODE = 10002
MESSAGE = "RPC execution error"
class RPCTimeoutException(RuntimeException):
CODE = 10008
MESSAGE = "RPC timeout error"
def __init__(self, timeout: Optional[float]):
super().__init__(self.MESSAGE)
self.timeout = timeout
def data(self):
result = super().data()
result.update(
{
"timeout": self.timeout,
"message": f"RPC timed out after {self.timeout}s",
}
)
return result
class RPCKilledException(RuntimeException):
CODE = 10009
MESSAGE = "RPC process killed"
def __init__(self, signum: int):
self.signum = signum
self.msg = f"RPC process killed by signal {self.signum}"
super().__init__(self.msg)
def data(self):
return {
"signum": self.signum,
"message": self.msg,
}
class RPCCompiling(RuntimeException):
CODE = 10010
MESSAGE = 'RPC server is compiling the project, call the "status" method for' " compile status"
def __init__(self, msg: str = None, node=None):
if msg is None:
msg = "compile in progress"
super().__init__(msg, node)
class RPCLoadException(RuntimeException):
CODE = 10011
MESSAGE = (
'RPC server failed to compile project, call the "status" method for' " compile status"
)
def __init__(self, cause: Dict[str, Any]):
self.cause = cause
self.msg = f'{self.MESSAGE}: {self.cause["message"]}'
super().__init__(self.msg)
def data(self):
return {"cause": self.cause, "message": self.msg}
class DatabaseException(RuntimeException):
CODE = 10003
MESSAGE = "Database Error"
def process_stack(self):
lines = []
if hasattr(self.node, "build_path") and self.node.build_path:
lines.append(f"compiled Code at {self.node.build_path}")
return lines + RuntimeException.process_stack(self)
@property
def type(self):
return "Database"
class CompilationException(RuntimeException):
CODE = 10004
MESSAGE = "Compilation Error"
@property
def type(self):
return "Compilation"
def _fix_dupe_msg(self, path_1: str, path_2: str, name: str, type_name: str) -> str:
if path_1 == path_2:
return (
f"remove one of the {type_name} entries for {name} in this file:\n - {path_1!s}\n"
)
else:
return (
f"remove the {type_name} entry for {name} in one of these files:\n"
f" - {path_1!s}\n{path_2!s}"
)
class RecursionException(RuntimeException):
pass
class ValidationException(RuntimeException):
CODE = 10005
MESSAGE = "Validation Error"
class ParsingException(RuntimeException):
CODE = 10015
MESSAGE = "Parsing Error"
@property
def type(self):
return "Parsing"
# TODO: this isn't raised in the core codebase. Is it raised elsewhere?
class JSONValidationException(ValidationException):
def __init__(self, typename, errors):
self.typename = typename
self.errors = errors
self.errors_message = ", ".join(errors)
msg = f'Invalid arguments passed to "{self.typename}" instance: {self.errors_message}'
super().__init__(msg)
def __reduce__(self):
# see https://stackoverflow.com/a/36342588 for why this is necessary
return (JSONValidationException, (self.typename, self.errors))
class IncompatibleSchemaException(RuntimeException):
def __init__(self, expected: str, found: Optional[str]):
self.expected = expected
self.found = found
self.filename = "input file"
super().__init__(msg=self.get_message())
def add_filename(self, filename: str):
self.filename = filename
self.msg = self.get_message()
def get_message(self) -> str:
found_str = "nothing"
if self.found is not None:
found_str = f'"{self.found}"'
msg = (
f'Expected a schema version of "{self.expected}" in '
f"{self.filename}, but found {found_str}. Are you running with a "
f"different version of dbt?"
)
return msg
CODE = 10014
MESSAGE = "Incompatible Schema"
class JinjaRenderingException(CompilationException):
pass
class UndefinedMacroException(CompilationException):
def __str__(self, prefix: str = "! ") -> str:
msg = super().__str__(prefix)
return (
f"{msg}. This can happen when calling a macro that does "
"not exist. Check for typos and/or install package dependencies "
'with "dbt deps".'
)
class UnknownAsyncIDException(Exception):
CODE = 10012
MESSAGE = "RPC server got an unknown async ID"
def __init__(self, task_id):
self.task_id = task_id
def __str__(self):
return f"{self.MESSAGE}: {self.task_id}"
class AliasException(ValidationException):
pass
class DependencyException(Exception):
# this can happen due to raise_dependency_error and its callers
CODE = 10006
MESSAGE = "Dependency Error"
class DbtConfigError(RuntimeException):
CODE = 10007
MESSAGE = "DBT Configuration Error"
def __init__(self, msg: str, project=None, result_type="invalid_project", path=None):
self.project = project
super().__init__(msg)
self.result_type = result_type
self.path = path
def __str__(self, prefix="! ") -> str:
msg = super().__str__(prefix)
if self.path is None:
return msg
else:
return f"{msg}\n\nError encountered in {self.path}"
class FailFastException(RuntimeException):
CODE = 10013
MESSAGE = "FailFast Error"
def __init__(self, msg: str, result=None, node=None):
super().__init__(msg=msg, node=node)
self.result = result
@property
def type(self):
return "FailFast"
class DbtProjectError(DbtConfigError):
pass
class DbtSelectorsError(DbtConfigError):
pass
class DbtProfileError(DbtConfigError):
pass
class SemverException(Exception):
def __init__(self, msg: str = None):
self.msg = msg
if msg is not None:
super().__init__(msg)
else:
super().__init__()
class VersionsNotCompatibleException(SemverException):
pass
class NotImplementedException(Exception):
def __init__(self, msg: str):
self.msg = msg
self.formatted_msg = f"ERROR: {self.msg}"
super().__init__(self.formatted_msg)
class FailedToConnectException(DatabaseException):
pass
class CommandError(RuntimeException):
def __init__(self, cwd: str, cmd: List[str], msg: str = "Error running command"):
cmd_scrubbed = list(scrub_secrets(cmd_txt, env_secrets()) for cmd_txt in cmd)
super().__init__(msg)
self.cwd = cwd
self.cmd = cmd_scrubbed
self.args = (cwd, cmd_scrubbed, msg)
def __str__(self):
if len(self.cmd) == 0:
return f"{self.msg}: No arguments given"
return f'{self.msg}: "{self.cmd[0]}"'
class ExecutableError(CommandError):
def __init__(self, cwd: str, cmd: List[str], msg: str):
super().__init__(cwd, cmd, msg)
class WorkingDirectoryError(CommandError):
def __init__(self, cwd: str, cmd: List[str], msg: str):
super().__init__(cwd, cmd, msg)
def __str__(self):
return f'{self.msg}: "{self.cwd}"'
class CommandResultError(CommandError):
def __init__(
self,
cwd: str,
cmd: List[str],
returncode: Union[int, Any],
stdout: bytes,
stderr: bytes,
msg: str = "Got a non-zero returncode",
):
super().__init__(cwd, cmd, msg)
self.returncode = returncode
self.stdout = scrub_secrets(stdout.decode("utf-8"), env_secrets())
self.stderr = scrub_secrets(stderr.decode("utf-8"), env_secrets())
self.args = (cwd, self.cmd, returncode, self.stdout, self.stderr, msg)
def __str__(self):
return f"{self.msg} running: {self.cmd}"
class InvalidConnectionException(RuntimeException):
def __init__(self, thread_id, known: List):
self.thread_id = thread_id
self.known = known
super().__init__(
msg="connection never acquired for thread {self.thread_id}, have {self.known}"
)
class InvalidSelectorException(RuntimeException):
def __init__(self, name: str):
self.name = name
super().__init__(name)
class DuplicateYamlKeyException(CompilationException):
pass
class ConnectionException(Exception):
"""
There was a problem with the connection that returned a bad response,
timed out, or resulted in a file that is corrupt.
"""
pass
# event level exception
class EventCompilationException(CompilationException):
def __init__(self, msg: str, node):
self.msg = scrub_secrets(msg, env_secrets())
self.node = node
super().__init__(msg=self.msg)
# compilation level exceptions
class GraphDependencyNotFound(CompilationException):
def __init__(self, node, dependency: str):
self.node = node
self.dependency = dependency
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"'{self.node.unique_id}' depends on '{self.dependency}' which is not in the graph!"
return msg
# client level exceptions
class NoSupportedLanguagesFound(CompilationException):
def __init__(self, node):
self.node = node
self.msg = f"No supported_languages found in materialization macro {self.node.name}"
super().__init__(msg=self.msg)
class MaterializtionMacroNotUsed(CompilationException):
def __init__(self, node):
self.node = node
self.msg = "Only materialization macros can be used with this function"
super().__init__(msg=self.msg)
class UndefinedCompilation(CompilationException):
def __init__(self, name: str, node):
self.name = name
self.node = node
self.msg = f"{self.name} is undefined"
super().__init__(msg=self.msg)
class CaughtMacroExceptionWithNode(CompilationException):
def __init__(self, exc, node):
self.exc = exc
self.node = node
super().__init__(msg=str(exc))
class CaughtMacroException(CompilationException):
def __init__(self, exc):
self.exc = exc
super().__init__(msg=str(exc))
class MacroNameNotString(CompilationException):
def __init__(self, kwarg_value):
self.kwarg_value = kwarg_value
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = (
f"The macro_name parameter ({self.kwarg_value}) "
"to adapter.dispatch was not a string"
)
return msg
class MissingControlFlowStartTag(CompilationException):
def __init__(self, tag, expected_tag: str, tag_parser):
self.tag = tag
self.expected_tag = expected_tag
self.tag_parser = tag_parser
super().__init__(msg=self.get_message())
def get_message(self) -> str:
linepos = self.tag_parser.linepos(self.tag.start)
msg = (
f"Got an unexpected control flow end tag, got {self.tag.block_type_name} but "
f"expected {self.expected_tag} next (@ {linepos})"
)
return msg
class UnexpectedControlFlowEndTag(CompilationException):
def __init__(self, tag, expected_tag: str, tag_parser):
self.tag = tag
self.expected_tag = expected_tag
self.tag_parser = tag_parser
super().__init__(msg=self.get_message())
def get_message(self) -> str:
linepos = self.tag_parser.linepos(self.tag.start)
msg = (
f"Got an unexpected control flow end tag, got {self.tag.block_type_name} but "
f"never saw a preceeding {self.expected_tag} (@ {linepos})"
)
return msg
class UnexpectedMacroEOF(CompilationException):
def __init__(self, expected_name: str, actual_name: str):
self.expected_name = expected_name
self.actual_name = actual_name
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f'unexpected EOF, expected {self.expected_name}, got "{self.actual_name}"'
return msg
class MacroNamespaceNotString(CompilationException):
def __init__(self, kwarg_type: Any):
self.kwarg_type = kwarg_type
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = (
"The macro_namespace parameter to adapter.dispatch "
f"is a {self.kwarg_type}, not a string"
)
return msg
class NestedTags(CompilationException):
def __init__(self, outer, inner):
self.outer = outer
self.inner = inner
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = (
f"Got nested tags: {self.outer.block_type_name} (started at {self.outer.start}) did "
f"not have a matching {{{{% end{self.outer.block_type_name} %}}}} before a "
f"subsequent {self.inner.block_type_name} was found (started at {self.inner.start})"
)
return msg
class BlockDefinitionNotAtTop(CompilationException):
def __init__(self, tag_parser, tag_start):
self.tag_parser = tag_parser
self.tag_start = tag_start
super().__init__(msg=self.get_message())
def get_message(self) -> str:
position = self.tag_parser.linepos(self.tag_start)
msg = (
f"Got a block definition inside control flow at {position}. "
"All dbt block definitions must be at the top level"
)
return msg
class MissingCloseTag(CompilationException):
def __init__(self, block_type_name: str, linecount: int):
self.block_type_name = block_type_name
self.linecount = linecount
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"Reached EOF without finding a close tag for {self.block_type_name} (searched from line {self.linecount})"
return msg
class GitCloningProblem(RuntimeException):
def __init__(self, repo: str):
self.repo = scrub_secrets(repo, env_secrets())
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"""\
Something went wrong while cloning {self.repo}
Check the debug logs for more information
"""
return msg
class GitCloningError(InternalException):
def __init__(self, repo: str, revision: str, error: CommandResultError):
self.repo = repo
self.revision = revision
self.error = error
super().__init__(msg=self.get_message())
def get_message(self) -> str:
stderr = self.error.stderr.strip()
if "usage: git" in stderr:
stderr = stderr.split("\nusage: git")[0]
if re.match("fatal: destination path '(.+)' already exists", stderr):
self.error.cmd = list(scrub_secrets(str(self.error.cmd), env_secrets()))
raise self.error
msg = f"Error checking out spec='{self.revision}' for repo {self.repo}\n{stderr}"
return scrub_secrets(msg, env_secrets())
class GitCheckoutError(InternalException):
def __init__(self, repo: str, revision: str, error: CommandResultError):
self.repo = repo
self.revision = revision
self.stderr = error.stderr.strip()
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"Error checking out spec='{self.revision}' for repo {self.repo}\n{self.stderr}"
return scrub_secrets(msg, env_secrets())
class InvalidMaterializationArg(CompilationException):
def __init__(self, name: str, argument: str):
self.name = name
self.argument = argument
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"materialization '{self.name}' received unknown argument '{self.argument}'."
return msg
class SymbolicLinkError(CompilationException):
def __init__(self):
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = (
"dbt encountered an error when attempting to create a symbolic link. "
"If this error persists, please create an issue at: \n\n"
"https://github.com/dbt-labs/dbt-core"
)
return msg
# context level exceptions
class ZipStrictWrongType(CompilationException):
def __init__(self, exc):
self.exc = exc
msg = str(self.exc)
super().__init__(msg=msg)
class SetStrictWrongType(CompilationException):
def __init__(self, exc):
self.exc = exc
msg = str(self.exc)
super().__init__(msg=msg)
class LoadAgateTableValueError(CompilationException):
def __init__(self, exc: ValueError, node):
self.exc = exc
self.node = node
msg = str(self.exc)
super().__init__(msg=msg)
class LoadAgateTableNotSeed(CompilationException):
def __init__(self, resource_type, node):
self.resource_type = resource_type
self.node = node
msg = f"can only load_agate_table for seeds (got a {self.resource_type})"
super().__init__(msg=msg)
class MacrosSourcesUnWriteable(CompilationException):
def __init__(self, node):
self.node = node
msg = 'cannot "write" macros or sources'
super().__init__(msg=msg)
class PackageNotInDeps(CompilationException):
def __init__(self, package_name: str, node):
self.package_name = package_name
self.node = node
msg = f"Node package named {self.package_name} not found!"
super().__init__(msg=msg)
class OperationsCannotRefEphemeralNodes(CompilationException):
def __init__(self, target_name: str, node):
self.target_name = target_name
self.node = node
msg = f"Operations can not ref() ephemeral nodes, but {target_name} is ephemeral"
super().__init__(msg=msg)
class InvalidPersistDocsValueType(CompilationException):
def __init__(self, persist_docs: Any):
self.persist_docs = persist_docs
msg = (
"Invalid value provided for 'persist_docs'. Expected dict "
f"but received {type(self.persist_docs)}"
)
super().__init__(msg=msg)
class InvalidInlineModelConfig(CompilationException):
def __init__(self, node):
self.node = node
msg = "Invalid inline model config"
super().__init__(msg=msg)
class ConflictingConfigKeys(CompilationException):
def __init__(self, oldkey: str, newkey: str, node):
self.oldkey = oldkey
self.newkey = newkey
self.node = node
msg = f'Invalid config, has conflicting keys "{self.oldkey}" and "{self.newkey}"'
super().__init__(msg=msg)
class InvalidNumberSourceArgs(CompilationException):
def __init__(self, args, node):
self.args = args
self.node = node
msg = f"source() takes exactly two arguments ({len(self.args)} given)"
super().__init__(msg=msg)
class RequiredVarNotFound(CompilationException):
def __init__(self, var_name: str, merged: Dict, node):
self.var_name = var_name
self.merged = merged
self.node = node
super().__init__(msg=self.get_message())
def get_message(self) -> str:
if self.node is not None:
node_name = self.node.name
else:
node_name = "<Configuration>"
dct = {k: self.merged[k] for k in self.merged}
pretty_vars = json.dumps(dct, sort_keys=True, indent=4)
msg = f"Required var '{self.var_name}' not found in config:\nVars supplied to {node_name} = {pretty_vars}"
return msg
class PackageNotFoundForMacro(CompilationException):
def __init__(self, package_name: str):
self.package_name = package_name
msg = f"Could not find package '{self.package_name}'"
super().__init__(msg=msg)
class DisallowSecretEnvVar(ParsingException):
def __init__(self, env_var_name: str):
self.env_var_name = env_var_name
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = (
"Secret env vars are allowed only in profiles.yml or packages.yml. "
f"Found '{self.env_var_name}' referenced elsewhere."
)
return msg
class InvalidMacroArgType(CompilationException):
def __init__(self, method_name: str, arg_name: str, got_value: Any, expected_type):
self.method_name = method_name
self.arg_name = arg_name
self.got_value = got_value
self.expected_type = expected_type
super().__init__(msg=self.get_message())
def get_message(self) -> str:
got_type = type(self.got_value)
msg = (
f"'adapter.{self.method_name}' expects argument "
f"'{self.arg_name}' to be of type '{self.expected_type}', instead got "
f"{self.got_value} ({got_type})"
)
return msg
class InvalidBoolean(CompilationException):
def __init__(self, return_value: Any, macro_name: str):
self.return_value = return_value
self.macro_name = macro_name
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = (
f"Macro '{self.macro_name}' returns '{self.return_value}'. It is not type 'bool' "
"and cannot not be converted reliably to a bool."
)
return msg
class RefInvalidArgs(CompilationException):
def __init__(self, node, args):
self.node = node
self.args = args
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"ref() takes at most two arguments ({len(self.args)} given)"
return msg
class MetricInvalidArgs(CompilationException):
def __init__(self, node, args):
self.node = node
self.args = args
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"metric() takes at most two arguments ({len(self.args)} given)"
return msg
class RefBadContext(CompilationException):
def __init__(self, node, args):
self.node = node
self.args = args
super().__init__(msg=self.get_message())
def get_message(self) -> str:
# This explicitly references model['name'], instead of model['alias'], for
# better error messages. Ex. If models foo_users and bar_users are aliased
# to 'users', in their respective schemas, then you would want to see
# 'bar_users' in your error messge instead of just 'users'.
if isinstance(self.node, dict):
model_name = self.node["name"]
else:
model_name = self.node.name
ref_args = ", ".join("'{}'".format(a) for a in self.args)
ref_string = f"{{{{ ref({ref_args}) }}}}"
msg = f"""dbt was unable to infer all dependencies for the model "{model_name}".
This typically happens when ref() is placed within a conditional block.
To fix this, add the following hint to the top of the model "{model_name}":
-- depends_on: {ref_string}"""
return msg
class InvalidDocArgs(CompilationException):
def __init__(self, node, args):
self.node = node
self.args = args
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"doc() takes at most two arguments ({len(self.args)} given)"
return msg
class DocTargetNotFound(CompilationException):
def __init__(self, node, target_doc_name: str, target_doc_package: Optional[str]):
self.node = node
self.target_doc_name = target_doc_name
self.target_doc_package = target_doc_package
super().__init__(msg=self.get_message())
def get_message(self) -> str:
target_package_string = ""
if self.target_doc_package is not None:
target_package_string = f"in package '{self. target_doc_package}' "
msg = f"Documentation for '{self.node.unique_id}' depends on doc '{self.target_doc_name}' {target_package_string} which was not found"
return msg
class MacroInvalidDispatchArg(CompilationException):
def __init__(self, macro_name: str):
self.macro_name = macro_name
super().__init__(msg=self.get_message())
def get_message(self) -> str:
msg = f"""\
The "packages" argument of adapter.dispatch() has been deprecated.
Use the "macro_namespace" argument instead.
Raised during dispatch for: {self.macro_name}