You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by mi...@apache.org on 2025/02/12 14:40:55 UTC

(superset) branch 5.0 updated (890186a8e2 -> c6e764ebbe)

This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a change to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git


    from 890186a8e2 chore: Adds RC1 data to CHANGELOG.md and UPDATING.md
     new faae9cc326 chore(timeseries charts): adjust legend width by padding (#32030)
     new deb88e4174 fix: Local tarball Docker container is missing zstd dependency (#32135)
     new 92bc43e38b fix: move oauth2 capture to `get_sqla_engine` (#32137)
     new 923d076603 fix(releasing): fix borked SVN-based image building process (#32151)
     new e67089b5ce fix(migrations): Handle no params in time comparison migration (#32155)
     new 50705e7253 fix: ScreenshotCachePayload serialization (#32156)
     new cbebac9404 fix(docker): Docker python-translation-build (#32163)
     new 8ad24fabc9 fix(virtual dataset sync): Sync virtual dataset columns when changing the SQL query (#30903)
     new 53d05a460d fix(sqllab): correct URL format for SQL Lab permalinks (#32154)
     new ed82e6ac75 fix: Adds an entry to UPDATING.md about DISABLE_LEGACY_DATASOURCE_EDITOR (#32185)
     new d83ae362cf fix: TDengine move tdengine.png to databases/ subfolder (#32176)
     new 9ea2ad5105 fix: handlebars html and css templates reset on dataset update (#32195)
     new 000f2e3780 fix: hidrate datasetsStatus (#32211)
     new 8ba36abc87 fix(SaveDatasetModal): repairs field alignment in the SaveDatasetModal component (#32222)
     new 699d22c5fe fix: set `Rich tooltip` -> 'Show percentage' to false by default (#32212)
     new 8b1de4c12c fix(sqllab): close the table tab (#32224)
     new c6e764ebbe fix(Scope): Correct issue where filters appear out of scope when sort is unchecked. (#32115)

The 17 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 Dockerfile                                         |   8 +-
 RELEASING/Dockerfile.from_local_tarball            |   6 +-
 RELEASING/Dockerfile.from_svn_tarball              |  19 +-
 UPDATING.md                                        |   1 +
 docs/src/resources/data.js                         |   5 +
 docs/static/img/databases/tdengine.png             | Bin 0 -> 32453 bytes
 .../cypress/e2e/explore/control.test.ts            |   4 +-
 superset-frontend/jest.config.js                   |   1 +
 .../superset-ui-chart-controls/src/types.ts        |  13 +
 .../superset-ui-core/src/query/types/Metric.ts     |   4 +-
 .../src/Timeseries/transformProps.ts               |   1 +
 .../plugins/plugin-chart-echarts/src/controls.tsx  |   2 +-
 .../plugin-chart-echarts/src/utils/series.ts       |  22 +-
 .../test/BigNumber/transformProps.test.ts          |   2 +-
 .../src/plugin/controls/handlebarTemplate.tsx      |   1 +
 .../src/plugin/controls/style.tsx                  |   1 +
 .../SqlLab/components/SaveDatasetModal/index.tsx   |  16 +-
 .../SqlLab/components/SouthPane/SouthPane.test.tsx |  24 +-
 .../src/SqlLab/components/SouthPane/index.tsx      |   2 +-
 .../src/components/Datasource/DatasourceEditor.jsx | 136 +---
 .../src/components/Datasource/DatasourceModal.tsx  | 277 ++++----
 .../src/components/Datasource/utils.js             | 102 +++
 superset-frontend/src/components/Tooltip/index.tsx |   8 +-
 superset-frontend/src/dashboard/actions/hydrate.js |   3 +-
 .../components/nativeFilters/state.test.ts         | 126 ++++
 .../dashboard/components/nativeFilters/state.ts    |  25 +-
 .../src/explore/actions/exploreActions.ts          |  16 +
 .../components/controls/TextAreaControl.jsx        |  61 +-
 .../src/explore/reducers/exploreReducer.js         |  18 +
 .../DatabaseConnectionForm/EncryptedField.tsx      |  14 +-
 .../databases/DatabaseModal/index.test.tsx         | 701 ++++++++++-----------
 .../src/features/databases/DatabaseModal/index.tsx |   4 +-
 .../UploadDataModel/UploadDataModal.test.tsx       |   6 +-
 superset-frontend/src/features/datasets/types.ts   |  24 +-
 superset/charts/api.py                             |   4 +-
 superset/dashboards/api.py                         |   4 +-
 ...9123a_update_charts_with_old_time_comparison.py |   8 +
 superset/models/core.py                            |  31 +-
 superset/sqllab/permalink/api.py                   |   2 +-
 superset/utils/oauth2.py                           |  18 +-
 superset/utils/screenshots.py                      |  51 +-
 superset/views/sqllab.py                           |  10 +-
 ...update_charts_with_old_time_comparison__test.py |  12 +
 tests/unit_tests/models/core_test.py               |  98 ++-
 tests/unit_tests/utils/screenshot_test.py          |  22 +-
 45 files changed, 1180 insertions(+), 733 deletions(-)
 create mode 100644 docs/static/img/databases/tdengine.png
 create mode 100644 superset-frontend/src/dashboard/components/nativeFilters/state.test.ts


(superset) 03/17: fix: move oauth2 capture to `get_sqla_engine` (#32137)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 92bc43e38b135bbd4bc1b365dc2f3b5935bb2fab
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Tue Feb 4 18:24:05 2025 -0500

    fix: move oauth2 capture to `get_sqla_engine` (#32137)
    
    (cherry picked from commit c7c3b1b0e99228f261415742469cd4a7f929da7b)
---
 superset/models/core.py              | 31 ++++++------
 superset/utils/oauth2.py             | 18 ++++++-
 tests/unit_tests/models/core_test.py | 98 +++++++++++++++++++++++++++++++++---
 3 files changed, 123 insertions(+), 24 deletions(-)

diff --git a/superset/models/core.py b/superset/models/core.py
index 6f32383ab8..96a1953fae 100755
--- a/superset/models/core.py
+++ b/superset/models/core.py
@@ -84,7 +84,11 @@ from superset.superset_typing import (
 from superset.utils import cache as cache_util, core as utils, json
 from superset.utils.backports import StrEnum
 from superset.utils.core import get_username
-from superset.utils.oauth2 import get_oauth2_access_token, OAuth2ClientConfigSchema
+from superset.utils.oauth2 import (
+    check_for_oauth2,
+    get_oauth2_access_token,
+    OAuth2ClientConfigSchema,
+)
 
 config = app.config
 custom_password_store = config["SQLALCHEMY_CUSTOM_PASSWORD_STORE"]
@@ -451,13 +455,14 @@ class Database(Model, AuditMixinNullable, ImportExportMixin):  # pylint: disable
 
             engine_context_manager = config["ENGINE_CONTEXT_MANAGER"]
             with engine_context_manager(self, catalog, schema):
-                yield self._get_sqla_engine(
-                    catalog=catalog,
-                    schema=schema,
-                    nullpool=nullpool,
-                    source=source,
-                    sqlalchemy_uri=sqlalchemy_uri,
-                )
+                with check_for_oauth2(self):
+                    yield self._get_sqla_engine(
+                        catalog=catalog,
+                        schema=schema,
+                        nullpool=nullpool,
+                        source=source,
+                        sqlalchemy_uri=sqlalchemy_uri,
+                    )
 
     def _get_sqla_engine(  # pylint: disable=too-many-locals  # noqa: C901
         self,
@@ -583,10 +588,9 @@ class Database(Model, AuditMixinNullable, ImportExportMixin):  # pylint: disable
             nullpool=nullpool,
             source=source,
         ) as engine:
-            try:
+            with check_for_oauth2(self):
                 with closing(engine.raw_connection()) as conn:
-                    # pre-session queries are used to set the selected schema and, in the  # noqa: E501
-                    # future, the selected catalog
+                    # pre-session queries are used to set the selected catalog/schema
                     for prequery in self.db_engine_spec.get_prequeries(
                         database=self,
                         catalog=catalog,
@@ -597,11 +601,6 @@ class Database(Model, AuditMixinNullable, ImportExportMixin):  # pylint: disable
 
                     yield conn
 
-            except Exception as ex:
-                if self.is_oauth2_enabled() and self.db_engine_spec.needs_oauth2(ex):
-                    self.db_engine_spec.start_oauth2_dance(self)
-                raise
-
     def get_default_catalog(self) -> str | None:
         """
         Return the default configured catalog for the database.
diff --git a/superset/utils/oauth2.py b/superset/utils/oauth2.py
index 0918f0792a..b93f89c870 100644
--- a/superset/utils/oauth2.py
+++ b/superset/utils/oauth2.py
@@ -17,8 +17,9 @@
 
 from __future__ import annotations
 
+from contextlib import contextmanager
 from datetime import datetime, timedelta, timezone
-from typing import Any, TYPE_CHECKING
+from typing import Any, Iterator, TYPE_CHECKING
 
 import backoff
 import jwt
@@ -32,7 +33,7 @@ from superset.superset_typing import OAuth2ClientConfig, OAuth2State
 
 if TYPE_CHECKING:
     from superset.db_engine_specs.base import BaseEngineSpec
-    from superset.models.core import DatabaseUserOAuth2Tokens
+    from superset.models.core import Database, DatabaseUserOAuth2Tokens
 
 JWT_EXPIRATION = timedelta(minutes=5)
 
@@ -197,3 +198,16 @@ class OAuth2ClientConfigSchema(Schema):
         load_default=lambda: "json",
         validate=validate.OneOf(["json", "data"]),
     )
+
+
+@contextmanager
+def check_for_oauth2(database: Database) -> Iterator[None]:
+    """
+    Run code and check if OAuth2 is needed.
+    """
+    try:
+        yield
+    except Exception as ex:
+        if database.is_oauth2_enabled() and database.db_engine_spec.needs_oauth2(ex):
+            database.db_engine_spec.start_oauth2_dance(database)
+        raise
diff --git a/tests/unit_tests/models/core_test.py b/tests/unit_tests/models/core_test.py
index 5b269fc3ba..50ccde6605 100644
--- a/tests/unit_tests/models/core_test.py
+++ b/tests/unit_tests/models/core_test.py
@@ -558,16 +558,47 @@ def test_get_oauth2_config(app_context: None) -> None:
     }
 
 
-def test_raw_connection_oauth(mocker: MockerFixture) -> None:
+def test_raw_connection_oauth_engine(mocker: MockerFixture) -> None:
     """
     Test that we can start OAuth2 from `raw_connection()` errors.
 
-    Some databases that use OAuth2 need to trigger the flow when the connection is
-    created, rather than when the query runs. This happens when the SQLAlchemy engine
-    URI cannot be built without the user personal token.
+    With OAuth2, some databases will raise an exception when the engine is first created
+    (eg, BigQuery). Others, like, Snowflake, when the connection is created. And
+    finally, GSheets will raise an exception when the query is executed.
 
-    This test verifies that the exception is captured and raised correctly so that the
-    frontend can trigger the OAuth2 dance.
+    This tests verifies that when calling `raw_connection()` the OAuth2 flow is
+    triggered when the engine is created.
+    """
+    g = mocker.patch("superset.db_engine_specs.base.g")
+    g.user = mocker.MagicMock()
+    g.user.id = 42
+
+    database = Database(
+        id=1,
+        database_name="my_db",
+        sqlalchemy_uri="sqlite://",
+        encrypted_extra=json.dumps(oauth2_client_info),
+    )
+    database.db_engine_spec.oauth2_exception = OAuth2Error  # type: ignore
+    _get_sqla_engine = mocker.patch.object(database, "_get_sqla_engine")
+    _get_sqla_engine.side_effect = OAuth2Error("OAuth2 required")
+
+    with pytest.raises(OAuth2RedirectError) as excinfo:
+        with database.get_raw_connection() as conn:
+            conn.cursor()
+    assert str(excinfo.value) == "You don't have permission to access the data."
+
+
+def test_raw_connection_oauth_connection(mocker: MockerFixture) -> None:
+    """
+    Test that we can start OAuth2 from `raw_connection()` errors.
+
+    With OAuth2, some databases will raise an exception when the engine is first created
+    (eg, BigQuery). Others, like, Snowflake, when the connection is created. And
+    finally, GSheets will raise an exception when the query is executed.
+
+    This tests verifies that when calling `raw_connection()` the OAuth2 flow is
+    triggered when the connection is created.
     """
     g = mocker.patch("superset.db_engine_specs.base.g")
     g.user = mocker.MagicMock()
@@ -591,6 +622,40 @@ def test_raw_connection_oauth(mocker: MockerFixture) -> None:
     assert str(excinfo.value) == "You don't have permission to access the data."
 
 
+def test_raw_connection_oauth_execute(mocker: MockerFixture) -> None:
+    """
+    Test that we can start OAuth2 from `raw_connection()` errors.
+
+    With OAuth2, some databases will raise an exception when the engine is first created
+    (eg, BigQuery). Others, like, Snowflake, when the connection is created. And
+    finally, GSheets will raise an exception when the query is executed.
+
+    This tests verifies that when calling `raw_connection()` the OAuth2 flow is
+    triggered when the connection is created.
+    """
+    g = mocker.patch("superset.db_engine_specs.base.g")
+    g.user = mocker.MagicMock()
+    g.user.id = 42
+
+    database = Database(
+        id=1,
+        database_name="my_db",
+        sqlalchemy_uri="sqlite://",
+        encrypted_extra=json.dumps(oauth2_client_info),
+    )
+    database.db_engine_spec.oauth2_exception = OAuth2Error  # type: ignore
+    get_sqla_engine = mocker.patch.object(database, "get_sqla_engine")
+    get_sqla_engine().__enter__().raw_connection().cursor().execute.side_effect = (
+        OAuth2Error("OAuth2 required")
+    )
+
+    with pytest.raises(OAuth2RedirectError) as excinfo:  # noqa: PT012
+        with database.get_raw_connection() as conn:
+            cursor = conn.cursor()
+            cursor.execute("SELECT 1")
+    assert str(excinfo.value) == "You don't have permission to access the data."
+
+
 def test_get_schema_access_for_file_upload() -> None:
     """
     Test the `get_schema_access_for_file_upload` method.
@@ -638,6 +703,27 @@ def test_engine_context_manager(mocker: MockerFixture) -> None:
     )
 
 
+def test_engine_oauth2(mocker: MockerFixture) -> None:
+    """
+    Test that we handle OAuth2 when `create_engine` fails.
+    """
+    database = Database(database_name="my_db", sqlalchemy_uri="trino://")
+    mocker.patch.object(database, "_get_sqla_engine", side_effect=Exception)
+    mocker.patch.object(database, "is_oauth2_enabled", return_value=True)
+    mocker.patch.object(database.db_engine_spec, "needs_oauth2", return_value=True)
+    start_oauth2_dance = mocker.patch.object(
+        database.db_engine_spec,
+        "start_oauth2_dance",
+        side_effect=OAuth2Error("OAuth2 required"),
+    )
+
+    with pytest.raises(OAuth2Error):
+        with database.get_sqla_engine("catalog", "schema"):
+            pass
+
+    start_oauth2_dance.assert_called_with(database)
+
+
 def test_purge_oauth2_tokens(session: Session) -> None:
     """
     Test the `purge_oauth2_tokens` method.


(superset) 10/17: fix: Adds an entry to UPDATING.md about DISABLE_LEGACY_DATASOURCE_EDITOR (#32185)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit ed82e6ac75e3ce9464a37b0da28893d521b4edc6
Author: Michael S. Molina <70...@users.noreply.github.com>
AuthorDate: Fri Feb 7 15:30:18 2025 -0300

    fix: Adds an entry to UPDATING.md about DISABLE_LEGACY_DATASOURCE_EDITOR (#32185)
---
 UPDATING.md | 1 +
 1 file changed, 1 insertion(+)

diff --git a/UPDATING.md b/UPDATING.md
index ee1f15cb3f..eaaea09dc6 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,7 @@ assists people when migrating to a new version.
 
 ## 5.0.0
 
+- [31976](https://github.com/apache/superset/pull/31976) Removed the `DISABLE_LEGACY_DATASOURCE_EDITOR` feature flag. The previous value of the feature flag was `True` and now the feature is permanently removed.
 - [31959](https://github.com/apache/superset/pull/32000) Removes CSV_UPLOAD_MAX_SIZE config, use your web server to control file upload size.
 - [31959](https://github.com/apache/superset/pull/31959) Removes the following endpoints from data uploads: `/api/v1/database/<id>/<file type>_upload` and `/api/v1/database/<file type>_metadata`, in favour of new one (Details on the PR). And simplifies permissions.
 - [31844](https://github.com/apache/superset/pull/31844) The `ALERT_REPORTS_EXECUTE_AS` and `THUMBNAILS_EXECUTE_AS` config parameters have been renamed to `ALERT_REPORTS_EXECUTORS` and `THUMBNAILS_EXECUTORS` respectively. A new config flag `CACHE_WARMUP_EXECUTORS` has also been introduced to be able to control which user is used to execute cache warmup tasks. Finally, the config flag `THUMBNAILS_SELENIUM_USER` has been removed. To use a fixed executor for async tasks, use the new `FixedE [...]


(superset) 16/17: fix(sqllab): close the table tab (#32224)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 8b1de4c12ceb2a6a02f45102be33ef2efc6237a5
Author: JUST.in DO IT <ju...@airbnb.com>
AuthorDate: Tue Feb 11 13:13:47 2025 -0800

    fix(sqllab): close the table tab (#32224)
    
    (cherry picked from commit 937d40cdde45da05a3cda1c50c864910570efd03)
---
 .../SqlLab/components/SouthPane/SouthPane.test.tsx | 24 +++++++++++++++++++++-
 .../src/SqlLab/components/SouthPane/index.tsx      |  2 +-
 2 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/superset-frontend/src/SqlLab/components/SouthPane/SouthPane.test.tsx b/superset-frontend/src/SqlLab/components/SouthPane/SouthPane.test.tsx
index 0d30c46f1e..dbfa9192ec 100644
--- a/superset-frontend/src/SqlLab/components/SouthPane/SouthPane.test.tsx
+++ b/superset-frontend/src/SqlLab/components/SouthPane/SouthPane.test.tsx
@@ -16,12 +16,13 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { render } from 'spec/helpers/testing-library';
+import { render, waitFor, within } from 'spec/helpers/testing-library';
 import SouthPane from 'src/SqlLab/components/SouthPane';
 import '@testing-library/jest-dom';
 import { STATUS_OPTIONS } from 'src/SqlLab/constants';
 import { initialState, table, defaultQueryEditor } from 'src/SqlLab/fixtures';
 import { denormalizeTimestamp } from '@superset-ui/core';
+import userEvent from '@testing-library/user-event';
 
 const mockedProps = {
   queryEditorId: defaultQueryEditor.id,
@@ -49,12 +50,14 @@ const mockState = {
     tables: [
       {
         ...table,
+        id: 't3',
         name: 'table3',
         dataPreviewQueryId: '2g2_iRFMl',
         queryEditorId: defaultQueryEditor.id,
       },
       {
         ...table,
+        id: 't4',
         name: 'table4',
         dataPreviewQueryId: 'erWdqEWPm',
         queryEditorId: defaultQueryEditor.id,
@@ -149,3 +152,22 @@ test('should render tabs for table metadata view', () => {
     expect(tabs[index + 2]).toHaveTextContent(`${schema}.${name}`);
   });
 });
+
+test('should remove tab', async () => {
+  const { getAllByRole } = await render(<SouthPane {...mockedProps} />, {
+    useRedux: true,
+    initialState: mockState,
+  });
+
+  const tabs = getAllByRole('tab');
+  const totalTabs = mockState.sqlLab.tables.length + 2;
+  expect(tabs).toHaveLength(totalTabs);
+  const removeButton = within(tabs[2].parentElement as HTMLElement).getByRole(
+    'button',
+    {
+      name: /remove/,
+    },
+  );
+  userEvent.click(removeButton);
+  await waitFor(() => expect(getAllByRole('tab')).toHaveLength(totalTabs - 1));
+});
diff --git a/superset-frontend/src/SqlLab/components/SouthPane/index.tsx b/superset-frontend/src/SqlLab/components/SouthPane/index.tsx
index dbde83ae9d..fe929cb080 100644
--- a/superset-frontend/src/SqlLab/components/SouthPane/index.tsx
+++ b/superset-frontend/src/SqlLab/components/SouthPane/index.tsx
@@ -136,7 +136,7 @@ const SouthPane = ({
         dispatch(removeTables([table]));
       }
     },
-    [dispatch, queryEditorId],
+    [dispatch, pinnedTables],
   );
 
   return offline ? (


(superset) 02/17: fix: Local tarball Docker container is missing zstd dependency (#32135)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit deb88e4174ada3f40a293bcf4693476193a898ce
Author: Michael S. Molina <70...@users.noreply.github.com>
AuthorDate: Tue Feb 4 16:02:01 2025 -0300

    fix: Local tarball Docker container is missing zstd dependency (#32135)
    
    (cherry picked from commit c64018d42135f36e81d0f630176880572e281dc3)
---
 RELEASING/Dockerfile.from_local_tarball | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/RELEASING/Dockerfile.from_local_tarball b/RELEASING/Dockerfile.from_local_tarball
index 0a2613c182..472f5ef498 100644
--- a/RELEASING/Dockerfile.from_local_tarball
+++ b/RELEASING/Dockerfile.from_local_tarball
@@ -30,7 +30,7 @@ RUN apt-get install -y apt-transport-https apt-utils
 # Install superset dependencies
 # https://superset.apache.org/docs/installation/installing-superset-from-scratch
 RUN apt-get install -y build-essential libssl-dev \
-    libffi-dev python3-dev libsasl2-dev libldap2-dev libxi-dev chromium
+    libffi-dev python3-dev libsasl2-dev libldap2-dev libxi-dev chromium zstd
 
 # Install nodejs for custom build
 # https://nodejs.org/en/download/package-manager/
@@ -64,7 +64,7 @@ RUN pip install --upgrade setuptools pip \
 RUN flask fab babel-compile --target superset/translations
 
 ENV PATH=/home/superset/superset/bin:$PATH \
-    PYTHONPATH=/home/superset/superset/:$PYTHONPATH \
+    PYTHONPATH=/home/superset/superset/ \
     SUPERSET_TESTENV=true
 COPY from_tarball_entrypoint.sh /entrypoint.sh
 ENTRYPOINT ["/entrypoint.sh"]


(superset) 09/17: fix(sqllab): correct URL format for SQL Lab permalinks (#32154)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 53d05a460d2fcba66d4d7cc194496986523e2fd1
Author: Levis Mbote <11...@users.noreply.github.com>
AuthorDate: Fri Feb 7 19:53:29 2025 +0300

    fix(sqllab): correct URL format for SQL Lab permalinks (#32154)
    
    (cherry picked from commit f9f8c5d07a6bf960a597e7ff07d1564f514e8760)
---
 superset/sqllab/permalink/api.py |  2 +-
 superset/views/sqllab.py         | 10 +++++++++-
 2 files changed, 10 insertions(+), 2 deletions(-)

diff --git a/superset/sqllab/permalink/api.py b/superset/sqllab/permalink/api.py
index 35eae9f906..4bdd293414 100644
--- a/superset/sqllab/permalink/api.py
+++ b/superset/sqllab/permalink/api.py
@@ -87,7 +87,7 @@ class SqlLabPermalinkRestApi(BaseSupersetApi):
         try:
             state = self.add_model_schema.load(request.json)
             key = CreateSqlLabPermalinkCommand(state=state).run()
-            url = url_for("SqllabView.root", key=key, _external=True)
+            url = url_for("SqllabView.permalink_view", permalink=key, _external=True)
             return self.response(201, key=key, url=url)
         except ValidationError as ex:
             return self.response(400, message=ex.messages)
diff --git a/superset/views/sqllab.py b/superset/views/sqllab.py
index b34a3af7d4..740b241f13 100644
--- a/superset/views/sqllab.py
+++ b/superset/views/sqllab.py
@@ -37,17 +37,25 @@ class SqllabView(BaseSupersetView):
     method_permission_name = MODEL_API_RW_METHOD_PERMISSION_MAP
 
     @expose("/", methods=["GET", "POST"])
-    @expose("/p/<string:permalink>/", methods=["GET"])
     @has_access
     @permission_name("read")
     @event_logger.log_this
     def root(self, **kwargs: Any) -> FlaskResponse:
+        """Handles the default SQL Lab page."""
         payload = {}
         if form_data := request.form.get("form_data"):
             with contextlib.suppress(json.JSONDecodeError):
                 payload["requested_query"] = json.loads(form_data)
         return self.render_app_template(payload)
 
+    @expose("/p/<string:permalink>/", methods=["GET"])
+    @has_access
+    @permission_name("read")
+    @event_logger.log_this
+    def permalink_view(self, permalink: str, **kwargs: Any) -> FlaskResponse:
+        """Handles permalinks for SQL Lab."""
+        return self.root(permalink=permalink, **kwargs)
+
     @expose("/history/", methods=("GET",))
     @has_access
     @permission_name("read")


(superset) 12/17: fix: handlebars html and css templates reset on dataset update (#32195)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 9ea2ad5105a8f4cb24fb988a1c2a185e07bdb82a
Author: Damian Pendrak <dp...@gmail.com>
AuthorDate: Mon Feb 10 16:40:55 2025 +0100

    fix: handlebars html and css templates reset on dataset update (#32195)
    
    (cherry picked from commit 0f6bd5ea83edeb7e5b15618b63f2a21bcbca76cf)
---
 .../plugin-chart-handlebars/src/plugin/controls/handlebarTemplate.tsx    | 1 +
 .../plugins/plugin-chart-handlebars/src/plugin/controls/style.tsx        | 1 +
 2 files changed, 2 insertions(+)

diff --git a/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/handlebarTemplate.tsx b/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/handlebarTemplate.tsx
index 71b5b9b067..22281f09bf 100644
--- a/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/handlebarTemplate.tsx
+++ b/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/handlebarTemplate.tsx
@@ -65,6 +65,7 @@ export const handlebarsTemplateControlSetItem: ControlSetItem = {
 </ul>`,
     isInt: false,
     renderTrigger: true,
+    valueKey: null,
 
     validators: [validateNonEmpty],
     mapStateToProps: ({ controls }) => ({
diff --git a/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/style.tsx b/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/style.tsx
index b5f8dc9382..9723228146 100644
--- a/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/style.tsx
+++ b/superset-frontend/plugins/plugin-chart-handlebars/src/plugin/controls/style.tsx
@@ -75,6 +75,7 @@ export const styleControlSetItem: ControlSetItem = {
     description: t('CSS applied to the chart'),
     isInt: false,
     renderTrigger: true,
+    valueKey: null,
 
     validators: [],
     mapStateToProps: ({ controls }) => ({


(superset) 17/17: fix(Scope): Correct issue where filters appear out of scope when sort is unchecked. (#32115)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit c6e764ebbeeed36a93d4b57a78a52d744bb14c63
Author: Levis Mbote <11...@users.noreply.github.com>
AuthorDate: Wed Feb 12 16:32:20 2025 +0300

    fix(Scope): Correct issue where filters appear out of scope when sort is unchecked. (#32115)
    
    (cherry picked from commit af3589fe91f369656a19972f08adde28ed731e9e)
---
 .../components/nativeFilters/state.test.ts         | 126 +++++++++++++++++++++
 .../dashboard/components/nativeFilters/state.ts    |  25 ++--
 2 files changed, 144 insertions(+), 7 deletions(-)

diff --git a/superset-frontend/src/dashboard/components/nativeFilters/state.test.ts b/superset-frontend/src/dashboard/components/nativeFilters/state.test.ts
new file mode 100644
index 0000000000..7cd694b4ca
--- /dev/null
+++ b/superset-frontend/src/dashboard/components/nativeFilters/state.test.ts
@@ -0,0 +1,126 @@
+/**
+ * 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.
+ */
+
+import { renderHook } from '@testing-library/react-hooks';
+import { useSelector } from 'react-redux';
+import { NativeFilterType, Filter, Divider } from '@superset-ui/core';
+import { useIsFilterInScope, useSelectFiltersInScope } from './state';
+
+jest.mock('react-redux', () => {
+  const actual = jest.requireActual('react-redux');
+  return {
+    ...actual,
+    useSelector: jest.fn(),
+  };
+});
+
+beforeEach(() => {
+  (useSelector as jest.Mock).mockImplementation(selector => {
+    if (selector.name === 'useActiveDashboardTabs') {
+      return ['TAB_1'];
+    }
+    return [];
+  });
+});
+
+describe('useIsFilterInScope', () => {
+  it('should return true for dividers (always in scope)', () => {
+    const divider: Divider = {
+      id: 'divider_1',
+      type: NativeFilterType.Divider,
+      title: 'Sample Divider',
+      description: 'Divider description',
+    };
+
+    const { result } = renderHook(() => useIsFilterInScope());
+    expect(result.current(divider)).toBe(true);
+  });
+
+  it('should return true for filters with charts in active tabs', () => {
+    const filter: Filter = {
+      id: 'filter_1',
+      name: 'Test Filter',
+      filterType: 'filter_select',
+      type: NativeFilterType.NativeFilter,
+      chartsInScope: [123],
+      scope: { rootPath: ['TAB_1'], excluded: [] },
+      controlValues: {},
+      defaultDataMask: {},
+      cascadeParentIds: [],
+      targets: [{ column: { name: 'column_name' }, datasetId: 1 }],
+      description: 'Sample filter description',
+    };
+
+    const { result } = renderHook(() => useIsFilterInScope());
+    expect(result.current(filter)).toBe(true);
+  });
+
+  it('should return false for filters with inactive rootPath', () => {
+    const filter: Filter = {
+      id: 'filter_3',
+      name: 'Test Filter 3',
+      filterType: 'filter_select',
+      type: NativeFilterType.NativeFilter,
+      scope: { rootPath: ['TAB_99'], excluded: [] },
+      controlValues: {},
+      defaultDataMask: {},
+      cascadeParentIds: [],
+      targets: [{ column: { name: 'column_name' }, datasetId: 3 }],
+      description: 'Sample filter description',
+    };
+
+    const { result } = renderHook(() => useIsFilterInScope());
+    expect(result.current(filter)).toBe(false);
+  });
+});
+
+describe('useSelectFiltersInScope', () => {
+  it('should return all filters in scope when no tabs exist', () => {
+    const filters: Filter[] = [
+      {
+        id: 'filter_1',
+        name: 'Filter 1',
+        filterType: 'filter_select',
+        type: NativeFilterType.NativeFilter,
+        scope: { rootPath: [], excluded: [] },
+        controlValues: {},
+        defaultDataMask: {},
+        cascadeParentIds: [],
+        targets: [{ column: { name: 'column_name' }, datasetId: 1 }],
+        description: 'Sample filter description',
+      },
+      {
+        id: 'filter_2',
+        name: 'Filter 2',
+        filterType: 'filter_select',
+        type: NativeFilterType.NativeFilter,
+        scope: { rootPath: [], excluded: [] },
+        controlValues: {},
+        defaultDataMask: {},
+        cascadeParentIds: [],
+        targets: [{ column: { name: 'column_name' }, datasetId: 2 }],
+        description: 'Sample filter description',
+      },
+    ];
+
+    const { result } = renderHook(() => useSelectFiltersInScope(filters));
+    expect(result.current[0]).toEqual(filters);
+    expect(result.current[1]).toEqual([]);
+  });
+});
diff --git a/superset-frontend/src/dashboard/components/nativeFilters/state.ts b/superset-frontend/src/dashboard/components/nativeFilters/state.ts
index 498fcf9a77..3404107498 100644
--- a/superset-frontend/src/dashboard/components/nativeFilters/state.ts
+++ b/superset-frontend/src/dashboard/components/nativeFilters/state.ts
@@ -106,16 +106,27 @@ export function useIsFilterInScope() {
   // Chart is in an active tab tree if all of its ancestors of type TAB are active
   // Dividers are always in scope
   return useCallback(
-    (filter: Filter | Divider) =>
-      isFilterDivider(filter) ||
-      ('chartsInScope' in filter &&
-        filter.chartsInScope?.some((chartId: number) => {
+    (filter: Filter | Divider) => {
+      if (isFilterDivider(filter)) return true;
+
+      const isChartInScope =
+        Array.isArray(filter.chartsInScope) &&
+        filter.chartsInScope.length > 0 &&
+        filter.chartsInScope.some((chartId: number) => {
           const tabParents = selectChartTabParents(chartId);
           return (
-            tabParents?.length === 0 ||
-            tabParents?.every(tab => activeTabs.includes(tab))
+            !tabParents ||
+            tabParents.length === 0 ||
+            tabParents.every(tab => activeTabs.includes(tab))
           );
-        })),
+        });
+
+      const isFilterInActiveTab =
+        filter.scope?.rootPath &&
+        filter.scope.rootPath.some(tab => activeTabs.includes(tab));
+
+      return isChartInScope || isFilterInActiveTab;
+    },
     [selectChartTabParents, activeTabs],
   );
 }


(superset) 01/17: chore(timeseries charts): adjust legend width by padding (#32030)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit faae9cc32616e6da459059354404a099eea1d5c0
Author: Elizabeth Thompson <es...@gmail.com>
AuthorDate: Mon Feb 3 14:11:09 2025 -0800

    chore(timeseries charts): adjust legend width by padding (#32030)
    
    (cherry picked from commit 8984f88a3e1c2843dea00230263ea6323ef83308)
---
 .../superset-ui-chart-controls/src/types.ts        |  7 +++++++
 .../src/Timeseries/transformProps.ts               |  1 +
 .../plugin-chart-echarts/src/utils/series.ts       | 22 ++++++++++++++++++++--
 3 files changed, 28 insertions(+), 2 deletions(-)

diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
index 09667004a5..a53a45de35 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
@@ -515,6 +515,13 @@ export enum SortSeriesType {
   Avg = 'avg',
 }
 
+export type LegendPaddingType = {
+  top?: number;
+  bottom?: number;
+  left?: number;
+  right?: number;
+};
+
 export type SortSeriesData = {
   sort_series_type: SortSeriesType;
   sort_series_ascending: boolean;
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts
index 219df879e7..0fb392a12d 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/Timeseries/transformProps.ts
@@ -622,6 +622,7 @@ export default function transformProps(
         theme,
         zoomable,
         legendState,
+        padding,
       ),
       data: legendData as string[],
     },
diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts b/superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts
index 0aa0ae988e..bbf222a2a5 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/utils/series.ts
@@ -33,7 +33,7 @@ import {
   TimeFormatter,
   ValueFormatter,
 } from '@superset-ui/core';
-import { SortSeriesType } from '@superset-ui/chart-controls';
+import { SortSeriesType, LegendPaddingType } from '@superset-ui/chart-controls';
 import { format } from 'echarts/core';
 import type { LegendComponentOption } from 'echarts/components';
 import type { SeriesOption } from 'echarts';
@@ -425,6 +425,7 @@ export function getLegendProps(
   theme: SupersetTheme,
   zoomable = false,
   legendState?: LegendState,
+  padding?: LegendPaddingType,
 ): LegendComponentOption | LegendComponentOption[] {
   const legend: LegendComponentOption | LegendComponentOption[] = {
     orient: [LegendOrientation.Top, LegendOrientation.Bottom].includes(
@@ -443,13 +444,30 @@ export function getLegendProps(
       borderColor: theme.colors.grayscale.base,
     },
   };
+  const MIN_LEGEND_WIDTH = 0;
+  const MARGIN_GUTTER = 45;
+  const getLegendWidth = (paddingWidth: number) =>
+    Math.max(paddingWidth - MARGIN_GUTTER, MIN_LEGEND_WIDTH);
+
   switch (orientation) {
     case LegendOrientation.Left:
       legend.left = 0;
+      if (padding?.left) {
+        legend.textStyle = {
+          overflow: 'truncate',
+          width: getLegendWidth(padding.left),
+        };
+      }
       break;
     case LegendOrientation.Right:
       legend.right = 0;
       legend.top = zoomable ? TIMESERIES_CONSTANTS.legendRightTopOffset : 0;
+      if (padding?.right) {
+        legend.textStyle = {
+          overflow: 'truncate',
+          width: getLegendWidth(padding.right),
+        };
+      }
       break;
     case LegendOrientation.Bottom:
       legend.bottom = 0;
@@ -467,7 +485,7 @@ export function getChartPadding(
   show: boolean,
   orientation: LegendOrientation,
   margin?: string | number | null,
-  padding?: { top?: number; bottom?: number; left?: number; right?: number },
+  padding?: LegendPaddingType,
   isHorizontal?: boolean,
 ): {
   bottom: number;


(superset) 04/17: fix(releasing): fix borked SVN-based image building process (#32151)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 923d076603edb6aef34b1afe26105f80d5fd2779
Author: Đỗ Trọng Hải <41...@users.noreply.github.com>
AuthorDate: Wed Feb 5 23:06:21 2025 +0700

    fix(releasing): fix borked SVN-based image building process (#32151)
    
    Signed-off-by: hainenber <do...@gmail.com>
    (cherry picked from commit ea5879bf2b976efb6fbe7f805f0407091fbed75a)
---
 RELEASING/Dockerfile.from_local_tarball |  2 +-
 RELEASING/Dockerfile.from_svn_tarball   | 19 ++++++++++---------
 2 files changed, 11 insertions(+), 10 deletions(-)

diff --git a/RELEASING/Dockerfile.from_local_tarball b/RELEASING/Dockerfile.from_local_tarball
index 472f5ef498..6240439050 100644
--- a/RELEASING/Dockerfile.from_local_tarball
+++ b/RELEASING/Dockerfile.from_local_tarball
@@ -35,7 +35,7 @@ RUN apt-get install -y build-essential libssl-dev \
 # Install nodejs for custom build
 # https://nodejs.org/en/download/package-manager/
 RUN set -eux; \
-    curl -sL https://deb.nodesource.com/setup_18.x | bash -; \
+    curl -sL https://deb.nodesource.com/setup_20.x | bash -; \
     apt-get install -y nodejs; \
     node --version;
 RUN if ! which npm; then apt-get install -y npm; fi
diff --git a/RELEASING/Dockerfile.from_svn_tarball b/RELEASING/Dockerfile.from_svn_tarball
index 22883552ca..f14754c690 100644
--- a/RELEASING/Dockerfile.from_svn_tarball
+++ b/RELEASING/Dockerfile.from_svn_tarball
@@ -29,13 +29,16 @@ RUN apt-get install -y apt-transport-https apt-utils
 
 # Install superset dependencies
 # https://superset.apache.org/docs/installation/installing-superset-from-scratch
-RUN apt-get install -y build-essential libssl-dev \
-    libffi-dev python3-dev libsasl2-dev libldap2-dev libxi-dev chromium
+RUN apt-get install -y subversion build-essential libssl-dev \
+    libffi-dev python3-dev libsasl2-dev libldap2-dev libxi-dev chromium zstd
 
 # Install nodejs for custom build
 # https://nodejs.org/en/download/package-manager/
-RUN curl -sL https://deb.nodesource.com/setup_16.x | bash - \
-    && apt-get install -y nodejs
+RUN set -eux; \
+    curl -sL https://deb.nodesource.com/setup_20.x | bash -; \
+    apt-get install -y nodejs; \
+    node --version;
+RUN if ! which npm; then apt-get install -y npm; fi
 
 RUN mkdir -p /home/superset
 RUN chown superset /home/superset
@@ -46,14 +49,12 @@ ARG VERSION
 # Can fetch source from svn or copy tarball from local mounted directory
 RUN svn co https://dist.apache.org/repos/dist/dev/superset/$VERSION ./
 RUN tar -xvf *.tar.gz
-WORKDIR apache-superset-$VERSION
+WORKDIR /home/superset/apache-superset-$VERSION/superset-frontend
 
-RUN cd superset-frontend \
-    && npm ci \
+RUN npm ci \
     && npm run build \
     && rm -rf node_modules
 
-
 WORKDIR /home/superset/apache-superset-$VERSION
 RUN pip install --upgrade setuptools pip \
     && pip install -r requirements/base.txt \
@@ -62,6 +63,6 @@ RUN pip install --upgrade setuptools pip \
 RUN flask fab babel-compile --target superset/translations
 
 ENV PATH=/home/superset/superset/bin:$PATH \
-    PYTHONPATH=/home/superset/superset/:$PYTHONPATH
+    PYTHONPATH=/home/superset/superset/
 COPY from_tarball_entrypoint.sh /entrypoint.sh
 ENTRYPOINT ["/entrypoint.sh"]


(superset) 05/17: fix(migrations): Handle no params in time comparison migration (#32155)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit e67089b5ce2e133e7bc4d239d74816047076cf18
Author: Antonio Rivero <38...@users.noreply.github.com>
AuthorDate: Wed Feb 5 23:00:22 2025 +0100

    fix(migrations): Handle no params in time comparison migration (#32155)
    
    (cherry picked from commit 6ed9dae2f7c32602b152f476a89f82afe72eebc2)
---
 ...02_f84fde59123a_update_charts_with_old_time_comparison.py |  8 ++++++++
 ...fde59123a_update_charts_with_old_time_comparison__test.py | 12 ++++++++++++
 2 files changed, 20 insertions(+)

diff --git a/superset/migrations/versions/2024-05-10_18-02_f84fde59123a_update_charts_with_old_time_comparison.py b/superset/migrations/versions/2024-05-10_18-02_f84fde59123a_update_charts_with_old_time_comparison.py
index 57acaee9ef..b6f975dd02 100644
--- a/superset/migrations/versions/2024-05-10_18-02_f84fde59123a_update_charts_with_old_time_comparison.py
+++ b/superset/migrations/versions/2024-05-10_18-02_f84fde59123a_update_charts_with_old_time_comparison.py
@@ -63,6 +63,8 @@ time_map = {
 
 
 def upgrade_comparison_params(slice_params: dict[str, Any]) -> dict[str, Any]:
+    if not slice_params or not isinstance(slice_params, dict):
+        return {}
     params = deepcopy(slice_params)
 
     # Update time_comparison to time_compare
@@ -103,6 +105,8 @@ def upgrade():
         )
     ):
         try:
+            if not slc.params:  # Noop if there's no params on the slice
+                continue
             params = json.loads(slc.params)
             updated_slice_params = upgrade_comparison_params(params)
             slc.params = json.dumps(updated_slice_params)
@@ -119,6 +123,8 @@ def upgrade():
 
 
 def downgrade_comparison_params(slice_params: dict[str, Any]) -> dict[str, Any]:
+    if not slice_params or not isinstance(slice_params, dict):
+        return {}
     params = deepcopy(slice_params)
     params["enable_time_comparison"] = False
 
@@ -199,6 +205,8 @@ def downgrade():
         )
     ):
         try:
+            if not slc.params:  # Noop if there's no params on the slice
+                continue
             params = json.loads(slc.params)
             updated_slice_params = downgrade_comparison_params(params)
             slc.params = json.dumps(updated_slice_params)
diff --git a/tests/integration_tests/migrations/f84fde59123a_update_charts_with_old_time_comparison__test.py b/tests/integration_tests/migrations/f84fde59123a_update_charts_with_old_time_comparison__test.py
index cec6a636c5..a9f343b950 100644
--- a/tests/integration_tests/migrations/f84fde59123a_update_charts_with_old_time_comparison__test.py
+++ b/tests/integration_tests/migrations/f84fde59123a_update_charts_with_old_time_comparison__test.py
@@ -229,3 +229,15 @@ def test_downgrade_chart_params_other_than_custom_false():
     original_params = deepcopy(params_v2_other_than_custom_false)
     downgraded_params = downgrade_comparison_params(original_params)
     assert downgraded_params == params_v1_other_than_custom_false
+
+
+def test_upgrade_chart_params_empty():
+    """
+    Ensure that the migration does not fail when params is None or empty.
+    """
+    assert upgrade_comparison_params(None) == {}
+    assert upgrade_comparison_params({}) == {}
+    assert upgrade_comparison_params("") == {}
+    assert downgrade_comparison_params(None) == {}
+    assert downgrade_comparison_params({}) == {}
+    assert downgrade_comparison_params("") == {}


(superset) 13/17: fix: hidrate datasetsStatus (#32211)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 000f2e3780fa60f3882f24f3e5e645df280d9d41
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Tue Feb 11 09:50:45 2025 -0500

    fix: hidrate datasetsStatus (#32211)
    
    (cherry picked from commit eec54affc352f34bcaaab914df456dcc147dc6b2)
---
 superset-frontend/src/dashboard/actions/hydrate.js | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/superset-frontend/src/dashboard/actions/hydrate.js b/superset-frontend/src/dashboard/actions/hydrate.js
index 55754b1c27..693e208fea 100644
--- a/superset-frontend/src/dashboard/actions/hydrate.js
+++ b/superset-frontend/src/dashboard/actions/hydrate.js
@@ -310,7 +310,8 @@ export const hydrateDashboard =
           isRefreshing: false,
           isFiltersRefreshing: false,
           activeTabs: activeTabs || dashboardState?.activeTabs || [],
-          datasetsStatus: ResourceStatus.Loading,
+          datasetsStatus:
+            dashboardState?.datasetsStatus || ResourceStatus.Loading,
         },
         dashboardLayout,
       },


(superset) 08/17: fix(virtual dataset sync): Sync virtual dataset columns when changing the SQL query (#30903)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 8ad24fabc9ea7507add52c6f56e0f9dd098f9841
Author: Jack <41...@users.noreply.github.com>
AuthorDate: Fri Feb 7 11:16:44 2025 -0600

    fix(virtual dataset sync): Sync virtual dataset columns when changing the SQL query (#30903)
    
    Co-authored-by: Kamil Gabryjelski <ka...@gmail.com>
    (cherry picked from commit f3e7c64de636a2fd287abdc04e6a7bec0fa12f53)
---
 .../cypress/e2e/explore/control.test.ts            |   4 +-
 superset-frontend/jest.config.js                   |   1 +
 .../superset-ui-chart-controls/src/types.ts        |   6 +
 .../superset-ui-core/src/query/types/Metric.ts     |   4 +-
 .../test/BigNumber/transformProps.test.ts          |   2 +-
 .../src/components/Datasource/DatasourceEditor.jsx | 136 +---
 .../src/components/Datasource/DatasourceModal.tsx  | 277 ++++----
 .../src/components/Datasource/utils.js             | 102 +++
 superset-frontend/src/components/Tooltip/index.tsx |   8 +-
 .../src/explore/actions/exploreActions.ts          |  16 +
 .../components/controls/TextAreaControl.jsx        |  61 +-
 .../src/explore/reducers/exploreReducer.js         |  18 +
 .../DatabaseConnectionForm/EncryptedField.tsx      |  14 +-
 .../databases/DatabaseModal/index.test.tsx         | 701 ++++++++++-----------
 .../src/features/databases/DatabaseModal/index.tsx |   4 +-
 .../UploadDataModel/UploadDataModal.test.tsx       |   6 +-
 superset-frontend/src/features/datasets/types.ts   |  24 +-
 17 files changed, 734 insertions(+), 650 deletions(-)

diff --git a/superset-frontend/cypress-base/cypress/e2e/explore/control.test.ts b/superset-frontend/cypress-base/cypress/e2e/explore/control.test.ts
index b68d828ba8..c792a310ef 100644
--- a/superset-frontend/cypress-base/cypress/e2e/explore/control.test.ts
+++ b/superset-frontend/cypress-base/cypress/e2e/explore/control.test.ts
@@ -51,8 +51,8 @@ describe('Datasource control', () => {
     )
       .first()
       .focus();
-    cy.focused().clear();
-    cy.focused().type(`${newMetricName}{enter}`);
+    cy.focused().clear({ force: true });
+    cy.focused().type(`${newMetricName}{enter}`, { force: true });
 
     cy.get('[data-test="datasource-modal-save"]').click();
     cy.get('.antd5-modal-confirm-btns button').contains('OK').click();
diff --git a/superset-frontend/jest.config.js b/superset-frontend/jest.config.js
index 07553d889e..13d07aa198 100644
--- a/superset-frontend/jest.config.js
+++ b/superset-frontend/jest.config.js
@@ -75,4 +75,5 @@ module.exports = {
       },
     ],
   ],
+  testTimeout: 10000,
 };
diff --git a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
index a53a45de35..62ac944688 100644
--- a/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
+++ b/superset-frontend/packages/superset-ui-chart-controls/src/types.ts
@@ -84,6 +84,12 @@ export interface Dataset {
   filter_select?: boolean;
   filter_select_enabled?: boolean;
   column_names?: string[];
+  catalog?: string;
+  schema?: string;
+  table_name?: string;
+  database?: Record<string, unknown>;
+  normalize_columns?: boolean;
+  always_filter_main_dttm?: boolean;
 }
 
 export interface ControlPanelState {
diff --git a/superset-frontend/packages/superset-ui-core/src/query/types/Metric.ts b/superset-frontend/packages/superset-ui-core/src/query/types/Metric.ts
index 227ca6e71d..229852373a 100644
--- a/superset-frontend/packages/superset-ui-core/src/query/types/Metric.ts
+++ b/superset-frontend/packages/superset-ui-core/src/query/types/Metric.ts
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { Maybe, QueryFormMetric } from '../../types';
+import { Currency, Maybe, QueryFormMetric } from '../../types';
 import { Column } from './Column';
 
 export type Aggregate =
@@ -65,7 +65,7 @@ export interface Metric {
   certification_details?: Maybe<string>;
   certified_by?: Maybe<string>;
   d3format?: Maybe<string>;
-  currency?: Maybe<string>;
+  currency?: Maybe<Currency>;
   description?: Maybe<string>;
   is_certified?: boolean;
   verbose_name?: string;
diff --git a/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts b/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts
index 8c9ee5621c..8b0bf35525 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts
+++ b/superset-frontend/plugins/plugin-chart-echarts/test/BigNumber/transformProps.test.ts
@@ -173,7 +173,7 @@ describe('BigNumberWithTrendline', () => {
               label: 'value',
               metric_name: 'value',
               d3format: '.2f',
-              currency: `{symbol: 'USD', symbolPosition: 'prefix' }`,
+              currency: { symbol: 'USD', symbolPosition: 'prefix' },
             },
           ],
         },
diff --git a/superset-frontend/src/components/Datasource/DatasourceEditor.jsx b/superset-frontend/src/components/Datasource/DatasourceEditor.jsx
index d30b67ad2a..fae0270828 100644
--- a/superset-frontend/src/components/Datasource/DatasourceEditor.jsx
+++ b/superset-frontend/src/components/Datasource/DatasourceEditor.jsx
@@ -23,7 +23,6 @@ import { Radio } from 'src/components/Radio';
 import Card from 'src/components/Card';
 import Alert from 'src/components/Alert';
 import Badge from 'src/components/Badge';
-import { nanoid } from 'nanoid';
 import {
   css,
   isFeatureEnabled,
@@ -57,6 +56,7 @@ import CurrencyControl from 'src/explore/components/controls/CurrencyControl';
 import CollectionTable from './CollectionTable';
 import Fieldset from './Fieldset';
 import Field from './Field';
+import { fetchSyncedColumns, updateColumns } from './utils';
 
 const DatasourceContainer = styled.div`
   .change-warning {
@@ -140,6 +140,14 @@ const StyledButtonWrapper = styled.span`
   `}
 `;
 
+const sqlTooltipOptions = {
+  placement: 'topRight',
+  title: t(
+    'If changes are made to your SQL query, ' +
+      'columns in your dataset will be synced when saving the dataset.',
+  ),
+};
+
 const checkboxGenerator = (d, onChange) => (
   <CheckboxControl value={d} onChange={onChange} />
 );
@@ -694,116 +702,27 @@ class DatasourceEditor extends PureComponent {
     });
   }
 
-  updateColumns(cols) {
-    // cols: Array<{column_name: string; is_dttm: boolean; type: string;}>
-    const { databaseColumns } = this.state;
-    const databaseColumnNames = cols.map(col => col.column_name);
-    const currentCols = databaseColumns.reduce(
-      (agg, col) => ({
-        ...agg,
-        [col.column_name]: col,
-      }),
-      {},
-    );
-    const finalColumns = [];
-    const results = {
-      added: [],
-      modified: [],
-      removed: databaseColumns
-        .map(col => col.column_name)
-        .filter(col => !databaseColumnNames.includes(col)),
-    };
-    cols.forEach(col => {
-      const currentCol = currentCols[col.column_name];
-      if (!currentCol) {
-        // new column
-        finalColumns.push({
-          id: nanoid(),
-          column_name: col.column_name,
-          type: col.type,
-          groupby: true,
-          filterable: true,
-          is_dttm: col.is_dttm,
-        });
-        results.added.push(col.column_name);
-      } else if (
-        currentCol.type !== col.type ||
-        (!currentCol.is_dttm && col.is_dttm)
-      ) {
-        // modified column
-        finalColumns.push({
-          ...currentCol,
-          type: col.type,
-          is_dttm: currentCol.is_dttm || col.is_dttm,
-        });
-        results.modified.push(col.column_name);
-      } else {
-        // unchanged
-        finalColumns.push(currentCol);
-      }
-    });
-    if (
-      results.added.length ||
-      results.modified.length ||
-      results.removed.length
-    ) {
-      this.setColumns({ databaseColumns: finalColumns });
-    }
-    return results;
-  }
-
-  syncMetadata() {
+  async syncMetadata() {
     const { datasource } = this.state;
-    const params = {
-      datasource_type: datasource.type || datasource.datasource_type,
-      database_name:
-        datasource.database.database_name || datasource.database.name,
-      catalog_name: datasource.catalog,
-      schema_name: datasource.schema,
-      table_name: datasource.table_name,
-      normalize_columns: datasource.normalize_columns,
-      always_filter_main_dttm: datasource.always_filter_main_dttm,
-    };
-    Object.entries(params).forEach(([key, value]) => {
-      // rison can't encode the undefined value
-      if (value === undefined) {
-        params[key] = null;
-      }
-    });
-    const endpoint = `/datasource/external_metadata_by_name/?q=${rison.encode_uri(
-      params,
-    )}`;
     this.setState({ metadataLoading: true });
-
-    SupersetClient.get({ endpoint })
-      .then(({ json }) => {
-        const results = this.updateColumns(json);
-        if (results.modified.length) {
-          this.props.addSuccessToast(
-            t('Modified columns: %s', results.modified.join(', ')),
-          );
-        }
-        if (results.removed.length) {
-          this.props.addSuccessToast(
-            t('Removed columns: %s', results.removed.join(', ')),
-          );
-        }
-        if (results.added.length) {
-          this.props.addSuccessToast(
-            t('New columns added: %s', results.added.join(', ')),
-          );
-        }
-        this.props.addSuccessToast(t('Metadata has been synced'));
-        this.setState({ metadataLoading: false });
-      })
-      .catch(response =>
-        getClientErrorObject(response).then(({ error, statusText }) => {
-          this.props.addDangerToast(
-            error || statusText || t('An error has occurred'),
-          );
-          this.setState({ metadataLoading: false });
-        }),
+    try {
+      const newCols = await fetchSyncedColumns(datasource);
+      const columnChanges = updateColumns(
+        datasource.columns,
+        newCols,
+        this.props.addSuccessToast,
       );
+      this.setColumns({ databaseColumns: columnChanges.finalColumns });
+      this.props.addSuccessToast(t('Metadata has been synced'));
+      this.setState({ metadataLoading: false });
+    } catch (error) {
+      const { error: clientError, statusText } =
+        await getClientErrorObject(error);
+      this.props.addDangerToast(
+        clientError || statusText || t('An error has occurred'),
+      );
+      this.setState({ metadataLoading: false });
+    }
   }
 
   findDuplicates(arr, accessor) {
@@ -1146,6 +1065,7 @@ class DatasourceEditor extends PureComponent {
                         maxLines={Infinity}
                         readOnly={!this.state.isEditMode}
                         resize="both"
+                        tooltipOptions={sqlTooltipOptions}
                       />
                     }
                   />
diff --git a/superset-frontend/src/components/Datasource/DatasourceModal.tsx b/superset-frontend/src/components/Datasource/DatasourceModal.tsx
index 78483771d3..33cd820677 100644
--- a/superset-frontend/src/components/Datasource/DatasourceModal.tsx
+++ b/superset-frontend/src/components/Datasource/DatasourceModal.tsx
@@ -17,11 +17,11 @@
  * under the License.
  */
 import { FunctionComponent, useState, useRef } from 'react';
+import { useDispatch, useSelector } from 'react-redux';
 import Alert from 'src/components/Alert';
 import Button from 'src/components/Button';
 import {
   isDefined,
-  Metric,
   styled,
   SupersetClient,
   getClientErrorObject,
@@ -33,7 +33,16 @@ import Modal from 'src/components/Modal';
 import AsyncEsmComponent from 'src/components/AsyncEsmComponent';
 import ErrorMessageWithStackTrace from 'src/components/ErrorMessage/ErrorMessageWithStackTrace';
 import withToasts from 'src/components/MessageToasts/withToasts';
-import { useSelector } from 'react-redux';
+import {
+  startMetaDataLoading,
+  stopMetaDataLoading,
+  syncDatasourceMetadata,
+} from 'src/explore/actions/exploreActions';
+import {
+  fetchSyncedColumns,
+  updateColumns,
+} from 'src/components/Datasource/utils';
+import { DatasetObject } from '../../features/datasets/types';
 
 const DatasourceEditor = AsyncEsmComponent(() => import('./DatasourceEditor'));
 
@@ -60,14 +69,17 @@ const StyledDatasourceModal = styled(Modal)`
 
 interface DatasourceModalProps {
   addSuccessToast: (msg: string) => void;
-  datasource: any;
+  addDangerToast: (msg: string) => void;
+  datasource: DatasetObject;
   onChange: () => {};
   onDatasourceSave: (datasource: object, errors?: Array<any>) => {};
   onHide: () => {};
   show: boolean;
 }
 
-function buildExtraJsonObject(item: Record<string, unknown>) {
+function buildExtraJsonObject(
+  item: DatasetObject['metrics'][0] | DatasetObject['columns'][0],
+) {
   const certification =
     item?.certified_by || item?.certification_details
       ? {
@@ -83,18 +95,14 @@ function buildExtraJsonObject(item: Record<string, unknown>) {
 
 const DatasourceModal: FunctionComponent<DatasourceModalProps> = ({
   addSuccessToast,
+  addDangerToast,
   datasource,
   onDatasourceSave,
   onHide,
   show,
 }) => {
-  const [currentDatasource, setCurrentDatasource] = useState({
-    ...datasource,
-    metrics: datasource?.metrics?.map((metric: Metric) => ({
-      ...metric,
-      currency: JSON.parse(metric.currency || 'null'),
-    })),
-  });
+  const dispatch = useDispatch();
+  const [currentDatasource, setCurrentDatasource] = useState(datasource);
   const currencies = useSelector<
     {
       common: {
@@ -108,130 +116,145 @@ const DatasourceModal: FunctionComponent<DatasourceModalProps> = ({
   const [isEditing, setIsEditing] = useState<boolean>(false);
   const dialog = useRef<any>(null);
   const [modal, contextHolder] = Modal.useModal();
-
-  const onConfirmSave = () => {
+  const buildPayload = (datasource: Record<string, any>) => ({
+    table_name: datasource.table_name,
+    database_id: datasource.database?.id,
+    sql: datasource.sql,
+    filter_select_enabled: datasource.filter_select_enabled,
+    fetch_values_predicate: datasource.fetch_values_predicate,
+    schema:
+      datasource.tableSelector?.schema ||
+      datasource.databaseSelector?.schema ||
+      datasource.schema,
+    description: datasource.description,
+    main_dttm_col: datasource.main_dttm_col,
+    normalize_columns: datasource.normalize_columns,
+    always_filter_main_dttm: datasource.always_filter_main_dttm,
+    offset: datasource.offset,
+    default_endpoint: datasource.default_endpoint,
+    cache_timeout:
+      datasource.cache_timeout === '' ? null : datasource.cache_timeout,
+    is_sqllab_view: datasource.is_sqllab_view,
+    template_params: datasource.template_params,
+    extra: datasource.extra,
+    is_managed_externally: datasource.is_managed_externally,
+    external_url: datasource.external_url,
+    metrics: datasource?.metrics?.map((metric: DatasetObject['metrics'][0]) => {
+      const metricBody: any = {
+        expression: metric.expression,
+        description: metric.description,
+        metric_name: metric.metric_name,
+        metric_type: metric.metric_type,
+        d3format: metric.d3format || null,
+        currency: !isDefined(metric.currency)
+          ? null
+          : JSON.stringify(metric.currency),
+        verbose_name: metric.verbose_name,
+        warning_text: metric.warning_text,
+        uuid: metric.uuid,
+        extra: buildExtraJsonObject(metric),
+      };
+      if (!Number.isNaN(Number(metric.id))) {
+        metricBody.id = metric.id;
+      }
+      return metricBody;
+    }),
+    columns: datasource?.columns?.map(
+      (column: DatasetObject['columns'][0]) => ({
+        id: typeof column.id === 'number' ? column.id : undefined,
+        column_name: column.column_name,
+        type: column.type,
+        advanced_data_type: column.advanced_data_type,
+        verbose_name: column.verbose_name,
+        description: column.description,
+        expression: column.expression,
+        filterable: column.filterable,
+        groupby: column.groupby,
+        is_active: column.is_active,
+        is_dttm: column.is_dttm,
+        python_date_format: column.python_date_format || null,
+        uuid: column.uuid,
+        extra: buildExtraJsonObject(column),
+      }),
+    ),
+    owners: datasource.owners.map(
+      (o: Record<string, number>) => o.value || o.id,
+    ),
+  });
+  const onConfirmSave = async () => {
     // Pull out extra fields into the extra object
-    const schema =
-      currentDatasource.tableSelector?.schema ||
-      currentDatasource.databaseSelector?.schema ||
-      currentDatasource.schema;
-
     setIsSaving(true);
-    SupersetClient.put({
-      endpoint: `/api/v1/dataset/${currentDatasource.id}`,
-      jsonPayload: {
-        table_name: currentDatasource.table_name,
-        database_id: currentDatasource.database?.id,
-        sql: currentDatasource.sql,
-        filter_select_enabled: currentDatasource.filter_select_enabled,
-        fetch_values_predicate: currentDatasource.fetch_values_predicate,
-        schema,
-        description: currentDatasource.description,
-        main_dttm_col: currentDatasource.main_dttm_col,
-        normalize_columns: currentDatasource.normalize_columns,
-        always_filter_main_dttm: currentDatasource.always_filter_main_dttm,
-        offset: currentDatasource.offset,
-        default_endpoint: currentDatasource.default_endpoint,
-        cache_timeout:
-          currentDatasource.cache_timeout === ''
-            ? null
-            : currentDatasource.cache_timeout,
-        is_sqllab_view: currentDatasource.is_sqllab_view,
-        template_params: currentDatasource.template_params,
-        extra: currentDatasource.extra,
-        is_managed_externally: currentDatasource.is_managed_externally,
-        external_url: currentDatasource.external_url,
-        metrics: currentDatasource?.metrics?.map(
-          (metric: Record<string, unknown>) => {
-            const metricBody: any = {
-              expression: metric.expression,
-              description: metric.description,
-              metric_name: metric.metric_name,
-              metric_type: metric.metric_type,
-              d3format: metric.d3format || null,
-              currency: !isDefined(metric.currency)
-                ? null
-                : JSON.stringify(metric.currency),
-              verbose_name: metric.verbose_name,
-              warning_text: metric.warning_text,
-              uuid: metric.uuid,
-              extra: buildExtraJsonObject(metric),
-            };
-            if (!Number.isNaN(Number(metric.id))) {
-              metricBody.id = metric.id;
-            }
-            return metricBody;
-          },
-        ),
-        columns: currentDatasource?.columns?.map(
-          (column: Record<string, unknown>) => ({
-            id: typeof column.id === 'number' ? column.id : undefined,
-            column_name: column.column_name,
-            type: column.type,
-            advanced_data_type: column.advanced_data_type,
-            verbose_name: column.verbose_name,
-            description: column.description,
-            expression: column.expression,
-            filterable: column.filterable,
-            groupby: column.groupby,
-            is_active: column.is_active,
-            is_dttm: column.is_dttm,
-            python_date_format: column.python_date_format || null,
-            uuid: column.uuid,
-            extra: buildExtraJsonObject(column),
-          }),
-        ),
-        owners: currentDatasource.owners.map(
-          (o: Record<string, number>) => o.value || o.id,
-        ),
-      },
-    })
-      .then(() => {
-        addSuccessToast(t('The dataset has been saved'));
-        return SupersetClient.get({
-          endpoint: `/api/v1/dataset/${currentDatasource?.id}`,
-        });
-      })
-      .then(({ json }) => {
-        // eslint-disable-next-line no-param-reassign
-        json.result.type = 'table';
-        onDatasourceSave({
-          ...json.result,
-          owners: currentDatasource.owners,
-        });
-        onHide();
-      })
-      .catch(response => {
-        setIsSaving(false);
-        getClientErrorObject(response).then(error => {
-          let errorResponse: SupersetError | undefined;
-          let errorText: string | undefined;
-          // sip-40 error response
-          if (error?.errors?.length) {
-            errorResponse = error.errors[0];
-          } else if (typeof error.error === 'string') {
-            // backward compatible with old error messages
-            errorText = error.error;
-          }
-          modal.error({
-            title: t('Error saving dataset'),
-            okButtonProps: { danger: true, className: 'btn-danger' },
-            content: (
-              <ErrorMessageWithStackTrace
-                error={errorResponse}
-                source="crud"
-                fallback={errorText}
-              />
-            ),
-          });
+    try {
+      await SupersetClient.put({
+        endpoint: `/api/v1/dataset/${currentDatasource.id}`,
+        jsonPayload: buildPayload(currentDatasource),
+      });
+      if (datasource.sql !== currentDatasource.sql) {
+        // if sql has changed, save a second time with synced columns
+        dispatch(startMetaDataLoading());
+        try {
+          const columnJson = await fetchSyncedColumns(currentDatasource);
+          const columnChanges = updateColumns(
+            currentDatasource.columns,
+            columnJson,
+            addSuccessToast,
+          );
+          currentDatasource.columns = columnChanges.finalColumns;
+          dispatch(syncDatasourceMetadata(currentDatasource));
+          dispatch(stopMetaDataLoading());
+          addSuccessToast(t('Metadata has been synced'));
+        } catch (error) {
+          dispatch(stopMetaDataLoading());
+          addDangerToast(
+            t('An error has occurred while syncing virtual dataset columns'),
+          );
+        }
+        await SupersetClient.put({
+          endpoint: `/api/v1/dataset/${currentDatasource.id}`,
+          jsonPayload: buildPayload(currentDatasource),
         });
+      }
+      const { json } = await SupersetClient.get({
+        endpoint: `/api/v1/dataset/${currentDatasource?.id}`,
+      });
+      addSuccessToast(t('The dataset has been saved'));
+      // eslint-disable-next-line no-param-reassign
+      json.result.type = 'table';
+      onDatasourceSave({
+        ...json.result,
+        owners: currentDatasource.owners,
+      });
+      onHide();
+    } catch (response) {
+      setIsSaving(false);
+      const error = await getClientErrorObject(response);
+      let errorResponse: SupersetError | undefined;
+      let errorText: string | undefined;
+      // sip-40 error response
+      if (error?.errors?.length) {
+        errorResponse = error.errors[0];
+      } else if (typeof error.error === 'string') {
+        // backward compatible with old error messages
+        errorText = error.error;
+      }
+      modal.error({
+        title: t('Error saving dataset'),
+        okButtonProps: { danger: true, className: 'btn-danger' },
+        content: (
+          <ErrorMessageWithStackTrace
+            error={errorResponse}
+            source="crud"
+            fallback={errorText}
+          />
+        ),
       });
+    }
   };
 
-  const onDatasourceChange = (data: Record<string, any>, err: Array<any>) => {
+  const onDatasourceChange = (data: DatasetObject, err: Array<any>) => {
     setCurrentDatasource({
       ...data,
-      metrics: data?.metrics.map((metric: Record<string, unknown>) => ({
+      metrics: data?.metrics.map((metric: DatasetObject['metrics'][0]) => ({
         ...metric,
         is_certified: metric?.certified_by || metric?.certification_details,
       })),
diff --git a/superset-frontend/src/components/Datasource/utils.js b/superset-frontend/src/components/Datasource/utils.js
index ccdb1b414a..001a1a30b7 100644
--- a/superset-frontend/src/components/Datasource/utils.js
+++ b/superset-frontend/src/components/Datasource/utils.js
@@ -17,6 +17,9 @@
  * under the License.
  */
 import { Children, cloneElement } from 'react';
+import { nanoid } from 'nanoid';
+import { SupersetClient, tn } from '@superset-ui/core';
+import rison from 'rison';
 
 export function recurseReactClone(children, type, propExtender) {
   /**
@@ -40,3 +43,102 @@ export function recurseReactClone(children, type, propExtender) {
     return newChild;
   });
 }
+
+export function updateColumns(prevCols, newCols, addSuccessToast) {
+  // cols: Array<{column_name: string; is_dttm: boolean; type: string;}>
+  const databaseColumnNames = newCols.map(col => col.column_name);
+  const currentCols = prevCols.reduce((agg, col) => {
+    // eslint-disable-next-line no-param-reassign
+    agg[col.column_name] = col;
+    return agg;
+  }, {});
+  const columnChanges = {
+    added: [],
+    modified: [],
+    removed: prevCols
+      .map(col => col.column_name)
+      .filter(col => !databaseColumnNames.includes(col)),
+    finalColumns: [],
+  };
+  newCols.forEach(col => {
+    const currentCol = currentCols[col.column_name];
+    if (!currentCol) {
+      // new column
+      columnChanges.finalColumns.push({
+        id: nanoid(),
+        column_name: col.column_name,
+        type: col.type,
+        groupby: true,
+        filterable: true,
+        is_dttm: col.is_dttm,
+      });
+      columnChanges.added.push(col.column_name);
+    } else if (
+      currentCol.type !== col.type ||
+      currentCol.is_dttm !== col.is_dttm
+    ) {
+      // modified column
+      columnChanges.finalColumns.push({
+        ...currentCol,
+        type: col.type,
+        is_dttm: currentCol.is_dttm || col.is_dttm,
+      });
+      columnChanges.modified.push(col.column_name);
+    } else {
+      // unchanged
+      columnChanges.finalColumns.push(currentCol);
+    }
+  });
+  if (columnChanges.modified.length) {
+    addSuccessToast(
+      tn(
+        'Modified 1 column in the virtual dataset',
+        'Modified %s columns in the virtual dataset',
+        columnChanges.modified.length,
+      ),
+    );
+  }
+  if (columnChanges.removed.length) {
+    addSuccessToast(
+      tn(
+        'Removed 1 column from the virtual dataset',
+        'Removed %s columns from the virtual dataset',
+        columnChanges.removed.length,
+      ),
+    );
+  }
+  if (columnChanges.added.length) {
+    addSuccessToast(
+      tn(
+        'Added 1 new column to the virtual dataset',
+        'Added %s new columns to the virtual dataset',
+        columnChanges.added.length,
+      ),
+    );
+  }
+  return columnChanges;
+}
+
+export async function fetchSyncedColumns(datasource) {
+  const params = {
+    datasource_type: datasource.type,
+    database_name:
+      datasource.database?.database_name || datasource.database?.name,
+    catalog_name: datasource.catalog,
+    schema_name: datasource.schema,
+    table_name: datasource.table_name,
+    normalize_columns: datasource.normalize_columns,
+    always_filter_main_dttm: datasource.always_filter_main_dttm,
+  };
+  Object.entries(params).forEach(([key, value]) => {
+    // rison can't encode the undefined value
+    if (value === undefined) {
+      params[key] = null;
+    }
+  });
+  const endpoint = `/datasource/external_metadata_by_name/?q=${rison.encode_uri(
+    params,
+  )}`;
+  const { json } = await SupersetClient.get({ endpoint });
+  return json;
+}
diff --git a/superset-frontend/src/components/Tooltip/index.tsx b/superset-frontend/src/components/Tooltip/index.tsx
index de5eef4b40..252aac3402 100644
--- a/superset-frontend/src/components/Tooltip/index.tsx
+++ b/superset-frontend/src/components/Tooltip/index.tsx
@@ -18,13 +18,9 @@
  */
 import { supersetTheme } from '@superset-ui/core';
 import { Tooltip as AntdTooltip } from 'antd-v5';
-import {
-  TooltipProps as AntdTooltipProps,
-  TooltipPlacement as AntdTooltipPlacement,
-} from 'antd-v5/lib/tooltip';
+import { TooltipProps, TooltipPlacement } from 'antd-v5/lib/tooltip';
 
-export type TooltipPlacement = AntdTooltipPlacement;
-export type TooltipProps = AntdTooltipProps;
+export { TooltipProps, TooltipPlacement };
 
 export const Tooltip = ({ overlayStyle, ...props }: TooltipProps) => (
   <>
diff --git a/superset-frontend/src/explore/actions/exploreActions.ts b/superset-frontend/src/explore/actions/exploreActions.ts
index da702ac16f..25b03ec9f2 100644
--- a/superset-frontend/src/explore/actions/exploreActions.ts
+++ b/superset-frontend/src/explore/actions/exploreActions.ts
@@ -164,6 +164,21 @@ export function setStashFormData(
   };
 }
 
+export const START_METADATA_LOADING = 'START_METADATA_LOADING';
+export function startMetaDataLoading() {
+  return { type: START_METADATA_LOADING };
+}
+
+export const STOP_METADATA_LOADING = 'STOP_METADATA_LOADING';
+export function stopMetaDataLoading() {
+  return { type: STOP_METADATA_LOADING };
+}
+
+export const SYNC_DATASOURCE_METADATA = 'SYNC_DATASOURCE_METADATA';
+export function syncDatasourceMetadata(datasource: Dataset) {
+  return { type: SYNC_DATASOURCE_METADATA, datasource };
+}
+
 export const exploreActions = {
   ...toastActions,
   fetchDatasourcesStarted,
@@ -178,6 +193,7 @@ export const exploreActions = {
   createNewSlice,
   sliceUpdated,
   setForceQuery,
+  syncDatasourceMetadata,
 };
 
 export type ExploreActions = typeof exploreActions;
diff --git a/superset-frontend/src/explore/components/controls/TextAreaControl.jsx b/superset-frontend/src/explore/components/controls/TextAreaControl.jsx
index fc0545d8c4..e8f165c8e1 100644
--- a/superset-frontend/src/explore/components/controls/TextAreaControl.jsx
+++ b/superset-frontend/src/explore/components/controls/TextAreaControl.jsx
@@ -19,6 +19,10 @@
 import { Component } from 'react';
 import PropTypes from 'prop-types';
 import { TextArea } from 'src/components/Input';
+import {
+  Tooltip,
+  TooltipProps as TooltipOptions,
+} from 'src/components/Tooltip';
 import { t, withTheme } from '@superset-ui/core';
 
 import Button from 'src/components/Button';
@@ -55,6 +59,7 @@ const propTypes = {
     'vertical',
   ]),
   textAreaStyles: PropTypes.object,
+  tooltipOptions: PropTypes.oneOf([null, TooltipOptions]),
 };
 
 const defaultProps = {
@@ -67,6 +72,7 @@ const defaultProps = {
   readOnly: false,
   resize: null,
   textAreaStyles: {},
+  tooltipOptions: {},
 };
 
 class TextAreaControl extends Component {
@@ -94,31 +100,44 @@ class TextAreaControl extends Component {
       if (this.props.readOnly) {
         style.backgroundColor = '#f2f2f2';
       }
+      const codeEditor = (
+        <div>
+          <TextAreaEditor
+            mode={this.props.language}
+            style={style}
+            minLines={minLines}
+            maxLines={inModal ? 1000 : this.props.maxLines}
+            editorProps={{ $blockScrolling: true }}
+            defaultValue={this.props.initialValue}
+            readOnly={this.props.readOnly}
+            key={this.props.name}
+            {...this.props}
+            onChange={this.onAreaEditorChange.bind(this)}
+          />
+        </div>
+      );
+
+      if (this.props.tooltipOptions) {
+        return <Tooltip {...this.props.tooltipOptions}>{codeEditor}</Tooltip>;
+      }
+      return codeEditor;
+    }
 
-      return (
-        <TextAreaEditor
-          mode={this.props.language}
-          style={style}
-          minLines={minLines}
-          maxLines={inModal ? 1000 : this.props.maxLines}
-          editorProps={{ $blockScrolling: true }}
+    const textArea = (
+      <div>
+        <TextArea
+          placeholder={t('textarea')}
+          onChange={this.onControlChange.bind(this)}
           defaultValue={this.props.initialValue}
-          readOnly={this.props.readOnly}
-          key={this.props.name}
-          {...this.props}
-          onChange={this.onAreaEditorChange.bind(this)}
+          disabled={this.props.readOnly}
+          style={{ height: this.props.height }}
         />
-      );
-    }
-    return (
-      <TextArea
-        placeholder={t('textarea')}
-        onChange={this.onControlChange.bind(this)}
-        defaultValue={this.props.initialValue}
-        disabled={this.props.readOnly}
-        style={{ height: this.props.height }}
-      />
+      </div>
     );
+    if (this.props.tooltipOptions) {
+      return <Tooltip {...this.props.tooltipOptions}>{textArea}</Tooltip>;
+    }
+    return textArea;
   }
 
   renderModalBody() {
diff --git a/superset-frontend/src/explore/reducers/exploreReducer.js b/superset-frontend/src/explore/reducers/exploreReducer.js
index 377a66d5b5..2677c1e3ff 100644
--- a/superset-frontend/src/explore/reducers/exploreReducer.js
+++ b/superset-frontend/src/explore/reducers/exploreReducer.js
@@ -50,6 +50,24 @@ export default function exploreReducer(state = {}, action) {
         isDatasourceMetaLoading: true,
       };
     },
+    [actions.START_METADATA_LOADING]() {
+      return {
+        ...state,
+        isDatasourceMetaLoading: true,
+      };
+    },
+    [actions.STOP_METADATA_LOADING]() {
+      return {
+        ...state,
+        isDatasourceMetaLoading: false,
+      };
+    },
+    [actions.SYNC_DATASOURCE_METADATA]() {
+      return {
+        ...state,
+        datasource: action.datasource,
+      };
+    },
     [actions.UPDATE_FORM_DATA_BY_DATASOURCE]() {
       const newFormData = { ...state.form_data };
       const { prevDatasource, newDatasource } = action;
diff --git a/superset-frontend/src/features/databases/DatabaseModal/DatabaseConnectionForm/EncryptedField.tsx b/superset-frontend/src/features/databases/DatabaseModal/DatabaseConnectionForm/EncryptedField.tsx
index 147b983c45..ad80699802 100644
--- a/superset-frontend/src/features/databases/DatabaseModal/DatabaseConnectionForm/EncryptedField.tsx
+++ b/superset-frontend/src/features/databases/DatabaseModal/DatabaseConnectionForm/EncryptedField.tsx
@@ -16,7 +16,7 @@
  * specific language governing permissions and limitations
  * under the License.
  */
-import { useState } from 'react';
+import { useRef, useState } from 'react';
 import { SupersetTheme, t } from '@superset-ui/core';
 import { Button, AntdSelect } from 'src/components';
 import InfoTooltip from 'src/components/InfoTooltip';
@@ -46,6 +46,7 @@ export const EncryptedField = ({
   db,
   editNewDb,
 }: FieldPropTypes) => {
+  const selectedFileInputRef = useRef<HTMLInputElement | null>(null);
   const [uploadOption, setUploadOption] = useState<number>(
     CredentialInfoOptions.JsonUpload.valueOf(),
   );
@@ -152,9 +153,7 @@ export const EncryptedField = ({
             {!fileToUpload && (
               <Button
                 className="input-upload-btn"
-                onClick={() =>
-                  document?.getElementById('selectedFile')?.click()
-                }
+                onClick={() => selectedFileInputRef.current?.click()}
               >
                 {t('Choose File')}
               </Button>
@@ -178,6 +177,7 @@ export const EncryptedField = ({
             )}
 
             <input
+              ref={selectedFileInputRef}
               id="selectedFile"
               accept=".json"
               className="input-upload"
@@ -196,9 +196,9 @@ export const EncryptedField = ({
                     checked: false,
                   },
                 });
-                (
-                  document.getElementById('selectedFile') as HTMLInputElement
-                ).value = null as any;
+                if (selectedFileInputRef.current) {
+                  selectedFileInputRef.current.value = null as any;
+                }
               }}
             />
           </div>
diff --git a/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx b/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx
index b6b3e208bd..5c109a1c4e 100644
--- a/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx
+++ b/superset-frontend/src/features/databases/DatabaseModal/index.test.tsx
@@ -21,14 +21,7 @@
 
 import fetchMock from 'fetch-mock';
 import userEvent from '@testing-library/user-event';
-import {
-  render,
-  screen,
-  within,
-  cleanup,
-  act,
-  waitFor,
-} from 'spec/helpers/testing-library';
+import { render, screen, within, waitFor } from 'spec/helpers/testing-library';
 import { getExtensionsRegistry } from '@superset-ui/core';
 import setupExtensions from 'src/setup/setupExtensions';
 import * as hooks from 'src/views/CRUD/hooks';
@@ -37,6 +30,7 @@ import DatabaseModal, {
   dbReducer,
   DBReducerActionType,
   ActionType,
+  DatabaseModalProps,
 } from './index';
 
 jest.mock('@superset-ui/core', () => ({
@@ -64,279 +58,281 @@ const AVAILABLE_DB_ENDPOINT = 'glob:*/api/v1/database/available*';
 const VALIDATE_PARAMS_ENDPOINT = 'glob:*/api/v1/database/validate_parameters*';
 const DATABASE_CONNECT_ENDPOINT = 'glob:*/api/v1/database/';
 
-fetchMock.post(DATABASE_CONNECT_ENDPOINT, {
-  id: 10,
-  result: {
-    configuration_method: 'sqlalchemy_form',
-    database_name: 'Other2',
-    driver: 'apsw',
-    expose_in_sqllab: true,
-    extra: '{"allows_virtual_table_explore":true}',
-    sqlalchemy_uri: 'gsheets://',
-  },
-  json: 'foo',
-});
+const databaseFixture: DatabaseObject = {
+  id: 123,
+  backend: 'postgres',
+  configuration_method: ConfigurationMethod.DynamicForm,
+  database_name: 'Postgres',
+  name: 'PostgresDB',
+  is_managed_externally: false,
+  driver: 'psycopg2',
+};
 
-fetchMock.config.overwriteRoutes = true;
-fetchMock.get(DATABASE_FETCH_ENDPOINT, {
-  result: {
-    id: 10,
-    database_name: 'my database',
-    expose_in_sqllab: false,
-    allow_ctas: false,
-    allow_cvas: false,
-    configuration_method: 'sqlalchemy_form',
-  },
-});
-fetchMock.mock(AVAILABLE_DB_ENDPOINT, {
-  databases: [
-    {
-      available_drivers: ['psycopg2'],
-      default_driver: 'psycopg2',
-      engine: 'postgresql',
-      name: 'PostgreSQL',
-      parameters: {
-        properties: {
-          database: {
-            description: 'Database name',
-            type: 'string',
-          },
-          encryption: {
-            description: 'Use an encrypted connection to the database',
-            type: 'boolean',
-          },
-          host: {
-            description: 'Hostname or IP address',
-            type: 'string',
-          },
-          password: {
-            description: 'Password',
-            nullable: true,
-            type: 'string',
-          },
-          port: {
-            description: 'Database port',
-            format: 'int32',
-            maximum: 65536,
-            minimum: 0,
-            type: 'integer',
-          },
-          query: {
-            additionalProperties: {},
-            description: 'Additional parameters',
-            type: 'object',
-          },
-          ssh: {
-            description: 'Create SSH Tunnel',
-            type: 'boolean',
-          },
-          username: {
-            description: 'Username',
-            nullable: true,
-            type: 'string',
-          },
-        },
-        required: ['database', 'host', 'port', 'username'],
-        type: 'object',
-      },
-      preferred: true,
-      sqlalchemy_uri_placeholder:
-        'postgresql://user:password@host:port/dbname[?key=value&key=value...]',
-      engine_information: {
-        supports_file_upload: true,
-        disable_ssh_tunneling: false,
+describe('DatabaseModal', () => {
+  beforeEach(() => {
+    fetchMock.post(DATABASE_CONNECT_ENDPOINT, {
+      id: 10,
+      result: {
+        configuration_method: 'sqlalchemy_form',
+        database_name: 'Other2',
+        driver: 'apsw',
+        expose_in_sqllab: true,
+        extra: '{"allows_virtual_table_explore":true}',
+        sqlalchemy_uri: 'gsheets://',
       },
-    },
-    {
-      available_drivers: ['rest'],
-      engine: 'presto',
-      name: 'Presto',
-      preferred: true,
-      engine_information: {
-        supports_file_upload: true,
-        disable_ssh_tunneling: false,
+      json: 'foo',
+    });
+
+    fetchMock.get(DATABASE_FETCH_ENDPOINT, {
+      result: {
+        id: 10,
+        database_name: 'my database',
+        expose_in_sqllab: false,
+        allow_ctas: false,
+        allow_cvas: false,
+        configuration_method: 'sqlalchemy_form',
       },
-    },
-    {
-      available_drivers: ['mysqldb'],
-      default_driver: 'mysqldb',
-      engine: 'mysql',
-      name: 'MySQL',
-      parameters: {
-        properties: {
-          database: {
-            description: 'Database name',
-            type: 'string',
-          },
-          encryption: {
-            description: 'Use an encrypted connection to the database',
-            type: 'boolean',
-          },
-          host: {
-            description: 'Hostname or IP address',
-            type: 'string',
+    });
+    fetchMock.mock(AVAILABLE_DB_ENDPOINT, {
+      databases: [
+        {
+          available_drivers: ['psycopg2'],
+          default_driver: 'psycopg2',
+          engine: 'postgresql',
+          name: 'PostgreSQL',
+          parameters: {
+            properties: {
+              database: {
+                description: 'Database name',
+                type: 'string',
+              },
+              encryption: {
+                description: 'Use an encrypted connection to the database',
+                type: 'boolean',
+              },
+              host: {
+                description: 'Hostname or IP address',
+                type: 'string',
+              },
+              password: {
+                description: 'Password',
+                nullable: true,
+                type: 'string',
+              },
+              port: {
+                description: 'Database port',
+                format: 'int32',
+                maximum: 65536,
+                minimum: 0,
+                type: 'integer',
+              },
+              query: {
+                additionalProperties: {},
+                description: 'Additional parameters',
+                type: 'object',
+              },
+              ssh: {
+                description: 'Create SSH Tunnel',
+                type: 'boolean',
+              },
+              username: {
+                description: 'Username',
+                nullable: true,
+                type: 'string',
+              },
+            },
+            required: ['database', 'host', 'port', 'username'],
+            type: 'object',
           },
-          password: {
-            description: 'Password',
-            nullable: true,
-            type: 'string',
+          preferred: true,
+          sqlalchemy_uri_placeholder:
+            'postgresql://user:password@host:port/dbname[?key=value&key=value...]',
+          engine_information: {
+            supports_file_upload: true,
+            disable_ssh_tunneling: false,
           },
-          port: {
-            description: 'Database port',
-            format: 'int32',
-            maximum: 65536,
-            minimum: 0,
-            type: 'integer',
+        },
+        {
+          available_drivers: ['rest'],
+          engine: 'presto',
+          name: 'Presto',
+          preferred: true,
+          engine_information: {
+            supports_file_upload: true,
+            disable_ssh_tunneling: false,
           },
-          query: {
-            additionalProperties: {},
-            description: 'Additional parameters',
+        },
+        {
+          available_drivers: ['mysqldb'],
+          default_driver: 'mysqldb',
+          engine: 'mysql',
+          name: 'MySQL',
+          parameters: {
+            properties: {
+              database: {
+                description: 'Database name',
+                type: 'string',
+              },
+              encryption: {
+                description: 'Use an encrypted connection to the database',
+                type: 'boolean',
+              },
+              host: {
+                description: 'Hostname or IP address',
+                type: 'string',
+              },
+              password: {
+                description: 'Password',
+                nullable: true,
+                type: 'string',
+              },
+              port: {
+                description: 'Database port',
+                format: 'int32',
+                maximum: 65536,
+                minimum: 0,
+                type: 'integer',
+              },
+              query: {
+                additionalProperties: {},
+                description: 'Additional parameters',
+                type: 'object',
+              },
+              username: {
+                description: 'Username',
+                nullable: true,
+                type: 'string',
+              },
+            },
+            required: ['database', 'host', 'port', 'username'],
             type: 'object',
           },
-          username: {
-            description: 'Username',
-            nullable: true,
-            type: 'string',
+          preferred: true,
+          sqlalchemy_uri_placeholder:
+            'mysql://user:password@host:port/dbname[?key=value&key=value...]',
+          engine_information: {
+            supports_file_upload: true,
+            disable_ssh_tunneling: false,
           },
         },
-        required: ['database', 'host', 'port', 'username'],
-        type: 'object',
-      },
-      preferred: true,
-      sqlalchemy_uri_placeholder:
-        'mysql://user:password@host:port/dbname[?key=value&key=value...]',
-      engine_information: {
-        supports_file_upload: true,
-        disable_ssh_tunneling: false,
-      },
-    },
-    {
-      available_drivers: ['pysqlite'],
-      engine: 'sqlite',
-      name: 'SQLite',
-      preferred: true,
-      engine_information: {
-        supports_file_upload: true,
-        disable_ssh_tunneling: false,
-      },
-    },
-    {
-      available_drivers: ['rest'],
-      engine: 'druid',
-      name: 'Apache Druid',
-      preferred: false,
-      engine_information: {
-        supports_file_upload: true,
-        disable_ssh_tunneling: false,
-      },
-    },
-    {
-      available_drivers: ['bigquery'],
-      default_driver: 'bigquery',
-      engine: 'bigquery',
-      name: 'Google BigQuery',
-      parameters: {
-        properties: {
-          credentials_info: {
-            description: 'Contents of BigQuery JSON credentials.',
-            type: 'string',
-            'x-encrypted-extra': true,
-          },
-          query: {
-            type: 'object',
+        {
+          available_drivers: ['pysqlite'],
+          engine: 'sqlite',
+          name: 'SQLite',
+          preferred: true,
+          engine_information: {
+            supports_file_upload: true,
+            disable_ssh_tunneling: false,
           },
         },
-        type: 'object',
-      },
-      preferred: false,
-      sqlalchemy_uri_placeholder: 'bigquery://{project_id}',
-      engine_information: {
-        supports_file_upload: true,
-        disable_ssh_tunneling: true,
-      },
-    },
-    {
-      available_drivers: ['rest'],
-      default_driver: 'apsw',
-      engine: 'gsheets',
-      name: 'Google Sheets',
-      preferred: false,
-      engine_information: {
-        supports_file_upload: false,
-        disable_ssh_tunneling: true,
-      },
-    },
-    {
-      available_drivers: ['connector'],
-      default_driver: 'connector',
-      engine: 'databricks',
-      name: 'Databricks',
-      parameters: {
-        properties: {
-          access_token: {
-            type: 'string',
+        {
+          available_drivers: ['rest'],
+          engine: 'druid',
+          name: 'Apache Druid',
+          preferred: false,
+          engine_information: {
+            supports_file_upload: true,
+            disable_ssh_tunneling: false,
           },
-          database: {
-            type: 'string',
+        },
+        {
+          available_drivers: ['bigquery'],
+          default_driver: 'bigquery',
+          engine: 'bigquery',
+          name: 'Google BigQuery',
+          parameters: {
+            properties: {
+              credentials_info: {
+                description: 'Contents of BigQuery JSON credentials.',
+                type: 'string',
+                'x-encrypted-extra': true,
+              },
+              query: {
+                type: 'object',
+              },
+            },
+            type: 'object',
           },
-          host: {
-            type: 'string',
+          preferred: false,
+          sqlalchemy_uri_placeholder: 'bigquery://{project_id}',
+          engine_information: {
+            supports_file_upload: true,
+            disable_ssh_tunneling: true,
           },
-          http_path: {
-            type: 'string',
+        },
+        {
+          available_drivers: ['rest'],
+          default_driver: 'apsw',
+          engine: 'gsheets',
+          name: 'Google Sheets',
+          preferred: false,
+          engine_information: {
+            supports_file_upload: false,
+            disable_ssh_tunneling: true,
           },
-          port: {
-            format: 'int32',
-            type: 'integer',
+        },
+        {
+          available_drivers: ['connector'],
+          default_driver: 'connector',
+          engine: 'databricks',
+          name: 'Databricks',
+          parameters: {
+            properties: {
+              access_token: {
+                type: 'string',
+              },
+              database: {
+                type: 'string',
+              },
+              host: {
+                type: 'string',
+              },
+              http_path: {
+                type: 'string',
+              },
+              port: {
+                format: 'int32',
+                type: 'integer',
+              },
+            },
+            required: ['access_token', 'database', 'host', 'http_path', 'port'],
+            type: 'object',
           },
+          preferred: true,
+          sqlalchemy_uri_placeholder:
+            'databricks+connector://token:{access_token}@{host}:{port}/{database_name}',
         },
-        required: ['access_token', 'database', 'host', 'http_path', 'port'],
-        type: 'object',
-      },
-      preferred: true,
-      sqlalchemy_uri_placeholder:
-        'databricks+connector://token:{access_token}@{host}:{port}/{database_name}',
-    },
-  ],
-});
-fetchMock.post(VALIDATE_PARAMS_ENDPOINT, {
-  message: 'OK',
-});
-
-const databaseFixture: DatabaseObject = {
-  id: 123,
-  backend: 'postgres',
-  configuration_method: ConfigurationMethod.DynamicForm,
-  database_name: 'Postgres',
-  name: 'PostgresDB',
-  is_managed_externally: false,
-  driver: 'psycopg2',
-};
-
-describe('DatabaseModal', () => {
-  const renderAndWait = async () =>
-    waitFor(() =>
-      render(<DatabaseModal {...dbProps} />, {
-        useRedux: true,
-      }),
-    );
+      ],
+    });
+    fetchMock.post(VALIDATE_PARAMS_ENDPOINT, {
+      message: 'OK',
+    });
+  });
 
-  beforeEach(async () => {
-    await renderAndWait();
+  beforeEach(() => {
+    jest.clearAllMocks();
+  });
+  afterEach(() => {
+    fetchMock.restore();
   });
 
-  afterEach(cleanup);
+  const setup = (propsOverwrite: Partial<DatabaseModalProps> = {}) =>
+    render(<DatabaseModal {...dbProps} {...propsOverwrite} />, {
+      useRedux: true,
+    });
 
   describe('Visual: New database connection', () => {
-    test('renders the initial load of Step 1 correctly', () => {
+    test('renders the initial load of Step 1 correctly', async () => {
+      setup();
+
       // ---------- Components ----------
       // <TabHeader> - AntD header
-      const closeButton = screen.getByLabelText('Close');
+      const closeButton = await screen.findByLabelText('Close');
       const step1Header = screen.getByRole('heading', {
         name: /connect a database/i,
       });
       // <ModalHeader> - Connection header
-      const step1Helper = screen.getByText(/step 1 of 3/i);
+      const step1Helper = await screen.findByText(/step 1 of 3/i);
       const selectDbHeader = screen.getByRole('heading', {
         name: /select a database to connect/i,
       });
@@ -376,7 +372,8 @@ describe('DatabaseModal', () => {
         hidden: true,
       });
 
-      const footer = document.getElementsByClassName('ant-modal-footer');
+      const modal = screen.getByRole('dialog');
+      const footer = modal.querySelector('.ant-modal-footer');
       // ---------- TODO (lyndsiWilliams): Selector options, can't seem to get these to render properly.
 
       // renderAvailableSelector() => <Alert> - Supported databases alert
@@ -415,13 +412,15 @@ describe('DatabaseModal', () => {
         expect(component).toBeInTheDocument();
       });
       // there should be a footer but it should not have any buttons in it
-      expect(footer[0]).toBeEmptyDOMElement();
+      expect(footer).toBeEmptyDOMElement();
     });
 
     test('renders the "Basic" tab of SQL Alchemy form (step 2 of 2) correctly', async () => {
+      setup();
+
       // On step 1, click dbButton to access SQL Alchemy form
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
@@ -429,7 +428,7 @@ describe('DatabaseModal', () => {
 
       // ---------- Components ----------
       // <TabHeader> - AntD header
-      const closeButton = screen.getByRole('button', { name: 'Close' });
+      const closeButton = await screen.findByRole('button', { name: 'Close' });
 
       const basicHeader = screen.getByRole('heading', {
         name: /connect a database/i,
@@ -462,7 +461,7 @@ describe('DatabaseModal', () => {
       // <SSHTunnelForm> - Basic tab's SSH Tunnel Form
       const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
       userEvent.click(SSHTunnelingToggle);
-      const SSHTunnelServerAddressInput = screen.getByTestId(
+      const SSHTunnelServerAddressInput = await screen.findByTestId(
         'ssh-tunnel-server_address-input',
       );
       const SSHTunnelServerPortInput = screen.getByTestId(
@@ -527,9 +526,11 @@ describe('DatabaseModal', () => {
     });
 
     test('renders the unexpanded "Advanced" tab correctly', async () => {
+      setup();
+
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
@@ -626,18 +627,20 @@ describe('DatabaseModal', () => {
     });
 
     test('renders the "Advanced" - SQL LAB tab correctly (unexpanded)', async () => {
+      setup();
+
       // ---------- Components ----------
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
       // Click the "Advanced" tab
-      userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
+      userEvent.click(await screen.findByRole('tab', { name: /advanced/i }));
       // Click the "SQL Lab" tab
       userEvent.click(
-        screen.getByRole('tab', {
+        await screen.findByRole('tab', {
           name: /right sql lab adjust how this database will interact with sql lab\./i,
         }),
       );
@@ -645,7 +648,7 @@ describe('DatabaseModal', () => {
 
       // ----- BEGIN STEP 2 (ADVANCED - SQL LAB)
       // <TabHeader> - AntD header
-      const closeButton = screen.getByRole('button', { name: /close/i });
+      const closeButton = await screen.findByRole('button', { name: /close/i });
       const advancedHeader = screen.getByRole('heading', {
         name: /connect a database/i,
       });
@@ -788,10 +791,12 @@ describe('DatabaseModal', () => {
     });
 
     test('renders the "Advanced" - PERFORMANCE tab correctly', async () => {
+      setup();
+
       // ---------- Components ----------
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
@@ -851,10 +856,12 @@ describe('DatabaseModal', () => {
     });
 
     test('renders the "Advanced" - SECURITY tab correctly', async () => {
+      setup();
+
       // ---------- Components ----------
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
@@ -935,10 +942,12 @@ describe('DatabaseModal', () => {
     });
 
     it('renders the "Advanced" - SECURITY tab correctly after selecting Allow file uploads', async () => {
+      setup();
+
       // ---------- Components ----------
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
@@ -1021,10 +1030,12 @@ describe('DatabaseModal', () => {
     });
 
     test('renders the "Advanced" - OTHER tab correctly', async () => {
+      setup();
+
       // ---------- Components ----------
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /sqlite/i,
         }),
       );
@@ -1040,7 +1051,7 @@ describe('DatabaseModal', () => {
 
       // ----- BEGIN STEP 2 (ADVANCED - OTHER)
       // <TabHeader> - AntD header
-      const closeButton = screen.getByRole('button', { name: /close/i });
+      const closeButton = await screen.findByRole('button', { name: /close/i });
       const advancedHeader = screen.getByRole('heading', {
         name: /connect a database/i,
       });
@@ -1092,10 +1103,12 @@ describe('DatabaseModal', () => {
     });
 
     test('Dynamic form', async () => {
+      setup();
+
       // ---------- Components ----------
       // On step 1, click dbButton to access step 2
       userEvent.click(
-        screen.getByRole('button', {
+        await screen.findByRole('button', {
           name: /postgresql/i,
         }),
       );
@@ -1107,9 +1120,11 @@ describe('DatabaseModal', () => {
 
   describe('Functional: Create new database', () => {
     test('directs databases to the appropriate form (dynamic vs. SQL Alchemy)', async () => {
+      setup();
+
       // ---------- Dynamic example (3-step form)
       // Click the PostgreSQL button to enter the dynamic form
-      const postgreSQLButton = screen.getByRole('button', {
+      const postgreSQLButton = await screen.findByRole('button', {
         name: /postgresql/i,
       });
       userEvent.click(postgreSQLButton);
@@ -1139,8 +1154,10 @@ describe('DatabaseModal', () => {
 
     describe('SQL Alchemy form flow', () => {
       test('enters step 2 of 2 when proper database is selected', async () => {
+        setup();
+
         userEvent.click(
-          screen.getByRole('button', {
+          await screen.findByRole('button', {
             name: /sqlite/i,
           }),
         );
@@ -1167,8 +1184,10 @@ describe('DatabaseModal', () => {
 
       describe('step 2 component interaction', () => {
         test('properly interacts with textboxes', async () => {
+          setup();
+
           userEvent.click(
-            screen.getByRole('button', {
+            await screen.findByRole('button', {
               name: /sqlite/i,
             }),
           );
@@ -1211,15 +1230,17 @@ describe('DatabaseModal', () => {
 
       describe('SSH Tunnel Form interaction', () => {
         test('properly interacts with SSH Tunnel form textboxes for dynamic form', async () => {
+          setup();
+
           userEvent.click(
-            screen.getByRole('button', {
+            await screen.findByRole('button', {
               name: /postgresql/i,
             }),
           );
           expect(await screen.findByText(/step 2 of 3/i)).toBeInTheDocument();
           const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
           userEvent.click(SSHTunnelingToggle);
-          const SSHTunnelServerAddressInput = screen.getByTestId(
+          const SSHTunnelServerAddressInput = await screen.findByTestId(
             'ssh-tunnel-server_address-input',
           );
           expect(SSHTunnelServerAddressInput).toHaveValue('');
@@ -1246,8 +1267,10 @@ describe('DatabaseModal', () => {
         });
 
         test('properly interacts with SSH Tunnel form textboxes', async () => {
+          setup();
+
           userEvent.click(
-            screen.getByRole('button', {
+            await screen.findByRole('button', {
               name: /sqlite/i,
             }),
           );
@@ -1255,7 +1278,7 @@ describe('DatabaseModal', () => {
           expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
           const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
           userEvent.click(SSHTunnelingToggle);
-          const SSHTunnelServerAddressInput = screen.getByTestId(
+          const SSHTunnelServerAddressInput = await screen.findByTestId(
             'ssh-tunnel-server_address-input',
           );
           expect(SSHTunnelServerAddressInput).toHaveValue('');
@@ -1282,8 +1305,10 @@ describe('DatabaseModal', () => {
         });
 
         test('if the SSH Tunneling toggle is not true, no inputs are displayed', async () => {
+          setup();
+
           userEvent.click(
-            screen.getByRole('button', {
+            await screen.findByRole('button', {
               name: /sqlite/i,
             }),
           );
@@ -1310,8 +1335,10 @@ describe('DatabaseModal', () => {
         });
 
         test('If user changes the login method, the inputs change', async () => {
+          setup();
+
           userEvent.click(
-            screen.getByRole('button', {
+            await screen.findByRole('button', {
               name: /sqlite/i,
             }),
           );
@@ -1319,7 +1346,7 @@ describe('DatabaseModal', () => {
           expect(await screen.findByText(/step 2 of 2/i)).toBeInTheDocument();
           const SSHTunnelingToggle = screen.getByTestId('ssh-tunnel-switch');
           userEvent.click(SSHTunnelingToggle);
-          const SSHTunnelUsePasswordInput = screen.getByTestId(
+          const SSHTunnelUsePasswordInput = await screen.findByTestId(
             'ssh-tunnel-use_password-radio',
           );
           expect(SSHTunnelUsePasswordInput).toBeInTheDocument();
@@ -1348,6 +1375,8 @@ describe('DatabaseModal', () => {
 
     describe('Dynamic form flow', () => {
       test('enters step 2 of 3 when proper database is selected', async () => {
+        setup();
+
         expect(await screen.findByText(/step 1 of 3/i)).toBeInTheDocument();
         userEvent.click(
           screen.getByRole('button', {
@@ -1355,14 +1384,13 @@ describe('DatabaseModal', () => {
           }),
         );
         expect(await screen.findByText(/step 2 of 3/i)).toBeInTheDocument();
-
-        const step2of3text = screen.getByText(/step 2 of 3/i);
-        expect(step2of3text).toBeVisible();
       });
 
       test('enters form credentials and runs fetchResource when "Connect" is clicked', async () => {
+        setup();
+
         userEvent.click(
-          screen.getByRole('button', {
+          await screen.findByRole('button', {
             name: /postgresql/i,
           }),
         );
@@ -1403,9 +1431,11 @@ describe('DatabaseModal', () => {
 
     describe('Import database flow', () => {
       test('imports a file', async () => {
-        const importDbButton = screen.getByTestId(
+        setup();
+
+        const importDbButton = (await screen.findByTestId(
           'import-database-btn',
-        ) as HTMLInputElement;
+        )) as HTMLInputElement;
         importDbButton.type = 'file';
         importDbButton.files = {} as FileList;
         expect(importDbButton).toBeInTheDocument();
@@ -1423,54 +1453,25 @@ describe('DatabaseModal', () => {
   });
 
   describe('DatabaseModal w/ Deeplinking Engine', () => {
-    const renderAndWait = async () => {
-      const mounted = act(async () => {
-        render(<DatabaseModal {...dbProps} dbEngine="PostgreSQL" />, {
-          useRedux: true,
-        });
-      });
-
-      return mounted;
-    };
-
-    beforeEach(async () => {
-      await renderAndWait();
-    });
-
-    test('enters step 2 of 3 when proper database is selected', () => {
-      const step2of3text = screen.getByText(/step 2 of 3/i);
+    test('enters step 2 of 3 when proper database is selected', async () => {
+      setup({ dbEngine: 'PostgreSQL' });
+      const step2of3text = await screen.findByText(/step 2 of 3/i);
       expect(step2of3text).toBeInTheDocument();
     });
   });
 
   describe('DatabaseModal w/ GSheet Engine', () => {
-    const renderAndWait = async () => {
-      const dbProps = {
-        show: true,
-        database_name: 'my database',
-        sqlalchemy_uri: 'gsheets://',
-      };
-      const mounted = act(async () => {
-        render(<DatabaseModal {...dbProps} dbEngine="Google Sheets" />, {
-          useRedux: true,
-        });
-      });
-
-      return mounted;
-    };
-
-    beforeEach(async () => {
-      await renderAndWait();
-    });
-
-    it('enters step 2 of 2 when proper database is selected', () => {
-      const step2of2text = screen.getByText(/step 2 of 2/i);
+    it('enters step 2 of 2 when proper database is selected', async () => {
+      setup({ dbEngine: 'Google Sheets' });
+      const step2of2text = await screen.findByText(/step 2 of 2/i);
       expect(step2of2text).toBeInTheDocument();
     });
 
     it('renders the "Advanced" - SECURITY tab without Allow File Upload Checkbox', async () => {
+      setup({ dbEngine: 'Google Sheets' });
+
       // Click the "Advanced" tab
-      userEvent.click(screen.getByRole('tab', { name: /advanced/i }));
+      userEvent.click(await screen.findByRole('tab', { name: /advanced/i }));
       // Click the "Security" tab
       userEvent.click(
         screen.getByRole('tab', {
@@ -1509,6 +1510,8 @@ describe('DatabaseModal', () => {
     });
 
     it('if the SSH Tunneling toggle is not displayed, nothing should get displayed', async () => {
+      setup({ dbEngine: 'Google Sheets' });
+
       const SSHTunnelingToggle = screen.queryByTestId('ssh-tunnel-switch');
       expect(SSHTunnelingToggle).not.toBeInTheDocument();
       const SSHTunnelServerAddressInput = screen.queryByTestId(
@@ -1536,22 +1539,9 @@ describe('DatabaseModal', () => {
       useSingleViewResource: jest.fn(),
     }));
 
-    const renderAndWait = async () => {
-      const mounted = act(async () => {
-        render(<DatabaseModal {...dbProps} dbEngine="PostgreSQL" />, {
-          useRedux: true,
-        });
-      });
-
-      return mounted;
-    };
-
-    beforeEach(async () => {
-      await renderAndWait();
-    });
-
     test('Error displays when it is an object', async () => {
-      const step2of3text = screen.getByText(/step 2 of 3/i);
+      setup({ dbEngine: 'PostgreSQL' });
+      const step2of3text = await screen.findByText(/step 2 of 3/i);
       const errorSection = screen.getByText(/Database Creation Error/i);
       expect(step2of3text).toBeInTheDocument();
       expect(errorSection).toBeInTheDocument();
@@ -1581,22 +1571,10 @@ describe('DatabaseModal', () => {
       setResource: jest.fn(),
     });
 
-    const renderAndWait = async () => {
-      const mounted = act(async () => {
-        render(<DatabaseModal {...dbProps} dbEngine="PostgreSQL" />, {
-          useRedux: true,
-        });
-      });
-
-      return mounted;
-    };
-
-    beforeEach(async () => {
-      await renderAndWait();
-    });
-
     test('Error displays when it is a string', async () => {
-      const step2of3text = screen.getByText(/step 2 of 3/i);
+      setup({ dbEngine: 'PostgreSQL' });
+
+      const step2of3text = await screen.findByText(/step 2 of 3/i);
       const errorTitleMessage = screen.getByText(/Database Creation Error/i);
       const button = screen.getByText('See more');
       userEvent.click(button);
@@ -1608,7 +1586,7 @@ describe('DatabaseModal', () => {
   });
 
   describe('DatabaseModal w Extensions', () => {
-    const renderAndWait = async () => {
+    beforeAll(() => {
       const extensionsRegistry = getExtensionsRegistry();
 
       extensionsRegistry.set('ssh_tunnel.form.switch', () => (
@@ -1616,23 +1594,12 @@ describe('DatabaseModal', () => {
       ));
 
       setupExtensions();
-
-      const mounted = act(async () => {
-        render(<DatabaseModal {...dbProps} dbEngine="SQLite" />, {
-          useRedux: true,
-        });
-      });
-
-      return mounted;
-    };
-
-    beforeEach(async () => {
-      await renderAndWait();
     });
 
-    test('should render an extension component if one is supplied', () => {
+    test('should render an extension component if one is supplied', async () => {
+      setup({ dbEngine: 'SQLite' });
       expect(
-        screen.getByText('ssh_tunnel.form.switch extension component'),
+        await screen.findByText('ssh_tunnel.form.switch extension component'),
       ).toBeInTheDocument();
     });
   });
diff --git a/superset-frontend/src/features/databases/DatabaseModal/index.tsx b/superset-frontend/src/features/databases/DatabaseModal/index.tsx
index 10ae7a82cc..3a7eb0d21d 100644
--- a/superset-frontend/src/features/databases/DatabaseModal/index.tsx
+++ b/superset-frontend/src/features/databases/DatabaseModal/index.tsx
@@ -139,7 +139,7 @@ const SSHTunnelContainer = styled.div`
   `};
 `;
 
-interface DatabaseModalProps {
+export interface DatabaseModalProps {
   addDangerToast: (msg: string) => void;
   addSuccessToast: (msg: string) => void;
   onDatabaseAdd?: (database?: DatabaseObject) => void;
@@ -1335,7 +1335,7 @@ const DatabaseModal: FunctionComponent<DatabaseModalProps> = ({
   useEffect(() => {
     if (importingModal) {
       document
-        .getElementsByClassName('ant-upload-list-item-name')[0]
+        ?.getElementsByClassName('ant-upload-list-item-name')[0]
         .scrollIntoView();
     }
   }, [importingModal]);
diff --git a/superset-frontend/src/features/databases/UploadDataModel/UploadDataModal.test.tsx b/superset-frontend/src/features/databases/UploadDataModel/UploadDataModal.test.tsx
index 5a3958e00a..34bebac917 100644
--- a/superset-frontend/src/features/databases/UploadDataModel/UploadDataModal.test.tsx
+++ b/superset-frontend/src/features/databases/UploadDataModel/UploadDataModal.test.tsx
@@ -622,7 +622,7 @@ test('CSV form post', async () => {
 
   // Select a file from the file dialog
   const file = new File(['test'], 'test.csv', { type: 'text' });
-  const inputElement = document.querySelector('input[type="file"]');
+  const inputElement = screen.getByTestId('model-file-input');
 
   if (inputElement) {
     userEvent.upload(inputElement as HTMLElement, file);
@@ -680,7 +680,7 @@ test('Excel form post', async () => {
 
   // Select a file from the file dialog
   const file = new File(['test'], 'test.xls', { type: 'text' });
-  const inputElement = document.querySelector('input[type="file"]');
+  const inputElement = screen.getByTestId('model-file-input');
 
   if (inputElement) {
     userEvent.upload(inputElement as HTMLElement, file);
@@ -738,7 +738,7 @@ test('Columnar form post', async () => {
 
   // Select a file from the file dialog
   const file = new File(['test'], 'test.parquet', { type: 'text' });
-  const inputElement = document.querySelector('input[type="file"]');
+  const inputElement = screen.getByTestId('model-file-input');
 
   if (inputElement) {
     userEvent.upload(inputElement as HTMLElement, file);
diff --git a/superset-frontend/src/features/datasets/types.ts b/superset-frontend/src/features/datasets/types.ts
index 6ac19a7649..e0afb07670 100644
--- a/superset-frontend/src/features/datasets/types.ts
+++ b/superset-frontend/src/features/datasets/types.ts
@@ -1,4 +1,5 @@
-import { Currency } from '@superset-ui/core';
+import { Currency, type DatasourceType } from '@superset-ui/core';
+import { Owner } from '@superset-ui/chart-controls';
 
 /**
  * Licensed to the Apache Software Foundation (ASF) under one
@@ -32,37 +33,52 @@ export type ColumnObject = {
   python_date_format?: string;
   uuid?: string;
   extra?: string;
+  certified_by?: string;
+  certification_details?: string;
+  warning_markdown?: string;
+  advanced_data_type?: string;
 };
 
 type MetricObject = {
   id: number;
+  uuid: number;
   expression?: string;
   description?: string;
   metric_name: string;
+  verbose_name?: string;
   metric_type: string;
   d3format?: string;
   currency?: Currency;
   warning_text?: string;
+  certified_by?: string;
+  certification_details?: string;
+  warning_markdown?: string;
 };
 
 export type DatasetObject = {
+  id: number;
   table_name?: string;
   sql?: string;
   filter_select_enabled?: boolean;
   fetch_values_predicate?: string;
   schema?: string;
-  description?: string;
-  main_dttm_col?: string;
+  description: string | null;
+  main_dttm_col: string;
   offset?: number;
   default_endpoint?: string;
   cache_timeout?: number;
   is_sqllab_view?: boolean;
   template_params?: string;
-  owners: number[];
+  owners: Owner[];
   columns: ColumnObject[];
   metrics: MetricObject[];
   extra?: string;
   is_managed_externally: boolean;
   normalize_columns: boolean;
   always_filter_main_dttm: boolean;
+  type: DatasourceType;
+  column_formats: Record<string, string>;
+  currency_formats: Record<string, Currency>;
+  datasource_name: string | null;
+  verbose_map: Record<string, string>;
 };


(superset) 14/17: fix(SaveDatasetModal): repairs field alignment in the SaveDatasetModal component (#32222)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 8ba36abc87fd3b09440c36b78f04bae3d9af4eb0
Author: Enzo Martellucci <52...@users.noreply.github.com>
AuthorDate: Tue Feb 11 19:16:54 2025 +0100

    fix(SaveDatasetModal): repairs field alignment in the SaveDatasetModal component (#32222)
    
    Co-authored-by: Geido <60...@users.noreply.github.com>
    (cherry picked from commit 650fa5ccfb6bfaf4c8132a0658b3374e18af1711)
---
 .../src/SqlLab/components/SaveDatasetModal/index.tsx     | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)

diff --git a/superset-frontend/src/SqlLab/components/SaveDatasetModal/index.tsx b/superset-frontend/src/SqlLab/components/SaveDatasetModal/index.tsx
index 379b0726ac..ab17556a72 100644
--- a/superset-frontend/src/SqlLab/components/SaveDatasetModal/index.tsx
+++ b/superset-frontend/src/SqlLab/components/SaveDatasetModal/index.tsx
@@ -96,32 +96,36 @@ interface SaveDatasetModalProps {
 }
 
 const Styles = styled.div`
+  ${({ theme }) => `
   .sdm-body {
-    margin: 0 8px;
+    margin: 0 ${theme.gridUnit * 2}px;
   }
   .sdm-input {
-    margin-left: 45px;
+    margin-left: ${theme.gridUnit * 10}px;
     width: 401px;
   }
   .sdm-autocomplete {
     width: 401px;
     align-self: center;
+    margin-left: ${theme.gridUnit}px;
   }
   .sdm-radio {
-    display: block;
     height: 30px;
     margin: 10px 0px;
     line-height: 30px;
   }
+  .sdm-radio span {
+    display: inline-flex;
+    padding-right: 0px;
+  }
   .sdm-overwrite-msg {
-    margin: 7px;
+    margin: ${theme.gridUnit * 2}px;
   }
   .sdm-overwrite-container {
     flex: 1 1 auto;
     display: flex;
-  }
+  `}
 `;
-
 const updateDataset = async (
   dbId: number,
   datasetId: number,


(superset) 06/17: fix: ScreenshotCachePayload serialization (#32156)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 50705e72530e05f280e7df27f290d96e155d8048
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Thu Feb 6 15:13:40 2025 -0500

    fix: ScreenshotCachePayload serialization (#32156)
    
    (cherry picked from commit e8990f4a365e5b0cb5922d9bbdc21075a6685b5c)
---
 superset/charts/api.py                    |  4 +--
 superset/dashboards/api.py                |  4 +--
 superset/utils/screenshots.py             | 51 +++++++++++++++++++++++++------
 tests/unit_tests/utils/screenshot_test.py | 22 ++++++-------
 4 files changed, 56 insertions(+), 25 deletions(-)

diff --git a/superset/charts/api.py b/superset/charts/api.py
index a600a3ca7f..292575feac 100644
--- a/superset/charts/api.py
+++ b/superset/charts/api.py
@@ -623,7 +623,7 @@ class ChartRestApi(BaseSupersetModelRestApi):
 
         if cache_payload.should_trigger_task(force):
             logger.info("Triggering screenshot ASYNC")
-            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload())
+            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload().to_dict())
             cache_chart_thumbnail.delay(
                 current_user=get_current_user(),
                 chart_id=chart.id,
@@ -755,7 +755,7 @@ class ChartRestApi(BaseSupersetModelRestApi):
             logger.info(
                 "Triggering thumbnail compute (chart id: %s) ASYNC", str(chart.id)
             )
-            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload())
+            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload().to_dict())
             cache_chart_thumbnail.delay(
                 current_user=current_user,
                 chart_id=chart.id,
diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py
index c8c744ec63..c15610010b 100644
--- a/superset/dashboards/api.py
+++ b/superset/dashboards/api.py
@@ -1115,7 +1115,7 @@ class DashboardRestApi(BaseSupersetModelRestApi):
 
         if cache_payload.should_trigger_task(force):
             logger.info("Triggering screenshot ASYNC")
-            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload())
+            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload().to_dict())
             cache_dashboard_screenshot.delay(
                 username=get_current_user(),
                 guest_token=(
@@ -1296,7 +1296,7 @@ class DashboardRestApi(BaseSupersetModelRestApi):
                 "Triggering thumbnail compute (dashboard id: %s) ASYNC",
                 str(dashboard.id),
             )
-            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload())
+            screenshot_obj.cache.set(cache_key, ScreenshotCachePayload().to_dict())
             cache_dashboard_thumbnail.delay(
                 current_user=current_user,
                 dashboard_id=dashboard.id,
diff --git a/superset/utils/screenshots.py b/superset/utils/screenshots.py
index 86f5a94ce7..7f40c0a820 100644
--- a/superset/utils/screenshots.py
+++ b/superset/utils/screenshots.py
@@ -20,7 +20,7 @@ import logging
 from datetime import datetime
 from enum import Enum
 from io import BytesIO
-from typing import TYPE_CHECKING
+from typing import cast, TYPE_CHECKING, TypedDict
 
 from flask import current_app
 
@@ -63,13 +63,37 @@ class StatusValues(Enum):
     ERROR = "Error"
 
 
+class ScreenshotCachePayloadType(TypedDict):
+    image: bytes | None
+    timestamp: str
+    status: str
+
+
 class ScreenshotCachePayload:
-    def __init__(self, image: bytes | None = None):
+    def __init__(
+        self,
+        image: bytes | None = None,
+        status: StatusValues = StatusValues.PENDING,
+        timestamp: str = "",
+    ):
         self._image = image
-        self._timestamp = datetime.now().isoformat()
-        self.status = StatusValues.PENDING
-        if image:
-            self.status = StatusValues.UPDATED
+        self._timestamp = timestamp or datetime.now().isoformat()
+        self.status = StatusValues.UPDATED if image else status
+
+    @classmethod
+    def from_dict(cls, payload: ScreenshotCachePayloadType) -> ScreenshotCachePayload:
+        return cls(
+            image=payload["image"],
+            status=StatusValues(payload["status"]),
+            timestamp=payload["timestamp"],
+        )
+
+    def to_dict(self) -> ScreenshotCachePayloadType:
+        return {
+            "image": self._image,
+            "timestamp": self._timestamp,
+            "status": self.status.value,
+        }
 
     def update_timestamp(self) -> None:
         self._timestamp = datetime.now().isoformat()
@@ -177,9 +201,16 @@ class BaseScreenshot:
     def get_from_cache_key(cls, cache_key: str) -> ScreenshotCachePayload | None:
         logger.info("Attempting to get from cache: %s", cache_key)
         if payload := cls.cache.get(cache_key):
-            # for backwards compatability, byte objects should be converted
-            if not isinstance(payload, ScreenshotCachePayload):
+            # Initially, only bytes were stored. This was changed to store an instance
+            # of ScreenshotCachePayload, but since it can't be serialized in all
+            # backends it was further changed to a dict of attributes.
+            if isinstance(payload, bytes):
                 payload = ScreenshotCachePayload(payload)
+            elif isinstance(payload, ScreenshotCachePayload):
+                pass
+            elif isinstance(payload, dict):
+                payload = cast(ScreenshotCachePayloadType, payload)
+                payload = ScreenshotCachePayload.from_dict(payload)
             return payload
         logger.info("Failed at getting from cache: %s", cache_key)
         return None
@@ -217,7 +248,7 @@ class BaseScreenshot:
         thumb_size = thumb_size or self.thumb_size
         logger.info("Processing url for thumbnail: %s", cache_key)
         cache_payload.computing()
-        self.cache.set(cache_key, cache_payload)
+        self.cache.set(cache_key, cache_payload.to_dict())
         image = None
         # Assuming all sorts of things can go wrong with Selenium
         try:
@@ -239,7 +270,7 @@ class BaseScreenshot:
             logger.info("Caching thumbnail: %s", cache_key)
             with event_logger.log_context(f"screenshot.cache.{self.thumbnail_type}"):
                 cache_payload.update(image)
-        self.cache.set(cache_key, cache_payload)
+        self.cache.set(cache_key, cache_payload.to_dict())
         logger.info("Updated thumbnail cache; Status: %s", cache_payload.get_status())
         return
 
diff --git a/tests/unit_tests/utils/screenshot_test.py b/tests/unit_tests/utils/screenshot_test.py
index 5d29d829a2..fa928fc73f 100644
--- a/tests/unit_tests/utils/screenshot_test.py
+++ b/tests/unit_tests/utils/screenshot_test.py
@@ -26,7 +26,7 @@ from superset.utils.hashing import md5_sha_from_dict
 from superset.utils.screenshots import (
     BaseScreenshot,
     ScreenshotCachePayload,
-    StatusValues,
+    ScreenshotCachePayloadType,
 )
 
 BASE_SCREENSHOT_PATH = "superset.utils.screenshots.BaseScreenshot"
@@ -121,24 +121,24 @@ class TestComputeAndCache:
     def test_happy_path(self, mocker: MockerFixture, screenshot_obj):
         self._setup_compute_and_cache(mocker, screenshot_obj)
         screenshot_obj.compute_and_cache(force=False)
-        cache_payload: ScreenshotCachePayload = screenshot_obj.cache.get("key")
-        assert cache_payload.status == StatusValues.UPDATED
+        cache_payload: ScreenshotCachePayloadType = screenshot_obj.cache.get("key")
+        assert cache_payload["status"] == "Updated"
 
     def test_screenshot_error(self, mocker: MockerFixture, screenshot_obj):
         mocks = self._setup_compute_and_cache(mocker, screenshot_obj)
         get_screenshot: MagicMock = mocks.get("get_screenshot")
         get_screenshot.side_effect = Exception
         screenshot_obj.compute_and_cache(force=False)
-        cache_payload: ScreenshotCachePayload = screenshot_obj.cache.get("key")
-        assert cache_payload.status == StatusValues.ERROR
+        cache_payload: ScreenshotCachePayloadType = screenshot_obj.cache.get("key")
+        assert cache_payload["status"] == "Error"
 
     def test_resize_error(self, mocker: MockerFixture, screenshot_obj):
         mocks = self._setup_compute_and_cache(mocker, screenshot_obj)
         resize_image: MagicMock = mocks.get("resize_image")
         resize_image.side_effect = Exception
         screenshot_obj.compute_and_cache(force=False)
-        cache_payload: ScreenshotCachePayload = screenshot_obj.cache.get("key")
-        assert cache_payload.status == StatusValues.ERROR
+        cache_payload: ScreenshotCachePayloadType = screenshot_obj.cache.get("key")
+        assert cache_payload["status"] == "Error"
 
     def test_skips_if_computing(self, mocker: MockerFixture, screenshot_obj):
         mocks = self._setup_compute_and_cache(mocker, screenshot_obj)
@@ -155,8 +155,8 @@ class TestComputeAndCache:
         # Ensure that it processes when force = True
         screenshot_obj.compute_and_cache(force=True)
         get_screenshot.assert_called_once()
-        cache_payload: ScreenshotCachePayload = screenshot_obj.cache.get("key")
-        assert cache_payload.status == StatusValues.UPDATED
+        cache_payload: ScreenshotCachePayloadType = screenshot_obj.cache.get("key")
+        assert cache_payload["status"] == "Updated"
 
     def test_skips_if_updated(self, mocker: MockerFixture, screenshot_obj):
         mocks = self._setup_compute_and_cache(mocker, screenshot_obj)
@@ -177,8 +177,8 @@ class TestComputeAndCache:
             force=True, window_size=window_size, thumb_size=thumb_size
         )
         get_screenshot.assert_called_once()
-        cache_payload: ScreenshotCachePayload = screenshot_obj.cache.get("key")
-        assert cache_payload._image != b"initial_value"
+        cache_payload: ScreenshotCachePayloadType = screenshot_obj.cache.get("key")
+        assert cache_payload["image"] != b"initial_value"
 
     def test_resize(self, mocker: MockerFixture, screenshot_obj):
         mocks = self._setup_compute_and_cache(mocker, screenshot_obj)


(superset) 07/17: fix(docker): Docker python-translation-build (#32163)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit cbebac94045c7f5576bf19570b262e1f7b519005
Author: EmmanuelCbd <10...@users.noreply.github.com>
AuthorDate: Thu Feb 6 21:49:36 2025 +0100

    fix(docker): Docker python-translation-build (#32163)
    
    (cherry picked from commit 5a8488af36b0134793525a239069f31853585f76)
---
 Dockerfile | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/Dockerfile b/Dockerfile
index aa83fc8f1c..acfba0dce5 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -23,11 +23,14 @@ ARG PY_VER=3.11-slim-bookworm
 # If BUILDPLATFORM is null, set it to 'amd64' (or leave as is otherwise).
 ARG BUILDPLATFORM=${BUILDPLATFORM:-amd64}
 
+# Include translations in the final build
+ARG BUILD_TRANSLATIONS="false"
+
 ######################################################################
 # superset-node-ci used as a base for building frontend assets and CI
 ######################################################################
 FROM --platform=${BUILDPLATFORM} node:20-bullseye-slim AS superset-node-ci
-ARG BUILD_TRANSLATIONS="false" # Include translations in the final build
+ARG BUILD_TRANSLATIONS
 ENV BUILD_TRANSLATIONS=${BUILD_TRANSLATIONS}
 ARG DEV_MODE="false"           # Skip frontend build in dev mode
 ENV DEV_MODE=${DEV_MODE}
@@ -122,6 +125,9 @@ ENV PATH="/app/.venv/bin:${PATH}"
 ######################################################################
 FROM python-base AS python-translation-compiler
 
+ARG BUILD_TRANSLATIONS
+ENV BUILD_TRANSLATIONS=${BUILD_TRANSLATIONS}
+
 # Install Python dependencies using docker/pip-install.sh
 COPY requirements/translations.txt requirements/
 RUN --mount=type=cache,target=/root/.cache/uv \


(superset) 15/17: fix: set `Rich tooltip` -> 'Show percentage' to false by default (#32212)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 699d22c5fe767d7759dc4c93ba6cf8464603a1bd
Author: Maxime Beauchemin <ma...@gmail.com>
AuthorDate: Tue Feb 11 10:58:49 2025 -0800

    fix: set `Rich tooltip` -> 'Show percentage' to false by default (#32212)
    
    (cherry picked from commit d3b854a8339bb33ada29c6c83f285995c33cf3c5)
---
 superset-frontend/plugins/plugin-chart-echarts/src/controls.tsx | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/superset-frontend/plugins/plugin-chart-echarts/src/controls.tsx b/superset-frontend/plugins/plugin-chart-echarts/src/controls.tsx
index db7daa02b6..5c52bb1762 100644
--- a/superset-frontend/plugins/plugin-chart-echarts/src/controls.tsx
+++ b/superset-frontend/plugins/plugin-chart-echarts/src/controls.tsx
@@ -230,7 +230,7 @@ const tooltipPercentageControl: ControlSetItem = {
     type: 'CheckboxControl',
     label: t('Show percentage'),
     renderTrigger: true,
-    default: true,
+    default: false,
     description: t('Whether to display the percentage value in the tooltip'),
     visibility: ({ controls, form_data }: ControlPanelsContainerProps) =>
       Boolean(controls?.rich_tooltip?.value) &&


(superset) 11/17: fix: TDengine move tdengine.png to databases/ subfolder (#32176)

Posted by mi...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

michaelsmolina pushed a commit to branch 5.0
in repository https://gitbox.apache.org/repos/asf/superset.git

commit d83ae362cf9b5f342af0deb0b77f2fe3cb4b3225
Author: Alex Duan <51...@users.noreply.github.com>
AuthorDate: Sat Feb 8 02:39:54 2025 +0800

    fix: TDengine move tdengine.png to databases/ subfolder (#32176)
    
    (cherry picked from commit 06f8f8e6082371df603571aa3fde8c763ed4f77e)
---
 docs/src/resources/data.js             |   5 +++++
 docs/static/img/databases/tdengine.png | Bin 0 -> 32453 bytes
 2 files changed, 5 insertions(+)

diff --git a/docs/src/resources/data.js b/docs/src/resources/data.js
index baeed74eb9..7bd418778e 100644
--- a/docs/src/resources/data.js
+++ b/docs/src/resources/data.js
@@ -137,4 +137,9 @@ export const Databases = [
     href: 'https://www.denodo.com/',
     imgName: 'denodo.png',
   },
+  {
+    title: 'TDengine',
+    href: 'https://www.tdengine.com/',
+    imgName: 'tdengine.png',
+  },
 ];
diff --git a/docs/static/img/databases/tdengine.png b/docs/static/img/databases/tdengine.png
new file mode 100644
index 0000000000..cc9d1852e0
Binary files /dev/null and b/docs/static/img/databases/tdengine.png differ