dabla commented on code in PR #77423:
URL: https://github.com/apache/airflow/pull/77423#discussion_r4655166406


##########
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

Review Comment:
   **[nit]** `from urllib.parse import …` can move to the top of the module now 
that the lines are being moved anyway.
   
   It is stdlib, so nothing is gained by importing it inside the method. The 
lazy `sqlalchemy.engine.URL` import on L157 is different (optional dependency) 
and should stay where it is.



##########
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)))

Review Comment:
   **[warning]** The drivers call `DbApiHook` methods unbound, with the hook as 
`self`, and "use the default" is spelled three different ways.
   
   Thanks for picking this up, the branching is gone and the hook reads much 
better. One thing in the shape of the driver classes I would still change:
   
   - `DbApiHook.get_uri(hook)` (here), 
`DbApiHook._make_common_data_structure(hook, result)` (L91), 
`DbApiHook.set_autocommit(hook, conn, autocommit)` (L179) and 
`DbApiHook.get_autocommit(hook, conn)` (L182) replace what was `super().…` 
before. The driver now has to know which class the hook inherits from, it 
reaches a protected method of that class (ruff 
[SLF001](https://docs.astral.sh/ruff/rules/private-member-access/)), and the 
call no longer follows the MRO: with `class MyHook(MsSqlHook, SomeDbApiMixin)` 
the mixin's `get_uri` / `set_autocommit` was called before this PR and is 
skipped now. So "no behavior change" holds for `MsSqlHook` itself, not for 
every subclass.
   - The same idea, "nothing special for this driver", is expressed as 
`placeholder = None` (L50), as `sqlalchemy_url()` returning `None` (L66-68), 
and as these explicit calls back into the base class. The hook then needs an 
`if url is None` and an `if driver_placeholder` to undo the first two.
   - Every method takes `hook`, and five of them do not use it or `self` (ruff 
[ARG002](https://docs.astral.sh/ruff/rules/unused-method-argument/) on L66, 
L84, L87, L184; [PLR6301](https://docs.astral.sh/ruff/rules/no-self-use/) on 
most of the others).
   
   All three go away when the default behaviour has one home: a small base 
class for the drivers that holds the plain DB-API behaviour, with each driver 
overriding only what it does differently. `supports_autocommit` is `True` on 
`MsSqlHook`, so the base-class autocommit pair reduces to the two lines below 
and nothing changes:
   
   ```python
   class _DbApiDriver:
       placeholder = "%s"
   
       def set_autocommit(self, conn: Any, autocommit: bool) -> None:
           conn.autocommit = autocommit
   
       def get_autocommit(self, conn: Any) -> bool:
           return getattr(conn, "autocommit", False)
   
       def make_common_data_structure(self, result: Any) -> tuple | list[tuple] 
| None:
           return result
   
   
   class _PymssqlDriver(_DbApiDriver):
       def set_autocommit(self, conn: Any, autocommit: bool) -> None:
           conn.autocommit(autocommit)
   
       def get_autocommit(self, conn: Any) -> bool:
           return conn.autocommit_state
   ```
   
   For the URI, the hook can keep its `super().get_uri()` call and hand the 
result to the driver (`self._driver.rewrite_uri(super().get_uri(), 
self.sqlalchemy_scheme)` or similar), so pymssql rewrites a string and 
mssql-python ignores it and builds its own. `connect` then only needs the 
connection and the schema, not the whole hook.



##########
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:
   **[nit]** `sqlalchemy_url()` and `build_url()` are the same method twice.
   
   `sqlalchemy_url` only returns `self.build_url(hook)`, and `get_uri` calls 
`build_url` too. One method is enough. Note also that on `main` `get_uri()` 
went through the hook's own `self.sqlalchemy_url` property for this driver, so 
a subclass that overrides the property got a matching URI; it now goes straight 
to the driver. `self.sqlalchemy_url.render_as_string(hide_password=False)` in 
the hook's `get_uri` for this driver would keep that.
   
   Small naming point on the same classes: `extras()`, `sqlalchemy_url()` and 
`build_url()` are methods, so a verb reads better (`get_extras`, 
`build_sqlalchemy_url`), as `connect` and `get_uri` already do.



##########
providers/microsoft/mssql/src/airflow/providers/microsoft/mssql/hooks/mssql.py:
##########
@@ -103,27 +244,24 @@ def dbapi_driver(self) -> str:
 
         return driver.lower()
 
+    @cached_property
+    def _driver(self) -> _PymssqlDriver | _MssqlPythonDriver:

Review Comment:
   **[warning]** The two drivers share no declared contract, and the list of 
drivers lives in two places.
   
   The description says a new driver is one new class. As it stands it is also: 
this return annotation (`_PymssqlDriver | _MssqlPythonDriver`, which grows by 
one name per driver), the tuple in `_DRIVERS` (L194), a `DBAPI_DRIVER_*` 
constant and `SUPPORTED_DBAPI_DRIVERS` (L218-220). Nothing tells the author of 
the third class which methods and attributes it must have; a missing one shows 
up at call time.
   
   `dbapi_driver` validates against `SUPPORTED_DBAPI_DRIVERS` while `_driver` 
looks up `_DRIVERS`. These are the same fact kept twice, and they can disagree: 
a subclass that extends the public `SUPPORTED_DBAPI_DRIVERS` passes validation 
and then gets a bare `KeyError` here (on `main` it fell through to the pymssql 
behaviour).
   
   Suggestion: annotate `_driver` with the shared base class from [1] (or a 
[`typing.Protocol`](https://peps.python.org/pep-0544/) if you prefer no 
inheritance), and derive one from the other, e.g. `SUPPORTED_DBAPI_DRIVERS = 
tuple(_DRIVERS)`, with `DBAPI_DRIVER_PYMSSQL` / `DBAPI_DRIVER_MSSQL_PYTHON` 
kept as they are for compatibility. Then a new driver really is one class plus 
one entry.



-- 
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]

Reply via email to