aminghadersohi commented on code in PR #45843:
URL: https://github.com/apache/superset/pull/45843#discussion_r4417704751


##########
superset/db_engine_specs/databricks.py:
##########
@@ -932,12 +973,22 @@ def adjust_engine_params(
 
         if schema:
             uri = uri.update_query_dict({"schema": schema})
+        elif (
+            "schema" not in uri.query and "schema" not in connect_args and 
uri.database
+        ):
+            # The SQLAlchemy 2 dialect reads schema from the query, not the 
path.
+            uri = uri.update_query_dict({"schema": uri.database})
+
+        # Edits made in the native form take precedence over legacy 
connect_args.
+        for key in ("http_path", "catalog", "schema"):
+            if key in uri.query:
+                connect_args.pop(key, None)

Review Comment:
   Fixed in a7badf30d3372822bba048f750f4babfca640d0a. SQLAlchemy drops empty 
query values, so I reconcile explicitly cleared field values with legacy 
connect_args before building/testing/saving the URI. Only the corresponding 
legacy keys are removed; unrelated settings remain. The hook is shared by 
pre-save validation and both create/update schemas. 
`test_native_form_clear_overrides_legacy_connect_args` covers all three keys 
and `test_databricks_form_clear_catalog_removes_legacy_override` covers the 
real POST and PUT schemas. Required schema/HTTP-path validation is unchanged; 
the optional catalog can be cleared with a freshly entered token when the 
destination changes.
   
   Searched: `rg -n 
'build_sqlalchemy_uri\(|get_extra_from_parameters|adjust_engine_params' 
superset/databases/schemas.py superset/commands/database/validate.py 
superset/db_engine_specs`.
   Siblings checked:
   - superset/db_engine_specs/databricks.py:927 — fixed in 
a7badf30d3372822bba048f750f4babfca640d0a
   - superset/databases/schemas.py:440 — fixed in 
a7badf30d3372822bba048f750f4babfca640d0a
   - superset/commands/database/validate.py:86 — fixed in 
a7badf30d3372822bba048f750f4babfca640d0a
   - superset/db_engine_specs/base.py:3229 — not affected: all other specs 
receive an identity/no-op hook.
   - superset/commands/database/importers/v1/utils.py — not affected: imports 
provide an explicit URI/extra rather than field-form parameters.
   
   Verification: regression selections failed against 
54f95ada005a48e5baa6ca86ea5d6f7501d8837c and pass with 
a7badf30d3372822bba048f750f4babfca640d0a. Focused backend suites: 416 passed, 1 
skipped; picker API test: 1 passed; DatabaseModal/reducer Jest: 94 passed. 
Branch-scoped pre-commit passed, including mypy.
   



##########
superset/migrations/versions/2026-10-29_00-00_b8f3a2c91d64_migrate_databricks_connector_uri.py:
##########
@@ -0,0 +1,176 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Use the SQLAlchemy 2 Databricks dialect for saved legacy connections.
+
+Revision ID: b8f3a2c91d64
+Revises: f72b6e9c104a
+
+Only the URI prefix is rewritten. Credentials live in the separate encrypted
+password column, which this migration never reads or writes. The extra marker
+and a migration-owned fingerprint table limit rollback to unchanged converted 
rows.
+"""
+
+from datetime import datetime
+from hashlib import sha256
+from typing import Any
+
+import sqlalchemy as sa
+from alembic import op
+
+from superset.migrations.shared.utils import create_table, drop_table, 
has_table
+from superset.utils import json
+
+revision = "b8f3a2c91d64"
+down_revision = "f72b6e9c104a"
+
+LEGACY_PREFIX = "databricks+connector://"
+NATIVE_PREFIX = "databricks://"
+MARKER = "migrated_from_databricks_connector_uri"
+BATCH_SIZE = 1000
+
+# Deliberately independent of application models and encrypted column types.
+databases = sa.table(
+    "dbs",
+    sa.column("id", sa.Integer),
+    sa.column("sqlalchemy_uri", sa.String(1024)),
+    sa.column("extra", sa.Text),
+    sa.column("changed_on", sa.DateTime),
+)
+
+
+# Fingerprints avoid copying connection settings or credentials into a backup 
table.
+records = sa.table(
+    "databricks_uri_migration",
+    sa.column("id", sa.Integer),
+    sa.column("fingerprint", sa.String(64)),
+    sa.column("extra_marked", sa.Boolean),
+)
+
+
+def _load_extra(value: str | None) -> dict[str, Any] | None:
+    """Return no object for malformed settings, without replacing their 
text."""
+    try:
+        extra = json.loads(value) if value is not None else None
+    except (ValueError, RecursionError):
+        return None
+    return extra if isinstance(extra, dict) else None
+
+
+def _fingerprint(uri: str, extra: str | None, changed_on: datetime | None) -> 
str:
+    """Recognize the migrated state, including edits to other database 
fields."""
+    state = json.dumps([uri, extra, str(changed_on)])
+    return sha256(state.encode("utf-8")).hexdigest()
+
+
+def _query(upgrading: bool, tracked: bool, last_id: int) -> sa.sql.Select:
+    """Find source URIs or rollback candidates, including exported markers."""
+    query = sa.select(databases).where(databases.c.id > last_id)
+    if upgrading:
+        query = 
query.where(databases.c.sqlalchemy_uri.like(f"{LEGACY_PREFIX}%"))
+    elif tracked:
+        query = (
+            query.add_columns(records.c.fingerprint, records.c.extra_marked)
+            .select_from(databases.outerjoin(records, databases.c.id == 
records.c.id))
+            .where(
+                sa.or_(records.c.id.isnot(None), 
databases.c.extra.like(f"%{MARKER}%"))
+            )
+        )
+    else:
+        query = query.add_columns(
+            sa.literal(None).label("fingerprint"),
+            sa.literal(None).label("extra_marked"),
+        ).where(databases.c.extra.like(f"%{MARKER}%"))
+    return query
+
+
+def _migrate(upgrading: bool) -> None:
+    """Use keyset batches so rewriting the filter cannot skip later rows."""
+    bind = op.get_bind()
+    tracked = has_table(records.name)
+    last_id = -1
+    while True:
+        query = _query(upgrading, tracked, last_id)
+        rows = 
bind.execute(query.order_by(databases.c.id).limit(BATCH_SIZE)).fetchall()
+        if not rows:
+            break
+        for row in rows:
+            last_id = row.id
+            extra = _load_extra(row.extra)
+            uri = row.sqlalchemy_uri
+            extra_text = row.extra
+            if upgrading:
+                # LIKE can be case-insensitive on some metadata databases.
+                if not uri.startswith(LEGACY_PREFIX):
+                    continue
+                uri = NATIVE_PREFIX + uri[len(LEGACY_PREFIX) :]
+                extra_marked = extra is not None and (
+                    MARKER not in extra or extra[MARKER] is True
+                )
+                if extra is not None and extra_marked:
+                    extra[MARKER] = True
+                    extra_text = json.dumps(extra)
+                # Preserve conflicting user settings instead of aborting the 
upgrade.
+                bind.execute(records.delete().where(records.c.id == row.id))
+                bind.execute(
+                    records.insert().values(
+                        id=row.id,
+                        fingerprint=_fingerprint(uri, extra_text, 
row.changed_on),
+                        extra_marked=extra_marked,
+                    )
+                )
+            else:
+                unchanged = row.fingerprint == _fingerprint(
+                    uri, extra_text, row.changed_on
+                )
+                imported = (
+                    row.fingerprint is None
+                    and uri.startswith(NATIVE_PREFIX)
+                    and extra is not None
+                    and extra.get(MARKER) is True
+                )
+                if (unchanged or imported) and uri.startswith(NATIVE_PREFIX):
+                    uri = LEGACY_PREFIX + uri[len(NATIVE_PREFIX) :]
+                if (
+                    (row.extra_marked or imported)
+                    and extra is not None
+                    and extra.get(MARKER) is True
+                ):
+                    del extra[MARKER]
+                    extra_text = json.dumps(extra)
+            bind.execute(
+                databases.update()
+                .where(databases.c.id == row.id)
+                .values(sqlalchemy_uri=uri, extra=extra_text)
+            )

Review Comment:
   Fixed in a7badf30d3372822bba048f750f4babfca640d0a. Both upgrade and 
downgrade updates compare ID, URI, extra, and changed_on with the batch 
snapshot. Upgrade bookkeeping is written only after a successful conditional 
update. `test_migration_preserves_edit_after_batch_read` injects an edit after 
SELECT materialization and covers both directions; the edited row survives and 
a skipped upgrade has no fingerprint record.
   
   Searched: `rg -n 'databases.update|records.insert|_migrate' 
superset/migrations/versions/2026-10-29_00-00_b8f3a2c91d64_migrate_databricks_connector_uri.py`.
   Siblings checked:
   - 
superset/migrations/versions/2026-10-29_00-00_b8f3a2c91d64_migrate_databricks_connector_uri.py:149
 — fixed in a7badf30d3372822bba048f750f4babfca640d0a
   - 
superset/migrations/versions/2026-10-29_00-00_b8f3a2c91d64_migrate_databricks_connector_uri.py:161
 — fixed in a7badf30d3372822bba048f750f4babfca640d0a
   - superset/migrations/shared/utils.py — not affected: the shared calls here 
only create/drop the bookkeeping table, not connection rows.
   
   Verification: regression selections failed against 
54f95ada005a48e5baa6ca86ea5d6f7501d8837c and pass with 
a7badf30d3372822bba048f750f4babfca640d0a. Focused backend suites: 416 passed, 1 
skipped; picker API test: 1 passed; DatabaseModal/reducer Jest: 94 passed. 
Branch-scoped pre-commit passed, including mypy.
   



##########
superset/db_engine_specs/databricks.py:
##########
@@ -897,18 +902,54 @@ def get_parameters_from_uri(  # type: ignore
             "access_token": url.password,
             "host": url.host,
             "port": url.port,
-            "http_path_field": query["http_path"],
-            "default_catalog": query["catalog"],
-            "default_schema": query["schema"],
+            "http_path_field": query.get("http_path", ""),
+            "default_catalog": query.get("catalog", ""),
+            "default_schema": query.get("schema", url.database or ""),
             "encryption": encryption,
         }
 
+    @classmethod
+    def get_parameters_from_database(
+        cls, database: Database, encrypted_extra: dict[str, Any]
+    ) -> dict[str, Any]:
+        """Expose legacy connect_args in the native connector's field-based 
form."""
+        parameters = super().get_parameters_from_database(database, 
encrypted_extra)
+        query = database.url_object.query
+        for field, key in (
+            ("http_path_field", "http_path"),
+            ("default_catalog", "catalog"),
+            ("default_schema", "schema"),
+        ):
+            if key not in query and key in database.connect_args:
+                parameters[field] = database.connect_args[key]
+        return parameters
+
+    @classmethod
+    def get_connection_identity(cls, uri: URL, connect_args: dict[str, Any]) 
-> URL:
+        """
+        Describe legacy connect_args and native query settings identically.
+
+        Mirrors ``adjust_engine_params``: query settings take precedence over
+        connect_args, and the URI path is the schema when neither sets one.
+        """
+        query: dict[str, str | tuple[str, ...]] = {
+            key: str(connect_args[key])
+            for key in ("http_path", "catalog", "schema")
+            if key in connect_args
+        }
+        query.update(uri.query)
+        if "schema" not in query and uri.database:
+            query["schema"] = uri.database
+        return uri._replace(database=None).set(query=query)
+
     @classmethod
     def get_default_catalog(
         cls,
         database: Database,
     ) -> str | None:
-        return database.url_object.query.get("catalog")
+        return database.url_object.query.get("catalog") or 
database.connect_args.get(
+            "catalog"
+        )

Review Comment:
   Fixed in a7badf30d3372822bba048f750f4babfca640d0a. I applied the 
marker-scoped legacy default-catalog fallback. Explicit URI/connect_args 
catalogs still win, and unmarked native rows still return None. 
`test_migrated_default_catalog_preserves_legacy_runtime_default` exercises both 
a single SHOW CATALOGS result and the current_catalog() fallback for a marked 
row whose only connect_arg is http_path.
   
   Searched: `rg -n 'def 
get_default_catalog|migrated_from_databricks_connector_uri' 
superset/db_engine_specs superset/commands/database/update.py 
superset/security`.
   Siblings checked:
   - superset/db_engine_specs/databricks.py:968 — fixed in 
a7badf30d3372822bba048f750f4babfca640d0a
   - superset/db_engine_specs/databricks.py:1143 — not affected: the legacy 
runtime-default implementation is retained and delegated to for marked rows.
   - superset/commands/database/update.py:99 — fixed in 
a7badf30d3372822bba048f750f4babfca640d0a
   - superset/db_engine_specs/postgres.py:905 — not affected: the fallback is 
restricted to the Databricks migration marker.
   - superset/db_engine_specs/snowflake.py:466 — not affected: no Databricks 
marker-specific behavior is applied to other engines.
   
   Verification: regression selections failed against 
54f95ada005a48e5baa6ca86ea5d6f7501d8837c and pass with 
a7badf30d3372822bba048f750f4babfca640d0a. Focused backend suites: 416 passed, 1 
skipped; picker API test: 1 passed; DatabaseModal/reducer Jest: 94 passed. 
Branch-scoped pre-commit passed, including mypy.
   



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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to