You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by el...@apache.org on 2026/09/15 05:21:24 UTC
(superset) 01/01: feat(trino): add dynamic connection form for Trino
This is an automated email from the ASF dual-hosted git repository.
eschutho pushed a commit to branch sc-121000-trino-new-form
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 414c518fc126a6ca6ab05cf12c6ec7c5a5f9207a
Author: Elizabeth Thompson <es...@gmail.com>
AuthorDate: Tue Sep 15 05:19:32 2026 +0000
feat(trino): add dynamic connection form for Trino
Add the dynamic ('new') database connection form to TrinoEngineSpec by
mixing in BasicParametersMixin, so /api/v1/database/available/ returns
form parameters (host, port, username, optional password, catalog and an
encryption toggle) instead of the raw SQLAlchemy-URI box.
Trino's SQLAlchemy dialect registers a single 'trino' dialect whose
reported driver is 'rest', so default_driver='rest' is required for the
form to be advertised, but the built URI stays driverless ('trino://...')
since 'trino+rest://' is not a loadable plugin. The catalog maps to the
URI's database component. The encryption toggle is round-tripped through
a 'protocol' query parameter and translated into the 'http_scheme'
connect arg (which the Trino dialect reads) in adjust_engine_params.
Only TrinoEngineSpec is changed; PrestoEngineSpec/presto behavior is
untouched.
Co-Authored-By: Claude Opus 4.8 <no...@anthropic.com>
---
superset/db_engine_specs/trino.py | 84 ++++++++++++-
tests/unit_tests/db_engine_specs/test_trino.py | 156 +++++++++++++++++++++++++
2 files changed, 239 insertions(+), 1 deletion(-)
diff --git a/superset/db_engine_specs/trino.py b/superset/db_engine_specs/trino.py
index d7a7f6e2f09..708f836411e 100644
--- a/superset/db_engine_specs/trino.py
+++ b/superset/db_engine_specs/trino.py
@@ -28,6 +28,7 @@ from typing import Any, Callable, TYPE_CHECKING
import requests
from flask import copy_current_request_context, ctx, current_app as app, Flask, g
from flask_babel import gettext as __
+from marshmallow import fields
from sqlalchemy.engine.reflection import Inspector
from sqlalchemy.engine.url import URL
from sqlalchemy.exc import NoSuchTableError
@@ -38,6 +39,9 @@ from superset.common.db_query_status import QueryStatus
from superset.constants import QUERY_CANCEL_KEY, QUERY_EARLY_CANCEL_KEY
from superset.db_engine_specs.base import (
BaseEngineSpec,
+ BasicParametersMixin,
+ BasicParametersSchema,
+ BasicParametersType,
convert_inspector_columns,
DatabaseCategory,
)
@@ -69,12 +73,39 @@ except ImportError:
HttpError = Exception
-class TrinoEngineSpec(PrestoBaseEngineSpec):
+class TrinoParametersSchema(BasicParametersSchema):
+ # For Trino the "database" component of the SQLAlchemy URI is the catalog:
+ # trino://user[:password]@host:port/<catalog>[/schema]
+ # so relabel the generic "database" field accordingly for the dynamic form.
+ database = fields.String(
+ required=True,
+ metadata={"description": __("Catalog name")},
+ )
+
+
+class TrinoEngineSpec(BasicParametersMixin, PrestoBaseEngineSpec):
engine = "trino"
engine_name = "Trino"
allows_alias_to_source_column = False
supports_grouping_sets = True
+ # Dynamic connection ("new") form. Trino's SQLAlchemy dialect registers a
+ # single ``trino`` dialect whose reported ``driver`` is ``rest``, so
+ # ``default_driver`` must be ``rest`` for ``/api/v1/database/available/`` to
+ # advertise the form. The built URI stays driverless (``trino://...``)
+ # because ``trino+rest://`` is not a loadable SQLAlchemy plugin; see
+ # ``build_sqlalchemy_uri`` below.
+ default_driver = "rest"
+ parameters_schema = TrinoParametersSchema()
+ sqlalchemy_uri_placeholder = "trino://user:password@host:port/catalog[/schema]"
+
+ # The form's encryption toggle maps to Trino's http/https scheme. The Trino
+ # dialect ignores the URI scheme and reads ``http_scheme`` from
+ # ``connect_args`` instead, so the toggle is round-tripped through a
+ # ``protocol`` query parameter (via ``encryption_parameters``) and
+ # translated back into ``connect_args`` in ``adjust_engine_params``.
+ encryption_parameters = {"protocol": "https"}
+
encrypted_extra_sensitive_fields = {
**PrestoBaseEngineSpec.encrypted_extra_sensitive_fields,
"$.oauth2_client_info.secret": "OAuth2 client secret",
@@ -182,6 +213,57 @@ class TrinoEngineSpec(PrestoBaseEngineSpec):
supports_oauth2 = True
oauth2_token_request_type = "data" # noqa: S105
+ @classmethod
+ def build_sqlalchemy_uri(
+ cls,
+ parameters: BasicParametersType,
+ encrypted_extra: dict[str, str] | None = None,
+ ) -> str:
+ """
+ Build the SQLAlchemy URI from the dynamic form parameters.
+
+ Mirrors ``BasicParametersMixin.build_sqlalchemy_uri`` but forces the
+ driverless ``trino`` scheme: ``default_driver`` is ``rest`` only so the
+ connection form is advertised, and ``trino+rest://`` is not a loadable
+ SQLAlchemy dialect.
+ """
+ # make a copy so that we don't update the original
+ query = parameters.get("query", {}).copy()
+ if parameters.get("encryption"):
+ query.update(cls.encryption_parameters)
+
+ return URL.create(
+ cls.engine,
+ username=parameters.get("username"),
+ password=parameters.get("password"),
+ host=parameters["host"],
+ port=parameters["port"],
+ database=parameters["database"],
+ query=query,
+ ).render_as_string(hide_password=False)
+
+ @classmethod
+ def adjust_engine_params(
+ cls,
+ uri: URL,
+ connect_args: dict[str, Any],
+ catalog: str | None = None,
+ schema: str | None = None,
+ ) -> tuple[URL, dict[str, Any]]:
+ # The dynamic form's encryption toggle is stored as a ``protocol`` query
+ # parameter (see ``encryption_parameters``). The Trino dialect reads the
+ # scheme from ``connect_args["http_scheme"]``, not from the URI, so
+ # translate it here and drop the parameter from the URI.
+ if protocol := uri.query.get("protocol"):
+ uri = uri.set(
+ query={
+ key: value for key, value in uri.query.items() if key != "protocol"
+ }
+ )
+ connect_args.setdefault("http_scheme", protocol)
+
+ return super().adjust_engine_params(uri, connect_args, catalog, schema)
+
@classmethod
def needs_oauth2(cls, ex: Exception) -> bool:
"""
diff --git a/tests/unit_tests/db_engine_specs/test_trino.py b/tests/unit_tests/db_engine_specs/test_trino.py
index 0d744d16ae1..9aa867f70bb 100644
--- a/tests/unit_tests/db_engine_specs/test_trino.py
+++ b/tests/unit_tests/db_engine_specs/test_trino.py
@@ -1946,3 +1946,159 @@ def test_impersonate_user_with_token_no_verify_configured() -> None:
connect_args = new_kwargs["connect_args"]
assert "verify" not in connect_args
assert connect_args["http_session"].verify is True
+
+
+def test_default_driver_and_parameters_schema() -> None:
+ """
+ Trino exposes the dynamic connection form via ``BasicParametersMixin``.
+
+ ``default_driver`` must match the driver reported by the Trino SQLAlchemy
+ dialect (``rest``) so ``/api/v1/database/available/`` advertises the form.
+ """
+ from superset.db_engine_specs.base import BasicParametersMixin
+ from superset.db_engine_specs.trino import TrinoEngineSpec, TrinoParametersSchema
+
+ assert issubclass(TrinoEngineSpec, BasicParametersMixin)
+ assert TrinoEngineSpec.default_driver == "rest"
+ assert isinstance(TrinoEngineSpec.parameters_schema, TrinoParametersSchema)
+
+
+def test_build_sqlalchemy_uri_basic() -> None:
+ """
+ ``build_sqlalchemy_uri`` builds a driverless ``trino://`` URI where the
+ ``database`` field is the catalog. ``trino+rest://`` is not a loadable
+ SQLAlchemy dialect, so the driver must not leak into the URI.
+ """
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ uri = TrinoEngineSpec.build_sqlalchemy_uri(
+ {
+ "username": "user",
+ "password": "pass", # noqa: S106
+ "host": "localhost",
+ "port": 8080,
+ "database": "hive",
+ }
+ )
+ assert uri == "trino://user:pass@localhost:8080/hive"
+
+ # The built URI must resolve to a real, loadable dialect.
+ assert make_url(uri).get_dialect() is TrinoDialect
+
+
+def test_build_sqlalchemy_uri_no_password() -> None:
+ """Password is optional for Trino connections."""
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ uri = TrinoEngineSpec.build_sqlalchemy_uri(
+ {
+ "username": "user",
+ "host": "localhost",
+ "port": 8080,
+ "database": "hive",
+ }
+ )
+ assert uri == "trino://user@localhost:8080/hive"
+
+
+def test_build_sqlalchemy_uri_with_encryption() -> None:
+ """The encryption toggle is encoded as a ``protocol=https`` query param."""
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ uri = TrinoEngineSpec.build_sqlalchemy_uri(
+ {
+ "username": "user",
+ "host": "localhost",
+ "port": 443,
+ "database": "hive",
+ "encryption": True,
+ }
+ )
+ assert uri == "trino://user@localhost:443/hive?protocol=https"
+
+
+def test_parameters_uri_round_trip() -> None:
+ """
+ ``get_parameters_from_uri`` and ``build_sqlalchemy_uri`` round-trip,
+ including the encryption toggle.
+ """
+ from superset.db_engine_specs.base import BasicParametersType
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ parameters: BasicParametersType = {
+ "username": "user",
+ "password": "pass", # noqa: S106
+ "host": "localhost",
+ "port": 443,
+ "database": "hive",
+ "encryption": True,
+ }
+ uri = TrinoEngineSpec.build_sqlalchemy_uri(parameters)
+ recovered = TrinoEngineSpec.get_parameters_from_uri(uri)
+
+ assert recovered["username"] == "user"
+ assert recovered["password"] == "pass" # noqa: S105
+ assert recovered["host"] == "localhost"
+ assert recovered["port"] == 443
+ assert recovered["database"] == "hive"
+ assert recovered["encryption"] is True
+ # The encryption marker is not surfaced as an "additional parameter".
+ assert recovered["query"] == {}
+
+
+def test_get_parameters_from_uri_without_encryption() -> None:
+ """A plain ``trino://`` URI reports encryption disabled."""
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ recovered = TrinoEngineSpec.get_parameters_from_uri(
+ "trino://user@localhost:8080/hive"
+ )
+ assert recovered["encryption"] is False
+
+
+def test_adjust_engine_params_encryption_sets_http_scheme() -> None:
+ """
+ The ``protocol`` query param (from the encryption toggle) is translated
+ into the ``http_scheme`` connect arg the Trino dialect reads, and stripped
+ from the URI.
+ """
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ url = make_url("trino://user@localhost:443/hive?protocol=https")
+ connect_args: dict[str, Any] = {}
+
+ uri, connect_args = TrinoEngineSpec.adjust_engine_params(url, connect_args)
+
+ assert connect_args["http_scheme"] == "https"
+ assert "protocol" not in uri.query
+ assert (
+ uri.render_as_string(hide_password=False) == "trino://user@localhost:443/hive"
+ )
+
+
+def test_adjust_engine_params_preserves_existing_http_scheme() -> None:
+ """A pre-existing ``http_scheme`` (e.g. from a server cert) wins."""
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ url = make_url("trino://user@localhost:8080/hive?protocol=https")
+ connect_args: dict[str, Any] = {
+ "http_scheme": "https",
+ "verify": "/path/to/tls.crt",
+ }
+
+ _, connect_args = TrinoEngineSpec.adjust_engine_params(url, connect_args)
+
+ assert connect_args["http_scheme"] == "https"
+
+
+def test_adjust_engine_params_without_protocol_preserves_other_query() -> None:
+ """Non-encryption query params are left untouched when no protocol is set."""
+ from superset.db_engine_specs.trino import TrinoEngineSpec
+
+ url = make_url("trino://user@localhost:8080/hive?source=custom")
+ connect_args: dict[str, Any] = {}
+
+ uri, connect_args = TrinoEngineSpec.adjust_engine_params(url, connect_args)
+
+ assert "http_scheme" not in connect_args
+ assert uri.query.get("source") == "custom"