Repository: dbt-labs/dbt-bigquery (python)

Issue:
[CT-1682] Replace deprecated exception functions
`dbt-core` has deprecated functions to raise exceptions in favor of directly raising the exceptions. Nothing should be broken (yet) and the functions still raise as expected but they also will log a deprecation warning (pending https://github.com/dbt-labs/dbt-core/pull/6413). It would be good to resolve these deprecation messages before the 1.4 rc.

There are a lot of deprecated function so it's easier to search for `dbt.exceptions` and look at each callsite to determine if it's using a function or already directly raising an exception. Then replace anywhere using functions with directly raising an exception.

We can create new exceptions in `dbt-core` to raise or the adapters could start to own their own exceptions within the adapter code base that inherit from exceptions in `dbt-core`.

For examples, see [`dbt-core` PR](https://github.com/dbt-labs/dbt-core/pull/6347) that replaced all functions with raises.

Pull request description:
update exception names
resolves #441 

### Description

Replace exception functions and rename exceptions. Currently point to a branch of core for testing.

### Checklist

- [ ] I have read [the contributing guide](https://github.com/dbt-labs/dbt-bigquery/blob/main/CONTRIBUTING.md) and understand what's expected of me
- [ ] I have signed the [CLA](https://docs.getdbt.com/docs/contributor-license-agreements)
- [ ] I have run this code in development and it appears to resolve the stated issue
- [ ] This PR includes tests, or tests are not required/relevant for this PR
- [ ] I have [opened an issue to add/update docs](https://github.com/dbt-labs/docs.getdbt.com/issues/new/choose), or docs changes are not required/relevant for this PR
- [ ] I have run `changie new` to [create a changelog entry](https://github.com/dbt-labs/dbt-bigquery/blob/main/CONTRIBUTING.md#Adding-CHANGELOG-Entry)


Patch:
diff --git a/.changes/unreleased/Under the Hood-20230110-110016.yaml b/.changes/unreleased/Under the Hood-20230110-110016.yaml
new file mode 100644
index 0000000..3f428a8
--- /dev/null
+++ b/.changes/unreleased/Under the Hood-20230110-110016.yaml
@@ -0,0 +1,7 @@
+kind: Under the Hood
+body: Update exception names to match dbt-core
+time: 2023-01-10T11:00:16.649793-06:00
+custom:
+  Author: emmyoop
+  Issue: "441"
+  PR: "460"
diff --git a/dbt/adapters/bigquery/connections.py b/dbt/adapters/bigquery/connections.py
index 7a09eb0..715dfb3 100644
--- a/dbt/adapters/bigquery/connections.py
+++ b/dbt/adapters/bigquery/connections.py
@@ -24,9 +24,9 @@ from dbt.config.profile import INVALID_PROFILE_MESSAGE
 from dbt.tracking import active_user
 from dbt.contracts.connection import ConnectionState, AdapterResponse
 from dbt.exceptions import (
-    FailedToConnectException,
-    RuntimeException,
-    DatabaseException,
+    FailedToConnectError,
+    DbtRuntimeError,
+    DbtDatabaseError,
     DbtProfileError,
 )
 from dbt.adapters.base import BaseConnectionManager, Credentials
@@ -196,7 +196,7 @@ class BigQueryConnectionManager(BaseConnectionManager):
                     error.query_job.location, error.query_job.project, error.query_job.job_id
                 )
             )
-        raise DatabaseException(error_msg)
+        raise DbtDatabaseError(error_msg)
 
     def clear_transaction(self):
         pass
@@ -223,12 +223,12 @@ class BigQueryConnectionManager(BaseConnectionManager):
                 "account you are trying to impersonate.\n\n"
                 f"{str(e)}"
             )
-            raise RuntimeException(message)
+            raise DbtRuntimeError(message)
 
         except Exception as e:
             logger.debug("Unhandled error while running:\n{}".format(sql))
             logger.debug(e)
-            if isinstance(e, RuntimeException):
+            if isinstance(e, DbtRuntimeError):
                 # during a sql query, an internal to dbt exception was raised.
                 # this sounds a lot like a signal handler and probably has
                 # useful information, so raise it without modification.
@@ -238,7 +238,7 @@ class BigQueryConnectionManager(BaseConnectionManager):
             # don't want to log. Hopefully they never change this!
             if BQ_QUERY_JOB_SPLIT in exc_message:
                 exc_message = exc_message.split(BQ_QUERY_JOB_SPLIT)[0].strip()
-            raise RuntimeException(exc_message)
+            raise DbtRuntimeError(exc_message)
 
     def cancel_open(self) -> None:
         pass
@@ -305,7 +305,7 @@ class BigQueryConnectionManager(BaseConnectionManager):
             )
 
         error = 'Invalid `method` in profile: "{}"'.format(method)
-        raise FailedToConnectException(error)
+        raise FailedToConnectError(error)
 
     @classmethod
     def get_impersonated_credentials(cls, profile_credentials):
@@ -362,7 +362,7 @@ class BigQueryConnectionManager(BaseConnectionManager):
             connection.handle = None
             connection.state = "fail"
 
-            raise FailedToConnectException(str(e))
+            raise FailedToConnectError(str(e))
 
         connection.handle = handle
         connection.state = "open"
diff --git a/dbt/adapters/bigquery/gcloud.py b/dbt/adapters/bigquery/gcloud.py
index eb418e9..c303097 100644
--- a/dbt/adapters/bigquery/gcloud.py
+++ b/dbt/adapters/bigquery/gcloud.py
@@ -25,4 +25,4 @@ def setup_default_credentials():
     if gcloud_installed():
         run_cmd(".", ["gcloud", "auth", "application-default", "login"])
     else:
-        raise dbt.exceptions.RuntimeException(NOT_INSTALLED_MSG)
+        raise dbt.exceptions.DbtRuntimeError(NOT_INSTALLED_MSG)
diff --git a/dbt/adapters/bigquery/impl.py b/dbt/adapters/bigquery/impl.py
index ec749c3..920b992 100644
--- a/dbt/adapters/bigquery/impl.py
+++ b/dbt/adapters/bigquery/impl.py
@@ -55,7 +55,7 @@ CREATE_SCHEMA_MACRO_NAME = "create_schema"
 
 def sql_escape(string):
     if not isinstance(string, str):
-        raise dbt.exceptions.CompilationException(f"cannot escape a non-string: {string}")
+        raise dbt.exceptions.CompilationError(f"cannot escape a non-string: {string}")
     return json.dumps(string)[1:-1]
 
 
@@ -98,9 +98,9 @@ class PartitionConfig(dbtClassMixin):
             cls.validate(raw_partition_by)
             return cls.from_dict(raw_partition_by)
         except ValidationError as exc:
-            raise dbt.exceptions.ValidationException("Could not parse partition config") from exc
+            raise dbt.exceptions.DbtValidationError("Could not parse partition config") from exc
         except TypeError:
-            raise dbt.exceptions.CompilationException(
+            raise dbt.exceptions.CompilationError(
                 f"Invalid partition_by config:\n"
                 f"  Got: {raw_partition_by}\n"
                 f'  Expected a dictionary with "field" and "data_type" keys'
@@ -173,9 +173,7 @@ class BigQueryAdapter(BaseAdapter):
         conn.handle.delete_table(table_ref)
 
     def truncate_relation(self, relation: BigQueryRelation) -> None:
-        raise dbt.exceptions.NotImplementedException(
-            "`truncate` is not implemented for this adapter!"
-        )
+        raise dbt.exceptions.NotImplementedError("`truncate` is not implemented for this adapter!")
 
     def rename_relation(
         self, from_relation: BigQueryRelation, to_relation: BigQueryRelation
@@ -191,7 +189,7 @@ class BigQueryAdapter(BaseAdapter):
             or from_relation.type == RelationType.View
             or to_relation.type == RelationType.View
         ):
-            raise dbt.exceptions.RuntimeException(
+            raise dbt.exceptions.DbtRuntimeError(
                 "Renaming of views is not currently supported in BigQuery"
             )
 
@@ -440,7 +438,7 @@ class BigQueryAdapter(BaseAdapter):
         elif materialization == "table":
             write_disposition = WRITE_TRUNCATE
         else:
-            dbt.exceptions.raise_compiler_error(
+            raise dbt.exceptions.CompilationError(
                 'Copy table materialization must be "copy" or "table", but '
                 f"config.get('copy_materialization', 'table') was "
                 f"{materialization}"
@@ -473,11 +471,11 @@ class BigQueryAdapter(BaseAdapter):
             job.reload()
 
         if job.state != "DONE":
-            raise dbt.exceptions.RuntimeException("BigQuery Timeout Exceeded")
+            raise dbt.exceptions.DbtRuntimeError("BigQuery Timeout Exceeded")
 
         elif job.error_result:
             message = "\n".join(error["message"].strip() for error in job.errors)
-            raise dbt.exceptions.RuntimeException(message)
+            raise dbt.exceptions.DbtRuntimeError(message)
 
     def _bq_table_to_relation(self, bq_table):
         if bq_table is None:
@@ -502,7 +500,7 @@ class BigQueryAdapter(BaseAdapter):
         if self.nice_connection_name() in ["on-run-start", "on-run-end"]:
             self.warning_on_hooks(self.nice_connection_name())
         else:
-            raise dbt.exceptions.NotImplementedException(
+            raise dbt.exceptions.NotImplementedError(
                 "`add_query` is not implemented for this adapter!"
             )
 
@@ -860,7 +858,7 @@ class BigQueryAdapter(BaseAdapter):
         elif location == "prepend":
             return f"concat('{value}', {add_to})"
         else:
-            raise dbt.exceptions.RuntimeException(
+            raise dbt.exceptions.DbtRuntimeError(
                 f'Got an unexpected location value of "{location}"'
             )
 
diff --git a/dbt/adapters/bigquery/relation.py b/dbt/adapters/bigquery/relation.py
index 7224de8..d496771 100644
--- a/dbt/adapters/bigquery/relation.py
+++ b/dbt/adapters/bigquery/relation.py
@@ -4,7 +4,7 @@ from typing import Optional
 from itertools import chain, islice
 
 from dbt.adapters.base.relation import BaseRelation, ComponentName, InformationSchema
-from dbt.exceptions import raise_compiler_error
+from dbt.exceptions import CompilationError
 from dbt.utils import filter_null_values
 from typing import TypeVar
 
@@ -94,7 +94,7 @@ class BigQueryInformationSchema(InformationSchema):
                 msg = (
                     f'No location/region found when trying to retrieve "{information_schema_view}"'
                 )
-                raise raise_compiler_error(msg)
+                raise CompilationError(msg)
             info_schema = info_schema.incorporate(location=relation.location)
         return info_schema
 


Test patch:
diff --git a/tests/integration/schema_tests_test/test_schema_v2_tests.py b/tests/integration/schema_tests_test/test_schema_v2_tests.py
index 0709fdb..7b213db 100644
--- a/tests/integration/schema_tests_test/test_schema_v2_tests.py
+++ b/tests/integration/schema_tests_test/test_schema_v2_tests.py
@@ -2,8 +2,6 @@ from tests.integration.base import DBTIntegrationTest, FakeArgs, use_profile
 import os
 
 from dbt.task.test import TestTask
-from dbt.exceptions import CompilationException
-from dbt.contracts.results import TestStatus
 
 class TestBQSchemaTests(DBTIntegrationTest):
     @property
diff --git a/tests/integration/simple_snapshot_test/test_simple_snapshot.py b/tests/integration/simple_snapshot_test/test_simple_snapshot.py
index 7f6c134..191dde7 100644
--- a/tests/integration/simple_snapshot_test/test_simple_snapshot.py
+++ b/tests/integration/simple_snapshot_test/test_simple_snapshot.py
@@ -1,7 +1,6 @@
 from tests.integration.base import DBTIntegrationTest, use_profile
 from datetime import datetime
 import pytz
-import dbt.exceptions
 
 
 class BaseSimpleSnapshotTest(DBTIntegrationTest):
diff --git a/tests/integration/sources_test/test_sources.py b/tests/integration/sources_test/test_sources.py
index 21dbb19..83a5864 100644
--- a/tests/integration/sources_test/test_sources.py
+++ b/tests/integration/sources_test/test_sources.py
@@ -4,7 +4,6 @@ from datetime import datetime, timedelta
 
 import yaml
 
-from dbt.exceptions import CompilationException
 import dbt.tracking
 import dbt.version
 from dbt.events.functions import reset_metadata_vars
diff --git a/tests/unit/test_bigquery_adapter.py b/tests/unit/test_bigquery_adapter.py
index cf8bcdf..29c7a9e 100644
--- a/tests/unit/test_bigquery_adapter.py
+++ b/tests/unit/test_bigquery_adapter.py
@@ -156,8 +156,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             connection = adapter.acquire_connection('dummy')
             self.assertEqual(connection.type, 'bigquery')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         except BaseException as e:
             raise
@@ -173,8 +173,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             connection = adapter.acquire_connection('dummy')
             self.assertEqual(connection.type, 'bigquery')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         except BaseException as e:
             raise
@@ -190,8 +190,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             connection = adapter.acquire_connection('dummy')
             self.assertEqual(connection.type, 'bigquery')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         except BaseException as e:
             raise
@@ -207,8 +207,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             connection = adapter.acquire_connection('dummy')
             self.assertEqual(connection.type, 'bigquery')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         except BaseException as e:
             raise
@@ -224,8 +224,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             connection = adapter.acquire_connection('dummy')
             self.assertEqual(connection.type, 'bigquery')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         except BaseException as e:
             raise
@@ -241,8 +241,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             connection = adapter.acquire_connection('dummy')
             self.assertEqual(connection.type, 'bigquery')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         except BaseException as e:
             raise
@@ -259,8 +259,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             self.assertEqual(connection.type, 'bigquery')
             self.assertEqual(connection.credentials.priority, 'batch')
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         mock_open_connection.assert_not_called()
         connection.handle
@@ -274,8 +274,8 @@ class TestBigQueryAdapterAcquire(BaseTestBigQueryAdapter):
             self.assertEqual(connection.type, 'bigquery')
             self.assertEqual(connection.credentials.maximum_bytes_billed, 0)
 
-        except dbt.exceptions.ValidationException as e:
-            self.fail('got ValidationException: {}'.format(str(e)))
+        except dbt.exceptions.DbtValidationError as e:
+            self.fail('got DbtValidationError: {}'.format(str(e)))
 
         mock_open_connection.assert_not_called()
         connection.handle
@@ -674,10 +674,10 @@ class TestBigQueryAdapter(BaseTestBigQueryAdapter):
     def test_parse_partition_by(self):
         adapter = self.get_adapter('oauth')
 
-        with self.assertRaises(dbt.exceptions.ValidationException):
+        with self.assertRaises(dbt.exceptions.DbtValidationError):
             adapter.parse_partition_by("date(ts)")
 
-        with self.assertRaises(dbt.exceptions.ValidationException):
+        with self.assertRaises(dbt.exceptions.DbtValidationError):
             adapter.parse_partition_by("ts")
 
         self.assertEqual(
@@ -841,7 +841,7 @@ class TestBigQueryAdapter(BaseTestBigQueryAdapter):
         )
 
         # Invalid, should raise an error
-        with self.assertRaises(dbt.exceptions.ValidationException):
+        with self.assertRaises(dbt.exceptions.DbtValidationError):
             adapter.parse_partition_by({})
 
         # passthrough