RehanAhmad25 commented on code in PR #77423:
URL: https://github.com/apache/airflow/pull/77423#discussion_r4655776398
##########
providers/microsoft/mssql/src/airflow/providers/microsoft/mssql/hooks/mssql.py:
##########
@@ -37,6 +37,162 @@
from airflow.providers.common.sql.dialects.dialect import Dialect
from airflow.providers.openlineage.sqlparser import DatabaseInfo
+# Connection extras that are handled by the hook itself and must never reach
the DBAPI driver.
+_AIRFLOW_ONLY_EXTRAS = frozenset({"sqlalchemy_scheme", "dbapi_driver"})
+
+
+class _PymssqlDriver:
+ """What ``MsSqlHook`` does differently when ``dbapi_driver`` is
``pymssql`` (the default)."""
+
+ name = "pymssql"
+ default_sqlalchemy_scheme = "mssql+pymssql"
+ # None means the placeholder of ``DbApiHook``.
+ placeholder: str | None = None
+
+ def connect(self, hook: MsSqlHook) -> PymssqlConnection:
+ conn = hook.connection
+ extra_conn_args = {
+ key: val for key, val in conn.extra_dejson.items() if key.lower()
not in _AIRFLOW_ONLY_EXTRAS
+ }
+ return pymssql.connect(
+ server=conn.host or "",
+ user=conn.login,
+ password=conn.password,
+ database=hook.schema or conn.schema or "",
+ port=str(conn.port),
+ **extra_conn_args,
+ )
+
+ def sqlalchemy_url(self, hook: MsSqlHook) -> URL | None:
+ # None means the default of ``DbApiHook``, so the engine is built from
``get_uri()``.
+ return None
+
+ def get_uri(self, hook: MsSqlHook) -> str:
+ from urllib.parse import parse_qs, urlencode, urlsplit, urlunsplit
+
+ r = list(urlsplit(DbApiHook.get_uri(hook)))
+ # change the sqlalchemy driver:
+ r[0] = hook.sqlalchemy_scheme
+ # remove query string parameters that are meant for the hook, not for
the sqlalchemy dialect:
+ qs = parse_qs(r[3], keep_blank_values=True)
+ for k in list(qs.keys()):
+ if k.lower() in _AIRFLOW_ONLY_EXTRAS:
+ qs.pop(k, None)
+ r[3] = urlencode(qs, doseq=True)
+ return urlunsplit(r)
+
+ def set_autocommit(self, hook: MsSqlHook, conn: Any, autocommit: bool) ->
None:
+ conn.autocommit(autocommit)
+
+ def get_autocommit(self, hook: MsSqlHook, conn: Any) -> bool:
+ return conn.autocommit_state
+
+ def make_common_data_structure(self, hook: MsSqlHook, result: Any) ->
tuple | list[tuple] | None:
+ return DbApiHook._make_common_data_structure(hook, result)
+
+
+class _MssqlPythonDriver:
+ """What ``MsSqlHook`` does differently when ``dbapi_driver`` is
``mssql_python``."""
+
+ name = "mssql_python"
+ default_sqlalchemy_scheme = "mssql+mssqlpython"
+ # mssql-python has no plain ``%s`` support.
+ placeholder: str | None = "?"
+ # mssql-python takes every other extra as a connection string keyword, and
the string built from a
+ # SQLAlchemy URL fails on unknown keywords. So the extras that
``DbApiHook`` reads for itself are
+ # filtered out for both the direct connection and the SQLAlchemy URL.
+ ignored_extras = _AIRFLOW_ONLY_EXTRAS | frozenset(
+ {
+ "placeholder",
+ "insert_statement_format",
+ "replace_statement_format",
+ "escape_word_format",
+ "escape_column_names",
+ "dialect",
+ }
+ )
+
+ def extras(self, hook: MsSqlHook) -> dict[str, Any]:
+ """Return the connection extras that are passed on to mssql-python,
without the empty ones."""
+ return {
+ key: val
+ for key, val in hook.connection.extra_dejson.items()
+ if key.lower() not in self.ignored_extras and val not in (None, "")
+ }
+
+ def connect(self, hook: MsSqlHook) -> Any:
+ try:
+ mssql_python = import_module("mssql_python")
+ except ImportError as e:
+ raise AirflowOptionalProviderFeatureException(
+ "The 'mssql_python' dbapi_driver needs the mssql-python
package. Install it with: "
+ "pip install
'apache-airflow-providers-microsoft-mssql[mssql-python]'"
+ ) from e
+
+ conn = hook.connection
+ server = conn.host or ""
+ if server and conn.port:
+ server = f"{server},{conn.port}"
+ params: dict[str, Any] = {
+ "Server": server,
+ "Database": hook.schema or conn.schema,
+ "UID": conn.login,
+ "PWD": conn.password,
+ }
+ params.update(self.extras(hook))
+ # The keyword arguments are escaped by mssql-python when it builds the
connection string.
+ return mssql_python.connect(**{key: val for key, val in params.items()
if val not in (None, "")})
+
+ def sqlalchemy_url(self, hook: MsSqlHook) -> URL | None:
+ return self.build_url(hook)
Review Comment:
Merged into one build_sqlalchemy_url, and extras() is get_extras() now.
get_uri() goes through self.sqlalchemy_url and falls back to the driver on
NotImplementedError, the same way DbApiHook.get_sqlalchemy_engine does, so a
subclass that overrides the property gets a matching URI again:
```python
def get_uri(self) -> str:
try:
url = self.sqlalchemy_url
except NotImplementedError:
return self._driver.rewrite_uri(super().get_uri(),
self.sqlalchemy_scheme)
return url.render_as_string(hide_password=False)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]