Repository: dbt-labs/dbt-core

Issue:
[CT-1440] [Bug] Connection reused event is not shown
### Is this a new bug in dbt-core?

- [X] I believe this is a new bug in dbt-core
- [X] I have searched the existing issues, and I could not find an existing issue for this bug

### Current Behavior

The connection reused event does not show in the logs: `Re-using an available connection from the pool (formerly {self.conn_name})`

I think this is because [the connection reused event](https://github.com/dbt-labs/dbt-core/blob/9b84b6e2e87f4e6ada4ccc343906749ba013b138/core/dbt/adapters/base/connections.py#L175) is never fired.

I am not completely sure if I am reading the code below correctly, but I think the `ConnectionReused` is misplaced and maybe never reached:

``` python
        conn = self.get_if_exists()
        if conn is None:
            conn = Connection(
                type=Identifier(self.TYPE),
                name=None,
                state=ConnectionState.INIT,
                transaction_open=False,
                handle=None,
                credentials=self.profile.credentials,
            )
            self.set_thread_connection(conn)

        if conn.name == conn_name and conn.state == "open":
            return conn

        fire_event(NewConnection(conn_name=conn_name, conn_type=self.TYPE))

        if conn.state == "open":
            fire_event(ConnectionReused(conn_name=conn_name))
        else:
            conn.handle = LazyHandle(self.open)

        conn.name = conn_name
        return conn
```

I read the following
1. The code fetches an existing connection
2. If no connection exists, it creates a new one and adds the connection to be used later
3. If the connection has the same name and is open, the connection is returned immediately
4. If not, a new connection event is sent
5. Then if the connection is open, a connection reused event is sent
6. Else lazy handler is set
7. Connection is returned

I do not understand why the connection reused event might be sent right after the new connection event is sent. 

Also, I do not understand when this `conn.name == conn_name` evaluates to `False`. When is a different connection name used within the same thread?

### Expected Behavior

``` python
        conn = self.get_if_exists()
        if conn is None:
            conn = Connection(
                type=Identifier(self.TYPE),
                name=None,
                state=ConnectionState.INIT,
                transaction_open=False,
                handle=None,
                credentials=self.profile.credentials,
            )
            self.set_thread_connection(conn)

        if conn.state == ConnectionState.OPEN.
            fire_event(ConnectionReused(conn_name=conn_name))
        else:
            fire_event(NewConnection(conn_name=conn_name, conn_type=self.TYPE))
            conn.handle = LazyHandle(self.open)
            conn.name = conn_name
        return conn
```

### Steps To Reproduce

NA

### Relevant log output

```shell
NA
```


### Environment

```markdown
- OS: NA
- Python: NA
- dbt: v.1.3.0
```


### Which database adapter are you using with dbt?

_No response_

### Additional Context

_No response_


Discussion:
thanks @JCZuurmond! your read on this makes sense to me 

Resolving patch:
diff --git a/core/dbt/adapters/base/connections.py b/core/dbt/adapters/base/connections.py
--- a/core/dbt/adapters/base/connections.py
+++ b/core/dbt/adapters/base/connections.py
@@ -142,44 +142,44 @@ def exception_handler(self, sql: str) -> ContextManager:
         )
 
     def set_connection_name(self, name: Optional[str] = None) -> Connection:
-        conn_name: str
-        if name is None:
-            # if a name isn't specified, we'll re-use a single handle
-            # named 'master'
-            conn_name = "master"
-        else:
-            if not isinstance(name, str):
-                raise dbt.exceptions.CompilerException(
-                    f"For connection name, got {name} - not a string!"
-                )
-            assert isinstance(name, str)
-            conn_name = name
+        """Called by 'acquire_connection' in BaseAdapter, which is called by
+        'connection_named', called by 'connection_for(node)'.
+        Creates a connection for this thread if one doesn't already
+        exist, and will rename an existing connection."""
 
+        conn_name: str = "master" if name is None else name
+
+        # Get a connection for this thread
         conn = self.get_if_exists()
+
+        if conn and conn.name == conn_name and conn.state == "open":
+            # Found a connection and nothing to do, so just return it
+            return conn
+
         if conn is None:
+            # Create a new connection
             conn = Connection(
                 type=Identifier(self.TYPE),
-                name=None,
+                name=conn_name,
                 state=ConnectionState.INIT,
                 transaction_open=False,
                 handle=None,
                 credentials=self.profile.credentials,
             )
-            self.set_thread_connection(conn)
-
-        if conn.name == conn_name and conn.state == "open":
-            return conn
-
-        fire_event(
-            NewConnection(conn_name=conn_name, conn_type=self.TYPE, node_info=get_node_info())
-        )
-
-        if conn.state == "open":
-            fire_event(ConnectionReused(conn_name=conn_name))
-        else:
             conn.handle = LazyHandle(self.open)
+            # Add the connection to thread_connections for this thread
+            self.set_thread_connection(conn)
+            fire_event(
+                NewConnection(conn_name=conn_name, conn_type=self.TYPE, node_info=get_node_info())
+            )
+        else:  # existing connection either wasn't open or didn't have the right name
+            if conn.state != "open":
+                conn.handle = LazyHandle(self.open)
+            if conn.name != conn_name:
+                orig_conn_name: str = conn.name or ""
+                conn.name = conn_name
+                fire_event(ConnectionReused(orig_conn_name=orig_conn_name, conn_name=conn_name))
 
-        conn.name = conn_name
         return conn
 
     @classmethod
diff --git a/core/dbt/events/proto_types.py b/core/dbt/events/proto_types.py
--- a/core/dbt/events/proto_types.py
+++ b/core/dbt/events/proto_types.py
@@ -531,6 +531,7 @@ class ConnectionReused(betterproto.Message):
     """E006"""
 
     conn_name: str = betterproto.string_field(1)
+    orig_conn_name: str = betterproto.string_field(2)
 
 
 @dataclass
diff --git a/core/dbt/events/types.py b/core/dbt/events/types.py
--- a/core/dbt/events/types.py
+++ b/core/dbt/events/types.py
@@ -449,7 +449,7 @@ def code(self):
         return "E006"
 
     def message(self) -> str:
-        return f"Re-using an available connection from the pool (formerly {self.conn_name})"
+        return f"Re-using an available connection from the pool (formerly {self.orig_conn_name}, now {self.conn_name})"
 
 
 @dataclass


Test patch:
diff --git a/tests/functional/logging/test_logging.py b/tests/functional/logging/test_logging.py
--- a/tests/functional/logging/test_logging.py
+++ b/tests/functional/logging/test_logging.py
@@ -1,6 +1,7 @@
 import pytest
 from dbt.tests.util import run_dbt, get_manifest, read_file
 import json
+import os
 
 
 my_model_sql = """
@@ -26,6 +27,7 @@ def test_basic(project, logs_dir):
     assert log_file
     node_start = False
     node_finished = False
+    connection_reused_data = []
     for log_line in log_file.split("\n"):
         # skip empty lines
         if len(log_line) == 0:
@@ -36,6 +38,8 @@ def test_basic(project, logs_dir):
         log_dct = json.loads(log_line)
         log_data = log_dct["data"]
         log_event = log_dct["info"]["name"]
+        if log_event == "ConnectionReused":
+            connection_reused_data.append(log_data)
         if log_event == "NodeStart":
             node_start = True
         if log_event == "NodeFinished":
@@ -50,3 +54,12 @@ def test_basic(project, logs_dir):
             if log_event == "TimingInfoCollected":
                 assert "node_info" in log_data
                 assert "timing_info" in log_data
+
+    # windows doesn't have the same thread/connection flow so the ConnectionReused
+    # events don't show up
+    if os.name != "nt":
+        # Verify the ConnectionReused event occurs and has the right data
+        assert connection_reused_data
+        for data in connection_reused_data:
+            assert "conn_name" in data and data["conn_name"]
+            assert "orig_conn_name" in data and data["orig_conn_name"]