You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2025/12/11 16:33:21 UTC
(superset) 04/04: fix(examples): Fix example data loading issues and chart configurations
This is an automated email from the ASF dual-hosted git repository.
rusackas pushed a commit to branch revamped-example-loading
in repository https://gitbox.apache.org/repos/asf/superset.git
commit 63a347422e542827aa0844617a30bdffa2cbce40
Author: Evan Rusackas <ev...@rusackas.com>
AuthorDate: Wed Dec 10 23:17:06 2025 -0800
fix(examples): Fix example data loading issues and chart configurations
- Add coordinate columns (LATITUDE, LONGITUDE, LATITUDE_DEST, LONGITUDE_DEST) to flights table
- Convert bart_lines path column to path_json format
- Fix OSM chart viz_type from 'osm' to 'mapbox'
- Fix numpy array serialization issues with safe fallback to string representation
- Move big_data.py stress testing utility to CLI tools
- Fix metadata.yaml filtering to ensure it's included in imports
- Make allow_csv_upload field optional in database imports
- Update documentation for new CLI test loaders
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <no...@anthropic.com>
---
UPDATING.md | 22 ++++++++
docs/docs/contributing/development.mdx | 43 +++++++++++++++
.../{examples/big_data.py => cli/test_loaders.py} | 12 +++++
superset/commands/database/importers/v1/utils.py | 12 +++--
.../charts/Misc Charts/OSM_Long_Lat_30.yaml | 2 +-
superset/examples/data/README.md | 14 ++++-
superset/examples/data/bart_lines.duckdb | Bin 536576 -> 798720 bytes
superset/examples/data/flights.duckdb | Bin 2633728 -> 8400896 bytes
superset/examples/data_loading.py | 9 ++--
superset/examples/generic_loader.py | 59 +++++++++++++++++++--
superset/examples/utils.py | 13 +++--
11 files changed, 169 insertions(+), 17 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index 384b7d2223..e60ceecfba 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,28 @@ assists people when migrating to a new version.
## Next
+### Example Data Loading Improvements
+
+#### Simplified DuckDB-based Loading
+- All example datasets now stored as self-contained DuckDB files in `superset/examples/data/`
+- Auto-discovery of datasets - just drop a `.duckdb` file to add a new example
+- Removed Python-based data generation from individual example files
+- Fixed birth_names dataset loading issue (was incorrectly skipped)
+
+#### Test Data Reorganization
+- Moved `big_data.py` to `superset/cli/test_loaders.py` - better reflects its purpose as a test utility
+- Fixed inverted logic for `--load-test-data` flag (now correctly includes .test.yaml files when flag is set)
+- Clarified CLI flags:
+ - `--force` / `-f`: Force reload even if tables exist
+ - `--only-metadata` / `-m`: Create table metadata without loading data
+ - `--load-test-data` / `-t`: Include test dashboards and .test.yaml configs
+ - `--load-big-data` / `-b`: Generate synthetic stress-test data
+
+#### Bug Fixes
+- Fixed numpy array serialization for PostgreSQL (converts complex types to JSON strings)
+- Fixed KeyError for `allow_csv_upload` field in database configs (now optional with default)
+- Fixed test data loading logic that was incorrectly filtering files
+
### MCP Service
The MCP (Model Context Protocol) service enables AI assistants and automation tools to interact programmatically with Superset.
diff --git a/docs/docs/contributing/development.mdx b/docs/docs/contributing/development.mdx
index c39502c3b6..370a44acab 100644
--- a/docs/docs/contributing/development.mdx
+++ b/docs/docs/contributing/development.mdx
@@ -350,6 +350,12 @@ superset init
# Note: you MUST have previously created an admin user with the username `admin` for this command to work.
superset load-examples
+# The load-examples command supports various options:
+# --force / -f Force reload data even if tables exist
+# --only-metadata / -m Only create table metadata without loading data (fast setup)
+# --load-test-data / -t Load additional test dashboards and datasets
+# --load-big-data / -b Generate synthetic data for stress testing (wide tables, many tables)
+
# Start the Flask dev web server from inside your virtualenv.
# Note that your page may not have CSS at this point.
# See instructions below on how to build the front-end assets.
@@ -692,6 +698,43 @@ secrets.
---
+## Example Data and Test Loaders
+
+### Example Datasets
+
+Superset includes example datasets stored as DuckDB files in `superset/examples/data/`. These are automatically discovered and loaded when running `superset load-examples`. To add a new example dataset:
+
+1. Create a DuckDB file with your data
+2. Place it in `superset/examples/data/`
+3. The dataset will be auto-discovered on the next load
+
+### Test Data Generation
+
+For stress testing and development, Superset includes special test data generators that create synthetic data:
+
+#### Big Data Loader (`--load-big-data`)
+
+Located in `superset/cli/test_loaders.py`, this generates:
+
+- **Wide Table** (`wide_table`): 100 columns of mixed types, 1000 rows
+- **Many Small Tables** (`small_table_0` through `small_table_999`): 1000 tables for testing catalog performance
+- **Long Name Table**: Table with 60-character random name for testing UI edge cases
+
+This is primarily used for:
+- Performance testing with extreme data shapes
+- UI edge case validation
+- Database catalog stress testing
+- CI/CD pipeline validation
+
+#### Test Dashboards (`--load-test-data`)
+
+Loads additional test-specific content:
+- Tabbed dashboard example
+- Supported charts dashboard
+- Test configuration files (*.test.yaml)
+
+---
+
## Testing
### Python Testing
diff --git a/superset/examples/big_data.py b/superset/cli/test_loaders.py
similarity index 87%
rename from superset/examples/big_data.py
rename to superset/cli/test_loaders.py
index 738cae3d57..79a756788e 100644
--- a/superset/examples/big_data.py
+++ b/superset/cli/test_loaders.py
@@ -14,6 +14,18 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
+"""Test data loaders for stress testing and development.
+
+This module contains specialized data loaders that generate synthetic data
+for testing Superset's capabilities with edge cases:
+- Wide tables (many columns)
+- Many tables (testing catalog performance)
+- Long table names (UI edge cases)
+
+These loaders are invoked via CLI flags and are not part of the standard
+example datasets.
+"""
+
import logging
import random
import string
diff --git a/superset/commands/database/importers/v1/utils.py b/superset/commands/database/importers/v1/utils.py
index 2b2fd2ac3f..203c3b2555 100644
--- a/superset/commands/database/importers/v1/utils.py
+++ b/superset/commands/database/importers/v1/utils.py
@@ -34,7 +34,7 @@ from superset.utils import json
logger = logging.getLogger(__name__)
-def import_database(
+def import_database( # noqa: C901
config: dict[str, Any],
overwrite: bool = False,
ignore_permissions: bool = False,
@@ -59,8 +59,14 @@ def import_database(
except SupersetSecurityException as exc:
raise ImportFailedError(exc.message) from exc
# https://github.com/apache/superset/pull/16756 renamed ``csv`` to ``file``.
- config["allow_file_upload"] = config.pop("allow_csv_upload")
- if "schemas_allowed_for_csv_upload" in config["extra"]:
+ # Handle both old and new field names, defaulting to True for examples database
+ if "allow_csv_upload" in config:
+ config["allow_file_upload"] = config.pop("allow_csv_upload")
+ elif "allow_file_upload" not in config:
+ # Default to True for backward compatibility
+ config["allow_file_upload"] = True
+
+ if "schemas_allowed_for_csv_upload" in config.get("extra", {}):
config["extra"]["schemas_allowed_for_file_upload"] = config["extra"].pop(
"schemas_allowed_for_csv_upload"
)
diff --git a/superset/examples/configs/charts/Misc Charts/OSM_Long_Lat_30.yaml b/superset/examples/configs/charts/Misc Charts/OSM_Long_Lat_30.yaml
index 42196da8ab..54bfcedd34 100644
--- a/superset/examples/configs/charts/Misc Charts/OSM_Long_Lat_30.yaml
+++ b/superset/examples/configs/charts/Misc Charts/OSM_Long_Lat_30.yaml
@@ -2,7 +2,7 @@ slice_name: OSM Long/Lat
description: null
certified_by: null
certification_details: null
-viz_type: osm
+viz_type: mapbox
params:
all_columns:
- occupancy
diff --git a/superset/examples/data/README.md b/superset/examples/data/README.md
index 6ff30a2aa9..5f50185e3b 100644
--- a/superset/examples/data/README.md
+++ b/superset/examples/data/README.md
@@ -13,6 +13,15 @@ To add a new example dataset:
superset load-examples
```
+## CLI Loading Options
+
+The `superset load-examples` command supports several flags for different use cases:
+
+- **`--force` / `-f`**: Force reload data even if tables already exist
+- **`--only-metadata` / `-m`**: Only create table metadata without loading actual data (fast setup)
+- **`--load-test-data` / `-t`**: Include test-specific dashboards and datasets (*.test.yaml files)
+- **`--load-big-data` / `-b`**: Generate synthetic stress-test data (wide tables, many tables)
+
## DuckDB File Structure
Each `.duckdb` file should contain a single table with the same name as the file:
@@ -68,7 +77,10 @@ DATASET_DESCRIPTIONS = {
## Custom Loaders
-For datasets requiring special processing (like creating dashboards or slices), create a custom loader in `superset/examples/your_dataset.py`. See `birth_names.py` for an example.
+For datasets requiring special processing (like creating dashboards or slices), create a custom loader. Custom loaders are used for:
+- Creating example dashboards (`supported_charts_dashboard.py`, `tabbed_dashboard.py`)
+- Loading CSS templates (`css_templates.py`)
+- Generating synthetic test data (moved to `superset/cli/test_loaders.py`)
## Testing Your Dataset
diff --git a/superset/examples/data/bart_lines.duckdb b/superset/examples/data/bart_lines.duckdb
index 2738a3d6b8..3bc15f7e70 100644
Binary files a/superset/examples/data/bart_lines.duckdb and b/superset/examples/data/bart_lines.duckdb differ
diff --git a/superset/examples/data/flights.duckdb b/superset/examples/data/flights.duckdb
index 3d2a9ec9f2..87d14977f2 100644
Binary files a/superset/examples/data/flights.duckdb and b/superset/examples/data/flights.duckdb differ
diff --git a/superset/examples/data_loading.py b/superset/examples/data_loading.py
index e98b6bb348..5f21999592 100644
--- a/superset/examples/data_loading.py
+++ b/superset/examples/data_loading.py
@@ -20,6 +20,8 @@ from pathlib import Path
from typing import Callable, Dict
# Import loaders that have custom logic (dashboards, CSS, etc.)
+from superset.cli.test_loaders import load_big_data
+
from .css_templates import load_css_templates
# Import generic loader for DuckDB datasets
@@ -30,10 +32,8 @@ from .utils import load_examples_from_configs
# Map of DuckDB files to their table names (if different from file name)
TABLE_NAME_OVERRIDES = {
- "birth_france_by_region": "country_map",
"fcc_2018_survey": "FCC 2018 Survey",
"sf_population": "sf_population_polygons",
- "wb_health_population": "wb_health_population",
}
# Dataset descriptions for documentation
@@ -89,10 +89,6 @@ def discover_datasets() -> Dict[str, Callable[..., None]]:
for duckdb_file in sorted(data_dir.glob("*.duckdb")):
dataset_name = duckdb_file.stem
- # Skip birth_names as it has custom loader
- if dataset_name == "birth_names":
- continue
-
# Determine table name
table_name = TABLE_NAME_OVERRIDES.get(dataset_name, dataset_name)
@@ -121,6 +117,7 @@ globals().update(_auto_loaders)
# Build __all__ list dynamically
__all__ = [
# Custom loaders (always included)
+ "load_big_data",
"load_css_templates",
"load_supported_charts_dashboard",
"load_tabbed_dashboard",
diff --git a/superset/examples/generic_loader.py b/superset/examples/generic_loader.py
index 4d0443a1e5..200856366c 100644
--- a/superset/examples/generic_loader.py
+++ b/superset/examples/generic_loader.py
@@ -17,8 +17,9 @@
"""Generic DuckDB example data loader."""
import logging
-from typing import Optional
+from typing import Any, Callable, Optional
+import numpy as np
from sqlalchemy import inspect
from superset import db
@@ -26,12 +27,27 @@ from superset.connectors.sqla.models import SqlaTable
from superset.examples.helpers import read_example_data
from superset.models.core import Database
from superset.sql.parse import Table
+from superset.utils import json
from superset.utils.database import get_example_database
logger = logging.getLogger(__name__)
-def load_duckdb_table(
+def serialize_numpy_arrays(obj: Any) -> Any: # noqa: C901
+ """Convert numpy arrays to JSON-serializable format."""
+ if isinstance(obj, np.ndarray):
+ return obj.tolist()
+ elif isinstance(obj, np.generic):
+ # Handle numpy scalar types
+ return obj.item()
+ elif isinstance(obj, (list, tuple)):
+ return [serialize_numpy_arrays(item) for item in obj]
+ elif isinstance(obj, dict):
+ return {key: serialize_numpy_arrays(val) for key, val in obj.items()}
+ return obj
+
+
+def load_duckdb_table( # noqa: C901
duckdb_file: str,
table_name: str,
database: Optional[Database] = None,
@@ -81,6 +97,43 @@ def load_duckdb_table(
if sample_rows:
pdf = pdf.head(sample_rows)
+ # Check for columns with complex types (numpy arrays, nested structures)
+ for col in pdf.columns:
+ # Check if any value in the column is a numpy array or nested structure
+ if pdf[col].dtype == object:
+ try:
+ # Check if the first non-null value is complex
+ sample_val = (
+ pdf[col].dropna().iloc[0]
+ if not pdf[col].dropna().empty
+ else None
+ )
+ if sample_val is not None and isinstance(
+ sample_val, (np.ndarray, list, dict)
+ ):
+ logger.info("Converting complex column %s to JSON string", col)
+
+ # Convert to JSON string for database storage
+ def safe_serialize(
+ x: Any, column_name: str = col
+ ) -> Optional[str]:
+ if x is None:
+ return None
+ try:
+ return json.dumps(serialize_numpy_arrays(x))
+ except (TypeError, ValueError) as e:
+ logger.warning(
+ "Failed to serialize value in column %s: %s",
+ column_name,
+ e,
+ )
+ # Convert to string representation as fallback
+ return str(x)
+
+ pdf[col] = pdf[col].apply(lambda x, c=col: safe_serialize(x, c))
+ except Exception as e:
+ logger.warning("Could not process column %s: %s", col, e)
+
# Write to target database
with database.get_sqla_engine() as engine:
pdf.to_sql(
@@ -124,7 +177,7 @@ def create_generic_loader(
table_name: Optional[str] = None,
description: Optional[str] = None,
sample_rows: Optional[int] = None,
-) -> callable:
+) -> Callable[[Database, SqlaTable], None]:
"""Create a loader function for a specific DuckDB file.
This factory function creates loaders that match the existing pattern
diff --git a/superset/examples/utils.py b/superset/examples/utils.py
index d5da9c7c53..9bb5cdbdec 100644
--- a/superset/examples/utils.py
+++ b/superset/examples/utils.py
@@ -43,7 +43,12 @@ def load_examples_from_configs(
def load_contents(load_test_data: bool = False) -> dict[str, Any]:
- """Traverse configs directory and load contents"""
+ """Traverse configs directory and load contents.
+
+ Args:
+ load_test_data: If True, includes test data files (*.test.yaml).
+ If False, excludes test data files.
+ """
root = files("superset") / "examples/configs"
resource_names = (files("superset") / str(root)).iterdir()
queue = [root / str(resource_name) for resource_name in resource_names]
@@ -51,7 +56,7 @@ def load_contents(load_test_data: bool = False) -> dict[str, Any]:
contents: dict[Path, str] = {}
while queue:
path_name = queue.pop()
- test_re = re.compile(r"\.test\.|metadata\.yaml$")
+ test_re = re.compile(r"\.test\.")
if (files("superset") / str(path_name)).is_dir():
queue.extend(
@@ -59,8 +64,10 @@ def load_contents(load_test_data: bool = False) -> dict[str, Any]:
for child_name in (files("superset") / str(path_name)).iterdir()
)
elif Path(str(path_name)).suffix.lower() in YAML_EXTENSIONS:
- if load_test_data and test_re.search(str(path_name)) is None:
+ # Skip test files if load_test_data is False
+ if not load_test_data and test_re.search(str(path_name)):
continue
+ # Always include all other YAML files (including metadata.yaml)
contents[Path(str(path_name))] = (
files("superset") / str(path_name)
).read_text("utf-8")