You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by be...@apache.org on 2025/08/19 19:39:28 UTC
(superset) 01/01: feat(bigquery): show materialized views
This is an automated email from the ASF dual-hosted git repository.
beto pushed a commit to branch bigquery-materialized-views
in repository https://gitbox.apache.org/repos/asf/superset.git
commit a2f5bcce955a0df2f72b51984a3e5cf65a8d66f2
Author: Beto Dealmeida <ro...@dealmeida.net>
AuthorDate: Tue Aug 19 15:39:13 2025 -0400
feat(bigquery): show materialized views
---
.../TableSelector/TableSelector.test.tsx | 47 ++++++++++++++++++++++
.../src/components/TableSelector/index.tsx | 2 +
superset/commands/database/tables.py | 31 +++++++++++++-
superset/db_engine_specs/bigquery.py | 47 ++++++++++++++++++++++
superset/models/core.py | 39 ++++++++++++++++++
.../db_engine_specs/bigquery_tests.py | 35 ++++++++++++++++
6 files changed, 200 insertions(+), 1 deletion(-)
diff --git a/superset-frontend/src/components/TableSelector/TableSelector.test.tsx b/superset-frontend/src/components/TableSelector/TableSelector.test.tsx
index 150f33e3d8..88f409afc3 100644
--- a/superset-frontend/src/components/TableSelector/TableSelector.test.tsx
+++ b/superset-frontend/src/components/TableSelector/TableSelector.test.tsx
@@ -259,3 +259,50 @@ test('table multi select retain all the values selected', async () => {
expect(selections[0]).toHaveTextContent('table_b');
expect(selections[1]).toHaveTextContent('table_c');
});
+
+test('renders correct icons for different table types', async () => {
+ const tablesMock = {
+ count: 3,
+ result: [
+ { value: 'regular_table', type: 'table', label: 'regular_table' },
+ { value: 'view_table', type: 'view', label: 'view_table' },
+ {
+ value: 'materialized_view_table',
+ type: 'materialized_view',
+ label: 'materialized_view_table',
+ },
+ ],
+ };
+
+ fetchMock.get(catalogApiRoute, { result: [] });
+ fetchMock.get(schemaApiRoute, { result: [] });
+ fetchMock.get(tablesApiRoute, tablesMock);
+
+ const props = createProps();
+ const { container } = render(<TableSelector {...props} />, {
+ useRedux: true,
+ store,
+ });
+
+ const tableSelect = screen.getByRole('combobox', {
+ name: 'Select table or type to search tables',
+ });
+
+ await userEvent.click(tableSelect);
+
+ // Wait for the dropdown to open and tables to be loaded
+ await waitFor(() => {
+ expect(screen.getByText('regular_table')).toBeInTheDocument();
+ });
+
+ // Verify all table types are displayed
+ expect(screen.getByText('view_table')).toBeInTheDocument();
+ expect(screen.getByText('materialized_view_table')).toBeInTheDocument();
+
+ // Check for the presence of different icon types in the dropdown
+ // InsertRowAboveOutlined for regular tables
+ // EyeOutlined for views
+ // DatabaseOutlined for materialized views
+ const iconContainers = container.querySelectorAll('.anticon');
+ expect(iconContainers.length).toBeGreaterThan(0);
+});
diff --git a/superset-frontend/src/components/TableSelector/index.tsx b/superset-frontend/src/components/TableSelector/index.tsx
index c53063f93a..6c2dfd49e3 100644
--- a/superset-frontend/src/components/TableSelector/index.tsx
+++ b/superset-frontend/src/components/TableSelector/index.tsx
@@ -127,6 +127,8 @@ export const TableOption = ({ table }: { table: Table }) => {
<TableLabel title={value}>
{type === 'view' ? (
<Icons.EyeOutlined iconSize="m" />
+ ) : type === 'materialized_view' ? (
+ <Icons.DatabaseOutlined iconSize="m" />
) : (
<Icons.InsertRowAboveOutlined iconSize="m" />
)}
diff --git a/superset/commands/database/tables.py b/superset/commands/database/tables.py
index 11b181e886..4428abab8b 100644
--- a/superset/commands/database/tables.py
+++ b/superset/commands/database/tables.py
@@ -94,6 +94,25 @@ class TablesDatabaseCommand(BaseCommand):
),
)
+ # Get materialized views if the database supports them
+ materialized_views = security_manager.get_datasources_accessible_by_user(
+ database=self._model,
+ catalog=self._catalog_name,
+ schema=self._schema_name,
+ datasource_names=sorted(
+ DatasourceName(*datasource_name)
+ for datasource_name in (
+ self._model.get_all_materialized_view_names_in_schema(
+ catalog=self._catalog_name,
+ schema=self._schema_name,
+ force=self._force,
+ cache=self._model.table_cache_enabled,
+ cache_timeout=self._model.table_cache_timeout,
+ )
+ )
+ ),
+ )
+
extra_dict_by_name = {
table.name: table.extra_dict
for table in (
@@ -131,11 +150,21 @@ class TablesDatabaseCommand(BaseCommand):
"type": "view",
}
for view in views
+ ]
+ + [
+ {
+ "value": mv.table,
+ "type": "materialized_view",
+ }
+ for mv in materialized_views
],
key=lambda item: item["value"],
)
- payload = {"count": len(tables) + len(views), "result": options}
+ payload = {
+ "count": len(tables) + len(views) + len(materialized_views),
+ "result": options,
+ }
return payload
except SupersetException:
raise
diff --git a/superset/db_engine_specs/bigquery.py b/superset/db_engine_specs/bigquery.py
index 9aa223bbcb..d28abce8c2 100644
--- a/superset/db_engine_specs/bigquery.py
+++ b/superset/db_engine_specs/bigquery.py
@@ -828,3 +828,50 @@ class BigQueryEngineSpec(BaseEngineSpec): # pylint: disable=too-many-public-met
# If for some reason we get an exception, for example, no new line
# We will return the original exception
return exception
+
+ @classmethod
+ def get_materialized_view_names(
+ cls,
+ database: Database,
+ inspector: Inspector,
+ schema: str | None,
+ ) -> set[str]:
+ """
+ Get all materialized views from BigQuery.
+
+ BigQuery materialized views are not returned by the standard
+ get_view_names() method, so we need to query INFORMATION_SCHEMA directly.
+ """
+ if not schema:
+ return set()
+
+ # Construct the query to get materialized views from INFORMATION_SCHEMA
+ catalog = database.get_default_catalog()
+ if catalog:
+ information_schema = f"`{catalog}.{schema}.INFORMATION_SCHEMA.TABLES`"
+ else:
+ information_schema = f"`{schema}.INFORMATION_SCHEMA.TABLES`"
+
+ # Use string formatting for the table name since it's not user input
+ # The catalog and schema are from trusted sources (database configuration)
+ query = f"""
+ SELECT table_name
+ FROM {information_schema}
+ WHERE table_type = 'MATERIALIZED VIEW'
+ """ # noqa: S608
+
+ materialized_views = set()
+ try:
+ with database.get_raw_connection(catalog=catalog, schema=schema) as conn:
+ cursor = conn.cursor()
+ cursor.execute(query)
+ materialized_views = {row[0] for row in cursor.fetchall()}
+ except Exception:
+ # If we can't fetch materialized views, return empty set
+ logger.warning(
+ "Unable to fetch materialized views for schema %s",
+ schema,
+ exc_info=True,
+ )
+
+ return materialized_views
diff --git a/superset/models/core.py b/superset/models/core.py
index 05267e457d..8c3a9a3360 100755
--- a/superset/models/core.py
+++ b/superset/models/core.py
@@ -864,6 +864,45 @@ class Database(Model, AuditMixinNullable, ImportExportMixin): # pylint: disable
except Exception as ex:
raise self.db_engine_spec.get_dbapi_mapped_exception(ex) from ex
+ @cache_util.memoized_func(
+ key="db:{self.id}:catalog:{catalog}:schema:{schema}:materialized_view_list",
+ cache=cache_manager.cache,
+ )
+ def get_all_materialized_view_names_in_schema(
+ self,
+ catalog: str | None,
+ schema: str,
+ ) -> set[tuple[str, str, str | None]]:
+ """Get all materialized views in the specified schema.
+
+ Parameters need to be passed as keyword arguments.
+
+ For unused parameters, they are referenced in
+ cache_util.memoized_func decorator.
+
+ :param catalog: optional catalog name
+ :param schema: schema name
+ :param cache: whether cache is enabled for the function
+ :param cache_timeout: timeout in seconds for the cache
+ :param force: whether to force refresh the cache
+ :return: set of materialized views
+ """
+ # Check if the engine spec has a method to get materialized views
+ if hasattr(self.db_engine_spec, "get_materialized_view_names"):
+ try:
+ with self.get_inspector(catalog=catalog, schema=schema) as inspector:
+ return {
+ (view, schema, catalog)
+ for view in self.db_engine_spec.get_materialized_view_names(
+ database=self,
+ inspector=inspector,
+ schema=schema,
+ )
+ }
+ except Exception as ex:
+ raise self.db_engine_spec.get_dbapi_mapped_exception(ex) from ex
+ return set()
+
@contextmanager
def get_inspector(
self,
diff --git a/tests/integration_tests/db_engine_specs/bigquery_tests.py b/tests/integration_tests/db_engine_specs/bigquery_tests.py
index aa584a26ee..c907f11cfd 100644
--- a/tests/integration_tests/db_engine_specs/bigquery_tests.py
+++ b/tests/integration_tests/db_engine_specs/bigquery_tests.py
@@ -328,3 +328,38 @@ class TestBigQueryDbEngineSpec(SupersetTestCase):
}
sql = table.get_query_str(query_obj)
assert "ORDER BY `gender_cc` ASC" in sql
+
+ def test_get_materialized_view_names(self):
+ """
+ DB Eng Specs (bigquery): Test get_materialized_view_names
+ """
+ database = mock.Mock()
+ database.get_default_catalog.return_value = "my_project"
+
+ inspector = mock.Mock()
+
+ # Mock the raw connection and cursor
+ cursor_mock = mock.Mock()
+ cursor_mock.fetchall.return_value = [
+ ("materialized_view_1",),
+ ("materialized_view_2",),
+ ]
+
+ connection_mock = mock.Mock()
+ connection_mock.cursor.return_value = cursor_mock
+ connection_mock.__enter__ = mock.Mock(return_value=connection_mock)
+ connection_mock.__exit__ = mock.Mock(return_value=None)
+
+ database.get_raw_connection.return_value = connection_mock
+
+ result = BigQueryEngineSpec.get_materialized_view_names(
+ database=database, inspector=inspector, schema="my_dataset"
+ )
+
+ assert result == {"materialized_view_1", "materialized_view_2"}
+
+ # Verify the SQL query was correct
+ cursor_mock.execute.assert_called_once()
+ executed_query = cursor_mock.execute.call_args[0][0]
+ assert "INFORMATION_SCHEMA.TABLES" in executed_query
+ assert "table_type = 'MATERIALIZED VIEW'" in executed_query