From c6c6305fdab2c261af4cc79233a45e0420d6d23d Mon Sep 17 00:00:00 2001 From: Dinis Louseiro Date: Mon, 16 Sep 2024 16:35:17 +0100 Subject: [PATCH] fix: Fix "Connection is closed" error when using browser authentication (#257) The purpose of this PR is to solve the issue reported [here](https://github.com/MeltanoLabs/target-snowflake/issues/225). ## Root cause: There was one usage of `engine.connect` outside of a context manager (in `create_engine`), causing the connector to leave one connection "lying around". I did not dive too deep into the internals of the connector nor focused too much in understanding why is it different for the browser authentication mechanism, but mostly in ensuring all calls to `engine.connect()` were done within a context manager, ensuring SQL alchemy does its job in closing all connections when they should be closed. ## Implementation details: - Use a context manager when checking if the database exists (in the `create_engine` ) method. --- target_snowflake/connector.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/target_snowflake/connector.py b/target_snowflake/connector.py index 4b7df6e..e78660a 100644 --- a/target_snowflake/connector.py +++ b/target_snowflake/connector.py @@ -192,11 +192,11 @@ def create_engine(self) -> Engine: connect_args=connect_args, echo=False, ) - connection = engine.connect() - db_names = [db[1] for db in connection.execute(text("SHOW DATABASES;")).fetchall()] - if self.config["database"] not in db_names: - msg = f"Database '{self.config['database']}' does not exist or the user/role doesn't have access to it." - raise Exception(msg) # noqa: TRY002 + with engine.connect() as conn: + db_names = [db[1] for db in conn.execute(text("SHOW DATABASES;")).fetchall()] + if self.config["database"] not in db_names: + msg = f"Database '{self.config['database']}' does not exist or the user/role doesn't have access to it." + raise Exception(msg) # noqa: TRY002 return engine def prepare_column(