Skip to content

Commit

Permalink
refactor: OdbcHook must use it's own connection when creating a sqlal…
Browse files Browse the repository at this point in the history
…chemy engine (apache#43145)

Co-authored-by: David Blain <david.blain@infrabel.be>
  • Loading branch information
2 people authored and ellisms committed Nov 13, 2024
1 parent b6fbcee commit f49b90a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions providers/src/airflow/providers/odbc/hooks/odbc.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,19 @@ def connect_kwargs(self) -> dict:

return merged_connect_kwargs

def get_sqlalchemy_engine(self, engine_kwargs=None):
"""
Get an sqlalchemy_engine object.
:param engine_kwargs: Kwargs used in :func:`~sqlalchemy.create_engine`.
:return: the created engine.
"""
if engine_kwargs is None:
engine_kwargs = {}
engine_kwargs["creator"] = self.get_conn

return super().get_sqlalchemy_engine(engine_kwargs)

def get_conn(self) -> Connection:
"""Return ``pyodbc`` connection object."""
conn = connect(self.odbc_connection_string, **self.connect_kwargs)
Expand Down
9 changes: 9 additions & 0 deletions providers/tests/odbc/hooks/test_odbc.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import json
import logging
import sqlite3
from dataclasses import dataclass
from unittest import mock
from unittest.mock import patch
Expand Down Expand Up @@ -340,3 +341,11 @@ def test_query_no_handler_return_none(self):
hook = mock_hook(OdbcHook)
result = hook.run("SQL")
assert result is None

def test_get_sqlalchemy_engine_verify_creator_is_being_used(self):
hook = mock_hook(OdbcHook, conn_params={"extra": {"sqlalchemy_scheme": "sqlite"}})

with sqlite3.connect(":memory:") as connection:
hook.get_conn = lambda: connection
engine = hook.get_sqlalchemy_engine()
assert engine.connect().connection.connection == connection

0 comments on commit f49b90a

Please sign in to comment.