mirror of
https://github.com/apache/superset.git
synced 2026-09-10 01:04:25 +00:00
Compare commits
33
Commits
@@ -41,7 +41,7 @@ jobs:
|
||||
|
||||
- name: Check for File Changes
|
||||
id: check
|
||||
uses: ./.github/actions/change-detector/
|
||||
uses: $/.github/actions/change-detector/
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Check for file changes
|
||||
id: check
|
||||
uses: ./.github/actions/change-detector/
|
||||
uses: $/.github/actions/change-detector/
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -109,13 +109,25 @@ jobs:
|
||||
submodules: recursive
|
||||
# -------------------------------------------------------
|
||||
- name: Setup Python
|
||||
uses: ./.github/actions/setup-backend/
|
||||
uses: $/.github/actions/setup-backend/
|
||||
- name: Setup postgres
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# cached-dependencies is a submodule (not a plain directory), and
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's link. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
with:
|
||||
run: setup-postgres
|
||||
- name: Import test data
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# cached-dependencies is a submodule (not a plain directory), and
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's link. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
with:
|
||||
run: playwright_testdata
|
||||
- name: Setup Node.js
|
||||
@@ -125,19 +137,42 @@ jobs:
|
||||
cache: "npm"
|
||||
cache-dependency-path: "superset-frontend/package-lock.json"
|
||||
- name: Install npm dependencies
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# cached-dependencies is a submodule (not a plain directory), and
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's link. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
with:
|
||||
run: npm-install
|
||||
- name: Build javascript packages
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# cached-dependencies is a submodule (not a plain directory), and
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's link. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
with:
|
||||
run: build-instrumented-assets
|
||||
- name: Install Playwright
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's gitlink. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
with:
|
||||
run: playwright-install
|
||||
- name: Run Playwright (Experimental Tests)
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# cached-dependencies is a submodule (not a plain directory), and
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's link. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
env:
|
||||
NODE_OPTIONS: "--max-old-space-size=4096"
|
||||
with:
|
||||
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
- name: Check for file changes
|
||||
id: check
|
||||
uses: ./.github/actions/change-detector/
|
||||
uses: $/.github/actions/change-detector/
|
||||
with:
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -75,9 +75,15 @@ jobs:
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Setup Python
|
||||
uses: ./.github/actions/setup-backend/
|
||||
uses: $/.github/actions/setup-backend/
|
||||
- name: Setup MySQL
|
||||
uses: ./.github/actions/cached-dependencies
|
||||
# cached-dependencies is a git submodule (not a plain directory), and
|
||||
# the $/ self-repository syntax resolves action files directly from
|
||||
# the repository without performing a real (submodule-aware)
|
||||
# checkout, so it can't see into a submodule's gitlink. Keep this one
|
||||
# on the workspace-relative ./ form, consistent with every other
|
||||
# workflow in the repo that references this action.
|
||||
uses: ./.github/actions/cached-dependencies # zizmor: ignore[self-repository] - $/ cannot resolve an action that lives in a submodule; ./ is required here
|
||||
with:
|
||||
run: setup-mysql
|
||||
- name: Start Celery worker
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
# db_engine_specs tests against real databases (testcontainers)
|
||||
name: Testcontainers
|
||||
|
||||
# Spins up real Docker containers (see tests/testcontainers/ for the current
|
||||
# dialect list) via testcontainers-python, which catches real dialect/driver
|
||||
# regressions -- the kind mocked db_engine_specs unit tests structurally
|
||||
# cannot, e.g. apache/superset#42899 (Trino emitting OFFSET before LIMIT).
|
||||
# Runs on a nightly cron (catches drift from a driver's own releases, not
|
||||
# just from Superset's changes) and on pull_request, scoped via `paths` to
|
||||
# only PRs that actually touch this test suite or the workflow itself, so
|
||||
# unrelated PRs across the repo are never affected.
|
||||
#
|
||||
# A matrix entry can set `nightly_only: true` to run only on the cron (or a
|
||||
# manual workflow_dispatch), never on pull_request -- for a dialect whose
|
||||
# image is too heavy (a multi-service cluster, a many-GB image, a slow
|
||||
# licensed installer) to justify adding its wall-clock/resource cost to
|
||||
# every PR that merely touches this suite. Omit the field entirely for a
|
||||
# normal dialect; it isn't nightly-only by default.
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: "0 5 * * *"
|
||||
workflow_dispatch: {}
|
||||
pull_request:
|
||||
paths:
|
||||
- ".github/workflows/testcontainers.yml"
|
||||
- "tests/testcontainers/**"
|
||||
- "superset/db_engine_specs/**"
|
||||
- "pyproject.toml"
|
||||
- "requirements/development.in"
|
||||
- "requirements/development.txt"
|
||||
|
||||
concurrency:
|
||||
# Scoped by ref, not just workflow name -- otherwise every PR run and the
|
||||
# nightly cron share one group, and starting the workflow on another PR
|
||||
# (or the nightly firing mid-PR-run) cancels an unrelated in-progress run.
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
compute-matrix:
|
||||
# Filters out `nightly_only` dialects for a pull_request run *before* any
|
||||
# testcontainers job is created for them, so a heavy dialect costs a PR
|
||||
# nothing at all -- not even its checkout/setup/driver-install steps --
|
||||
# rather than being merely skipped at the test step. A job-level `if:`
|
||||
# can't reference `matrix` (only github/inputs/needs/vars are available
|
||||
# there), so the filtering has to happen here, before the matrix exists,
|
||||
# instead of on the testcontainers job itself.
|
||||
runs-on: ubuntu-26.04
|
||||
outputs:
|
||||
include: ${{ steps.filter.outputs.include }}
|
||||
steps:
|
||||
- name: Filter nightly-only dialects
|
||||
id: filter
|
||||
env:
|
||||
# One entry per dialect rather than one job for the whole suite: a
|
||||
# single slow container would otherwise inflate the wall-clock
|
||||
# time for every dialect, not just its own. Running in parallel
|
||||
# means the suite's total time is bounded by the slowest dialect,
|
||||
# not the sum of all of them. Db2's first-boot init is documented
|
||||
# upstream as notably slow (a real instance bring-up, not just a
|
||||
# process start) and untested locally here (no arm64 image), so
|
||||
# it gets a wider timeout margin than the rest until real CI data
|
||||
# says otherwise.
|
||||
FULL_MATRIX: |
|
||||
[
|
||||
{"dialect": "cockroachdb", "timeout": 10},
|
||||
{"dialect": "crate", "timeout": 10},
|
||||
{"dialect": "trino", "timeout": 10},
|
||||
{"dialect": "mssql", "timeout": 10},
|
||||
{"dialect": "elasticsearch", "timeout": 10},
|
||||
{"dialect": "oracle", "timeout": 15},
|
||||
{"dialect": "db2", "timeout": 25},
|
||||
{"dialect": "mariadb", "timeout": 10},
|
||||
{"dialect": "timescaledb", "timeout": 10},
|
||||
{"dialect": "yugabytedb", "timeout": 10},
|
||||
{"dialect": "monetdb", "timeout": 10},
|
||||
{"dialect": "mongodb", "timeout": 10},
|
||||
{"dialect": "postgres", "timeout": 10},
|
||||
{"dialect": "mysql", "timeout": 10},
|
||||
{"dialect": "clickhouse", "timeout": 10},
|
||||
{"dialect": "starrocks", "timeout": 15},
|
||||
{"dialect": "databend", "timeout": 10},
|
||||
{"dialect": "risingwave", "timeout": 10},
|
||||
{"dialect": "firebird", "timeout": 10},
|
||||
{"dialect": "ydb", "timeout": 10},
|
||||
{"dialect": "oceanbase", "timeout": 20, "nightly_only": true}
|
||||
]
|
||||
run: |
|
||||
if [[ "${{ github.event_name }}" == "schedule" || "${{ github.event_name }}" == "workflow_dispatch" ]]; then
|
||||
include="$(jq -c '.' <<<"$FULL_MATRIX")"
|
||||
else
|
||||
include="$(jq -c '[.[] | select(.nightly_only != true)]' <<<"$FULL_MATRIX")"
|
||||
fi
|
||||
echo "include=${include}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
testcontainers:
|
||||
needs: [compute-matrix]
|
||||
runs-on: ubuntu-26.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJson(needs.compute-matrix.outputs.include) }}
|
||||
timeout-minutes: ${{ matrix.timeout }}
|
||||
env:
|
||||
PYTHONPATH: ${{ github.workspace }}
|
||||
SUPERSET_TESTENV: true
|
||||
SUPERSET_SECRET_KEY: not-a-secret
|
||||
# This job's matrix installs exactly one dialect's testcontainers
|
||||
# driver for exactly this job, so treat that driver as required: a
|
||||
# broken/missing import should fail the job, not silently skip to a
|
||||
# misleadingly green, zero-tests-run result. See _driver.py.
|
||||
SUPERSET_TESTCONTAINERS_STRICT: true
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Setup Python
|
||||
uses: ./.github/actions/setup-backend/
|
||||
with:
|
||||
python-version: current
|
||||
- name: Install db2 driver (ibm-db-sa)
|
||||
# ibm-db (the db2 DBAPI) ships no Linux arm64 wheel, so it's kept out
|
||||
# of the baseline dev install (requirements/development.in) to avoid
|
||||
# breaking the multi-platform dev Docker image build. Install it here
|
||||
# instead, only for this leg of the matrix.
|
||||
if: matrix.dialect == 'db2'
|
||||
run: uv pip install --system -e .[db2]
|
||||
- name: Install oceanbase driver (oceanbase_py)
|
||||
# oceanbase_py pins sqlalchemy-utils>=0.38.3,<0.39, which conflicts
|
||||
# outright with Superset's own sqlalchemy-utils==0.42.1 pin -- kept
|
||||
# out of the baseline dev install for the same reason as db2 above.
|
||||
# Installed as its own standalone package (not via `-e .[oceanbase]`)
|
||||
# so --no-deps only skips *oceanbase_py's* dependencies -- applied
|
||||
# to `-e .[oceanbase]` instead, --no-deps blocks pip from installing
|
||||
# anything the extras marker pulls in, including oceanbase_py
|
||||
# itself, which "succeeds" without actually installing it
|
||||
# (confirmed on real CI: the install step reported success, but the
|
||||
# module was still missing). This job only needs oceanbase_py's
|
||||
# dialect module importable, not its sqlalchemy-utils dependency
|
||||
# satisfied, since nothing here calls into it.
|
||||
if: >-
|
||||
matrix.dialect == 'oceanbase' &&
|
||||
(matrix.nightly_only != true ||
|
||||
github.event_name == 'schedule' ||
|
||||
github.event_name == 'workflow_dispatch')
|
||||
run: uv pip install --system --no-deps "oceanbase_py>=0.0.1.2"
|
||||
- name: Install Firebird client library (libfbclient2)
|
||||
# sqlalchemy-firebird's driver (firebird-driver) is a pure-Python
|
||||
# ctypes wrapper (its wheel is py3-none-any) that dynamically loads
|
||||
# the native Firebird client library from the host at import time
|
||||
# -- it doesn't bundle that library itself, so it has to come from
|
||||
# the system package manager, only for this leg of the matrix.
|
||||
if: matrix.dialect == 'firebird'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libfbclient2
|
||||
- name: Run testcontainers db_engine_specs tests (${{ matrix.dialect }})
|
||||
# nightly_only dialects are already excluded from the matrix itself
|
||||
# on pull_request runs (see the compute-matrix job above), so this
|
||||
# step needs no additional gating.
|
||||
run: |
|
||||
pytest --durations-min=2 -v -m testcontainers \
|
||||
./tests/testcontainers/db_engine_specs/test_${{ matrix.dialect }}.py \
|
||||
--junit-xml=test-results/junit-testcontainers-${{ matrix.dialect }}.xml
|
||||
- name: Upload JUnit test results
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: junit-results-testcontainers-${{ matrix.dialect }}
|
||||
path: test-results/
|
||||
retention-days: 7
|
||||
|
||||
actions-timeline:
|
||||
needs: [testcontainers]
|
||||
if: always()
|
||||
runs-on: ubuntu-26.04
|
||||
permissions:
|
||||
actions: read
|
||||
steps:
|
||||
- uses: Kesin11/actions-timeline@57fc93f20c6da7fbc14063c6d24a2a5627c799ad # v3.2.0
|
||||
+56
-25
@@ -231,20 +231,6 @@ RUN /app/docker/apt-install.sh \
|
||||
# The database file will be created at runtime when examples are loaded from Parquet files
|
||||
RUN mkdir -p /app/data && chown -R superset:superset /app/data
|
||||
|
||||
# Copy compiled things from previous stages
|
||||
COPY --from=superset-node /app/superset/static/assets superset/static/assets
|
||||
# Copy service.worker.js optionall as it doesn't exist when DEV_MODE=true
|
||||
COPY --from=superset-node /app/superset/static/service-worker.j[s] superset/static/service-worker.js
|
||||
|
||||
# TODO, when the next version comes out, use --exclude superset/translations
|
||||
COPY superset superset
|
||||
# TODO in the meantime, remove the .po files
|
||||
RUN rm superset/translations/*/*/*.po
|
||||
|
||||
# Merging translations from backend and frontend stages
|
||||
COPY --from=superset-node /app/superset/translations superset/translations
|
||||
COPY --from=python-translation-compiler /app/translations_mo superset/translations
|
||||
|
||||
# --- Realtime WebSocket server (part of the official image) ---------------
|
||||
# The realtime transport (superset-websocket) is a Node service, bundled by
|
||||
# esbuild into a single self-contained file. Copy the Node runtime plus that
|
||||
@@ -267,7 +253,10 @@ EXPOSE ${SUPERSET_PORT}
|
||||
######################################################################
|
||||
FROM python-common AS lean
|
||||
|
||||
# Install Python dependencies using docker/pip-install.sh
|
||||
# Install Python dependencies using docker/pip-install.sh.
|
||||
# Requirements are installed *before* the application source is copied
|
||||
# below so that source-only changes don't bust this (slow, network-bound)
|
||||
# cache layer or defeat --cache-from.
|
||||
COPY requirements/base.txt requirements/
|
||||
|
||||
# Copy superset-core package needed for editable install in base.txt
|
||||
@@ -275,9 +264,27 @@ COPY superset-core superset-core
|
||||
|
||||
RUN --mount=type=cache,target=${SUPERSET_HOME}/.cache/uv \
|
||||
/app/docker/pip-install.sh --requires-build-essential -r requirements/base.txt
|
||||
# Install the superset package
|
||||
|
||||
# Copy compiled frontend assets and application source now that
|
||||
# dependencies have been resolved and cached above.
|
||||
COPY --from=superset-node /app/superset/static/assets superset/static/assets
|
||||
# Copy service.worker.js optionally as it doesn't exist when DEV_MODE=true
|
||||
COPY --from=superset-node /app/superset/static/service-worker.j[s] superset/static/service-worker.js
|
||||
|
||||
# TODO, when the next version comes out, use --exclude superset/translations
|
||||
COPY superset superset
|
||||
# TODO in the meantime, remove the .po files
|
||||
RUN rm superset/translations/*/*/*.po
|
||||
|
||||
# Merging translations from backend and frontend stages
|
||||
COPY --from=superset-node /app/superset/translations superset/translations
|
||||
COPY --from=python-translation-compiler /app/translations_mo superset/translations
|
||||
|
||||
# Install the superset package itself. --no-deps because its dependencies
|
||||
# were already installed from requirements/base.txt above, so this layer
|
||||
# stays fast even though the source copy above changes on every edit.
|
||||
RUN --mount=type=cache,target=${SUPERSET_HOME}/.cache/uv \
|
||||
uv pip install -e .
|
||||
uv pip install -e . --no-deps
|
||||
RUN python -m compileall /app/superset
|
||||
|
||||
USER superset
|
||||
@@ -293,22 +300,46 @@ RUN /app/docker/apt-install.sh \
|
||||
pkg-config \
|
||||
default-libmysqlclient-dev
|
||||
|
||||
# Copy development requirements and install them
|
||||
# Copy development requirements and install them *before* the application
|
||||
# source is copied below, so source-only edits don't bust this cache layer.
|
||||
COPY requirements/*.txt requirements/
|
||||
|
||||
# Copy local packages needed for editable installs in development.txt
|
||||
COPY superset-core superset-core
|
||||
COPY superset-extensions-cli superset-extensions-cli
|
||||
|
||||
# Install Python dependencies using docker/pip-install.sh
|
||||
# requirements/development.txt is generated by `uv pip compile` and embeds
|
||||
# `-e .` (an editable install of this same package) as its first line. That
|
||||
# self-reference needs the full superset/ source tree, which hasn't been
|
||||
# copied in yet at this point, so it's stripped here; the real editable
|
||||
# install of `.` runs below, once the source is present.
|
||||
RUN --mount=type=cache,target=${SUPERSET_HOME}/.cache/uv \
|
||||
/app/docker/pip-install.sh --requires-build-essential -r requirements/development.txt
|
||||
# Install the superset package
|
||||
RUN --mount=type=cache,target=${SUPERSET_HOME}/.cache/uv \
|
||||
uv pip install -e .
|
||||
grep -vxF -- "-e ." requirements/development.txt > requirements/development-deps.txt && \
|
||||
/app/docker/pip-install.sh --requires-build-essential -r requirements/development-deps.txt
|
||||
|
||||
RUN uv pip install .[postgres]
|
||||
RUN python -m compileall /app/superset
|
||||
# Copy compiled frontend assets and application source now that
|
||||
# dependencies have been resolved and cached above.
|
||||
COPY --from=superset-node /app/superset/static/assets superset/static/assets
|
||||
# Copy service.worker.js optionally as it doesn't exist when DEV_MODE=true
|
||||
COPY --from=superset-node /app/superset/static/service-worker.j[s] superset/static/service-worker.js
|
||||
|
||||
# TODO, when the next version comes out, use --exclude superset/translations
|
||||
COPY superset superset
|
||||
# TODO in the meantime, remove the .po files
|
||||
RUN rm superset/translations/*/*/*.po
|
||||
|
||||
# Merging translations from backend and frontend stages
|
||||
COPY --from=superset-node /app/superset/translations superset/translations
|
||||
COPY --from=python-translation-compiler /app/translations_mo superset/translations
|
||||
|
||||
# Install the superset package together with its postgres extra, using the
|
||||
# same uv cache mount as the requirements install above. --no-deps because
|
||||
# all dependencies (including the postgres extra's psycopg2-binary) are
|
||||
# already installed from requirements/development.txt above.
|
||||
# NOTE: source is bind-mounted over /app/superset in DEV_MODE, so a
|
||||
# compileall pass here would be wasted work; unlike `lean`, `dev` skips it.
|
||||
RUN --mount=type=cache,target=${SUPERSET_HOME}/.cache/uv \
|
||||
uv pip install -e .[postgres] --no-deps
|
||||
|
||||
USER superset
|
||||
|
||||
|
||||
+3
-1
@@ -232,7 +232,7 @@ unknown impact as zero. Chart and dashboard purge endpoints are unchanged.
|
||||
- The dashboard datasource-based visibility fallback now fails closed: a dashboard whose member charts’ datasources cannot be resolved (deleted datasource rows, missing `datasource_id`, or unsupported datasource types) is no longer accessible to users without explicit editor/viewer rights, and a dashboard composed of semantic-view charts now requires `datasource_access` on (at least one of) its semantic views or their parent semantic layer — previously any authenticated user could open such a dashboard’s shell. Because the fallback now considers every member chart rather than only table-backed ones, a user holding `datasource_access` on any single member datasource — including a semantic view or its parent layer — can open a mixed dashboard that previously denied them. Dashboards with no charts remain accessible, and dashboards with explicit viewers are unaffected. Conversely, holders of `all_datasource_access` now see every published no-viewer dashboard in the dashboard list — including chart-less ones previously hidden by the inner joins — matching what the object-level gate already allowed them to open.
|
||||
- Version restore (`POST /api/v1/{chart,dashboard,dataset}/<uuid>/versions/<version_uuid>/restore`) now refuses an **externally managed** entity (`is_managed_externally = True`) with HTTP 403, enforcing server-side what the docs already promised. Previously the refusal existed only in the browser, so an otherwise-authorized editor could restore such an entity by calling the endpoint directly and have the restore overwritten on the next external sync. Soft-delete recovery is deliberately unaffected — it changes visibility, not content.
|
||||
- `SAMPLES_ROW_LIMIT` is now the default for `/datasource/samples` requests without a valid explicit `per_page`, rather than a hard per-request ceiling; explicit limits are honored up to the existing global row-limit ceiling, matching `/chart/data` SAMPLES requests.
|
||||
- The `cockroachdb` extra (`pip install apache-superset[cockroachdb]`) now installs `sqlalchemy-cockroachdb` instead of the abandoned `cockroachdb` package, whose SQLAlchemy dialect could not be imported under SQLAlchemy 2.0. Existing environments with the old package installed should `pip uninstall cockroachdb && pip install sqlalchemy-cockroachdb` (or simply reinstall the extra) to restore CockroachDB connectivity.
|
||||
- The `cockroachdb` extra (`pip install apache-superset[cockroachdb]`) now installs `sqlalchemy-cockroachdb` instead of the abandoned `cockroachdb` package, whose SQLAlchemy dialect could not be imported under SQLAlchemy 2.0. Existing environments with the old package installed must `pip uninstall cockroachdb` before reinstalling the extra -- both packages register the same `cockroachdb` SQLAlchemy dialect entry point, so leaving the old one in place can still load the abandoned implementation.
|
||||
|
||||
### Native Value filter "Select all" always targets the whole column
|
||||
|
||||
@@ -1233,6 +1233,8 @@ Custom time ranges that use the "Now" or "Today" anchor (for the Start, End, or
|
||||
|
||||
Charts and dashboards using these anchors will compute a different (correct) timestamp after upgrading; if a chart's filters or drill-downs were tuned to compensate for the old offset, review them after upgrading.
|
||||
|
||||
- [43916](https://github.com/apache/superset/pull/43916): The `docker-compose` dev loop now skips re-running `superset load_examples` on every `docker compose up` once the example data and dashboards are present in the databases (set `SUPERSET_FORCE_LOAD_EXAMPLES=yes` to reload them anyway), and the `superset-node` service now defaults `DISABLE_TS_CHECKER=true` like `docker-compose-light.yml` already did, skipping webpack's TypeScript type-checking pass in dev by default.
|
||||
|
||||
## 6.1.0
|
||||
|
||||
### ClickHouse minimum driver version bump
|
||||
|
||||
@@ -138,6 +138,7 @@ services:
|
||||
condition: service_started
|
||||
volumes: *superset-volumes
|
||||
environment:
|
||||
SUPERSET_FORCE_LOAD_EXAMPLES: "${SUPERSET_FORCE_LOAD_EXAMPLES:-}"
|
||||
DATABASE_HOST: db-light
|
||||
DATABASE_DB: superset_light
|
||||
POSTGRES_DB: superset_light
|
||||
|
||||
@@ -183,6 +183,8 @@ services:
|
||||
condition: service_started
|
||||
user: *superset-user
|
||||
volumes: *superset-volumes
|
||||
environment:
|
||||
SUPERSET_FORCE_LOAD_EXAMPLES: "${SUPERSET_FORCE_LOAD_EXAMPLES:-}"
|
||||
healthcheck:
|
||||
disable: true
|
||||
|
||||
@@ -202,6 +204,7 @@ services:
|
||||
BUILD_SUPERSET_FRONTEND_IN_DOCKER: true
|
||||
NPM_RUN_PRUNE: false
|
||||
SCARF_ANALYTICS: "${SCARF_ANALYTICS:-}"
|
||||
DISABLE_TS_CHECKER: "${DISABLE_TS_CHECKER:-true}"
|
||||
# configuring the dev-server to use the host.docker.internal to connect to the backend
|
||||
superset: "http://superset:8088"
|
||||
# Webpack dev server must bind to 0.0.0.0 to be accessible from outside the container
|
||||
|
||||
@@ -73,6 +73,12 @@ SUPERSET_ENV=development
|
||||
# Swagger UI is opt-in (off by default); enable it for local development.
|
||||
SUPERSET_ENABLE_SWAGGER_UI=true
|
||||
SUPERSET_LOAD_EXAMPLES=yes
|
||||
# Once the example data and dashboards are present in the databases,
|
||||
# `docker-init.sh` skips `superset load_examples` on later runs. Set to "yes"
|
||||
# (or run `SUPERSET_FORCE_LOAD_EXAMPLES=yes docker compose up`) to reload the
|
||||
# examples anyway, e.g. after changing the example datasets or after a partial
|
||||
# load.
|
||||
#SUPERSET_FORCE_LOAD_EXAMPLES=no
|
||||
CYPRESS_CONFIG=false
|
||||
SUPERSET_PORT=8088
|
||||
MAPBOX_API_KEY=''
|
||||
|
||||
+33
-3
@@ -66,14 +66,44 @@ echo_step "3" "Starting" "Setting up roles and perms"
|
||||
superset init
|
||||
echo_step "3" "Complete" "Setting up roles and perms"
|
||||
|
||||
# Loading examples parses and inserts every example dataset, chart and
|
||||
# dashboard and is one of the slowest steps of `docker compose up`. Rather
|
||||
# than trusting a marker file (which goes stale as soon as the database volume
|
||||
# is recreated), ask the databases themselves: when both the example data and
|
||||
# the dashboards imported from it are present, the previous load completed and
|
||||
# there is nothing left to redo. Any failure here (missing tables, unreachable
|
||||
# database, import error) simply reports "not loaded" so the full load runs.
|
||||
examples_already_loaded() {
|
||||
python - <<'PY' 2>/dev/null
|
||||
import sys
|
||||
|
||||
from superset.app import create_app
|
||||
from superset.sql.parse import Table
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
from superset import db
|
||||
from superset.models.dashboard import Dashboard
|
||||
from superset.utils.database import get_example_database
|
||||
|
||||
has_dashboard = (
|
||||
db.session.query(Dashboard).filter_by(slug="world_health").first() is not None
|
||||
)
|
||||
has_data = get_example_database().has_table(Table("wb_health_population"))
|
||||
sys.exit(0 if has_dashboard and has_data else 1)
|
||||
PY
|
||||
}
|
||||
|
||||
if [ "$SUPERSET_LOAD_EXAMPLES" = "yes" ]; then
|
||||
# Load some data to play with
|
||||
echo_step "4" "Starting" "Loading examples"
|
||||
|
||||
|
||||
# If Cypress run which consumes superset_test_config – load required data for tests
|
||||
# Cypress runs always load, since they need a distinct set of test data
|
||||
# (`--load-test-data`) in a separate database. Set
|
||||
# SUPERSET_FORCE_LOAD_EXAMPLES=yes to reload the examples regardless.
|
||||
if [ "$CYPRESS_CONFIG" == "true" ]; then
|
||||
superset load_examples --load-test-data
|
||||
elif [ "$SUPERSET_FORCE_LOAD_EXAMPLES" != "yes" ] && examples_already_loaded; then
|
||||
echo "Examples already loaded, skipping (set SUPERSET_FORCE_LOAD_EXAMPLES=yes to reload them)"
|
||||
else
|
||||
superset load_examples
|
||||
fi
|
||||
|
||||
@@ -259,8 +259,8 @@ Superset automatically retries webhook deliveries on `429 Too Many Requests` and
|
||||
|
||||
### Kubernetes-specific
|
||||
|
||||
- You must have a `celery beat` pod running. If you're using the chart included in the GitHub repository under [helm/superset](https://github.com/apache/superset/tree/master/helm/superset), you need to put `supersetCeleryBeat.enabled = true` in your values override.
|
||||
- You can see the dedicated docs about [Kubernetes installation](/admin-docs/installation/kubernetes) for more details.
|
||||
- You must have a `celery beat` pod running. For Kubernetes deployments, use the [Apache Superset Kubernetes Operator documentation](https://apache.github.io/superset-kubernetes-operator/) for deployment configuration.
|
||||
- Existing legacy Helm chart deployments configure this with `supersetCeleryBeat.enabled = true` in the values override.
|
||||
|
||||
### Docker Compose specific
|
||||
|
||||
|
||||
@@ -18,7 +18,7 @@ Since `docker compose` is primarily designed to run a set of containers on **a s
|
||||
and can't support requirements for **high availability**, we do not support nor recommend
|
||||
using our `docker compose` constructs to support production-type use-cases. For single host
|
||||
environments, we recommend using [minikube](https://minikube.sigs.k8s.io/docs/start/) along
|
||||
with our [installing on k8s](https://superset.apache.org/admin-docs/installation/running-on-kubernetes)
|
||||
with our [Kubernetes installation](/admin-docs/installation/kubernetes)
|
||||
documentation.
|
||||
:::
|
||||
|
||||
@@ -196,7 +196,9 @@ One important variable is `SUPERSET_LOAD_EXAMPLES` which determines whether the
|
||||
container will populate example data and visualizations into the metadata database. These examples
|
||||
are helpful for learning and testing out Superset but unnecessary for experienced users and
|
||||
production deployments. The loading process can sometimes take a few minutes and a good amount of
|
||||
CPU, so you may want to disable it on a resource-constrained device.
|
||||
CPU, so you may want to disable it on a resource-constrained device. Once the example data and
|
||||
dashboards are present in the databases, later `superset_init` runs skip loading them; run
|
||||
`SUPERSET_FORCE_LOAD_EXAMPLES=yes docker compose up` to reload the examples anyway.
|
||||
|
||||
For more advanced or dynamic configurations that are typically managed in a `superset_config.py` file
|
||||
located in your `PYTHONPATH`, note that it can be done by providing a
|
||||
|
||||
@@ -33,13 +33,13 @@ Ideally you will build your own image of Superset that extends `lean`, adding wh
|
||||
|
||||
**Summary:** This is the best-practice way to deploy a production instance of Superset, but has the steepest skill requirement - someone who knows Kubernetes.
|
||||
|
||||
You will deploy Superset into a K8s cluster. The most common method is using the community-maintained Helm chart, though work is now underway to implement [SIP-149 - a Kubernetes Operator for Superset](https://github.com/apache/superset/issues/31408).
|
||||
You will deploy Superset into a K8s cluster. The recommended method is the official [Apache Superset Kubernetes Operator](https://apache.github.io/superset-kubernetes-operator/). The in-tree Helm chart is deprecated and is not recommended for new deployments.
|
||||
|
||||
A K8s deployment can scale up and down based on usage and deploy rolling updates with zero downtime - features that big deployments appreciate.
|
||||
|
||||
**Responsibilities**
|
||||
|
||||
You will need to build your own Docker image, and back up your metadata DB, both as described in Docker Compose above. You'll also need to customize your Helm chart values and deploy and maintain your Kubernetes cluster.
|
||||
You will need to build your own Docker image, and back up your metadata DB, both as described in Docker Compose above. You'll also need to configure the operator's Superset resources and deploy and maintain your Kubernetes cluster.
|
||||
|
||||
## [PyPI (Python)](/admin-docs/installation/pypi)
|
||||
|
||||
|
||||
@@ -13,499 +13,35 @@ import useBaseUrl from '@docusaurus/useBaseUrl';
|
||||
<br />
|
||||
<br />
|
||||
|
||||
Running Superset on Kubernetes is supported with the provided [Helm](https://helm.sh/) chart
|
||||
found in the official [Superset helm repository](https://apache.github.io/superset/index.yaml).
|
||||
Running Superset on Kubernetes is supported through the official
|
||||
[Apache Superset Kubernetes Operator](https://apache.github.io/superset-kubernetes-operator/).
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- A Kubernetes cluster
|
||||
- Helm installed
|
||||
|
||||
:::note
|
||||
For simpler, single host environments, we recommend using
|
||||
[minikube](https://minikube.sigs.k8s.io/docs/start/) which is easy to setup on many platforms
|
||||
and works fantastically well with the Helm chart referenced here.
|
||||
:::warning
|
||||
The Superset Helm chart under
|
||||
[`helm/superset`](https://github.com/apache/superset/tree/master/helm/superset)
|
||||
is deprecated and is not recommended for new Kubernetes deployments.
|
||||
:::
|
||||
|
||||
## Running
|
||||
Use the operator documentation as the source of truth for Kubernetes installation and operations.
|
||||
It covers installing the operator, defining Superset deployments with Kubernetes custom resources,
|
||||
configuring dependencies, upgrades, and operational workflows.
|
||||
|
||||
1. Add the Superset helm repository
|
||||
## New Deployments
|
||||
|
||||
```sh
|
||||
helm repo add superset https://apache.github.io/superset
|
||||
"superset" has been added to your repositories
|
||||
```
|
||||
Start with the
|
||||
[Apache Superset Kubernetes Operator documentation](https://apache.github.io/superset-kubernetes-operator/).
|
||||
|
||||
2. View charts in repo
|
||||
## Existing Helm Deployments
|
||||
|
||||
```sh
|
||||
helm search repo superset
|
||||
NAME CHART VERSION APP VERSION DESCRIPTION
|
||||
superset/superset 0.1.1 1.0 Apache Superset is a modern, enterprise-ready b...
|
||||
```
|
||||
Existing Helm chart users should plan a migration to the operator. Follow the
|
||||
[Helm chart migration guide](https://apache.github.io/superset-kubernetes-operator/user-guide/migration/)
|
||||
for the recommended migration path.
|
||||
|
||||
3. Configure your setting overrides
|
||||
Until migration is complete, legacy chart reference material remains available in the deprecated
|
||||
[Helm chart README](https://github.com/apache/superset/tree/master/helm/superset).
|
||||
|
||||
Just like any typical Helm chart, you'll need to craft a `values.yaml` file that would define/override any of the values exposed into the default [values.yaml](https://github.com/apache/superset/tree/master/helm/superset/values.yaml), or from any of the dependent charts it depends on:
|
||||
## Resources
|
||||
|
||||
- [bitnami/redis](https://artifacthub.io/packages/helm/bitnami/redis)
|
||||
- [bitnami/postgresql](https://artifacthub.io/packages/helm/bitnami/postgresql)
|
||||
|
||||
More info down below on some important overrides you might need.
|
||||
|
||||
4. Install and run
|
||||
|
||||
```sh
|
||||
helm upgrade --install --values my-values.yaml superset superset/superset
|
||||
```
|
||||
|
||||
You should see various pods popping up, such as:
|
||||
|
||||
```sh
|
||||
kubectl get pods
|
||||
NAME READY STATUS RESTARTS AGE
|
||||
superset-celerybeat-7cdcc9575f-k6xmc 1/1 Running 0 119s
|
||||
superset-f5c9c667-dw9lp 1/1 Running 0 4m7s
|
||||
superset-f5c9c667-fk8bk 1/1 Running 0 4m11s
|
||||
superset-init-db-zlm9z 0/1 Completed 0 111s
|
||||
superset-postgresql-0 1/1 Running 0 6d20h
|
||||
superset-redis-master-0 1/1 Running 0 6d20h
|
||||
superset-worker-75b48bbcc-jmmjr 1/1 Running 0 4m8s
|
||||
superset-worker-75b48bbcc-qrq49 1/1 Running 0 4m12s
|
||||
```
|
||||
|
||||
The exact list will depend on some of your specific configuration overrides but you should generally expect:
|
||||
|
||||
- N `superset-xxxx-yyyy` and `superset-worker-xxxx-yyyy` pods (depending on your `supersetNode.replicaCount` and `supersetWorker.replicaCount` values)
|
||||
- 1 `superset-postgresql-0` depending on your postgres settings
|
||||
- 1 `superset-redis-master-0` depending on your redis settings
|
||||
- 1 `superset-celerybeat-xxxx-yyyy` pod if you have `supersetCeleryBeat.enabled = true` in your values overrides
|
||||
|
||||
1. Access it
|
||||
|
||||
The chart will publish appropriate services to expose the Superset UI internally within your k8s cluster. To access it externally you will have to either:
|
||||
|
||||
- Configure the Service as a `LoadBalancer` or `NodePort`
|
||||
- Set up an `Ingress` for it - the chart includes a definition, but will need to be tuned to your needs (hostname, tls, annotations etc...)
|
||||
- Set up a Gateway API `HTTPRoute` for it - see [Exposing Superset via Gateway API (HTTPRoute)](#exposing-superset-via-gateway-api-httproute) below
|
||||
- Run `kubectl port-forward superset-xxxx-yyyy :8088` to directly tunnel one pod's port into your localhost
|
||||
|
||||
Depending how you configured external access, the URL will vary. Once you've identified the appropriate URL you can log in with:
|
||||
|
||||
- user: `admin`
|
||||
- password: `admin`
|
||||
|
||||
## Important settings
|
||||
|
||||
### Security settings
|
||||
|
||||
Default security settings and passwords are included but you **MUST** update them to run `prod` instances, in particular:
|
||||
|
||||
```yaml
|
||||
postgresql:
|
||||
postgresqlPassword: superset
|
||||
```
|
||||
|
||||
Make sure, you set a unique strong complex alphanumeric string for your SECRET_KEY and use a tool to help you generate
|
||||
a sufficiently random sequence.
|
||||
|
||||
- To generate a good key you can run, `openssl rand -base64 42`
|
||||
|
||||
```yaml
|
||||
configOverrides:
|
||||
secret: |
|
||||
SECRET_KEY = 'YOUR_OWN_RANDOM_GENERATED_SECRET_KEY'
|
||||
```
|
||||
|
||||
If you want to change the previous secret key then you should rotate the keys.
|
||||
Default secret key for kubernetes deployment is `thisISaSECRET_1234`
|
||||
|
||||
```yaml
|
||||
configOverrides:
|
||||
my_override: |
|
||||
PREVIOUS_SECRET_KEY = 'YOUR_PREVIOUS_SECRET_KEY'
|
||||
SECRET_KEY = 'YOUR_OWN_RANDOM_GENERATED_SECRET_KEY'
|
||||
init:
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- |
|
||||
. {{ .Values.configMountPath }}/superset_bootstrap.sh
|
||||
superset re-encrypt-secrets
|
||||
. {{ .Values.configMountPath }}/superset_init.sh
|
||||
```
|
||||
|
||||
:::note
|
||||
Superset uses [Scarf Gateway](https://about.scarf.sh/) to collect telemetry data. Knowing the installation counts for different Superset versions informs the project's decisions about patching and long-term support. Scarf purges personally identifiable information (PII) and provides only aggregated statistics.
|
||||
|
||||
There are two independent telemetry channels:
|
||||
|
||||
- **Image pulls** (Scarf Gateway): to opt out, edit the `repository:` line in your `helm/superset/values.yaml` file, replacing `apachesuperset.docker.scarf.sh/apache/superset` with `apache/superset` to pull the image directly from Docker Hub.
|
||||
- **The analytics pixel** rendered in the UI: to opt out, set the `SCARF_ANALYTICS` environment variable to `false` on the Superset containers via `extraEnv` in your `values.yaml`:
|
||||
|
||||
```yaml
|
||||
extraEnv:
|
||||
SCARF_ANALYTICS: 'false'
|
||||
```
|
||||
|
||||
This is read at runtime, so it takes effect on the pre-built images without rebuilding the frontend.
|
||||
:::
|
||||
|
||||
### Dependencies
|
||||
|
||||
Install additional packages and do any other bootstrap configuration in the bootstrap script.
|
||||
For production clusters it's recommended to build own image with this step done in CI.
|
||||
|
||||
:::note
|
||||
|
||||
Superset requires a Python DB-API database driver and a SQLAlchemy
|
||||
dialect to be installed for each datastore you want to connect to.
|
||||
|
||||
See [Install Database Drivers](/user-docs/databases#installing-database-drivers) for more information.
|
||||
It is recommended that you refer to versions listed in
|
||||
[pyproject.toml](https://github.com/apache/superset/blob/master/pyproject.toml)
|
||||
instead of hard-coding them in your bootstrap script, as seen below.
|
||||
|
||||
:::
|
||||
|
||||
The following example installs the drivers for BigQuery and Elasticsearch, allowing you to connect to these data sources within your Superset setup:
|
||||
|
||||
```yaml
|
||||
bootstrapScript: |
|
||||
#!/bin/bash
|
||||
uv pip install .[postgres] \
|
||||
.[bigquery] \
|
||||
.[elasticsearch] &&\
|
||||
if [ ! -f ~/bootstrap ]; then echo "Running Superset with uid {{ .Values.runAsUser }}" > ~/bootstrap; fi
|
||||
```
|
||||
|
||||
### superset_config.py
|
||||
|
||||
The default `superset_config.py` is fairly minimal and you will very likely need to extend it. This is done by specifying one or more key/value entries in `configOverrides`, e.g.:
|
||||
|
||||
```yaml
|
||||
configOverrides:
|
||||
my_override: |
|
||||
# This will make sure the redirect_uri is properly computed, even with SSL offloading
|
||||
ENABLE_PROXY_FIX = True
|
||||
FEATURE_FLAGS = {
|
||||
"DYNAMIC_PLUGINS": True
|
||||
}
|
||||
```
|
||||
|
||||
Those will be evaluated as Helm templates and therefore will be able to reference other `values.yaml` variables e.g. `{{ .Values.ingress.hosts[0] }}` will resolve to your ingress external domain.
|
||||
|
||||
The entire `superset_config.py` will be installed as a secret, so it is safe to pass sensitive parameters directly... however it might be more readable to use secret env variables for that.
|
||||
|
||||
Full python files can be provided by running `helm upgrade --install --values my-values.yaml --set-file configOverrides.oauth=set_oauth.py`
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Those can be passed as key/values either with `extraEnv` or `extraSecretEnv` if they're sensitive. They can then be referenced from `superset_config.py` using e.g. `os.environ.get("VAR")`.
|
||||
|
||||
```yaml
|
||||
extraEnv:
|
||||
SMTP_HOST: smtp.gmail.com
|
||||
SMTP_USER: user@gmail.com
|
||||
SMTP_PORT: '587'
|
||||
SMTP_MAIL_FROM: user@gmail.com
|
||||
|
||||
extraSecretEnv:
|
||||
SMTP_PASSWORD: xxxx
|
||||
|
||||
configOverrides:
|
||||
smtp: |
|
||||
import ast
|
||||
SMTP_HOST = os.getenv("SMTP_HOST","localhost")
|
||||
SMTP_STARTTLS = ast.literal_eval(os.getenv("SMTP_STARTTLS", "True"))
|
||||
SMTP_SSL = ast.literal_eval(os.getenv("SMTP_SSL", "False"))
|
||||
SMTP_USER = os.getenv("SMTP_USER","superset")
|
||||
SMTP_PORT = os.getenv("SMTP_PORT",25)
|
||||
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD","superset")
|
||||
```
|
||||
|
||||
### System packages
|
||||
|
||||
If new system packages are required, they can be installed before application startup by overriding the container's `command`, e.g.:
|
||||
|
||||
```yaml
|
||||
supersetWorker:
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- |
|
||||
apt update
|
||||
apt install -y somepackage
|
||||
apt autoremove -yqq --purge
|
||||
apt clean
|
||||
|
||||
# Run celery worker
|
||||
. {{ .Values.configMountPath }}/superset_bootstrap.sh; celery --app=superset.tasks.celery_app:app worker
|
||||
```
|
||||
|
||||
### Data sources
|
||||
|
||||
Data source definitions can be automatically declared by providing key/value yaml definitions in `extraConfigs`:
|
||||
|
||||
```yaml
|
||||
extraConfigs:
|
||||
import_datasources.yaml: |
|
||||
databases:
|
||||
- allow_file_upload: true
|
||||
allow_ctas: true
|
||||
allow_cvas: true
|
||||
database_name: example-db
|
||||
extra: "{\r\n \"metadata_params\": {},\r\n \"engine_params\": {},\r\n \"\
|
||||
metadata_cache_timeout\": {},\r\n \"schemas_allowed_for_file_upload\": []\r\n\
|
||||
}"
|
||||
sqlalchemy_uri: example://example-db.local
|
||||
tables: []
|
||||
```
|
||||
|
||||
Those will also be mounted as secrets and can include sensitive parameters.
|
||||
|
||||
## Configuration Examples
|
||||
|
||||
### Setting up OAuth
|
||||
|
||||
:::note
|
||||
|
||||
OAuth setup requires that the [authlib](https://authlib.org/) Python library is installed. This can
|
||||
be done using `pip` by updating the `bootstrapScript`. See the [Dependencies](#dependencies) section
|
||||
for more information.
|
||||
|
||||
:::
|
||||
|
||||
```yaml
|
||||
extraEnv:
|
||||
AUTH_DOMAIN: example.com
|
||||
|
||||
extraSecretEnv:
|
||||
GOOGLE_KEY: xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com
|
||||
GOOGLE_SECRET: xxxxxxxxxxxxxxxxxxxxxxxx
|
||||
|
||||
configOverrides:
|
||||
enable_oauth: |
|
||||
# This will make sure the redirect_uri is properly computed, even with SSL offloading
|
||||
ENABLE_PROXY_FIX = True
|
||||
|
||||
from flask_appbuilder.security.manager import AUTH_OAUTH
|
||||
AUTH_TYPE = AUTH_OAUTH
|
||||
OAUTH_PROVIDERS = [
|
||||
{
|
||||
"name": "google",
|
||||
"icon": "fa-google",
|
||||
"token_key": "access_token",
|
||||
"remote_app": {
|
||||
"client_id": os.getenv("GOOGLE_KEY"),
|
||||
"client_secret": os.getenv("GOOGLE_SECRET"),
|
||||
"api_base_url": "https://www.googleapis.com/oauth2/v2/",
|
||||
"client_kwargs": {"scope": "email profile"},
|
||||
"request_token_url": None,
|
||||
"access_token_url": "https://accounts.google.com/o/oauth2/token",
|
||||
"authorize_url": "https://accounts.google.com/o/oauth2/auth",
|
||||
"authorize_params": {"hd": os.getenv("AUTH_DOMAIN", "")}
|
||||
},
|
||||
}
|
||||
]
|
||||
|
||||
# Map Authlib roles to superset roles
|
||||
AUTH_ROLE_ADMIN = 'Admin'
|
||||
AUTH_ROLE_PUBLIC = 'Public'
|
||||
|
||||
# Will allow user self registration, allowing to create Flask users from Authorized User
|
||||
AUTH_USER_REGISTRATION = True
|
||||
|
||||
# The default user self registration role
|
||||
AUTH_USER_REGISTRATION_ROLE = "Admin"
|
||||
```
|
||||
|
||||
### Exposing Superset via Gateway API (HTTPRoute)
|
||||
|
||||
As an alternative to `Ingress`, the chart can create a [Gateway API](https://gateway-api.sigs.k8s.io/)
|
||||
`HTTPRoute` that attaches to a Gateway already running in your cluster. This requires the Gateway
|
||||
API CRDs serving the configured `httproute.apiVersion` (`gateway.networking.k8s.io/v1` by default)
|
||||
to be installed, along with a Gateway resource for the route to attach to. If the Gateway lives in
|
||||
a different namespace than the `HTTPRoute` (as in the
|
||||
example below), its listener's `allowedRoutes` must explicitly permit routes from this release's
|
||||
namespace, or the `HTTPRoute` will install successfully but never attach.
|
||||
|
||||
```yaml
|
||||
httproute:
|
||||
enabled: true
|
||||
parentRefs:
|
||||
- name: my-gateway
|
||||
namespace: gateway-system
|
||||
hostnames:
|
||||
- superset.example.com
|
||||
rules:
|
||||
- matches:
|
||||
- path:
|
||||
type: PathPrefix
|
||||
value: /
|
||||
```
|
||||
|
||||
- `httproute.parentRefs` lists the Gateway(s) the route attaches to.
|
||||
- `httproute.hostnames` matches against the HTTP `Host` header; it's templated, so values like
|
||||
`{{ .Release.Name }}` can be used.
|
||||
- `httproute.rules` are routing rules backed by the Superset service; each rule accepts standard
|
||||
`matches`, `filters`, and `timeouts` fields, and an optional `weight` (defaults to `1`) applied to
|
||||
its single backend reference. Since each rule maps to one backend, `weight` has no traffic-splitting
|
||||
effect here; it only matters if you fork the template to add multiple `backendRefs` to a rule.
|
||||
`timeouts` only joined the Gateway API Standard channel in v1.2, so it requires both v1.2+ CRDs
|
||||
and a supporting controller; drop it if either predates that.
|
||||
- If `supersetWebsockets.enabled` is set, an extra rule routing `supersetWebsockets.ingress.path`
|
||||
(default `/ws`) to the `-ws` service is appended automatically, mirroring the `Ingress` behavior.
|
||||
WebSocket upgrade support is controller-dependent under Gateway API; check your Gateway
|
||||
implementation's docs in case it needs an explicit protocol opt-in for global async queries to
|
||||
keep working behind a Gateway.
|
||||
- If `supersetMcp.enabled` and `supersetMcp.httproute.enabled` are both set, an extra rule routing
|
||||
`supersetMcp.httproute.path` to the `-mcp` service is appended as well. Don't expose this route
|
||||
without first enabling MCP authentication — see the
|
||||
[MCP Server Deployment & Authentication](/admin-docs/configuration/mcp-server#authentication) doc;
|
||||
by default the MCP server runs in dev mode with auth disabled.
|
||||
- Set `httproute.apiVersion` to `gateway.networking.k8s.io/v1beta1` if your cluster's Gateway API
|
||||
installation hasn't promoted `HTTPRoute` to `v1` yet.
|
||||
|
||||
### Enable Alerts and Reports
|
||||
|
||||
For this, as per the [Alerts and Reports doc](/admin-docs/configuration/alerts-reports), you will need to:
|
||||
|
||||
#### Install a supported webdriver in the Celery worker
|
||||
|
||||
This is done either by using a custom image that has the webdriver pre-installed, or installing at startup time by overriding the `command`. Here's a working example for `chromedriver`:
|
||||
|
||||
```yaml
|
||||
supersetWorker:
|
||||
command:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- |
|
||||
# Install chrome webdriver
|
||||
# See https://github.com/apache/superset/blob/4fa3b6c7185629b87c27fc2c0e5435d458f7b73d/docs/src/pages/admin-docs/installation/email_reports.mdx
|
||||
apt-get update
|
||||
apt-get install -y wget
|
||||
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
|
||||
apt-get install -y --no-install-recommends ./google-chrome-stable_current_amd64.deb
|
||||
wget https://chromedriver.storage.googleapis.com/88.0.4324.96/chromedriver_linux64.zip
|
||||
apt-get install -y zip
|
||||
unzip chromedriver_linux64.zip
|
||||
chmod +x chromedriver
|
||||
mv chromedriver /usr/bin
|
||||
apt-get autoremove -yqq --purge
|
||||
apt-get clean
|
||||
rm -f google-chrome-stable_current_amd64.deb chromedriver_linux64.zip
|
||||
|
||||
# Run
|
||||
. {{ .Values.configMountPath }}/superset_bootstrap.sh; celery --app=superset.tasks.celery_app:app worker
|
||||
```
|
||||
|
||||
#### Run the Celery beat
|
||||
|
||||
This pod will trigger the scheduled tasks configured in the alerts and reports UI section:
|
||||
|
||||
```yaml
|
||||
supersetCeleryBeat:
|
||||
enabled: true
|
||||
```
|
||||
|
||||
#### Configure the appropriate Celery jobs and SMTP/Slack settings
|
||||
|
||||
```yaml
|
||||
extraEnv:
|
||||
SMTP_HOST: smtp.gmail.com
|
||||
SMTP_USER: user@gmail.com
|
||||
SMTP_PORT: '587'
|
||||
SMTP_MAIL_FROM: user@gmail.com
|
||||
|
||||
extraSecretEnv:
|
||||
SLACK_API_TOKEN: xoxb-xxxx-yyyy
|
||||
SMTP_PASSWORD: xxxx-yyyy
|
||||
|
||||
configOverrides:
|
||||
feature_flags: |
|
||||
import ast
|
||||
|
||||
FEATURE_FLAGS = {
|
||||
"ALERT_REPORTS": True
|
||||
}
|
||||
|
||||
SMTP_HOST = os.getenv("SMTP_HOST","localhost")
|
||||
SMTP_STARTTLS = ast.literal_eval(os.getenv("SMTP_STARTTLS", "True"))
|
||||
SMTP_SSL = ast.literal_eval(os.getenv("SMTP_SSL", "False"))
|
||||
SMTP_USER = os.getenv("SMTP_USER","superset")
|
||||
SMTP_PORT = os.getenv("SMTP_PORT",25)
|
||||
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD","superset")
|
||||
SMTP_MAIL_FROM = os.getenv("SMTP_MAIL_FROM","superset@superset.com")
|
||||
|
||||
SLACK_API_TOKEN = os.getenv("SLACK_API_TOKEN",None)
|
||||
celery_conf: |
|
||||
from celery.schedules import crontab
|
||||
|
||||
class CeleryConfig:
|
||||
broker_url = f"redis://{env('REDIS_HOST')}:{env('REDIS_PORT')}/0"
|
||||
imports = (
|
||||
"superset.sql_lab",
|
||||
"superset.tasks.cache",
|
||||
"superset.tasks.scheduler",
|
||||
)
|
||||
result_backend = f"redis://{env('REDIS_HOST')}:{env('REDIS_PORT')}/0"
|
||||
task_annotations = {
|
||||
"sql_lab.get_sql_results": {
|
||||
"rate_limit": "100/s",
|
||||
},
|
||||
}
|
||||
beat_schedule = {
|
||||
"reports.scheduler": {
|
||||
"task": "reports.scheduler",
|
||||
"schedule": crontab(minute="*", hour="*"),
|
||||
},
|
||||
"reports.prune_log": {
|
||||
"task": "reports.prune_log",
|
||||
'schedule': crontab(minute=0, hour=0),
|
||||
},
|
||||
'cache-warmup-hourly': {
|
||||
"task": "cache-warmup",
|
||||
"schedule": crontab(minute="*/30", hour="*"),
|
||||
"kwargs": {
|
||||
"strategy_name": "top_n_dashboards",
|
||||
"top_n": 10,
|
||||
"since": "7 days ago",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
CELERY_CONFIG = CeleryConfig
|
||||
reports: |
|
||||
EMAIL_PAGE_RENDER_WAIT = 60
|
||||
WEBDRIVER_BASEURL = "http://{{ template "superset.fullname" . }}:{{ .Values.service.port }}/"
|
||||
WEBDRIVER_BASEURL_USER_FRIENDLY = "https://www.example.com/"
|
||||
WEBDRIVER_TYPE= "chrome"
|
||||
WEBDRIVER_OPTION_ARGS = [
|
||||
"--force-device-scale-factor=2.0",
|
||||
"--high-dpi-support=2.0",
|
||||
"--headless",
|
||||
"--disable-gpu",
|
||||
"--disable-dev-shm-usage",
|
||||
# This is required because our process runs as root (in order to install pip packages)
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-extensions",
|
||||
]
|
||||
```
|
||||
|
||||
### Load the Examples data and dashboards
|
||||
|
||||
If you are trying Superset out and want some data and dashboards to explore, you can load some examples by creating a `my_values.yaml` and deploying it as described above in the **Configure your setting overrides** step of the **Running** section.
|
||||
To load the examples, add the following to the `my_values.yaml` file:
|
||||
|
||||
```yaml
|
||||
init:
|
||||
loadExamples: true
|
||||
```
|
||||
|
||||
:::resources
|
||||
|
||||
- [Tutorial: Mastering Data Visualization — Installing Superset on Kubernetes with Helm Chart](https://mahira-technology.medium.com/mastering-data-visualization-installing-superset-on-kubernetes-cluster-using-helm-chart-e4ec99199e1e)
|
||||
- [Tutorial: Installing Apache Superset in Kubernetes](https://aws.plainenglish.io/installing-apache-superset-in-kubernetes-1aec192ac495)
|
||||
:::
|
||||
- [Apache Superset Kubernetes Operator documentation](https://apache.github.io/superset-kubernetes-operator/)
|
||||
- [Apache Superset Kubernetes Operator repository](https://github.com/apache/superset-kubernetes-operator)
|
||||
- [Helm chart migration guide](https://apache.github.io/superset-kubernetes-operator/user-guide/migration/)
|
||||
|
||||
@@ -99,11 +99,16 @@ Affecting the Docker build process:
|
||||
- **INCLUDE_CHROMIUM (default=false):** whether to include the Chromium headless browser in the build
|
||||
- **BUILD_TRANSLATIONS(default=false):** whether to compile the translations from the .po files available
|
||||
- **SUPERSET_LOAD_EXAMPLES (default=yes):** whether to load the examples into the database upon startup,
|
||||
save some precious time on startup by `SUPERSET_LOAD_EXAMPLES=no docker compose up`
|
||||
save some precious time on startup by `SUPERSET_LOAD_EXAMPLES=no docker compose up`. Once the example
|
||||
data and dashboards are present in the databases, later `docker compose up` runs skip loading
|
||||
them; run `SUPERSET_FORCE_LOAD_EXAMPLES=yes docker compose up` to reload the examples anyway.
|
||||
- **SUPERSET_LOG_LEVEL (default=info)**: Can be set to debug, info, warning, error, critical
|
||||
for more verbose logging
|
||||
- **SUPERSET_DEBUG_ENABLED (default=false)**: Enable Werkzeug debugger with interactive console.
|
||||
Set to `true` for debugging: `SUPERSET_DEBUG_ENABLED=true docker compose up`
|
||||
- **DISABLE_TS_CHECKER (default=true)**: whether the `superset-node` webpack dev server skips
|
||||
TypeScript type-checking, which speeds up rebuilds and saves several GB of memory. Set to
|
||||
`false` to have webpack surface type errors during development.
|
||||
|
||||
For more env vars that affect your configuration, see this
|
||||
[superset_config.py](https://github.com/apache/superset/blob/master/docker/pythonpath_dev/superset_config.py)
|
||||
|
||||
@@ -93,7 +93,7 @@ Look through the GitHub issues. Issues tagged with
|
||||
|
||||
Superset could always use better documentation,
|
||||
whether as part of the official Superset docs,
|
||||
in docstrings, `docs/*.rst` or even on the web as blog posts or
|
||||
in docstrings, Markdown files in `docs/`, or even on the web as blog posts or
|
||||
articles. See [Documentation](./howtos.md#contributing-to-documentation) for more details.
|
||||
|
||||
### Add Translations
|
||||
|
||||
+1
-1
@@ -414,7 +414,7 @@ This can be used, for example, to convert UTC time to local time.
|
||||
Superset uses [Scarf](https://about.scarf.sh/) by default to collect basic telemetry data upon installing and/or running Superset. This data helps the maintainers of Superset better understand which versions of Superset are being used, in order to prioritize patch/minor releases and security fixes.
|
||||
We use the [Scarf Gateway](https://docs.scarf.sh/gateway/) to sit in front of container registries, the [scarf-js](https://about.scarf.sh/package-sdks) package to track `npm` installations, and a Scarf pixel to gather anonymous analytics on Superset page views.
|
||||
Scarf purges PII and provides aggregated statistics. Superset users can easily opt out of analytics in various ways documented [here](https://docs.scarf.sh/gateway/#do-not-track) and [here](https://docs.scarf.sh/package-analytics/#as-a-user-of-a-package-using-scarf-js-how-can-i-opt-out-of-analytics).
|
||||
You can also opt out of the analytics pixel by setting the `SCARF_ANALYTICS` environment variable to `false`. This is read at runtime, so setting it on the Superset container (for example via `extraEnv` in the Helm chart, or `docker/.env` for Docker Compose) disables the pixel on the pre-built images without rebuilding the frontend. Note that this only disables the page-view pixel; the Scarf Gateway (container registry) and `scarf-js` (`npm`) channels are opted out separately, as described above.
|
||||
You can also opt out of the analytics pixel by setting the `SCARF_ANALYTICS` environment variable to `false`. This is read at runtime, so setting it on the Superset container (for example via your Kubernetes deployment configuration, or `docker/.env` for Docker Compose) disables the pixel on the pre-built images without rebuilding the frontend. Note that this only disables the page-view pixel; the Scarf Gateway (container registry) and `scarf-js` (`npm`) channels are opted out separately, as described above.
|
||||
Additional opt-out instructions are available on the [Docker Compose](/admin-docs/installation/docker-compose) and [Kubernetes](/admin-docs/installation/kubernetes) installation pages.
|
||||
|
||||
## Does Superset have an archive panel or trash bin from which a user can recover deleted assets?
|
||||
|
||||
+1
-1
@@ -260,7 +260,7 @@ Understanding the Superset Points of View
|
||||
- Deploying Superset
|
||||
|
||||
- [Official Docker image](https://hub.docker.com/r/apache/superset)
|
||||
- [Helm Chart](https://github.com/apache/superset/tree/master/helm/superset)
|
||||
- [Kubernetes Operator](https://apache.github.io/superset-kubernetes-operator/)
|
||||
|
||||
- Recordings of Past [Superset Community Events](https://preset.io/events)
|
||||
|
||||
|
||||
+1
-1
@@ -88,7 +88,7 @@
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/react": "^19.1.8",
|
||||
"oxfmt": "^0.66.0",
|
||||
"oxlint": "^1.80.0",
|
||||
"oxlint": "^1.81.0",
|
||||
"oxlint-tsgolint": "^7.0.2001",
|
||||
"typescript": "7.0.2",
|
||||
"webpack": "^5.110.3"
|
||||
|
||||
@@ -3215,7 +3215,7 @@
|
||||
"logo": "cockroachdb.png",
|
||||
"homepage_url": "https://www.cockroachlabs.com/",
|
||||
"categories": ["Traditional RDBMS", "Open Source"],
|
||||
"pypi_packages": ["cockroachdb"],
|
||||
"pypi_packages": ["sqlalchemy-cockroachdb", "psycopg2-binary"],
|
||||
"connection_string": "cockroachdb://root@{hostname}:{port}/{database}?sslmode=disable",
|
||||
"default_port": 26257,
|
||||
"docs_url": "https://github.com/cockroachdb/sqlalchemy-cockroachdb",
|
||||
|
||||
Vendored
+1
-1
@@ -14,7 +14,7 @@ Superset is designed for data exploration and visualization at scale. It feature
|
||||
- [Architecture](https://superset.apache.org/docs/installation/architecture): Production deployment architecture and components
|
||||
- [Docker Compose](https://superset.apache.org/docs/installation/docker-compose): Install Superset using Docker Compose
|
||||
- [Docker Builds](https://superset.apache.org/docs/installation/docker-builds): Building and customizing Docker images
|
||||
- [Kubernetes](https://superset.apache.org/docs/installation/kubernetes): Deploy Superset on Kubernetes with Helm
|
||||
- [Kubernetes](https://superset.apache.org/docs/installation/kubernetes): Deploy Superset on Kubernetes with the official Kubernetes Operator
|
||||
- [PyPI](https://superset.apache.org/docs/installation/pypi): Install from PyPI using pip
|
||||
- [Upgrading Superset](https://superset.apache.org/docs/installation/upgrading-superset): Upgrade between Superset versions
|
||||
|
||||
|
||||
+99
-99
@@ -3203,100 +3203,100 @@
|
||||
resolved "https://registry.yarnpkg.com/@oxlint-tsgolint/win32-x64/-/win32-x64-7.0.2001.tgz#814bcdd2707fa8ab1ae0f0b51a7243b034d2833a"
|
||||
integrity sha512-FkDRm8hx9OwzGQqyWG1tO5QrTLRApff9DzSgpz9QZau37BR8d1VYKOxMLGf6shPZntJFoTwIIJYT68VndYDCog==
|
||||
|
||||
"@oxlint/binding-android-arm-eabi@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.80.0.tgz#924b041cbcea4e934fd9ef66a2d2b7d7463c0180"
|
||||
integrity sha512-RM3Plj+biQpxa5d1GOOX6ciDlcUROmm4OZ/pLTpitkQt2mJv4jhtY4cbgaetOm5UKWZe05/TGQ6o1Vl8EOHkrA==
|
||||
"@oxlint/binding-android-arm-eabi@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-android-arm-eabi/-/binding-android-arm-eabi-1.81.0.tgz#86a0305480e680431429c8259c5701ac5592e4a7"
|
||||
integrity sha512-IcCRsXiedJoJopY6mpZUBEeVFsUrutmrG7dZ87zMuKJlhg70Ora9bBl1WcCxZQtyI10YpnVdEso5oCg7YcfSHw==
|
||||
|
||||
"@oxlint/binding-android-arm64@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-android-arm64/-/binding-android-arm64-1.80.0.tgz#d1716d2be903de06b4fdb2fdaa121a2943695c35"
|
||||
integrity sha512-YlO5JEf0Yr2bUUlu8O8daVcUxtcGGbcSmyV7E7nSbJbfAdxTE0PFPwgnIlw7wXJaTYjb+qs5hI5q3jxUkI7cAw==
|
||||
"@oxlint/binding-android-arm64@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-android-arm64/-/binding-android-arm64-1.81.0.tgz#dba51cb2a1258f37eaca15a4e74d5d6ee19f238c"
|
||||
integrity sha512-GRrIPyTGVhx3L3h+0T5xT2A0jFAcdPv4+IfuXpGDLIdl6XeYhgg/zw72A5ILZoUgRqZuM8F1y+V/gfDriXSxzQ==
|
||||
|
||||
"@oxlint/binding-darwin-arm64@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.80.0.tgz#475eb4061db4d4fe9349e92f15962c0203e8ebec"
|
||||
integrity sha512-BULDOyO3AhsmdWfQeIUCykDt3dd7XZBGLhp1eIh56skRv01O+cNjNPwXMIbeW1x4+pxcln5if72wcRgViVo7PA==
|
||||
"@oxlint/binding-darwin-arm64@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-darwin-arm64/-/binding-darwin-arm64-1.81.0.tgz#f384ae1eddd399429281f88a0073729e287ec0b1"
|
||||
integrity sha512-qNQ9tXRgLuKbqSV1S2h9h4KPHjbovO7RRR2/enUOtHzTkFZ7B9X5zqqHJua8dRyc7dBy7Aoyq5pqTSLFVcAzGQ==
|
||||
|
||||
"@oxlint/binding-darwin-x64@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.80.0.tgz#602fa5681dd746c0fb5ca7a0e4a81d0dd07b7f90"
|
||||
integrity sha512-YJ4JzLw7N5TDSQFlA0hAQGHvnDZgyypm1yunObVWcWiF9KM7eGCJKYKLgTC2Fi/57OdnBhbj4OkzPGdFQJ6HyA==
|
||||
"@oxlint/binding-darwin-x64@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-darwin-x64/-/binding-darwin-x64-1.81.0.tgz#7167e3b4c18852fcd1ddade536d232d73d55d30c"
|
||||
integrity sha512-q0QTm32jWga2Gv4j7IaVZN0jYMi9UV73sWVgFtDA4iIfqwMCLLZ3ve+9KwfYtsaKZSgQhmPaogeZWqDZpcY1Pw==
|
||||
|
||||
"@oxlint/binding-freebsd-x64@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.80.0.tgz#4e0490c344726fd0b1a027afc129fb9c78f069ec"
|
||||
integrity sha512-AYUIk5QnL0s8oWAYsREZwkRYy1SupJTXALo93J1TgzHywxQtdM99FecRMQ87MXEdPQ0j1TmEpeeq3fGNkpvMqg==
|
||||
"@oxlint/binding-freebsd-x64@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-freebsd-x64/-/binding-freebsd-x64-1.81.0.tgz#64f230765343bfe7e2280b071bb191bb666303ac"
|
||||
integrity sha512-/+8wVWDXEC7wHVAhOc59Fw/SkMc1arLkFD8iQCaSsmzenK1X4doFqquL9H1wrtGUzaiycVqkf/sSpcILK6W1UA==
|
||||
|
||||
"@oxlint/binding-linux-arm-gnueabihf@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.80.0.tgz#82d215fc05e046a0ec085821c1da8ab99d35fbdc"
|
||||
integrity sha512-9hBZVANupQ89W9dXyE0n8doCyaW5pDyGn3y6XlIMPZ+rIKuyqkr3SNUXmVJIhuvUq0NBU3RBiSXXE69l4XI6KA==
|
||||
"@oxlint/binding-linux-arm-gnueabihf@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.81.0.tgz#5095f021a28009146f7536a7ccd518cdfcbfc3bf"
|
||||
integrity sha512-4xt422FEgioRq9hAL4Tq7fujGUWnc8z1BJ+Oi8RN8vB8axaP+sdK6a2xdlcQCCYnJg9QMuMFS0AucuIFx/EacA==
|
||||
|
||||
"@oxlint/binding-linux-arm-musleabihf@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.80.0.tgz#92068e3b51cd50fc5a83a3ebfba7925313d6cd11"
|
||||
integrity sha512-SvS2uKqzY+pbfuvAHzH4338R6Zwo805GAwrIMVvK1KxoOWCIjZUdfzTCvilD7z6JK91v011+zYMryabhDo2AsQ==
|
||||
"@oxlint/binding-linux-arm-musleabihf@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-1.81.0.tgz#d894dcfb6fb1b8b224b79e6ce07b17403f413749"
|
||||
integrity sha512-u3vna8KdGplH4DRCW9K54D68fcMo7IxVrkCJWwXnIhwtBdnDnYrmzOUA/XjmBlPpcLsgw9Z5BNdY4za9+Dj+MQ==
|
||||
|
||||
"@oxlint/binding-linux-arm64-gnu@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.80.0.tgz#6c81ddc85dd5b79070f87401d61813172068666d"
|
||||
integrity sha512-tCLadyqRVL3pQTRPNg7cjXKvcvS4fbyXeQHhKk5BTJ1oftQln5/yIIWbu/Xom/DX41zv2P9QGt6+D/TtQVtY3A==
|
||||
"@oxlint/binding-linux-arm64-gnu@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.81.0.tgz#bf8e362c87e7828ba28c2ec36bae73ad82989ef1"
|
||||
integrity sha512-3j9k+gsYsE7nv71GWotXsqsa2l9/aJenD7dVHNt/CBvsb0SgRjSMnHFeP59IXUAl1wvVFhqGl2wJNMwWU3UBlA==
|
||||
|
||||
"@oxlint/binding-linux-arm64-musl@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.80.0.tgz#11216704b606d67e946a868850243dc2739ec92e"
|
||||
integrity sha512-XfpCNRlOPcLlJl4Bn/FUhjqlR6BVavEykERBf/MV7YA9VZDa5g5znVqYhyviMafcxS9Pe/i/kPvHNO0U6svEHQ==
|
||||
"@oxlint/binding-linux-arm64-musl@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.81.0.tgz#2aa5214eb5b032e8f77d94a27c9bd3f6dbc446f3"
|
||||
integrity sha512-k5iAp3dNxW0/uDCBY+WSm8jKB2szu7SkEQZdgRRpDXvuDd69vvDcqhB3A/pWCfCwXyenjNjFn9Td1fVoyAc+Yg==
|
||||
|
||||
"@oxlint/binding-linux-ppc64-gnu@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.80.0.tgz#125302a0e6732e32e4a7d53f0212d58f1b13af01"
|
||||
integrity sha512-3I4yMwcFG9NeO8ioY6JBBuKsIm5GL/x7MATt1S4tVWaxPu5HcJ+XnLUbcVBTxG8q2Wu56HSj+NmXQiVYb1lp6A==
|
||||
"@oxlint/binding-linux-ppc64-gnu@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.81.0.tgz#a0af1af6fd309214555f33b4fa0432f3ec45f242"
|
||||
integrity sha512-TFqLja3uYmVSte6nof9GWrex9Z8WgdZrNiLC6Te5rXGDqXB2y4j/26iFhwosXiAFqDhE9JJVuuCkDKLwptTn1g==
|
||||
|
||||
"@oxlint/binding-linux-riscv64-gnu@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.80.0.tgz#03846614f184ed3dcbab4bffad7417fd54cd0967"
|
||||
integrity sha512-E1wAKymkpe1/E8helzBKdm81OBOF+ezxRyXRMEuik3ZpWDER5CPOKZwF66RsdwW98uwZv8UTFremUQtC1CzdJA==
|
||||
"@oxlint/binding-linux-riscv64-gnu@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-1.81.0.tgz#60413a335a63e0911a625d047690e41c03f2a833"
|
||||
integrity sha512-UEcySvGS0NOVo7h7n7CYyJL9+6gFAh7Zc/ToDXVScFvzHSTIxtzkMVU30rmQ6+nQ1LF+UdiRDdJajpDu+OylLg==
|
||||
|
||||
"@oxlint/binding-linux-riscv64-musl@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.80.0.tgz#49e0fb90e1c8358429b9989a407f4020c56d8ea9"
|
||||
integrity sha512-+gLRGD4sIo3+VA++iham5UxD9tKSoJ/VOrROCEXIcknrYtQg6iIQgvjN0cpiRF7N6UYC7pJbvHJlDnMge5LRpQ==
|
||||
"@oxlint/binding-linux-riscv64-musl@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-1.81.0.tgz#5f1dd7bc2bdbe92fa5454df081ee91fa2c499948"
|
||||
integrity sha512-H+diDbhD00+wI1IRP8Kz88x/lat+DgtoBJzoTthS16xkTJGNaEkfb8gzmd1rzc/2uDQQMl7GNl+JFUacVeWxIA==
|
||||
|
||||
"@oxlint/binding-linux-s390x-gnu@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.80.0.tgz#7aee2ae2426f7bdcae77969073a015a6b3f8373e"
|
||||
integrity sha512-aR0PrzHj9leW3NmzBAAP4EzdoBNoJcs9sjnIQPIwyRnBGYrRbXUIpEB5Q39AqK3PLY5JK5uEhDQDiUa1QSAstw==
|
||||
"@oxlint/binding-linux-s390x-gnu@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.81.0.tgz#830c5bdd145ad39c9b5371e3214d0a9f9c1f46b1"
|
||||
integrity sha512-8znJ/5TekjOKg1j1Acho4PJMdiAHLtlcXuWEiipOhAMV6rQcXdmDdXCbheyDczN6TjBwiNfjcP81k4AthrKRzw==
|
||||
|
||||
"@oxlint/binding-linux-x64-gnu@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.80.0.tgz#0c850b00faed2f884cf8665fe9c391f9f653d6ca"
|
||||
integrity sha512-vSVh5cSo3Xxs6ghBCcFJlpbkbENzDog1qXtoXLa/HC3aCrR4XO76GZbXmQoCPHnu99nQpdCeC3H9tdNICfDh7A==
|
||||
"@oxlint/binding-linux-x64-gnu@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.81.0.tgz#7f72ea3c9ae70a76c1a92e56a5755869f335e756"
|
||||
integrity sha512-Q2Wj70yFsvn5QjlmifFzbj4H+kJy53bwqc41o1fzoM7MpLV1NIbhg/LpWXRfC6KOkSAdUx1Wd8VJsdPmhp/HRA==
|
||||
|
||||
"@oxlint/binding-linux-x64-musl@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.80.0.tgz#91f54f1b0cc93a7e75ce4118aa85f9fd112f25c0"
|
||||
integrity sha512-FfzBXpNQ8u7/ZI/p8bl73MeZ508Ax3hxWp3SiJpEFiC+BB9XcXy5FAZHTLKDPSzrUpxQZSZJAVdDmuJp/+HDBQ==
|
||||
"@oxlint/binding-linux-x64-musl@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-linux-x64-musl/-/binding-linux-x64-musl-1.81.0.tgz#758fd6ea69123c6f4c1ba160bfc28f6b84548c11"
|
||||
integrity sha512-cPInHp/ddEe5qkyK2IiyQ8Q3Mp2oLLEhhsGgTK2oZx4L6+llGam1H1yBvJZ7qHfOXj8N3hxBS8sj4tO+gtFlIg==
|
||||
|
||||
"@oxlint/binding-openharmony-arm64@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.80.0.tgz#7ab37c21e547812177bffdbd97c8a34493eedd7b"
|
||||
integrity sha512-zMzbkumtmprCgRwoYNzcB3iC39fXdJIMLMU33KdCjEGLlJGOEt1+LwQ4LF8ndLzAEKVz4BR0y3V6Xrkk3Nm3yA==
|
||||
"@oxlint/binding-openharmony-arm64@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-openharmony-arm64/-/binding-openharmony-arm64-1.81.0.tgz#e492b7a1875b70ea55ffe13f685d4302e6b1900e"
|
||||
integrity sha512-0CQxSX4ajqm07AHBf5U33qQzXKdd7wtq/oTL/7vpY6RNNuxrRi8W4bqUV1Jyu/vj+9KmxQyDhxfeVX1nQL6kfg==
|
||||
|
||||
"@oxlint/binding-win32-arm64-msvc@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.80.0.tgz#5a470fa82339044ad9cceef2bb8c62d88695e394"
|
||||
integrity sha512-ib6iRcrXsk4t1fm3iKcwksyWh1ZkZXC/2mEzakl0ai2+6HZunf1WWMZ/xP9EJAvw9g9K4UVTC3NF/+G2qLrbTQ==
|
||||
"@oxlint/binding-win32-arm64-msvc@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.81.0.tgz#9247fdc1b4c86ecc718747c5f8c68902969677d1"
|
||||
integrity sha512-l0hbeISm9673hVrrQU8j/p2M7YH9Ouoj7p7E/QM55NTrKVLP+P3PF8hLu+OY+x0VtGRW+ggiQKZqmdYps9H+TA==
|
||||
|
||||
"@oxlint/binding-win32-ia32-msvc@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.80.0.tgz#06f6559998f1a53a8f5ace78d91f217a54f6a963"
|
||||
integrity sha512-xhRWBMpLxZvgKAH6+DJZmpP+W8Y8UdQOSU1JfxSWNXsaBaRGW77j+1hCuNHlzj7OH4SPN8fYd1q0o2qrDtoVyw==
|
||||
"@oxlint/binding-win32-ia32-msvc@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-1.81.0.tgz#dfa4eed78612c5f4df788eb056fd5d1b05a75bb1"
|
||||
integrity sha512-ksqPP5jbFXcYreEQ7zdJh06rJQBymCTyGRCdaXjfcf2aG4f8KxUWY5wcgYHmaTK+FJ4bPG5sUAdOX+6trnH1JA==
|
||||
|
||||
"@oxlint/binding-win32-x64-msvc@1.80.0":
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.80.0.tgz#d3abbf1a7a09b9039ca5ca570c9689908850efc4"
|
||||
integrity sha512-yAnO7lwBYQnz2pcfBPIGQQZWIX5zd5R/1aAKIF3oE+TVj7IhoHcROjOkz3sRDngzqhfPKfFaXqug5j5rE5dn6Q==
|
||||
"@oxlint/binding-win32-x64-msvc@1.81.0":
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/@oxlint/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.81.0.tgz#27a474cc288e47a0e5c2d9c922bee64de0cfd614"
|
||||
integrity sha512-IZuUCwGw9emG5JtCp+fYGB+Z4OWEoeEcM8R5BA1pYw63/ieYFVdcU2ylxTpHbVHSenZnsYE+ZZ20uHAJszQ4cA==
|
||||
|
||||
"@parcel/watcher-android-arm64@2.5.6":
|
||||
version "2.5.6"
|
||||
@@ -11580,30 +11580,30 @@ oxlint-tsgolint@^7.0.2001:
|
||||
"@oxlint-tsgolint/win32-arm64" "7.0.2001"
|
||||
"@oxlint-tsgolint/win32-x64" "7.0.2001"
|
||||
|
||||
oxlint@^1.80.0:
|
||||
version "1.80.0"
|
||||
resolved "https://registry.yarnpkg.com/oxlint/-/oxlint-1.80.0.tgz#228271087d3f04e391e383ccdc0e840458d8b653"
|
||||
integrity sha512-5nTiSps4qdbCWLbxzuO00alHkEO2exR9YMN/ig6QXWrLsYSG0KaObOAM+l6oU2LcKPWoSAGYbkZIGEu1ViiWKA==
|
||||
oxlint@^1.81.0:
|
||||
version "1.81.0"
|
||||
resolved "https://registry.yarnpkg.com/oxlint/-/oxlint-1.81.0.tgz#7b20ada29a171883de4517d041ea5b057fb48ab5"
|
||||
integrity sha512-HyrJYqeoOCL0iqaLEzGewGT48ZX99P3hxYh8udAF9RGGIghSamkXE4ClUyBpEDNqasamThgmlPbuMOe7SAZmHg==
|
||||
optionalDependencies:
|
||||
"@oxlint/binding-android-arm-eabi" "1.80.0"
|
||||
"@oxlint/binding-android-arm64" "1.80.0"
|
||||
"@oxlint/binding-darwin-arm64" "1.80.0"
|
||||
"@oxlint/binding-darwin-x64" "1.80.0"
|
||||
"@oxlint/binding-freebsd-x64" "1.80.0"
|
||||
"@oxlint/binding-linux-arm-gnueabihf" "1.80.0"
|
||||
"@oxlint/binding-linux-arm-musleabihf" "1.80.0"
|
||||
"@oxlint/binding-linux-arm64-gnu" "1.80.0"
|
||||
"@oxlint/binding-linux-arm64-musl" "1.80.0"
|
||||
"@oxlint/binding-linux-ppc64-gnu" "1.80.0"
|
||||
"@oxlint/binding-linux-riscv64-gnu" "1.80.0"
|
||||
"@oxlint/binding-linux-riscv64-musl" "1.80.0"
|
||||
"@oxlint/binding-linux-s390x-gnu" "1.80.0"
|
||||
"@oxlint/binding-linux-x64-gnu" "1.80.0"
|
||||
"@oxlint/binding-linux-x64-musl" "1.80.0"
|
||||
"@oxlint/binding-openharmony-arm64" "1.80.0"
|
||||
"@oxlint/binding-win32-arm64-msvc" "1.80.0"
|
||||
"@oxlint/binding-win32-ia32-msvc" "1.80.0"
|
||||
"@oxlint/binding-win32-x64-msvc" "1.80.0"
|
||||
"@oxlint/binding-android-arm-eabi" "1.81.0"
|
||||
"@oxlint/binding-android-arm64" "1.81.0"
|
||||
"@oxlint/binding-darwin-arm64" "1.81.0"
|
||||
"@oxlint/binding-darwin-x64" "1.81.0"
|
||||
"@oxlint/binding-freebsd-x64" "1.81.0"
|
||||
"@oxlint/binding-linux-arm-gnueabihf" "1.81.0"
|
||||
"@oxlint/binding-linux-arm-musleabihf" "1.81.0"
|
||||
"@oxlint/binding-linux-arm64-gnu" "1.81.0"
|
||||
"@oxlint/binding-linux-arm64-musl" "1.81.0"
|
||||
"@oxlint/binding-linux-ppc64-gnu" "1.81.0"
|
||||
"@oxlint/binding-linux-riscv64-gnu" "1.81.0"
|
||||
"@oxlint/binding-linux-riscv64-musl" "1.81.0"
|
||||
"@oxlint/binding-linux-s390x-gnu" "1.81.0"
|
||||
"@oxlint/binding-linux-x64-gnu" "1.81.0"
|
||||
"@oxlint/binding-linux-x64-musl" "1.81.0"
|
||||
"@oxlint/binding-openharmony-arm64" "1.81.0"
|
||||
"@oxlint/binding-win32-arm64-msvc" "1.81.0"
|
||||
"@oxlint/binding-win32-ia32-msvc" "1.81.0"
|
||||
"@oxlint/binding-win32-x64-msvc" "1.81.0"
|
||||
|
||||
p-cancelable@^3.0.0:
|
||||
version "3.0.0"
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
# limitations under the License.
|
||||
#
|
||||
apiVersion: v2
|
||||
deprecated: true
|
||||
appVersion: "6.1.0"
|
||||
description: Apache Superset is a modern, enterprise-ready business intelligence web application
|
||||
name: superset
|
||||
@@ -25,11 +26,7 @@ keywords:
|
||||
- data science
|
||||
sources:
|
||||
- https://github.com/apache/superset
|
||||
maintainers:
|
||||
- name: craig-rueda
|
||||
email: craig@craigrueda.com
|
||||
url: https://github.com/craig-rueda
|
||||
version: 0.22.7 # See [README](https://github.com/apache/superset/blob/master/helm/superset/README.md#versioning) for version details.
|
||||
version: 0.22.8 # See [README](https://github.com/apache/superset/blob/master/helm/superset/README.md#versioning) for version details.
|
||||
dependencies:
|
||||
- name: postgresql
|
||||
version: 16.7.27
|
||||
|
||||
+10
-1
@@ -23,7 +23,9 @@ NOTE: This file is generated by helm-docs: https://github.com/norwoodj/helm-docs
|
||||
|
||||
# superset
|
||||
|
||||

|
||||
> **:exclamation: This Helm Chart is deprecated!**
|
||||
|
||||

|
||||
|
||||
Apache Superset is a modern, enterprise-ready business intelligence web application
|
||||
|
||||
@@ -33,6 +35,13 @@ Apache Superset is a modern, enterprise-ready business intelligence web applicat
|
||||
|
||||
* <https://github.com/apache/superset>
|
||||
|
||||
## Deprecation Notice
|
||||
|
||||
> [!WARNING]
|
||||
> The Superset Helm chart is deprecated. For new Superset deployments on Kubernetes, use the official [Apache Superset Kubernetes Operator](https://github.com/apache/superset-kubernetes-operator) instead.
|
||||
>
|
||||
> Existing Helm chart users should plan a migration to the operator. Start with the [operator documentation](https://apache.github.io/superset-kubernetes-operator/) and the [Helm chart migration guide](https://apache.github.io/superset-kubernetes-operator/user-guide/migration/).
|
||||
|
||||
## TL;DR
|
||||
|
||||
```console
|
||||
|
||||
@@ -32,6 +32,13 @@ NOTE: This file is generated by helm-docs: https://github.com/norwoodj/helm-docs
|
||||
|
||||
{{ template "chart.sourcesSection" . }}
|
||||
|
||||
## Deprecation Notice
|
||||
|
||||
> [!WARNING]
|
||||
> The Superset Helm chart is deprecated. For new Superset deployments on Kubernetes, use the official [Apache Superset Kubernetes Operator](https://github.com/apache/superset-kubernetes-operator) instead.
|
||||
>
|
||||
> Existing Helm chart users should plan a migration to the operator. Start with the [operator documentation](https://apache.github.io/superset-kubernetes-operator/) and the [Helm chart migration guide](https://apache.github.io/superset-kubernetes-operator/user-guide/migration/).
|
||||
|
||||
## TL;DR
|
||||
|
||||
```console
|
||||
|
||||
+25
-6
@@ -151,10 +151,9 @@ clickhouse = ["clickhouse-connect>=1.7.2, <2.0"]
|
||||
# 2.0). sqlalchemy-cockroachdb is the actively maintained replacement,
|
||||
# already linked from CockroachDbEngineSpec.metadata's docs_url, and
|
||||
# registers the same `cockroachdb` SQLAlchemy dialect entry point.
|
||||
# sqlalchemy-cockroachdb depends only on SQLAlchemy itself, not on a DBAPI
|
||||
# driver, so psycopg2-binary is pinned alongside it (matching the `postgres`
|
||||
# extra) to keep this extra self-contained -- CockroachDB speaks the
|
||||
# PostgreSQL wire protocol, so psycopg2 is what actually opens connections.
|
||||
# sqlalchemy-cockroachdb itself declares no DBAPI dependency (its own docs
|
||||
# require picking one), so pull in the same psycopg2-binary pin as the
|
||||
# `postgres` extra -- CockroachDB speaks the Postgres wire protocol.
|
||||
cockroachdb = ["sqlalchemy-cockroachdb>=2.0.0, <3", "psycopg2-binary==2.9.12"]
|
||||
crate = ["sqlalchemy-cratedb>=0.43.1, <1"]
|
||||
# sqlalchemy-d1's only release (0.1.0, Nov 2025) pins sqlalchemy<2,>=1.4,
|
||||
@@ -226,6 +225,11 @@ impala = ["impyla>=0.24.0, <0.25"]
|
||||
# superset/db_engine_specs/kusto.py's known_incompatibilities metadata.
|
||||
kusto = ["sqlalchemy-kusto>=3.1.2, <4"]
|
||||
kylin = ["kylinpy>=2.8.4, <2.9"]
|
||||
# MariaDB is a MySQL fork implementing the same wire protocol - connects via
|
||||
# the plain mysql dialect, same driver as mysql.
|
||||
mariadb = ["apache-superset[mysql]"]
|
||||
monetdb = ["sqlalchemy-monetdb>=2.1.0, <3", "pymonetdb>=1.9.1, <2"]
|
||||
mongodb = ["pymongosql>=0.7.3, <1"]
|
||||
mssql = ["pymssql>=2.3.13, <3"]
|
||||
# motherduck is an alias for duckdb - MotherDuck works via the duckdb driver
|
||||
motherduck = ["apache-superset[duckdb]"]
|
||||
@@ -274,18 +278,33 @@ tdengine = [
|
||||
"taos-ws-py>=0.7.0"
|
||||
]
|
||||
teradata = ["teradatasql>=20.0.0.67"]
|
||||
# TimescaleDB is a genuine Postgres extension, not a fork - connects via the
|
||||
# plain postgresql dialect, same driver as postgres.
|
||||
timescaledb = ["apache-superset[postgres]"]
|
||||
thumbnails = [] # deprecated, will be removed in 7.0
|
||||
vertica = ["sqlalchemy-vertica-python>= 0.6.3, < 0.7"]
|
||||
netezza = ["nzalchemy>= 11.1.2, < 11.2"]
|
||||
starrocks = ["starrocks>=1.3.4, <2"]
|
||||
doris = ["pydoris>=1.2.0, <2.0.0"]
|
||||
oceanbase = ["oceanbase_py>=0.0.1.2"]
|
||||
# No `oceanbase` extra is published here: oceanbase_py pins
|
||||
# sqlalchemy-utils>=0.38.3,<0.39, which conflicts outright with Superset's
|
||||
# own sqlalchemy-utils==0.42.1 pin, so `pip install apache-superset[oceanbase]`
|
||||
# could never resolve. CI installs oceanbase_py as a standalone package with
|
||||
# --no-deps instead (see testcontainers.yml). Add the extra back once
|
||||
# oceanbase_py relaxes that pin.
|
||||
ydb = ["ydb-sqlalchemy>=0.1.22", "ydb-sqlglot-plugin>=0.2.8"]
|
||||
# YugabyteDB's YSQL layer is fully Postgres-wire compatible - connects via
|
||||
# the plain postgresql dialect, same driver as postgres.
|
||||
yugabytedb = ["apache-superset[postgres]"]
|
||||
development = [
|
||||
# no bounds for apache-superset-extensions-cli until a stable version
|
||||
"apache-superset-extensions-cli",
|
||||
"boto3",
|
||||
"docker",
|
||||
# 7.0.0 raises `docker.errors.DockerException: ... Not supported URL
|
||||
# scheme http+docker` against the requests/urllib3 versions pinned
|
||||
# elsewhere in this file -- breaks testcontainers (tests/testcontainers/)
|
||||
# before any container even starts. 7.2.0 is confirmed working.
|
||||
"docker>=7.2.0",
|
||||
"flask-testing",
|
||||
"freezegun",
|
||||
"grpcio>=1.83.1",
|
||||
|
||||
+7
-1
@@ -19,7 +19,13 @@ testpaths =
|
||||
tests
|
||||
python_files = *_test.py test_*.py *_tests.py *viz/utils.py
|
||||
# `-p no:warnings` temporarily disabled in favor of more finely tuned `filterwarnings`.
|
||||
#addopts = -p no:warnings
|
||||
# `not testcontainers` excludes tests/testcontainers/ by default: those spin up
|
||||
# real Docker containers, and `testpaths = tests` would otherwise pull them into
|
||||
# every plain `pytest` run. The dedicated CI job (testcontainers.yml) overrides
|
||||
# this with an explicit `-m testcontainers` to run them.
|
||||
addopts = -m "not testcontainers"
|
||||
markers =
|
||||
testcontainers: exercises a real database via testcontainers-python (needs Docker); excluded by default, see .github/workflows/testcontainers.yml
|
||||
asyncio_mode = auto
|
||||
|
||||
# `ignore` is effectively equivalent to `-p no:warnings`.
|
||||
|
||||
@@ -16,5 +16,32 @@
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
#
|
||||
-e .[development,bigquery,cockroachdb,druid,duckdb,fastmcp,gevent,gsheets,mysql,postgres,presto,prophet,trino,thumbnails]
|
||||
-e .[development,bigquery,clickhouse,cockroachdb,crate,databend,druid,duckdb,elasticsearch,fastmcp,firebird,gevent,gsheets,monetdb,mongodb,mssql,mysql,oracle,postgres,presto,prophet,risingwave,starrocks,trino,thumbnails,ydb]
|
||||
-e ./superset-extensions-cli[test]
|
||||
# testcontainers-backed db_engine_specs tests (tests/testcontainers/) --
|
||||
# see .github/workflows/testcontainers.yml
|
||||
#
|
||||
# `db2` (the `ibm-db-sa`/`ibm-db` driver) and `oceanbase` (the `oceanbase_py`
|
||||
# driver) are both deliberately left out of the baseline dev install above:
|
||||
# `ibm-db` ships no Linux arm64 wheel, breaking the multi-platform
|
||||
# (amd64+arm64) dev Docker image build; `oceanbase_py` pins
|
||||
# `sqlalchemy-utils>=0.38.3,<0.39`, which conflicts outright with Superset's
|
||||
# own `sqlalchemy-utils==0.42.1` pin -- there's no version of both that can
|
||||
# coexist in one resolved environment. Both testcontainers CI jobs install
|
||||
# their driver on demand instead, only for their own matrix leg -- see
|
||||
# .github/workflows/testcontainers.yml.
|
||||
#
|
||||
# mariadb/timescaledb/yugabytedb need no testcontainers extra of their own:
|
||||
# they reuse the postgres/mysql container classes pointed at a different
|
||||
# image, and psycopg2-binary/mysqlclient are already pulled in above via
|
||||
# the postgres/mysql extras. Plain postgres/mysql obviously need nothing
|
||||
# extra either. clickhouse and starrocks also need no testcontainers extra:
|
||||
# ClickHouseContainer has no driver import of its own (clickhouse-connect,
|
||||
# pulled in above via the clickhouse extra, is all the test needs), and
|
||||
# StarRocks has no dedicated testcontainers module at all -- its test uses
|
||||
# a generic DockerContainer plus the same mysqlclient the mysql extra
|
||||
# already provides. databend/risingwave/firebird/ydb are the same story:
|
||||
# none has a dedicated testcontainers module, so each test uses a generic
|
||||
# DockerContainer plus whatever driver its own extra above already
|
||||
# provides.
|
||||
testcontainers[cockroachdb,cratedb,mongodb,mssql,mysql,oracle,postgres,trino]>=4.15.0,<5
|
||||
|
||||
@@ -12,10 +12,17 @@
|
||||
# apache-superset
|
||||
aiofile==3.9.0
|
||||
# via py-key-value-aio
|
||||
aiohappyeyeballs==2.7.1
|
||||
# via aiohttp
|
||||
aiohttp==3.14.3
|
||||
# via ydb
|
||||
aiosignal==1.4.0
|
||||
# via aiohttp
|
||||
alembic==1.15.2
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# flask-migrate
|
||||
# starrocks
|
||||
amqp==5.3.1
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -24,6 +31,8 @@ annotated-types==0.7.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# pydantic
|
||||
antlr4-python3-runtime==4.13.2
|
||||
# via pymongosql
|
||||
anyio==4.11.0
|
||||
# via
|
||||
# httpx
|
||||
@@ -42,9 +51,12 @@ apsw==3.50.1.0
|
||||
# shillelagh
|
||||
astroid==3.3.10
|
||||
# via pylint
|
||||
asyncmy2==0.2.21
|
||||
# via starrocks
|
||||
attrs==25.3.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# aiohttp
|
||||
# cattrs
|
||||
# cyclopts
|
||||
# jsonschema
|
||||
@@ -65,6 +77,7 @@ backports-tarfile==1.2.0
|
||||
backports-zstd==1.6.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# clickhouse-connect
|
||||
# flask-compress
|
||||
bcrypt==4.3.0
|
||||
# via
|
||||
@@ -117,8 +130,11 @@ celery==5.6.3
|
||||
certifi==2026.5.20
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# clickhouse-connect
|
||||
# elasticsearch
|
||||
# httpcore
|
||||
# httpx
|
||||
# opensearch-py
|
||||
# requests
|
||||
cffi==2.0.0
|
||||
# via
|
||||
@@ -160,6 +176,8 @@ click-repl==0.3.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# celery
|
||||
clickhouse-connect==1.7.2
|
||||
# via apache-superset
|
||||
cmdstanpy==1.1.0
|
||||
# via prophet
|
||||
colorama==0.4.6
|
||||
@@ -171,6 +189,8 @@ contourpy==1.0.7
|
||||
# via matplotlib
|
||||
coverage==7.6.8
|
||||
# via pytest-cov
|
||||
crate==2.2.1
|
||||
# via sqlalchemy-cratedb
|
||||
cron-descriptor==1.4.5
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -186,14 +206,20 @@ cryptography==50.0.1
|
||||
# authlib
|
||||
# google-auth
|
||||
# joserfc
|
||||
# oracledb
|
||||
# paramiko
|
||||
# pyjwt
|
||||
# pymysql
|
||||
# pyopenssl
|
||||
# secretstorage
|
||||
cycler==0.12.1
|
||||
# via matplotlib
|
||||
cyclopts==4.2.4
|
||||
# via fastmcp-slim
|
||||
databend-driver==0.34.2
|
||||
# via databend-sqlalchemy
|
||||
databend-sqlalchemy==0.5.5
|
||||
# via apache-superset
|
||||
db-dtypes==1.3.1
|
||||
# via pandas-gbq
|
||||
defusedxml==0.7.1
|
||||
@@ -216,8 +242,11 @@ dnspython==2.7.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# email-validator
|
||||
docker==7.0.0
|
||||
# via apache-superset
|
||||
# pymongo
|
||||
docker==7.2.0
|
||||
# via
|
||||
# apache-superset
|
||||
# testcontainers
|
||||
docstring-parser==0.17.0
|
||||
# via cyclopts
|
||||
docutils==0.22.2
|
||||
@@ -228,6 +257,10 @@ duckdb==1.5.5
|
||||
# duckdb-engine
|
||||
duckdb-engine==0.17.0
|
||||
# via apache-superset
|
||||
elasticsearch==7.17.13
|
||||
# via elasticsearch-dbapi
|
||||
elasticsearch-dbapi==0.2.13
|
||||
# via apache-superset
|
||||
email-validator==2.2.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -237,6 +270,8 @@ et-xmlfile==2.0.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# openpyxl
|
||||
events==0.5
|
||||
# via opensearch-py
|
||||
exceptiongroup==1.3.0
|
||||
# via fastmcp-slim
|
||||
fastmcp==3.4.7
|
||||
@@ -247,6 +282,10 @@ filelock==3.20.3
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# virtualenv
|
||||
firebird-base==2.0.3
|
||||
# via firebird-driver
|
||||
firebird-driver==2.0.3
|
||||
# via sqlalchemy-firebird
|
||||
flask==3.1.3
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -327,12 +366,18 @@ fonttools==4.60.2
|
||||
# via matplotlib
|
||||
freezegun==1.5.1
|
||||
# via apache-superset
|
||||
frozenlist==1.8.0
|
||||
# via
|
||||
# aiohttp
|
||||
# aiosignal
|
||||
future==1.0.0
|
||||
# via pyhive
|
||||
geographiclib==2.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# geopy
|
||||
geojson==3.3.0
|
||||
# via sqlalchemy-cratedb
|
||||
geopy==2.4.1
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -389,6 +434,7 @@ grpcio==1.83.1
|
||||
# apache-superset
|
||||
# google-api-core
|
||||
# grpcio-status
|
||||
# ydb
|
||||
grpcio-status==1.60.1
|
||||
# via google-api-core
|
||||
gunicorn==26.2.0
|
||||
@@ -414,6 +460,7 @@ httpx==0.28.1
|
||||
# via
|
||||
# fastmcp-slim
|
||||
# mcp
|
||||
# testcontainers
|
||||
httpx-sse==0.4.1
|
||||
# via mcp
|
||||
humanize==4.12.3
|
||||
@@ -430,6 +477,7 @@ idna==3.15
|
||||
# httpx
|
||||
# requests
|
||||
# url-normalize
|
||||
# yarl
|
||||
importlib-metadata==8.7.0
|
||||
# via
|
||||
# keyring
|
||||
@@ -468,6 +516,7 @@ jmespath==1.1.0
|
||||
# via
|
||||
# boto3
|
||||
# botocore
|
||||
# pymongosql
|
||||
joserfc==1.7.2
|
||||
# via fastmcp-slim
|
||||
jsonpath-ng==1.8.0
|
||||
@@ -500,6 +549,8 @@ kombu==5.6.2
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# celery
|
||||
lark==1.3.1
|
||||
# via starrocks
|
||||
lazy-object-proxy==1.10.0
|
||||
# via openapi-spec-validator
|
||||
limits==5.1.0
|
||||
@@ -507,7 +558,9 @@ limits==5.1.0
|
||||
# -c requirements/base-constraint.txt
|
||||
# flask-limiter
|
||||
lz4==4.4.5
|
||||
# via trino
|
||||
# via
|
||||
# clickhouse-connect
|
||||
# trino
|
||||
mako==1.4.1
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -568,6 +621,10 @@ msgspec==0.19.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# flask-session
|
||||
multidict==6.7.1
|
||||
# via
|
||||
# aiohttp
|
||||
# yarl
|
||||
mysqlclient==2.2.8
|
||||
# via apache-superset
|
||||
nh3==0.3.7
|
||||
@@ -606,14 +663,22 @@ openpyxl==3.1.5
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# pandas
|
||||
opensearch-py==2.8.0
|
||||
# via elasticsearch-dbapi
|
||||
opentelemetry-api==1.39.1
|
||||
# via fastmcp-slim
|
||||
oracledb==4.0.2
|
||||
# via
|
||||
# apache-superset
|
||||
# testcontainers
|
||||
ordered-set==4.1.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# flask-limiter
|
||||
orjson==3.11.9
|
||||
# via trino
|
||||
# via
|
||||
# crate
|
||||
# trino
|
||||
packaging==25.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -621,8 +686,8 @@ packaging==25.0
|
||||
# apispec
|
||||
# db-dtypes
|
||||
# deprecation
|
||||
# docker
|
||||
# duckdb-engine
|
||||
# elasticsearch-dbapi
|
||||
# fastmcp-slim
|
||||
# google-cloud-bigquery
|
||||
# kombu
|
||||
@@ -632,6 +697,8 @@ packaging==25.0
|
||||
# pytest
|
||||
# shillelagh
|
||||
# sqlalchemy-bigquery
|
||||
# sqlalchemy-firebird
|
||||
# ydb
|
||||
pandas==2.3.3
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -693,16 +760,22 @@ prompt-toolkit==3.0.51
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# click-repl
|
||||
propcache==0.5.2
|
||||
# via
|
||||
# aiohttp
|
||||
# yarl
|
||||
prophet==1.4.0
|
||||
# via apache-superset
|
||||
proto-plus==1.25.0
|
||||
# via google-api-core
|
||||
protobuf==5.29.6
|
||||
# via
|
||||
# firebird-base
|
||||
# google-api-core
|
||||
# googleapis-common-protos
|
||||
# grpcio-status
|
||||
# proto-plus
|
||||
# ydb
|
||||
psutil==6.1.0
|
||||
# via
|
||||
# apache-superset
|
||||
@@ -776,6 +849,24 @@ pyjwt==2.13.0
|
||||
# mcp
|
||||
pylint==3.3.7
|
||||
# via apache-superset
|
||||
pymonetdb==1.9.1
|
||||
# via
|
||||
# apache-superset
|
||||
# sqlalchemy-monetdb
|
||||
pymongo==4.17.0
|
||||
# via
|
||||
# pymongosql
|
||||
# testcontainers
|
||||
pymongosql==0.7.3
|
||||
# via apache-superset
|
||||
pymssql==2.3.13
|
||||
# via
|
||||
# apache-superset
|
||||
# testcontainers
|
||||
pymysql==1.2.0
|
||||
# via
|
||||
# starrocks
|
||||
# testcontainers
|
||||
pynacl==1.6.2
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -820,11 +911,13 @@ python-dateutil==2.9.0.post0
|
||||
# botocore
|
||||
# celery
|
||||
# croniter
|
||||
# firebird-driver
|
||||
# flask-appbuilder
|
||||
# freezegun
|
||||
# google-cloud-bigquery
|
||||
# holidays
|
||||
# matplotlib
|
||||
# opensearch-py
|
||||
# pandas
|
||||
# pyhive
|
||||
# shillelagh
|
||||
@@ -835,6 +928,7 @@ python-dotenv==1.2.2
|
||||
# apache-superset
|
||||
# fastmcp-slim
|
||||
# pydantic-settings
|
||||
# testcontainers
|
||||
python-ldap==3.4.7
|
||||
# via apache-superset
|
||||
python-multipart==0.0.29
|
||||
@@ -878,6 +972,7 @@ requests==2.33.0
|
||||
# google-api-core
|
||||
# google-cloud-bigquery
|
||||
# jsonschema-path
|
||||
# opensearch-py
|
||||
# pydruid
|
||||
# pyhive
|
||||
# requests-cache
|
||||
@@ -956,7 +1051,9 @@ sqlalchemy==2.0.52
|
||||
# alembic
|
||||
# apache-superset
|
||||
# apache-superset-core
|
||||
# databend-sqlalchemy
|
||||
# duckdb-engine
|
||||
# elasticsearch-dbapi
|
||||
# flask-appbuilder
|
||||
# flask-sqlalchemy
|
||||
# marshmallow-sqlalchemy
|
||||
@@ -964,7 +1061,14 @@ sqlalchemy==2.0.52
|
||||
# sqlalchemy-bigquery
|
||||
# sqlalchemy-cockroachdb
|
||||
# sqlalchemy-continuum
|
||||
# sqlalchemy-cratedb
|
||||
# sqlalchemy-firebird
|
||||
# sqlalchemy-monetdb
|
||||
# sqlalchemy-risingwave
|
||||
# sqlalchemy-utils
|
||||
# starrocks
|
||||
# testcontainers
|
||||
# ydb-sqlalchemy
|
||||
sqlalchemy-bigquery==1.17.2
|
||||
# via apache-superset
|
||||
sqlalchemy-cockroachdb==2.0.4
|
||||
@@ -973,6 +1077,16 @@ sqlalchemy-continuum==1.7.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# apache-superset
|
||||
sqlalchemy-cratedb==0.43.1
|
||||
# via
|
||||
# apache-superset
|
||||
# testcontainers
|
||||
sqlalchemy-firebird==2.2.0
|
||||
# via apache-superset
|
||||
sqlalchemy-monetdb==2.1.0
|
||||
# via apache-superset
|
||||
sqlalchemy-risingwave==2.1.0
|
||||
# via apache-superset
|
||||
sqlalchemy-utils==0.42.1
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -984,6 +1098,7 @@ sqlglot==30.17.0
|
||||
# -c requirements/base-constraint.txt
|
||||
# apache-superset
|
||||
# apache-superset-core
|
||||
# ydb-sqlglot-plugin
|
||||
sqloxide==0.1.51
|
||||
# via apache-superset
|
||||
sse-starlette==3.0.2
|
||||
@@ -996,6 +1111,8 @@ starlette==1.3.1
|
||||
# via
|
||||
# fastmcp-slim
|
||||
# mcp
|
||||
starrocks==1.3.4
|
||||
# via apache-superset
|
||||
statsd==4.0.1
|
||||
# via apache-superset
|
||||
syntaqlite==0.9.0
|
||||
@@ -1004,6 +1121,8 @@ tabulate==0.10.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# apache-superset
|
||||
testcontainers==4.15.0
|
||||
# via -r requirements/development.in
|
||||
tiktoken==0.14.0
|
||||
# via apache-superset
|
||||
tomli-w==1.2.0
|
||||
@@ -1015,10 +1134,14 @@ tqdm==4.67.1
|
||||
# cmdstanpy
|
||||
# prophet
|
||||
trino==0.339.0
|
||||
# via apache-superset
|
||||
# via
|
||||
# apache-superset
|
||||
# testcontainers
|
||||
typing-extensions==4.16.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# aiohttp
|
||||
# aiosignal
|
||||
# alembic
|
||||
# anyio
|
||||
# apache-superset
|
||||
@@ -1030,6 +1153,7 @@ typing-extensions==4.16.0
|
||||
# limits
|
||||
# mcp
|
||||
# opentelemetry-api
|
||||
# oracledb
|
||||
# py-key-value-aio
|
||||
# pydantic
|
||||
# pydantic-core
|
||||
@@ -1038,6 +1162,7 @@ typing-extensions==4.16.0
|
||||
# shillelagh
|
||||
# sqlalchemy
|
||||
# starlette
|
||||
# testcontainers
|
||||
# typing-inspection
|
||||
typing-inspection==0.4.2
|
||||
# via
|
||||
@@ -1065,13 +1190,22 @@ urllib3==2.7.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# botocore
|
||||
# clickhouse-connect
|
||||
# crate
|
||||
# docker
|
||||
# elasticsearch
|
||||
# opensearch-py
|
||||
# requests
|
||||
# requests-cache
|
||||
# testcontainers
|
||||
uvicorn==0.37.0
|
||||
# via
|
||||
# fastmcp-slim
|
||||
# mcp
|
||||
verlib2==0.3.2
|
||||
# via
|
||||
# crate
|
||||
# sqlalchemy-cratedb
|
||||
vine==5.1.0
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -1105,6 +1239,7 @@ wrapt==1.17.2
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
# deprecated
|
||||
# testcontainers
|
||||
wtforms==3.2.2
|
||||
# via
|
||||
# -c requirements/base-constraint.txt
|
||||
@@ -1125,6 +1260,18 @@ xlsxwriter==3.2.9
|
||||
# -c requirements/base-constraint.txt
|
||||
# apache-superset
|
||||
# pandas
|
||||
yarl==1.24.5
|
||||
# via aiohttp
|
||||
ydb==3.31.4
|
||||
# via
|
||||
# ydb-dbapi
|
||||
# ydb-sqlalchemy
|
||||
ydb-dbapi==0.1.23
|
||||
# via ydb-sqlalchemy
|
||||
ydb-sqlalchemy==0.1.22
|
||||
# via apache-superset
|
||||
ydb-sqlglot-plugin==0.2.8
|
||||
# via apache-superset
|
||||
zipp==3.23.0
|
||||
# via importlib-metadata
|
||||
zope-event==5.0
|
||||
|
||||
Generated
+58
-213
@@ -244,7 +244,7 @@
|
||||
"html-webpack-plugin": "^5.6.8",
|
||||
"imports-loader": "^5.0.0",
|
||||
"jest": "^30.5.1",
|
||||
"jest-environment-jsdom": "^30.5.0",
|
||||
"jest-environment-jsdom": "^30.5.1",
|
||||
"jest-html-reporter": "^4.4.0",
|
||||
"jest-websocket-mock": "^2.5.0",
|
||||
"js-yaml-loader": "^1.2.2",
|
||||
@@ -5933,18 +5933,18 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/environment-jsdom-abstract": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jest/environment-jsdom-abstract/-/environment-jsdom-abstract-30.5.0.tgz",
|
||||
"integrity": "sha512-825vac4Dmysbn2kU7VUQPoKuj/HNUpSTgv98KCByMOSPvHuj1/HpVZeLRsP/itDB2HFiDcoTUrsg8fSu3PxKBw==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@jest/environment-jsdom-abstract/-/environment-jsdom-abstract-30.5.1.tgz",
|
||||
"integrity": "sha512-J395vmP3Fb2Te0JmF7pe4si4jpfbXef1YsY4UpHYL6OOxS2molu9Dsie1VmIiUalXdtmz1P5QRgc+5hBD+ssBg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/environment": "30.5.0",
|
||||
"@jest/fake-timers": "30.5.0",
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/environment": "30.5.1",
|
||||
"@jest/fake-timers": "30.5.1",
|
||||
"@jest/types": "30.5.1",
|
||||
"@types/node": "*",
|
||||
"jest-mock": "30.5.0",
|
||||
"jest-util": "30.5.0"
|
||||
"jest-mock": "30.5.1",
|
||||
"jest-util": "30.5.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
@@ -5961,34 +5961,34 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/environment-jsdom-abstract/node_modules/@jest/environment": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.0.tgz",
|
||||
"integrity": "sha512-HUaqexIauIh69IQ4NTuPDEUCB8g8T4TOPSIzQOS18mwI/KEHKQk1j013K2o6ra031szZE2t5jGmVx3xbzdjgKA==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.1.tgz",
|
||||
"integrity": "sha512-eYJAkOsrpwDXPcoLNEG6lN9Zo3Cy35pxnVQD74vyIfsi/Q8wB/lZFsEjU4wrecOgT4ZviQDZaX/cFIJyMdMxTw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/fake-timers": "30.5.0",
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/fake-timers": "30.5.1",
|
||||
"@jest/types": "30.5.1",
|
||||
"@types/node": "*",
|
||||
"jest-mock": "30.5.0"
|
||||
"jest-mock": "30.5.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/environment-jsdom-abstract/node_modules/@jest/fake-timers": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.0.tgz",
|
||||
"integrity": "sha512-sg8xIbYwe5GdB/vT3/0qrDIpO7Ov9mazHi++M95uynmDKEZ70G1r169AWct73H07VrTZhrz1SJEfLtjYv8tE3A==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.1.tgz",
|
||||
"integrity": "sha512-rEkV6YzpBXo/L9cnj2ibyuYZuyGiNWaPUsyCu3HYJbqCV4jnEiKmf7hId20z8eKjZ0JQ9jtIYKxRSmYB/OYSsA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/types": "30.5.1",
|
||||
"@sinonjs/fake-timers": "^15.4.0",
|
||||
"@types/node": "*",
|
||||
"jest-message-util": "30.5.0",
|
||||
"jest-mock": "30.5.0",
|
||||
"jest-util": "30.5.0"
|
||||
"jest-message-util": "30.5.1",
|
||||
"jest-mock": "30.5.1",
|
||||
"jest-util": "30.5.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
@@ -6028,20 +6028,20 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/environment-jsdom-abstract/node_modules/jest-message-util": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.0.tgz",
|
||||
"integrity": "sha512-dBYMhplGfspKaCnVk9TUy1cZnknWubpuPNEputjz0YJk1G/92R45rn45BvbPMPMtC5LVcIdxJGPOaOSQTiuzJw==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.1.tgz",
|
||||
"integrity": "sha512-UdQlLdd9wL/Ys7xRErckqwD6wPlSZYueosSWuHc1r2ztGLwlgPvtSJq2+BPEgaEY13WLvfFbmhTj8pba0Sd1jg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/types": "30.5.1",
|
||||
"@types/stack-utils": "^2.0.3",
|
||||
"chalk": "^4.1.2",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"jest-util": "30.5.0",
|
||||
"jest-util": "30.5.1",
|
||||
"picomatch": "^4.0.3",
|
||||
"pretty-format": "30.5.0",
|
||||
"pretty-format": "30.5.1",
|
||||
"slash": "^3.0.0",
|
||||
"stack-utils": "^2.0.6"
|
||||
},
|
||||
@@ -6063,9 +6063,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@jest/environment-jsdom-abstract/node_modules/pretty-format": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.0.tgz",
|
||||
"integrity": "sha512-mzNzBErpHwM0zpmWS7ExOv62yhQhvd546nUuFqVR0dmnJB59tfrw9sjDF0DJknwsr59OXP0buwJ7PaKguczHSg==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz",
|
||||
"integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -27311,32 +27311,6 @@
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/@jest/transform": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.5.0.tgz",
|
||||
"integrity": "sha512-n1cYhoByyULEIXi64wbT4Lq91qeT1E6bwpM//sprFXhw955qaiHTdAmy1c1rNFGB6fCf1J+nxDUSf3RGwgZP5A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.27.4",
|
||||
"@jest/types": "30.5.0",
|
||||
"@jridgewell/trace-mapping": "^0.3.31",
|
||||
"babel-plugin-istanbul": "^8.0.0",
|
||||
"chalk": "^4.1.2",
|
||||
"convert-source-map": "^2.0.0",
|
||||
"fast-json-stable-stringify": "^2.1.0",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"jest-haste-map": "30.5.0",
|
||||
"jest-regex-util": "30.5.0",
|
||||
"jest-util": "30.5.0",
|
||||
"pirates": "^4.0.7",
|
||||
"slash": "^3.0.0",
|
||||
"write-file-atomic": "^5.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/@napi-rs/wasm-runtime": {
|
||||
"version": "1.2.3",
|
||||
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.3.tgz",
|
||||
@@ -27685,48 +27659,6 @@
|
||||
"url": "https://github.com/chalk/ansi-styles?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/babel-jest": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-30.5.0.tgz",
|
||||
"integrity": "sha512-PrhPHlKC+MsLnuNzgIH/y1dkz1f6cSfKWaQeaG8WxLMuG44dYWQ8E9uRrsBbAGCU/3+BEFYPN4d6G3Zc5Y+waA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/transform": "30.5.0",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"babel-plugin-istanbul": "^8.0.0",
|
||||
"babel-preset-jest": "30.5.0",
|
||||
"chalk": "^4.1.2",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"slash": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@babel/core": "^7.11.0 || ^8.0.0-0"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/babel-plugin-istanbul": {
|
||||
"version": "8.0.0",
|
||||
"resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-8.0.0.tgz",
|
||||
"integrity": "sha512-18wCskrN3DgbuBmp1gr7LBGT8xdz5xhQQqFvFhVxbkl8VBCrMKQ2YtqBWtUal1Zrc1HTuX0011+Brjw78TCFkg==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"workspaces": [
|
||||
"test/babel-8"
|
||||
],
|
||||
"dependencies": {
|
||||
"@babel/helper-plugin-utils": "^7.0.0",
|
||||
"@istanbuljs/load-nyc-config": "^1.0.0",
|
||||
"@istanbuljs/schema": "^0.1.3",
|
||||
"istanbul-lib-instrument": "^6.0.2",
|
||||
"test-exclude": "^7.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/fdir": {
|
||||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
|
||||
@@ -27964,93 +27896,6 @@
|
||||
"url": "https://github.com/chalk/supports-color?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/test-exclude": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz",
|
||||
"integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@istanbuljs/schema": "^0.1.2",
|
||||
"glob": "^10.4.1",
|
||||
"minimatch": "^10.2.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/test-exclude/node_modules/brace-expansion": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
|
||||
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/test-exclude/node_modules/glob": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
|
||||
"integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
|
||||
"deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"foreground-child": "^3.1.0",
|
||||
"jackspeak": "^3.1.2",
|
||||
"minimatch": "^9.0.4",
|
||||
"minipass": "^7.1.2",
|
||||
"package-json-from-dist": "^1.0.0",
|
||||
"path-scurry": "^1.11.1"
|
||||
},
|
||||
"bin": {
|
||||
"glob": "dist/esm/bin.mjs"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/test-exclude/node_modules/glob/node_modules/minimatch": {
|
||||
"version": "9.0.9",
|
||||
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
|
||||
"integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"brace-expansion": "^2.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.17"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/test-exclude/node_modules/lru-cache": {
|
||||
"version": "10.4.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
||||
"dev": true,
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/jest-config/node_modules/test-exclude/node_modules/path-scurry": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
|
||||
"integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
"lru-cache": "^10.2.0",
|
||||
"minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16 || 14 >=14.18"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-config/node_modules/unrs-resolver": {
|
||||
"version": "1.12.2",
|
||||
"resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.12.2.tgz",
|
||||
@@ -28213,14 +28058,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jest-environment-jsdom": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-30.5.0.tgz",
|
||||
"integrity": "sha512-VVHN/G3zrxsQR398jvMalM76ALX6YBAftsYLCGtTeKRmz4f42YJAP05AGpk0VF5SLtoHdkfKunYGfnKPnmcEOA==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jest-environment-jsdom/-/jest-environment-jsdom-30.5.1.tgz",
|
||||
"integrity": "sha512-8lzKbC/SRbQE24wr1OOJV+aYtDAuVNKBryN6YcFiCcaZZ3I7grcZY7w91BwNvGET0ubKDmomEHZFHMaF+6pAlA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/environment": "30.5.0",
|
||||
"@jest/environment-jsdom-abstract": "30.5.0",
|
||||
"@jest/environment": "30.5.1",
|
||||
"@jest/environment-jsdom-abstract": "30.5.1",
|
||||
"@types/jsdom": "^21.1.7",
|
||||
"jsdom": "^26.1.0"
|
||||
},
|
||||
@@ -28237,34 +28082,34 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jest-environment-jsdom/node_modules/@jest/environment": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.0.tgz",
|
||||
"integrity": "sha512-HUaqexIauIh69IQ4NTuPDEUCB8g8T4TOPSIzQOS18mwI/KEHKQk1j013K2o6ra031szZE2t5jGmVx3xbzdjgKA==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.1.tgz",
|
||||
"integrity": "sha512-eYJAkOsrpwDXPcoLNEG6lN9Zo3Cy35pxnVQD74vyIfsi/Q8wB/lZFsEjU4wrecOgT4ZviQDZaX/cFIJyMdMxTw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/fake-timers": "30.5.0",
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/fake-timers": "30.5.1",
|
||||
"@jest/types": "30.5.1",
|
||||
"@types/node": "*",
|
||||
"jest-mock": "30.5.0"
|
||||
"jest-mock": "30.5.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jest-environment-jsdom/node_modules/@jest/fake-timers": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.0.tgz",
|
||||
"integrity": "sha512-sg8xIbYwe5GdB/vT3/0qrDIpO7Ov9mazHi++M95uynmDKEZ70G1r169AWct73H07VrTZhrz1SJEfLtjYv8tE3A==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.1.tgz",
|
||||
"integrity": "sha512-rEkV6YzpBXo/L9cnj2ibyuYZuyGiNWaPUsyCu3HYJbqCV4jnEiKmf7hId20z8eKjZ0JQ9jtIYKxRSmYB/OYSsA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/types": "30.5.1",
|
||||
"@sinonjs/fake-timers": "^15.4.0",
|
||||
"@types/node": "*",
|
||||
"jest-message-util": "30.5.0",
|
||||
"jest-mock": "30.5.0",
|
||||
"jest-util": "30.5.0"
|
||||
"jest-message-util": "30.5.1",
|
||||
"jest-mock": "30.5.1",
|
||||
"jest-util": "30.5.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0"
|
||||
@@ -28331,20 +28176,20 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jest-environment-jsdom/node_modules/jest-message-util": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.0.tgz",
|
||||
"integrity": "sha512-dBYMhplGfspKaCnVk9TUy1cZnknWubpuPNEputjz0YJk1G/92R45rn45BvbPMPMtC5LVcIdxJGPOaOSQTiuzJw==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.1.tgz",
|
||||
"integrity": "sha512-UdQlLdd9wL/Ys7xRErckqwD6wPlSZYueosSWuHc1r2ztGLwlgPvtSJq2+BPEgaEY13WLvfFbmhTj8pba0Sd1jg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.27.1",
|
||||
"@jest/types": "30.5.0",
|
||||
"@jest/types": "30.5.1",
|
||||
"@types/stack-utils": "^2.0.3",
|
||||
"chalk": "^4.1.2",
|
||||
"graceful-fs": "^4.2.11",
|
||||
"jest-util": "30.5.0",
|
||||
"jest-util": "30.5.1",
|
||||
"picomatch": "^4.0.3",
|
||||
"pretty-format": "30.5.0",
|
||||
"pretty-format": "30.5.1",
|
||||
"slash": "^3.0.0",
|
||||
"stack-utils": "^2.0.6"
|
||||
},
|
||||
@@ -28406,9 +28251,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jest-environment-jsdom/node_modules/pretty-format": {
|
||||
"version": "30.5.0",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.0.tgz",
|
||||
"integrity": "sha512-mzNzBErpHwM0zpmWS7ExOv62yhQhvd546nUuFqVR0dmnJB59tfrw9sjDF0DJknwsr59OXP0buwJ7PaKguczHSg==",
|
||||
"version": "30.5.1",
|
||||
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz",
|
||||
"integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
|
||||
@@ -321,7 +321,7 @@
|
||||
"html-webpack-plugin": "^5.6.8",
|
||||
"imports-loader": "^5.0.0",
|
||||
"jest": "^30.5.1",
|
||||
"jest-environment-jsdom": "^30.5.0",
|
||||
"jest-environment-jsdom": "^30.5.1",
|
||||
"jest-html-reporter": "^4.4.0",
|
||||
"jest-websocket-mock": "^2.5.0",
|
||||
"js-yaml-loader": "^1.2.2",
|
||||
|
||||
@@ -113,8 +113,19 @@ export interface BackendOwnState {
|
||||
* Each chart plugin can implement this to convert its internal state representation
|
||||
* to the standardized backend format.
|
||||
*/
|
||||
export interface ChartStateConverterOptions {
|
||||
// Set when converting for a download/export query rather than the chart's
|
||||
// live (re-)query. Some chart-specific state (e.g. AG Grid's client-side
|
||||
// sort/filter) is normally excluded from the live query's ownState to
|
||||
// avoid triggering an unnecessary requery, but a downloaded file has no
|
||||
// client-side pass to apply that state, so it still needs to be converted
|
||||
// for exports to reproduce the displayed view.
|
||||
forExport?: boolean;
|
||||
}
|
||||
|
||||
export type ChartStateConverter<TChartState = JsonObject> = (
|
||||
chartState: TChartState,
|
||||
options?: ChartStateConverterOptions,
|
||||
) => Partial<BackendOwnState>;
|
||||
|
||||
export interface PlainObject {
|
||||
|
||||
@@ -222,6 +222,7 @@ export type {
|
||||
GridState,
|
||||
GridReadyEvent,
|
||||
CellClickedEvent,
|
||||
CellContextMenuEvent,
|
||||
CellKeyDownEvent,
|
||||
CellClassParams,
|
||||
IMenuActionParams,
|
||||
|
||||
@@ -20,6 +20,15 @@ import type { DataRecordValue } from '../query/types/QueryResponse';
|
||||
import type { TimeFormatFunction } from './types';
|
||||
import normalizeTimestamp from './utils/normalizeTimestamp';
|
||||
|
||||
/**
|
||||
* A missing date can arrive as either `null`/`undefined` or an empty string
|
||||
* (e.g. a blank cell in an otherwise-numeric epoch column, which also has the
|
||||
* side effect of degrading the whole column's formatter to `String` - see
|
||||
* `isNumeric` in transformProps.ts). Both should be treated as "no value".
|
||||
*/
|
||||
export const isEmptyDateInput = (input: DataRecordValue): boolean =>
|
||||
input === null || input === undefined || input === '';
|
||||
|
||||
/**
|
||||
* Extended Date object with a custom formatter, and retains the original input
|
||||
* when the formatter is simple `String(..)`.
|
||||
|
||||
@@ -19,7 +19,10 @@
|
||||
|
||||
export { default as TimeFormats, LOCAL_PREFIX } from './TimeFormats';
|
||||
export { default as TimeFormatter, PREVIEW_TIME } from './TimeFormatter';
|
||||
export { default as DateWithFormatter } from './DateWithFormatter';
|
||||
export {
|
||||
default as DateWithFormatter,
|
||||
isEmptyDateInput,
|
||||
} from './DateWithFormatter';
|
||||
export { DEFAULT_D3_TIME_FORMAT } from './D3FormatConfig';
|
||||
|
||||
export {
|
||||
|
||||
@@ -79,4 +79,5 @@ export interface AgGridChartState {
|
||||
columnOrder?: string[];
|
||||
pageSize?: number;
|
||||
currentPage?: number;
|
||||
serverPagination?: boolean;
|
||||
}
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
GridReadyEvent,
|
||||
GridState,
|
||||
CellClickedEvent,
|
||||
CellContextMenuEvent,
|
||||
CellKeyDownEvent,
|
||||
SelectionChangedEvent,
|
||||
} from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
@@ -59,9 +60,13 @@ import getInitialSortState, { shouldSort } from '../utils/getInitialSortState';
|
||||
import getInitialFilterModel from '../utils/getInitialFilterModel';
|
||||
import reconcileColumnState from '../utils/reconcileColumnState';
|
||||
import getColumnStateSignature from '../utils/getColumnStateSignature';
|
||||
import { PAGE_SIZE_OPTIONS } from '../consts';
|
||||
import { getCompleteFilterState } from '../utils/filterStateManager';
|
||||
import { PAGE_SIZE_OPTIONS, ROW_NUMBER_COL_ID } from '../consts';
|
||||
import {
|
||||
getCompleteFilterState,
|
||||
type FilterState,
|
||||
} from '../utils/filterStateManager';
|
||||
import { copyCellValueOnKeyDown } from '../utils/copyCellValue';
|
||||
import type { ClientViewSnapshot } from '../utils/externalAPIs';
|
||||
|
||||
export interface AgGridState extends Partial<GridState> {
|
||||
timestamp?: number;
|
||||
@@ -77,7 +82,6 @@ export type AgGridChartStateWithMetadata = Partial<AgGridChartState> & {
|
||||
export interface AgGridTableProps {
|
||||
gridTheme?: string;
|
||||
isDarkMode?: boolean;
|
||||
gridHeight?: number;
|
||||
updateInterval?: number;
|
||||
data?: any[];
|
||||
onGridReady?: (params: GridReadyEvent) => void;
|
||||
@@ -100,17 +104,20 @@ export interface AgGridTableProps {
|
||||
serverPageLength: number;
|
||||
hasServerPageLengthChanged: boolean;
|
||||
handleCellClicked: (event: CellClickedEvent) => void;
|
||||
handleCellContextMenu?: (event: CellContextMenuEvent) => void;
|
||||
handleSelectionChanged: (event: SelectionChangedEvent) => void;
|
||||
filters?: Record<string, DataRecordValue[]> | null;
|
||||
isActiveFilterValue?: (key: string, val: DataRecordValue) => boolean;
|
||||
renderTimeComparisonDropdown: () => JSX.Element | null;
|
||||
cleanedTotals: DataRecord;
|
||||
showTotals: boolean;
|
||||
width: number;
|
||||
onColumnStateChange?: (state: AgGridChartStateWithMetadata) => void;
|
||||
onFilterChanged?: (filterModel: Record<string, any>) => void;
|
||||
onFilterChanged?: (completeFilterState: FilterState) => void;
|
||||
metricColumns?: string[];
|
||||
gridRef?: RefObject<AgGridReact>;
|
||||
chartState?: AgGridChartState;
|
||||
onClientViewChange?: (snapshot: ClientViewSnapshot) => void;
|
||||
}
|
||||
|
||||
ModuleRegistry.registerModules([AllCommunityModule, ClientSideRowModelModule]);
|
||||
@@ -119,7 +126,6 @@ const isSearchFocused = new Map<string, boolean>();
|
||||
|
||||
const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
({
|
||||
gridHeight,
|
||||
data = [],
|
||||
colDefsFromProps,
|
||||
includeSearch,
|
||||
@@ -140,8 +146,10 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
serverPageLength,
|
||||
hasServerPageLengthChanged,
|
||||
handleCellClicked,
|
||||
handleCellContextMenu,
|
||||
handleSelectionChanged,
|
||||
filters,
|
||||
isActiveFilterValue,
|
||||
renderTimeComparisonDropdown,
|
||||
cleanedTotals,
|
||||
showTotals,
|
||||
@@ -150,12 +158,14 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
onFilterChanged,
|
||||
metricColumns = [],
|
||||
chartState,
|
||||
onClientViewChange,
|
||||
}) => {
|
||||
const gridRef = useRef<AgGridReact>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const rowData = useMemo(() => data, [data]);
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const lastCapturedStateRef = useRef<string | null>(null);
|
||||
const hasCapturedInitialGridStateRef = useRef(false);
|
||||
const filterOperationVersionRef = useRef(0);
|
||||
|
||||
const searchId = `search-${id}`;
|
||||
@@ -189,13 +199,26 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
[],
|
||||
);
|
||||
|
||||
// Memoize container style
|
||||
// Fills the full height allotted by the chart container (StyledChartContainer);
|
||||
// the search/time-comparison controls and pagination bar take their natural
|
||||
// height and the grid flexes into whatever space remains (see gridFlexStyles),
|
||||
// instead of a hardcoded pixel height that drifts from the actual chrome height.
|
||||
const containerStyles = useMemo(
|
||||
() => ({
|
||||
height: gridHeight,
|
||||
height: '100%',
|
||||
width,
|
||||
display: 'flex',
|
||||
flexDirection: 'column' as const,
|
||||
}),
|
||||
[gridHeight, width],
|
||||
[width],
|
||||
);
|
||||
|
||||
const gridFlexStyles = useMemo(
|
||||
() => ({
|
||||
flex: '1 1 auto',
|
||||
minHeight: 0,
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
const [quickFilterText, setQuickFilterText] = useState<string>();
|
||||
@@ -293,6 +316,7 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
sortModel,
|
||||
filterModel,
|
||||
timestamp: Date.now(),
|
||||
serverPagination: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -321,49 +345,85 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
[serverPagination, gridInitialState, percentMetrics, onSortChange],
|
||||
);
|
||||
|
||||
const handleGridStateChange = useCallback(
|
||||
const captureGridState = useCallback(() => {
|
||||
const { api } = gridRef.current ?? {};
|
||||
if (!api) return null;
|
||||
|
||||
const columnState = api.getColumnState ? api.getColumnState() : [];
|
||||
const filterModel = api.getFilterModel ? api.getFilterModel() : {};
|
||||
const sortModel = columnState
|
||||
.filter(col => col.sort)
|
||||
.map(col => ({
|
||||
colId: col.colId,
|
||||
sort: col.sort as 'asc' | 'desc',
|
||||
sortIndex: col.sortIndex || 0,
|
||||
}))
|
||||
.sort((a, b) => (a.sortIndex || 0) - (b.sortIndex || 0));
|
||||
|
||||
return {
|
||||
stateToSave: {
|
||||
columnState,
|
||||
sortModel,
|
||||
filterModel,
|
||||
timestamp: Date.now(),
|
||||
serverPagination: !!serverPagination,
|
||||
},
|
||||
stateHash: getColumnStateSignature(columnState, sortModel, filterModel),
|
||||
};
|
||||
}, [serverPagination]);
|
||||
|
||||
const persistGridStateChange = useCallback(
|
||||
debounce(() => {
|
||||
if (onColumnStateChange && gridRef.current?.api) {
|
||||
try {
|
||||
const { api } = gridRef.current;
|
||||
if (!onColumnStateChange) return;
|
||||
try {
|
||||
const captured = captureGridState();
|
||||
if (!captured) return;
|
||||
const { stateToSave, stateHash } = captured;
|
||||
|
||||
const columnState = api.getColumnState ? api.getColumnState() : [];
|
||||
if (stateHash !== lastCapturedStateRef.current) {
|
||||
lastCapturedStateRef.current = stateHash;
|
||||
|
||||
const filterModel = api.getFilterModel ? api.getFilterModel() : {};
|
||||
|
||||
const sortModel = columnState
|
||||
.filter(col => col.sort)
|
||||
.map(col => ({
|
||||
colId: col.colId,
|
||||
sort: col.sort as 'asc' | 'desc',
|
||||
sortIndex: col.sortIndex || 0,
|
||||
}))
|
||||
.sort((a, b) => (a.sortIndex || 0) - (b.sortIndex || 0));
|
||||
|
||||
const stateToSave = {
|
||||
columnState,
|
||||
sortModel,
|
||||
filterModel,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
const stateHash = getColumnStateSignature(
|
||||
columnState,
|
||||
sortModel,
|
||||
filterModel,
|
||||
);
|
||||
|
||||
if (stateHash !== lastCapturedStateRef.current) {
|
||||
lastCapturedStateRef.current = stateHash;
|
||||
|
||||
onColumnStateChange(stateToSave);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Error capturing AG Grid state:', error);
|
||||
onColumnStateChange(stateToSave);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Error capturing AG Grid state:', error);
|
||||
}
|
||||
}, Constants.SLOW_DEBOUNCE),
|
||||
[onColumnStateChange],
|
||||
[onColumnStateChange, captureGridState],
|
||||
);
|
||||
|
||||
const handleGridStateChange = useCallback(() => {
|
||||
// AG Grid fires onStateUpdated once as it applies the initial
|
||||
// column/sort/filter state on mount, before any user interaction.
|
||||
// That first event just reflects the state the grid was initialized
|
||||
// with (chartState/gridInitialState) - not a user-driven change - so
|
||||
// it's captured synchronously as the baseline rather than persisted.
|
||||
// This check runs on every raw call, before debouncing, so a real
|
||||
// user action that lands inside the same debounce window as this
|
||||
// first call is never coalesced into it and dropped.
|
||||
if (!hasCapturedInitialGridStateRef.current) {
|
||||
hasCapturedInitialGridStateRef.current = true;
|
||||
try {
|
||||
const captured = captureGridState();
|
||||
if (captured) {
|
||||
lastCapturedStateRef.current = captured.stateHash;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Error capturing AG Grid state:', error);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
persistGridStateChange();
|
||||
}, [captureGridState, persistGridStateChange]);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
// Cleanup debounced grid-state capture
|
||||
() => {
|
||||
persistGridStateChange.cancel();
|
||||
},
|
||||
[persistGridStateChange],
|
||||
);
|
||||
|
||||
const handleFilterChanged = useCallback(async () => {
|
||||
@@ -416,6 +476,81 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
serverPaginationData?.agGridFilterModel,
|
||||
]);
|
||||
|
||||
// Captures the "current view" (post-filter/sort, all rows across all
|
||||
// pages) for the "Export Current View" menu, mirroring Table V1's
|
||||
// clientView snapshot. Client-side mode only: in server pagination mode
|
||||
// the grid only ever holds a single page's rows, so a client-derived
|
||||
// snapshot can't represent the full filtered/sorted result and export
|
||||
// falls back to a fresh backend query instead (see useExploreAdditionalActionsMenu).
|
||||
const lastClientViewSignatureRef = useRef<string | null>(null);
|
||||
// Unlike handleGridStateChange's columnState/sortModel/filterModel,
|
||||
// clientView is excluded from ownState re-query comparisons on both the
|
||||
// Explore (ExploreViewContainer) and dashboard (activeAllDashboardFilters)
|
||||
// paths, so publishing it - including the very first snapshot right
|
||||
// after mount - can't trigger a requery/remount loop. It's therefore
|
||||
// always persisted below rather than having its initial value skipped;
|
||||
// skipping it would leave "Export Current View" without a snapshot to
|
||||
// export until some later grid event changes the signature.
|
||||
// Debounced (like handleGridStateChange below) because the full
|
||||
// filtered+sorted traversal is O(n) and onModelUpdated can fire rapidly
|
||||
// in succession (e.g. while typing into a quick filter); only the
|
||||
// trailing update needs to recompute the snapshot.
|
||||
const handleModelUpdated = useCallback(
|
||||
debounce(() => {
|
||||
if (serverPagination || !onClientViewChange || !gridRef.current?.api) {
|
||||
return;
|
||||
}
|
||||
const { api } = gridRef.current;
|
||||
const displayedColumns = api
|
||||
.getAllDisplayedColumns()
|
||||
.filter(column => column.getColId() !== ROW_NUMBER_COL_ID);
|
||||
const columns = displayedColumns.map(column => {
|
||||
const colDef = column.getColDef();
|
||||
// For comparison columns, colId has "Main " stripped for display,
|
||||
// but row data is still keyed by the unstripped original field
|
||||
// (colDef.context.dataKey, set in useColDefs) -- use that to read
|
||||
// row values so exported rows aren't blank for the main metric.
|
||||
const dataKey = colDef.context?.dataKey ?? column.getColId();
|
||||
return {
|
||||
key: dataKey,
|
||||
label: colDef.headerName || column.getColId(),
|
||||
};
|
||||
});
|
||||
|
||||
const rows: Record<string, unknown>[] = [];
|
||||
api.forEachNodeAfterFilterAndSort(node => {
|
||||
if (node.data) {
|
||||
rows.push(node.data);
|
||||
}
|
||||
});
|
||||
|
||||
// Without a getRowId callback, AG Grid's node ids are purely
|
||||
// positional and reset to 0..n-1 on every setRowData call, so they
|
||||
// don't identify a row's content across a data refresh — hashing
|
||||
// the actual filtered+sorted row content (which this function
|
||||
// already has to visit to build `rows`) is what actually detects
|
||||
// both value changes (e.g. a refresh with the same row count) and
|
||||
// order changes (e.g. a pure sort), not just count/column changes.
|
||||
const signature = `${JSON.stringify(rows)}|${columns.map(c => c.key).join(',')}`;
|
||||
|
||||
if (signature === lastClientViewSignatureRef.current) {
|
||||
return;
|
||||
}
|
||||
lastClientViewSignatureRef.current = signature;
|
||||
onClientViewChange({ rows, columns, count: rows.length });
|
||||
}, Constants.SLOW_DEBOUNCE),
|
||||
[serverPagination, onClientViewChange],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
// Cleanup debounced client-view snapshot capture
|
||||
() => {
|
||||
handleModelUpdated.cancel();
|
||||
},
|
||||
[handleModelUpdated],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
hasServerPageLengthChanged &&
|
||||
@@ -436,14 +571,32 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
}
|
||||
}, [width]);
|
||||
|
||||
// Row highlighting must reflect the active cross filter regardless of how
|
||||
// it was applied (cell click, context menu, or an external dashboard
|
||||
// filter), so it survives re-renders and server-side re-queries rather
|
||||
// than only reflecting whichever handler last called setSelected.
|
||||
useEffect(() => {
|
||||
if (
|
||||
(!filters || Object.keys(filters).length === 0) &&
|
||||
gridRef.current?.api?.getSelectedRows().length
|
||||
) {
|
||||
gridRef.current.api.deselectAll();
|
||||
const api = gridRef.current?.api;
|
||||
if (!api) return;
|
||||
|
||||
if (!filters || Object.keys(filters).length === 0) {
|
||||
if (api.getSelectedRows().length) {
|
||||
api.deselectAll();
|
||||
}
|
||||
return;
|
||||
}
|
||||
}, [filters]);
|
||||
|
||||
if (!isActiveFilterValue) return;
|
||||
|
||||
api.forEachNode(node => {
|
||||
const matches = Object.keys(filters).some(key =>
|
||||
isActiveFilterValue(key, node.data?.[key] as DataRecordValue),
|
||||
);
|
||||
if (node.isSelected() !== matches) {
|
||||
node.setSelected(matches, false, 'api');
|
||||
}
|
||||
});
|
||||
}, [filters, isActiveFilterValue, rowData]);
|
||||
|
||||
const onGridReady = (params: GridReadyEvent) => {
|
||||
// This will make columns fill the grid width
|
||||
@@ -511,126 +664,130 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> = memo(
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ThemedAgGridReact
|
||||
ref={gridRef}
|
||||
onGridReady={onGridReady}
|
||||
className="ag-container"
|
||||
rowData={rowData}
|
||||
headerHeight={36}
|
||||
rowHeight={30}
|
||||
columnDefs={colDefsFromProps}
|
||||
defaultColDef={defaultColDef}
|
||||
onColumnGroupOpened={params => params.api.sizeColumnsToFit()}
|
||||
rowSelection="multiple"
|
||||
animateRows
|
||||
onCellClicked={handleCellClicked}
|
||||
onCellKeyDown={handleCellKeyDown}
|
||||
onSelectionChanged={handleSelectionChanged}
|
||||
onFilterChanged={handleFilterChanged}
|
||||
onStateUpdated={handleGridStateChange}
|
||||
initialState={gridInitialState}
|
||||
maintainColumnOrder
|
||||
suppressAggFuncInHeader
|
||||
// Clicking a cell should select (focus) the cell rather than select
|
||||
// its text content (#106389). enableCellTextSelection forces browser
|
||||
// text selection on click, which suppresses the cell-focus behavior.
|
||||
// Because the Enterprise clipboard module isn't registered, native
|
||||
// text selection was the only way to copy a value, so onCellKeyDown
|
||||
// (above) restores Ctrl/Cmd+C copy for the focused cell. Full
|
||||
// multi-cell range selection still requires AG Grid Enterprise, which
|
||||
// is not available in the Community build used here.
|
||||
enableCellTextSelection={false}
|
||||
quickFilterText={serverPagination ? '' : quickFilterText}
|
||||
suppressMovableColumns={!allowRearrangeColumns}
|
||||
pagination={pagination}
|
||||
paginationPageSize={pageSize}
|
||||
paginationPageSizeSelector={PAGE_SIZE_OPTIONS}
|
||||
suppressDragLeaveHidesColumns
|
||||
pinnedBottomRowData={showTotals ? [cleanedTotals] : undefined}
|
||||
tooltipShowDelay={500}
|
||||
localeText={{
|
||||
// Pagination controls
|
||||
next: t('Next'),
|
||||
previous: t('Previous'),
|
||||
page: t('Page'),
|
||||
more: t('More'),
|
||||
to: t('to'),
|
||||
of: t('of'),
|
||||
first: t('First'),
|
||||
last: t('Last'),
|
||||
loadingOoo: t('Loading...'),
|
||||
// Set Filter
|
||||
selectAll: t('Select All'),
|
||||
searchOoo: t('Search...'),
|
||||
blanks: t('Blanks'),
|
||||
// Filter operations
|
||||
filterOoo: t('Filter'),
|
||||
applyFilter: t('Apply Filter'),
|
||||
equals: t('Equals'),
|
||||
notEqual: t('Not Equal'),
|
||||
lessThan: t('Less Than'),
|
||||
greaterThan: t('Greater Than'),
|
||||
lessThanOrEqual: t('Less Than or Equal'),
|
||||
greaterThanOrEqual: t('Greater Than or Equal'),
|
||||
inRange: t('In Range'),
|
||||
contains: t('Contains'),
|
||||
notContains: t('Not Contains'),
|
||||
startsWith: t('Starts With'),
|
||||
endsWith: t('Ends With'),
|
||||
// Logical conditions
|
||||
andCondition: t('AND'),
|
||||
orCondition: t('OR'),
|
||||
// Panel and group labels
|
||||
group: t('Group'),
|
||||
columns: t('Columns'),
|
||||
filters: t('Filters'),
|
||||
valueColumns: t('Value Columns'),
|
||||
pivotMode: t('Pivot Mode'),
|
||||
groups: t('Groups'),
|
||||
values: t('Values'),
|
||||
pivots: t('Pivots'),
|
||||
toolPanelButton: t('Tool Panel'),
|
||||
// Enterprise menu items
|
||||
pinColumn: t('Pin Column'),
|
||||
valueAggregation: t('Value Aggregation'),
|
||||
autosizeThiscolumn: t('Autosize This Column'),
|
||||
autosizeAllColumns: t('Autosize All Columns'),
|
||||
groupBy: t('Group By'),
|
||||
ungroupBy: t('Ungroup By'),
|
||||
resetColumns: t('Reset Columns'),
|
||||
expandAll: t('Expand All'),
|
||||
collapseAll: t('Collapse All'),
|
||||
toolPanel: t('Tool Panel'),
|
||||
export: t('Export'),
|
||||
csvExport: t('CSV Export'),
|
||||
excelExport: t('Excel Export'),
|
||||
excelXmlExport: t('Excel XML Export'),
|
||||
// Aggregation functions
|
||||
sum: t('Sum'),
|
||||
min: t('Min'),
|
||||
max: t('Max'),
|
||||
none: t('None'),
|
||||
count: t('Count'),
|
||||
average: t('Average'),
|
||||
// Standard menu items
|
||||
copy: t('Copy'),
|
||||
copyWithHeaders: t('Copy with Headers'),
|
||||
paste: t('Paste'),
|
||||
// Column menu and sorting
|
||||
sortAscending: t('Sort Ascending'),
|
||||
sortDescending: t('Sort Descending'),
|
||||
sortUnSort: t('Clear Sort'),
|
||||
}}
|
||||
context={{
|
||||
onColumnHeaderClicked: handleColumnHeaderClick,
|
||||
initialSortState: getInitialSortState(
|
||||
serverPaginationData?.sortBy || [],
|
||||
),
|
||||
lastFilteredColumn: serverPaginationData?.lastFilteredColumn,
|
||||
lastFilteredInputPosition:
|
||||
serverPaginationData?.lastFilteredInputPosition,
|
||||
}}
|
||||
/>
|
||||
<div style={gridFlexStyles}>
|
||||
<ThemedAgGridReact
|
||||
ref={gridRef}
|
||||
onGridReady={onGridReady}
|
||||
className="ag-container"
|
||||
rowData={rowData}
|
||||
headerHeight={36}
|
||||
rowHeight={30}
|
||||
columnDefs={colDefsFromProps}
|
||||
defaultColDef={defaultColDef}
|
||||
onColumnGroupOpened={params => params.api.sizeColumnsToFit()}
|
||||
rowSelection="multiple"
|
||||
animateRows
|
||||
onCellClicked={handleCellClicked}
|
||||
onCellContextMenu={handleCellContextMenu}
|
||||
onCellKeyDown={handleCellKeyDown}
|
||||
onSelectionChanged={handleSelectionChanged}
|
||||
onFilterChanged={handleFilterChanged}
|
||||
onModelUpdated={handleModelUpdated}
|
||||
onStateUpdated={handleGridStateChange}
|
||||
initialState={gridInitialState}
|
||||
maintainColumnOrder
|
||||
suppressAggFuncInHeader
|
||||
// Clicking a cell should select (focus) the cell rather than select
|
||||
// its text content (#106389). enableCellTextSelection forces browser
|
||||
// text selection on click, which suppresses the cell-focus behavior.
|
||||
// Because the Enterprise clipboard module isn't registered, native
|
||||
// text selection was the only way to copy a value, so onCellKeyDown
|
||||
// (above) restores Ctrl/Cmd+C copy for the focused cell. Full
|
||||
// multi-cell range selection still requires AG Grid Enterprise, which
|
||||
// is not available in the Community build used here.
|
||||
enableCellTextSelection={false}
|
||||
quickFilterText={serverPagination ? '' : quickFilterText}
|
||||
suppressMovableColumns={!allowRearrangeColumns}
|
||||
pagination={pagination}
|
||||
paginationPageSize={pageSize}
|
||||
paginationPageSizeSelector={PAGE_SIZE_OPTIONS}
|
||||
suppressDragLeaveHidesColumns
|
||||
pinnedBottomRowData={showTotals ? [cleanedTotals] : undefined}
|
||||
tooltipShowDelay={500}
|
||||
localeText={{
|
||||
// Pagination controls
|
||||
next: t('Next'),
|
||||
previous: t('Previous'),
|
||||
page: t('Page'),
|
||||
more: t('More'),
|
||||
to: t('to'),
|
||||
of: t('of'),
|
||||
first: t('First'),
|
||||
last: t('Last'),
|
||||
loadingOoo: t('Loading...'),
|
||||
// Set Filter
|
||||
selectAll: t('Select All'),
|
||||
searchOoo: t('Search...'),
|
||||
blanks: t('Blanks'),
|
||||
// Filter operations
|
||||
filterOoo: t('Filter'),
|
||||
applyFilter: t('Apply Filter'),
|
||||
equals: t('Equals'),
|
||||
notEqual: t('Not Equal'),
|
||||
lessThan: t('Less Than'),
|
||||
greaterThan: t('Greater Than'),
|
||||
lessThanOrEqual: t('Less Than or Equal'),
|
||||
greaterThanOrEqual: t('Greater Than or Equal'),
|
||||
inRange: t('In Range'),
|
||||
contains: t('Contains'),
|
||||
notContains: t('Not Contains'),
|
||||
startsWith: t('Starts With'),
|
||||
endsWith: t('Ends With'),
|
||||
// Logical conditions
|
||||
andCondition: t('AND'),
|
||||
orCondition: t('OR'),
|
||||
// Panel and group labels
|
||||
group: t('Group'),
|
||||
columns: t('Columns'),
|
||||
filters: t('Filters'),
|
||||
valueColumns: t('Value Columns'),
|
||||
pivotMode: t('Pivot Mode'),
|
||||
groups: t('Groups'),
|
||||
values: t('Values'),
|
||||
pivots: t('Pivots'),
|
||||
toolPanelButton: t('Tool Panel'),
|
||||
// Enterprise menu items
|
||||
pinColumn: t('Pin Column'),
|
||||
valueAggregation: t('Value Aggregation'),
|
||||
autosizeThiscolumn: t('Autosize This Column'),
|
||||
autosizeAllColumns: t('Autosize All Columns'),
|
||||
groupBy: t('Group By'),
|
||||
ungroupBy: t('Ungroup By'),
|
||||
resetColumns: t('Reset Columns'),
|
||||
expandAll: t('Expand All'),
|
||||
collapseAll: t('Collapse All'),
|
||||
toolPanel: t('Tool Panel'),
|
||||
export: t('Export'),
|
||||
csvExport: t('CSV Export'),
|
||||
excelExport: t('Excel Export'),
|
||||
excelXmlExport: t('Excel XML Export'),
|
||||
// Aggregation functions
|
||||
sum: t('Sum'),
|
||||
min: t('Min'),
|
||||
max: t('Max'),
|
||||
none: t('None'),
|
||||
count: t('Count'),
|
||||
average: t('Average'),
|
||||
// Standard menu items
|
||||
copy: t('Copy'),
|
||||
copyWithHeaders: t('Copy with Headers'),
|
||||
paste: t('Paste'),
|
||||
// Column menu and sorting
|
||||
sortAscending: t('Sort Ascending'),
|
||||
sortDescending: t('Sort Descending'),
|
||||
sortUnSort: t('Clear Sort'),
|
||||
}}
|
||||
context={{
|
||||
onColumnHeaderClicked: handleColumnHeaderClick,
|
||||
initialSortState: getInitialSortState(
|
||||
serverPaginationData?.sortBy || [],
|
||||
),
|
||||
lastFilteredColumn: serverPaginationData?.lastFilteredColumn,
|
||||
lastFilteredInputPosition:
|
||||
serverPaginationData?.lastFilteredInputPosition,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
{serverPagination && (
|
||||
<Pagination
|
||||
currentPage={serverPaginationData?.currentPage || 0}
|
||||
|
||||
@@ -18,16 +18,28 @@
|
||||
*/
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
import {
|
||||
BinaryQueryObjectFilterClause,
|
||||
DataRecord,
|
||||
DataRecordValue,
|
||||
DateWithFormatter,
|
||||
extractTextFromHTML,
|
||||
getTimeFormatterForGranularity,
|
||||
isEmptyDateInput,
|
||||
} from '@superset-ui/core';
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { useCallback, useEffect, useRef, useState, useMemo } from 'react';
|
||||
import { isEqual } from 'lodash-es';
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
useMemo,
|
||||
} from 'react';
|
||||
import { debounce, isEqual } from 'lodash-es';
|
||||
|
||||
import {
|
||||
CellClickedEvent,
|
||||
CellContextMenuEvent,
|
||||
SelectionChangedEvent,
|
||||
} from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
import {
|
||||
@@ -37,20 +49,18 @@ import {
|
||||
SortByItem,
|
||||
} from './types';
|
||||
import AgGridDataTable from './AgGridTable';
|
||||
import { updateTableOwnState } from './utils/externalAPIs';
|
||||
import { updateTableOwnState, ClientViewSnapshot } from './utils/externalAPIs';
|
||||
import TimeComparisonVisibility from './AgGridTable/components/TimeComparisonVisibility';
|
||||
import { useColDefs } from './utils/useColDefs';
|
||||
import { buildSelectionCrossFilterDataMask } from './utils/getCrossFilterDataMask';
|
||||
import {
|
||||
buildSelectionCrossFilterDataMask,
|
||||
getCrossFilterDataMask,
|
||||
} from './utils/getCrossFilterDataMask';
|
||||
import { StyledChartContainer } from './styles';
|
||||
import type { FilterState } from './utils/filterStateManager';
|
||||
|
||||
const getGridHeight = (height: number, includeSearch: boolean | undefined) => {
|
||||
let calculatedGridHeight = height;
|
||||
if (includeSearch) {
|
||||
calculatedGridHeight -= 16;
|
||||
}
|
||||
return calculatedGridHeight - 80;
|
||||
};
|
||||
import { formatColumnValue } from './utils/formatValue';
|
||||
import getTimeRangeFromGranularity from './utils/getTimeRangeFromGranularity';
|
||||
import getScrollBarSize from './utils/getScrollBarSize';
|
||||
|
||||
export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
props: AgGridTableChartTransformedProps<D> & {},
|
||||
@@ -61,6 +71,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
data,
|
||||
includeSearch,
|
||||
allowRearrangeColumns,
|
||||
allowRenderHtml,
|
||||
pageSize,
|
||||
serverPagination,
|
||||
rowCount,
|
||||
@@ -88,8 +99,60 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
metricSqlExpressions,
|
||||
rawSummaryColumns,
|
||||
showNumberedColumn,
|
||||
onContextMenu,
|
||||
formData,
|
||||
} = props;
|
||||
|
||||
// The dashboard's layout engine reports a burst of close-but-not-identical
|
||||
// width/height values while it settles on initial load. Committing each
|
||||
// intermediate value resizes the chart container and re-fits AG Grid's
|
||||
// columns once per value; for any column with wrapText/autoHeight (the
|
||||
// default - see useColDefs), each re-fit can flip a borderline cell across
|
||||
// its wrap boundary and change that row's height, which is what actually
|
||||
// reads as "flicker" rather than the container resize itself.
|
||||
//
|
||||
// A scrollbar-sized threshold (matching plugin-chart-table/v1's guard)
|
||||
// filters out sub-pixel noise, but genuine multi-step settling still gets
|
||||
// through as several real width values in quick succession. Debouncing
|
||||
// every commit after the first collapses that burst into the single final
|
||||
// value once it stops changing, while still painting the first available
|
||||
// size immediately so the chart isn't blank while it waits.
|
||||
const [tableSize, setTableSize] = useState({ width: 0, height: 0 });
|
||||
const hasCommittedInitialSize = useRef(false);
|
||||
|
||||
const debouncedSetTableSize = useMemo(
|
||||
() =>
|
||||
debounce((size: { width: number; height: number }) => {
|
||||
setTableSize(size);
|
||||
}, 250),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
// Cleanup debounced size commit
|
||||
() => {
|
||||
debouncedSetTableSize.cancel();
|
||||
},
|
||||
[debouncedSetTableSize],
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const scrollBarSize = getScrollBarSize();
|
||||
const sizeChanged =
|
||||
Math.abs(width - tableSize.width) > scrollBarSize ||
|
||||
Math.abs(height - tableSize.height) > scrollBarSize;
|
||||
if (!sizeChanged) {
|
||||
return;
|
||||
}
|
||||
if (!hasCommittedInitialSize.current) {
|
||||
hasCommittedInitialSize.current = true;
|
||||
setTableSize({ width, height });
|
||||
} else {
|
||||
debouncedSetTableSize({ width, height });
|
||||
}
|
||||
}, [width, height, tableSize, debouncedSetTableSize]);
|
||||
|
||||
const [searchOptions, setSearchOptions] = useState<SearchOption[]>([]);
|
||||
|
||||
// Extract metric column names for SQL conversion
|
||||
@@ -114,6 +177,27 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
}
|
||||
}, [columns]);
|
||||
|
||||
// Tracks the most recently written ownState so that writes triggered
|
||||
// asynchronously (e.g. clientView from AG Grid's onModelUpdated, which can
|
||||
// fire with a stale closure) merge onto the latest known state instead of
|
||||
// a stale render-time serverPaginationData snapshot. updateTableOwnState
|
||||
// replaces ownState wholesale, so merging at write time - rather than at
|
||||
// render time - is what keeps concurrent writers from clobbering one
|
||||
// another's keys.
|
||||
const ownStateRef = useRef(serverPaginationData);
|
||||
useEffect(() => {
|
||||
ownStateRef.current = serverPaginationData;
|
||||
}, [serverPaginationData]);
|
||||
|
||||
const writeOwnState = useCallback(
|
||||
(patch: Record<string, unknown>) => {
|
||||
const nextOwnState = { ...ownStateRef.current, ...patch };
|
||||
ownStateRef.current = nextOwnState;
|
||||
updateTableOwnState(setDataMask, nextOwnState);
|
||||
},
|
||||
[setDataMask],
|
||||
);
|
||||
|
||||
// A single effect owns every ownState write derived from render state.
|
||||
// updateTableOwnState replaces ownState wholesale, so separate effects that
|
||||
// each spread serverPaginationData in the same render would clobber one
|
||||
@@ -121,7 +205,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
// columns and nudging a re-query for missing totals must be one combined
|
||||
// delta.
|
||||
useEffect(() => {
|
||||
const nextOwnState = { ...serverPaginationData };
|
||||
const patch: Record<string, unknown> = {};
|
||||
let changed = false;
|
||||
|
||||
if (serverPagination && serverPaginationData && rowCount !== undefined) {
|
||||
@@ -132,7 +216,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
// last remaining page.
|
||||
const clampedPage = Math.max(0, Math.min(currentPage, totalPages - 1));
|
||||
if (clampedPage !== currentPage) {
|
||||
nextOwnState.currentPage = clampedPage;
|
||||
patch.currentPage = clampedPage;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
@@ -140,22 +224,22 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
const primed = (serverPaginationData?.rawSummaryColumns ?? []) as string[];
|
||||
const requested = Boolean(serverPaginationData?.totalsRequested);
|
||||
if (isRawRecords && showTotals && !isEqual(primed, rawSummaryColumns)) {
|
||||
nextOwnState.rawSummaryColumns = rawSummaryColumns;
|
||||
patch.rawSummaryColumns = rawSummaryColumns;
|
||||
changed = true;
|
||||
}
|
||||
// A renderTrigger toggle re-renders without re-querying; requesting totals
|
||||
// through ownState dispatches the standard re-query whose buildQuery
|
||||
// carries the totals query for the active mode.
|
||||
if (showTotals && totals === undefined && !requested) {
|
||||
nextOwnState.totalsRequested = true;
|
||||
patch.totalsRequested = true;
|
||||
changed = true;
|
||||
} else if (!showTotals && requested) {
|
||||
nextOwnState.totalsRequested = false;
|
||||
patch.totalsRequested = false;
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
updateTableOwnState(setDataMask, nextOwnState);
|
||||
writeOwnState(patch);
|
||||
}
|
||||
}, [
|
||||
serverPagination,
|
||||
@@ -166,7 +250,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
totals,
|
||||
rawSummaryColumns,
|
||||
serverPaginationData,
|
||||
setDataMask,
|
||||
writeOwnState,
|
||||
]);
|
||||
|
||||
const comparisonColumns = [
|
||||
@@ -209,8 +293,7 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
}
|
||||
|
||||
// Prepare modified own state for server pagination
|
||||
const modifiedOwnState = {
|
||||
...serverPaginationData,
|
||||
writeOwnState({
|
||||
agGridFilterModel:
|
||||
completeFilterState.originalFilterModel &&
|
||||
Object.keys(completeFilterState.originalFilterModel).length > 0
|
||||
@@ -223,14 +306,11 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
lastFilteredInputPosition: completeFilterState.inputPosition,
|
||||
currentPage: 0, // Reset to first page when filtering
|
||||
metricSqlExpressions,
|
||||
};
|
||||
|
||||
updateTableOwnState(setDataMask, modifiedOwnState);
|
||||
});
|
||||
},
|
||||
[
|
||||
setDataMask,
|
||||
writeOwnState,
|
||||
serverPagination,
|
||||
serverPaginationData,
|
||||
onChartStateChange,
|
||||
chartState,
|
||||
metricSqlExpressions,
|
||||
@@ -273,15 +353,17 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
colorPositiveNegative,
|
||||
columnColorFormatters,
|
||||
allowRearrangeColumns,
|
||||
allowRenderHtml,
|
||||
basicColorFormatters,
|
||||
isUsingTimeComparison,
|
||||
emitCrossFilters,
|
||||
alignPositiveNegative,
|
||||
slice_id,
|
||||
conditionalFormatting: formData?.conditional_formatting,
|
||||
comparisonColorEnabled: formData?.comparison_color_enabled,
|
||||
comparisonColorScheme: formData?.comparison_color_scheme,
|
||||
});
|
||||
|
||||
const gridHeight = getGridHeight(height, includeSearch);
|
||||
|
||||
const isActiveFilterValue = useCallback(
|
||||
function isActiveFilterValue(key: string, val: DataRecordValue) {
|
||||
if (!filters || !filters[key]) return false;
|
||||
@@ -348,7 +430,17 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
|
||||
const handleSelectionChanged = useCallback(
|
||||
(event: SelectionChangedEvent) => {
|
||||
if (!emitCrossFilters || !activeColumnRef.current) return;
|
||||
// Selection changes triggered by the highlight-sync effect (source
|
||||
// 'api') reflect a filter that was already applied elsewhere (context
|
||||
// menu, dashboard filter, etc.), so re-deriving and re-dispatching a
|
||||
// mask from them here would use a stale activeColumnRef and could
|
||||
// clobber that filter with the wrong column.
|
||||
if (
|
||||
!emitCrossFilters ||
|
||||
!activeColumnRef.current ||
|
||||
event.source === 'api'
|
||||
)
|
||||
return;
|
||||
|
||||
const key = activeColumnRef.current;
|
||||
const selectedRows = event.api.getSelectedRows();
|
||||
@@ -368,75 +460,204 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
[emitCrossFilters, setDataMask, timeGrain, timestampFormatter],
|
||||
);
|
||||
|
||||
const drillColumns = isUsingTimeComparison
|
||||
? (filteredColumns as InputColumn[])
|
||||
: (columns as InputColumn[]);
|
||||
|
||||
const handleContextMenu = useCallback(
|
||||
(event: CellContextMenuEvent) => {
|
||||
if (!onContextMenu || isRawRecords || !event.column || !event.data) {
|
||||
return;
|
||||
}
|
||||
const nativeEvent = event.event as MouseEvent | null | undefined;
|
||||
if (!nativeEvent) return;
|
||||
nativeEvent.preventDefault();
|
||||
nativeEvent.stopPropagation();
|
||||
|
||||
const rowData = event.data as Record<string, DataRecordValue>;
|
||||
const key = event.column.getColId();
|
||||
const cellValue = event.value as DataRecordValue;
|
||||
const colDef = event.column.getColDef();
|
||||
const isMetric = Boolean(
|
||||
colDef.context?.isMetric || colDef.context?.isPercentMetric,
|
||||
);
|
||||
|
||||
const drillToDetailFilters: BinaryQueryObjectFilterClause[] = [];
|
||||
drillColumns.forEach(col => {
|
||||
if (col.isMetric || col.isPercentMetric) return;
|
||||
const dataRecordValue = rowData[col.key];
|
||||
|
||||
if (
|
||||
dataRecordValue == null ||
|
||||
(dataRecordValue instanceof DateWithFormatter &&
|
||||
isEmptyDateInput(dataRecordValue.input))
|
||||
) {
|
||||
drillToDetailFilters.push({
|
||||
col: col.key,
|
||||
op: 'IS NULL' as any,
|
||||
val: null,
|
||||
});
|
||||
} else if (col.dataType === GenericDataType.Temporal && timeGrain) {
|
||||
const startTime =
|
||||
dataRecordValue instanceof Date
|
||||
? dataRecordValue
|
||||
: new Date(dataRecordValue as string | number);
|
||||
|
||||
if (Number.isNaN(startTime.getTime())) {
|
||||
// Malformed temporal value: fall back to an equality filter
|
||||
// instead of building a TEMPORAL_RANGE, since toISOString()
|
||||
// throws on an Invalid Date and would crash the context menu.
|
||||
const sanitizedValue = extractTextFromHTML(dataRecordValue);
|
||||
drillToDetailFilters.push({
|
||||
col: col.key,
|
||||
op: '==',
|
||||
val: sanitizedValue as string | number | boolean,
|
||||
formattedVal: formatColumnValue(col, sanitizedValue)[1],
|
||||
});
|
||||
} else {
|
||||
const [rangeStartTime, rangeEndTime] = getTimeRangeFromGranularity(
|
||||
startTime,
|
||||
timeGrain,
|
||||
);
|
||||
const timeRangeValue = `${rangeStartTime.toISOString()} : ${rangeEndTime.toISOString()}`;
|
||||
|
||||
drillToDetailFilters.push({
|
||||
col: col.key,
|
||||
op: 'TEMPORAL_RANGE',
|
||||
val: timeRangeValue,
|
||||
grain: timeGrain,
|
||||
formattedVal: formatColumnValue(col, dataRecordValue)[1],
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const sanitizedValue = extractTextFromHTML(dataRecordValue);
|
||||
drillToDetailFilters.push({
|
||||
col: col.key,
|
||||
op: '==',
|
||||
val: sanitizedValue as string | number | boolean,
|
||||
formattedVal: formatColumnValue(col, sanitizedValue)[1],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const isCellValueNull =
|
||||
cellValue == null ||
|
||||
(cellValue instanceof DateWithFormatter &&
|
||||
isEmptyDateInput(cellValue.input));
|
||||
|
||||
onContextMenu(nativeEvent.clientX, nativeEvent.clientY, {
|
||||
drillToDetail: drillToDetailFilters,
|
||||
crossFilter: isMetric
|
||||
? undefined
|
||||
: getCrossFilterDataMask({
|
||||
key,
|
||||
value: cellValue,
|
||||
filters,
|
||||
timeGrain,
|
||||
isActiveFilterValue,
|
||||
timestampFormatter,
|
||||
}),
|
||||
drillBy: isMetric
|
||||
? undefined
|
||||
: {
|
||||
filters: [
|
||||
isCellValueNull
|
||||
? { col: key, op: 'IS NULL' as any, val: null }
|
||||
: {
|
||||
col: key,
|
||||
op: '==' as any,
|
||||
val: extractTextFromHTML(cellValue),
|
||||
},
|
||||
],
|
||||
groupbyFieldName: 'groupby',
|
||||
},
|
||||
});
|
||||
},
|
||||
[
|
||||
onContextMenu,
|
||||
isRawRecords,
|
||||
drillColumns,
|
||||
timeGrain,
|
||||
filters,
|
||||
isActiveFilterValue,
|
||||
timestampFormatter,
|
||||
],
|
||||
);
|
||||
|
||||
const handleServerPaginationChange = useCallback(
|
||||
(pageNumber: number, pageSize: number) => {
|
||||
const modifiedOwnState = {
|
||||
...serverPaginationData,
|
||||
writeOwnState({
|
||||
currentPage: pageNumber,
|
||||
pageSize,
|
||||
lastFilteredColumn: undefined,
|
||||
lastFilteredInputPosition: undefined,
|
||||
};
|
||||
updateTableOwnState(setDataMask, modifiedOwnState);
|
||||
});
|
||||
},
|
||||
[setDataMask],
|
||||
[writeOwnState],
|
||||
);
|
||||
|
||||
const handlePageSizeChange = useCallback(
|
||||
(pageSize: number) => {
|
||||
const modifiedOwnState = {
|
||||
...serverPaginationData,
|
||||
writeOwnState({
|
||||
currentPage: 0,
|
||||
pageSize,
|
||||
lastFilteredColumn: undefined,
|
||||
lastFilteredInputPosition: undefined,
|
||||
};
|
||||
updateTableOwnState(setDataMask, modifiedOwnState);
|
||||
});
|
||||
},
|
||||
[setDataMask],
|
||||
[writeOwnState],
|
||||
);
|
||||
|
||||
const handleChangeSearchCol = (searchCol: string) => {
|
||||
if (!isEqual(searchCol, serverPaginationData?.searchColumn)) {
|
||||
const modifiedOwnState = {
|
||||
...serverPaginationData,
|
||||
if (!isEqual(searchCol, ownStateRef.current?.searchColumn)) {
|
||||
writeOwnState({
|
||||
searchColumn: searchCol,
|
||||
searchText: '',
|
||||
currentPage: 0, // Reset to first page when the search column changes
|
||||
lastFilteredColumn: undefined,
|
||||
lastFilteredInputPosition: undefined,
|
||||
};
|
||||
updateTableOwnState(setDataMask, modifiedOwnState);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleSearch = useCallback(
|
||||
(searchText: string) => {
|
||||
const modifiedOwnState = {
|
||||
...serverPaginationData,
|
||||
writeOwnState({
|
||||
searchColumn:
|
||||
serverPaginationData?.searchColumn || searchOptions[0]?.value,
|
||||
(ownStateRef.current?.searchColumn as string | undefined) ||
|
||||
searchOptions[0]?.value,
|
||||
searchText,
|
||||
currentPage: 0, // Reset to first page when searching
|
||||
lastFilteredColumn: undefined,
|
||||
lastFilteredInputPosition: undefined,
|
||||
};
|
||||
updateTableOwnState(setDataMask, modifiedOwnState);
|
||||
});
|
||||
},
|
||||
[setDataMask, searchOptions],
|
||||
[writeOwnState, searchOptions],
|
||||
);
|
||||
|
||||
const handleSortByChange = useCallback(
|
||||
(sortBy: SortByItem[]) => {
|
||||
if (!serverPagination) return;
|
||||
const modifiedOwnState = {
|
||||
...serverPaginationData,
|
||||
writeOwnState({
|
||||
sortBy,
|
||||
lastFilteredColumn: undefined,
|
||||
lastFilteredInputPosition: undefined,
|
||||
};
|
||||
updateTableOwnState(setDataMask, modifiedOwnState);
|
||||
});
|
||||
},
|
||||
[setDataMask, serverPagination],
|
||||
[writeOwnState, serverPagination],
|
||||
);
|
||||
|
||||
// Feeds the "Export Current View" menu item (EXPORT_CURRENT_VIEW behavior),
|
||||
// mirroring Table V1's clientView snapshot on ownState. Written through
|
||||
// writeOwnState (rather than spreading serverPaginationData directly)
|
||||
// because onModelUpdated can fire with a stale closure relative to other
|
||||
// ownState writers (e.g. a just-applied filter), and updateTableOwnState
|
||||
// replaces ownState wholesale.
|
||||
const handleClientViewChange = useCallback(
|
||||
(clientView: ClientViewSnapshot) => {
|
||||
writeOwnState({ clientView });
|
||||
},
|
||||
[writeOwnState],
|
||||
);
|
||||
|
||||
const renderTimeComparisonVisibility = (): JSX.Element => (
|
||||
@@ -455,9 +676,22 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
.join('|');
|
||||
|
||||
return (
|
||||
<StyledChartContainer height={height}>
|
||||
<StyledChartContainer
|
||||
height={tableSize.height}
|
||||
onContextMenu={event => {
|
||||
// Safety net: AG Grid only calls handleContextMenu (which calls
|
||||
// preventDefault) when it resolves the native contextmenu event to
|
||||
// a cell. If that per-cell resolution ever misses - e.g. a second,
|
||||
// near-duplicate contextmenu event dispatched in quick succession by
|
||||
// some mice's right-button switches - the event still bubbles
|
||||
// through this container, so the browser's native menu is
|
||||
// suppressed here regardless of whether AG Grid's own handler ran.
|
||||
if (!isRawRecords) {
|
||||
event.preventDefault();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<AgGridDataTable
|
||||
gridHeight={gridHeight}
|
||||
key={descriptionsKey}
|
||||
data={data || []}
|
||||
colDefsFromProps={colDefs}
|
||||
@@ -478,8 +712,10 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
metricColumns={metricColumns}
|
||||
id={slice_id}
|
||||
handleCellClicked={handleCellClicked}
|
||||
handleCellContextMenu={handleContextMenu}
|
||||
handleSelectionChanged={handleSelectionChanged}
|
||||
filters={filters}
|
||||
isActiveFilterValue={isActiveFilterValue}
|
||||
percentMetrics={percentMetrics}
|
||||
serverPageLength={serverPageLength}
|
||||
hasServerPageLengthChanged={hasServerPageLengthChanged}
|
||||
@@ -490,9 +726,10 @@ export default function TableChart<D extends DataRecord = DataRecord>(
|
||||
showTotals={
|
||||
showTotals && totals !== undefined && Object.keys(totals).length > 0
|
||||
}
|
||||
width={width}
|
||||
width={tableSize.width}
|
||||
onColumnStateChange={handleColumnStateChange}
|
||||
chartState={chartState}
|
||||
onClientViewChange={handleClientViewChange}
|
||||
/>
|
||||
</StyledChartContainer>
|
||||
);
|
||||
|
||||
@@ -674,6 +674,29 @@ export const buildQueryUncached: BuildQuery<TableChartFormData> = (
|
||||
}
|
||||
}
|
||||
|
||||
// Build the "all records" percent-metric denominator query AFTER all
|
||||
// filter mutations (interactive group-by, search, AG Grid WHERE/HAVING)
|
||||
// above, so its denominator reflects the same filtered result set as the
|
||||
// main query instead of a stale pre-filter snapshot.
|
||||
const calculationMode = formData.percent_metric_calculation || 'row_limit';
|
||||
|
||||
if (
|
||||
calculationMode === 'all_records' &&
|
||||
percentMetrics &&
|
||||
percentMetrics.length > 0
|
||||
) {
|
||||
extraQueries.push({
|
||||
...queryObject,
|
||||
columns: [],
|
||||
metrics: percentMetrics,
|
||||
post_processing: [],
|
||||
row_limit: 0,
|
||||
row_offset: 0,
|
||||
orderby: [],
|
||||
is_timeseries: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Create totals query AFTER all filters (including AG Grid filters) are applied
|
||||
// This ensures we can properly exclude AG Grid WHERE filters from the totals
|
||||
// In raw records mode the summary is a SUM over the numeric columns primed
|
||||
@@ -714,33 +737,21 @@ export const buildQueryUncached: BuildQuery<TableChartFormData> = (
|
||||
: undefined;
|
||||
|
||||
if (showAggregateTotals || rawSummaryColumns.length > 0) {
|
||||
// Create a copy of extras without the AG Grid WHERE clause
|
||||
// AG Grid filters in extras.where can reference calculated columns
|
||||
// which aren't available in the totals subquery
|
||||
const totalsExtras = { ...queryObject.extras };
|
||||
if (ownState.agGridComplexWhere) {
|
||||
// Remove AG Grid WHERE clause from totals query
|
||||
const whereClause = totalsExtras.where;
|
||||
if (whereClause) {
|
||||
// Remove the AG Grid filter part from the WHERE clause using string methods
|
||||
const agGridWhere = ownState.agGridComplexWhere;
|
||||
let newWhereClause = whereClause;
|
||||
|
||||
// Try to remove with " AND " before
|
||||
newWhereClause = newWhereClause.replace(` AND ${agGridWhere}`, '');
|
||||
// Try to remove with " AND " after
|
||||
newWhereClause = newWhereClause.replace(`${agGridWhere} AND `, '');
|
||||
// If it's the only clause, remove it entirely
|
||||
if (newWhereClause === agGridWhere) {
|
||||
newWhereClause = '';
|
||||
}
|
||||
|
||||
if (newWhereClause.trim()) {
|
||||
totalsExtras.where = newWhereClause;
|
||||
} else {
|
||||
delete totalsExtras.where;
|
||||
}
|
||||
}
|
||||
// Start from the original, pre-filter extras (captured before any
|
||||
// AG Grid WHERE/HAVING or download sqlClauses were merged in above)
|
||||
// rather than trying to subtract those fragments back out of the
|
||||
// now-combined `queryObject.extras` string. AG Grid filters can
|
||||
// reference calculated columns that aren't available once the
|
||||
// totals subquery drops all grouping columns (columns: []), and that
|
||||
// applies to HAVING just as much as WHERE, and to the download
|
||||
// sqlClauses path just as much as the live agGridComplexWhere path —
|
||||
// starting clean avoids having to special-case each source.
|
||||
const totalsExtras = { ...extras };
|
||||
if (!totalsExtras.where) {
|
||||
delete totalsExtras.where;
|
||||
}
|
||||
if (!totalsExtras.having) {
|
||||
delete totalsExtras.having;
|
||||
}
|
||||
|
||||
extraQueries.push({
|
||||
|
||||
@@ -39,6 +39,8 @@ import {
|
||||
shouldSkipMetricColumn,
|
||||
isRegularMetric,
|
||||
isPercentMetric,
|
||||
ConditionalFormattingConfig,
|
||||
ObjectFormattingEnum,
|
||||
ColorSchemeEnum,
|
||||
} from '@superset-ui/chart-controls';
|
||||
import { t } from '@apache-superset/core/translation';
|
||||
@@ -194,6 +196,23 @@ const percentMetricsControl: typeof sharedControls.metrics = {
|
||||
validators: [],
|
||||
};
|
||||
|
||||
const percentMetricCalculationControl: ControlConfig<'SelectControl'> = {
|
||||
type: 'SelectControl',
|
||||
label: t('Percentage metric calculation'),
|
||||
description: t(
|
||||
'Row Limit: percentages are calculated based on the subset of data retrieved, respecting the row limit. ' +
|
||||
'All Records: Percentages are calculated based on the total dataset, ignoring the row limit.',
|
||||
),
|
||||
default: 'row_limit',
|
||||
clearable: false,
|
||||
choices: [
|
||||
['row_limit', t('Row limit')],
|
||||
['all_records', t('All records')],
|
||||
],
|
||||
visibility: isAggMode,
|
||||
renderTrigger: false,
|
||||
};
|
||||
|
||||
/*
|
||||
Options for row limit control
|
||||
*/
|
||||
@@ -431,6 +450,12 @@ const config: ControlPanelConfig = {
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
name: 'percent_metric_calculation',
|
||||
config: percentMetricCalculationControl,
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -481,6 +506,36 @@ const config: ControlPanelConfig = {
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
name: 'allow_rearrange_columns',
|
||||
config: {
|
||||
type: 'CheckboxControl',
|
||||
label: t('Allow columns to be rearranged'),
|
||||
renderTrigger: true,
|
||||
default: false,
|
||||
description: t(
|
||||
"Allow end user to drag-and-drop column headers to rearrange them. Note their changes won't persist for the next time they open the chart.",
|
||||
),
|
||||
visibility: ({ controls }: ControlPanelsContainerProps) =>
|
||||
isEmpty(controls?.time_compare?.value),
|
||||
},
|
||||
},
|
||||
],
|
||||
[
|
||||
{
|
||||
name: 'allow_render_html',
|
||||
config: {
|
||||
type: 'CheckboxControl',
|
||||
label: t('Render columns in HTML format'),
|
||||
renderTrigger: true,
|
||||
default: true,
|
||||
description: t(
|
||||
'Renders table cells as HTML when applicable. For example, HTML <a> tags will be rendered as hyperlinks.',
|
||||
),
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -573,11 +628,14 @@ const config: ControlPanelConfig = {
|
||||
const updatedColtypes: GenericDataType[] = [];
|
||||
|
||||
colnames
|
||||
.map(
|
||||
(colname, index) => [colname, index] as [string, number],
|
||||
)
|
||||
.filter(
|
||||
colname =>
|
||||
([colname]) =>
|
||||
last(colname.split('__')) !== timeComparisonValue,
|
||||
)
|
||||
.forEach((colname, index) => {
|
||||
.forEach(([colname, originalIndex]) => {
|
||||
if (
|
||||
shouldSkipMetricColumn({
|
||||
colname,
|
||||
@@ -614,7 +672,12 @@ const config: ControlPanelConfig = {
|
||||
});
|
||||
} else {
|
||||
updatedColnames.push(colname);
|
||||
updatedColtypes.push(coltypes[index]);
|
||||
// Look up by the column's original position in
|
||||
// colnames/coltypes, not its position after the
|
||||
// filter above — those diverge whenever any
|
||||
// earlier column is a comparison-suffixed one that
|
||||
// got filtered out.
|
||||
updatedColtypes.push(coltypes[originalIndex]);
|
||||
childColumnMap[colname] = false;
|
||||
timeComparisonColumnMap[colname] = false;
|
||||
}
|
||||
@@ -749,24 +812,71 @@ const config: ControlPanelConfig = {
|
||||
: [];
|
||||
|
||||
const chartStatus = chart?.chartStatus;
|
||||
// Normalize legacy `toAllRow`/`toTextColor` flags saved before
|
||||
// `columnFormatting`/`objectFormatting` existed, so "entire row"
|
||||
// formatters set under the old schema keep working.
|
||||
const value = _?.value ?? [];
|
||||
if (value && Array.isArray(value)) {
|
||||
value.forEach(
|
||||
(item: ConditionalFormattingConfig, index, array) => {
|
||||
if (
|
||||
item.colorScheme &&
|
||||
(typeof item.colorScheme !== 'string' ||
|
||||
!['Green', 'Red'].includes(item.colorScheme))
|
||||
) {
|
||||
if (item.columnFormatting === undefined) {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
array[index] = {
|
||||
...item,
|
||||
...(item.toTextColor === true && {
|
||||
objectFormatting: ObjectFormattingEnum.TEXT_COLOR,
|
||||
}),
|
||||
...(item.toAllRow === true && {
|
||||
columnFormatting: ObjectFormattingEnum.ENTIRE_ROW,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
const { colnames, coltypes } =
|
||||
chart?.queriesResponse?.[0] ?? {};
|
||||
const numericColumns =
|
||||
Array.isArray(colnames) && Array.isArray(coltypes)
|
||||
? colnames
|
||||
.filter(
|
||||
(colname: string, index: number) =>
|
||||
coltypes[index] === GenericDataType.Numeric,
|
||||
)
|
||||
.map((colname: string) => ({
|
||||
value: colname,
|
||||
label: Array.isArray(verboseMap)
|
||||
? colname
|
||||
: (verboseMap[colname] ?? colname),
|
||||
dataType:
|
||||
colnames && coltypes[colnames?.indexOf(colname)],
|
||||
}))
|
||||
: [];
|
||||
const hasColumns =
|
||||
Array.isArray(colnames) && Array.isArray(coltypes);
|
||||
const allColumns = hasColumns
|
||||
? [
|
||||
{
|
||||
value: ObjectFormattingEnum.ENTIRE_ROW,
|
||||
label: t('entire row'),
|
||||
dataType: GenericDataType.String,
|
||||
},
|
||||
...colnames.map((colname: string, index: number) => ({
|
||||
value: colname,
|
||||
label: Array.isArray(verboseMap)
|
||||
? colname
|
||||
: (verboseMap?.[colname] ?? colname),
|
||||
dataType: coltypes[index],
|
||||
})),
|
||||
]
|
||||
: [];
|
||||
const numericColumns = hasColumns
|
||||
? colnames
|
||||
.filter(
|
||||
(colname: string, index: number) =>
|
||||
coltypes[index] === GenericDataType.Numeric,
|
||||
)
|
||||
.map((colname: string) => ({
|
||||
value: colname,
|
||||
label: Array.isArray(verboseMap)
|
||||
? colname
|
||||
: (verboseMap?.[colname] ?? colname),
|
||||
// Every entry here already passed the Numeric filter
|
||||
// above, so the type is always Numeric — no need to
|
||||
// re-look it up (which breaks on duplicate colnames).
|
||||
dataType: GenericDataType.Numeric,
|
||||
}))
|
||||
: [];
|
||||
const columnOptions = hasTimeComparison
|
||||
? processComparisonColumns(
|
||||
numericColumns || [],
|
||||
@@ -778,6 +888,7 @@ const config: ControlPanelConfig = {
|
||||
removeIrrelevantConditions: chartStatus === 'success',
|
||||
columnOptions,
|
||||
verboseMap,
|
||||
allColumns,
|
||||
extraColorChoices,
|
||||
serverPagination: Boolean(
|
||||
explore?.controls?.server_pagination?.value,
|
||||
|
||||
@@ -44,6 +44,7 @@ const metadata = new ChartMetadata({
|
||||
Behavior.InteractiveChart,
|
||||
Behavior.DrillToDetail,
|
||||
Behavior.DrillBy,
|
||||
'EXPORT_CURRENT_VIEW' as Behavior,
|
||||
],
|
||||
category: t('Table'),
|
||||
canBeAnnotationTypes: ['EVENT', 'INTERVAL'],
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
import {
|
||||
BackendOwnState,
|
||||
ChartStateConverterOptions,
|
||||
QuerySortBy,
|
||||
type AgGridChartState,
|
||||
type AgGridSortModel,
|
||||
@@ -353,7 +354,24 @@ export function convertFilterModel(
|
||||
*/
|
||||
export function convertAgGridStateToOwnState(
|
||||
agGridState: AgGridChartState,
|
||||
options: ChartStateConverterOptions = {},
|
||||
): Partial<BackendOwnState> {
|
||||
// In client mode, AG Grid handles sort/filter/pagination locally, so for
|
||||
// the *live* query none of it needs to reach the backend -- folding it
|
||||
// into ownState there would only trigger an unnecessary requery/remount.
|
||||
// A *download* query has no client-side pass to apply that state though:
|
||||
// dashboard doesn't consume the Explore-only clientView snapshot, so
|
||||
// exports still need it converted to reproduce the displayed
|
||||
// sort/filter/columns (options.forExport).
|
||||
//
|
||||
// Only an explicit `false` is treated as "definitely client mode":
|
||||
// legacy persisted table_state/permalinks predate serverPagination and
|
||||
// have it `undefined`, and treating that the same as `false` would
|
||||
// silently drop their persisted server-side sort/filter on restore.
|
||||
if (agGridState.serverPagination === false && !options.forExport) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const ownState: Partial<BackendOwnState> = {};
|
||||
|
||||
const sortBy = convertSortModel(agGridState.sortModel);
|
||||
|
||||
@@ -184,6 +184,7 @@ export const PaginationContainer = styled.div`
|
||||
color: ${theme.colorTextBase};
|
||||
transform: translateY(-${theme.sizeUnit}px);
|
||||
background: ${theme.colorBgBase};
|
||||
flex-shrink: 0;
|
||||
`}
|
||||
`;
|
||||
|
||||
@@ -353,6 +354,7 @@ export const StyledChartContainer = styled.div<{
|
||||
.dropdown-controls-container {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.time-comparison-dropdown {
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
getNumberFormatter,
|
||||
getTimeFormatter,
|
||||
getTimeFormatterForGranularity,
|
||||
normalizeCurrency,
|
||||
NumberFormats,
|
||||
QueryMode,
|
||||
SMART_DATE_ID,
|
||||
@@ -60,7 +61,11 @@ const { DATABASE_DATETIME } = TimeFormats;
|
||||
|
||||
function isNumeric(key: string, data: DataRecord[] = []) {
|
||||
return data.every(
|
||||
x => x[key] === null || x[key] === undefined || typeof x[key] === 'number',
|
||||
x =>
|
||||
x[key] === null ||
|
||||
x[key] === undefined ||
|
||||
x[key] === '' ||
|
||||
typeof x[key] === 'number',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -168,7 +173,33 @@ const getComparisonColFormatter = (
|
||||
return formatter;
|
||||
};
|
||||
|
||||
const processComparisonDataRecords = memoizeOne(
|
||||
// transformProps is a single module-level function shared by every mounted
|
||||
// instance of this chart plugin on a dashboard (one plugin registration,
|
||||
// not one per chart). memoizeOne only remembers the single most-recent
|
||||
// call, so wrapping a function in it directly here means unrelated chart
|
||||
// instances evict each other's cached result whenever they render in the
|
||||
// same tick, forcing a full rebuild - with brand-new array/object
|
||||
// references - even when a given chart's own inputs are unchanged. AG
|
||||
// Grid treats a new colDefs identity as "columns changed" and re-measures
|
||||
// autoHeight/wrapText rows, which is what actually reads as a layout
|
||||
// flicker on a chart that never changed. Keying a separate memoized
|
||||
// function per chart id isolates each chart's cache from its siblings.
|
||||
function memoizePerChart<Args extends unknown[], R>(
|
||||
fn: (...args: Args) => R,
|
||||
isEqual?: (newArgs: Args, lastArgs: Args) => boolean,
|
||||
) {
|
||||
const memoizedByChart = new Map<number, (...args: Args) => R>();
|
||||
return (sliceId: number, ...args: Args): R => {
|
||||
let fnForChart = memoizedByChart.get(sliceId);
|
||||
if (!fnForChart) {
|
||||
fnForChart = isEqual ? memoizeOne(fn, isEqual) : memoizeOne(fn);
|
||||
memoizedByChart.set(sliceId, fnForChart);
|
||||
}
|
||||
return fnForChart(...args);
|
||||
};
|
||||
}
|
||||
|
||||
const processComparisonDataRecords = memoizePerChart(
|
||||
function processComparisonDataRecords(
|
||||
originalData: DataRecord[] | undefined,
|
||||
originalColumns: DataColumnMeta[],
|
||||
@@ -309,7 +340,7 @@ const processComparisonColumns = (
|
||||
|
||||
const serverPageLengthMap = new Map();
|
||||
|
||||
const processDataRecords = memoizeOne(function processDataRecords(
|
||||
const processDataRecords = memoizePerChart(function processDataRecords(
|
||||
data: DataRecord[] | undefined,
|
||||
columns: DataColumnMeta[],
|
||||
) {
|
||||
@@ -336,11 +367,16 @@ const processDataRecords = memoizeOne(function processDataRecords(
|
||||
return data;
|
||||
});
|
||||
|
||||
const processColumns = memoizeOne(function processColumns(
|
||||
const processColumns = memoizePerChart(function processColumns(
|
||||
props: TableChartProps,
|
||||
) {
|
||||
const {
|
||||
datasource: { columnFormats, currencyFormats, verboseMap },
|
||||
datasource: {
|
||||
columnFormats,
|
||||
currencyFormats,
|
||||
verboseMap,
|
||||
currencyCodeColumn,
|
||||
},
|
||||
rawFormData: {
|
||||
table_timestamp_format: tableTimestampFormat,
|
||||
metrics: metrics_,
|
||||
@@ -352,7 +388,12 @@ const processColumns = memoizeOne(function processColumns(
|
||||
queriesData,
|
||||
} = props;
|
||||
const granularity = extractTimegrain(props.rawFormData);
|
||||
const { data: records, colnames, coltypes } = queriesData[0] || {};
|
||||
const {
|
||||
data: records,
|
||||
colnames,
|
||||
coltypes,
|
||||
detected_currency: detectedCurrency,
|
||||
} = queriesData[0] || {};
|
||||
// convert `metrics` and `percentMetrics` to the key names in `data.records`
|
||||
const metrics = (metrics_ ?? []).map(getMetricLabel);
|
||||
const rawPercentMetrics = (percentMetrics_ ?? []).map(getMetricLabel);
|
||||
@@ -363,13 +404,18 @@ const processColumns = memoizeOne(function processColumns(
|
||||
const rawPercentMetricsSet = new Set(rawPercentMetrics);
|
||||
|
||||
const columns: DataColumnMeta[] = (colnames || [])
|
||||
.map((key: string, originalIndex: number) => ({ key, originalIndex }))
|
||||
.filter(
|
||||
key =>
|
||||
({ key }) =>
|
||||
// if a metric was only added to percent_metrics, they should not show up in the table.
|
||||
!(rawPercentMetricsSet.has(key) && !metricsSet.has(key)),
|
||||
)
|
||||
.map((key: string, i) => {
|
||||
const dataType = coltypes[i];
|
||||
.map(({ key, originalIndex }) => {
|
||||
// Look up by the column's original position in colnames/coltypes,
|
||||
// not its position after the filter above — those diverge whenever
|
||||
// an earlier column (e.g. a percent-metric-only one) got filtered
|
||||
// out, which would otherwise shift every later column's dataType.
|
||||
const dataType = coltypes[originalIndex];
|
||||
const config = columnConfig[key] || {};
|
||||
// for the purpose of presentation, only numeric values are treated as metrics
|
||||
// because users can also add things like `MAX(str_col)` as a metric.
|
||||
@@ -431,10 +477,25 @@ const processColumns = memoizeOne(function processColumns(
|
||||
// percent metrics have a default format
|
||||
formatter = getNumberFormatter(numberFormat || PERCENT_3_POINT);
|
||||
} else if (isMetric || (isNumber && (numberFormat || currency))) {
|
||||
formatter = currency?.symbol
|
||||
// Resolve AUTO currency when currency column isn't in query results
|
||||
let resolvedCurrency = currency;
|
||||
if (
|
||||
currency?.symbol === 'AUTO' &&
|
||||
detectedCurrency &&
|
||||
(!currencyCodeColumn || !colnames?.includes(currencyCodeColumn))
|
||||
) {
|
||||
const normalizedCurrency = normalizeCurrency(detectedCurrency);
|
||||
if (normalizedCurrency) {
|
||||
resolvedCurrency = {
|
||||
...currency,
|
||||
symbol: normalizedCurrency,
|
||||
};
|
||||
}
|
||||
}
|
||||
formatter = resolvedCurrency?.symbol
|
||||
? new CurrencyFormatter({
|
||||
d3Format: numberFormat,
|
||||
currency,
|
||||
currency: resolvedCurrency,
|
||||
})
|
||||
: getNumberFormatter(numberFormat);
|
||||
}
|
||||
@@ -448,6 +509,7 @@ const processColumns = memoizeOne(function processColumns(
|
||||
formatter,
|
||||
config,
|
||||
description,
|
||||
currencyCodeColumn,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => {
|
||||
@@ -494,7 +556,7 @@ const transformProps = (
|
||||
queriesData = [],
|
||||
ownState: serverPaginationData,
|
||||
filterState,
|
||||
hooks: { setDataMask = () => {}, onChartStateChange },
|
||||
hooks: { setDataMask = () => {}, onChartStateChange, onContextMenu },
|
||||
emitCrossFilters,
|
||||
theme,
|
||||
} = chartProps;
|
||||
@@ -526,10 +588,10 @@ const transformProps = (
|
||||
comparison_color_enabled: comparisonColorEnabled = false,
|
||||
comparison_color_scheme: comparisonColorScheme = ColorSchemeEnum.Green,
|
||||
show_numbered_column: showNumberedColumn = false,
|
||||
allow_rearrange_columns: allowRearrangeColumns = true,
|
||||
allow_render_html: allowRenderHtml = true,
|
||||
} = formData;
|
||||
|
||||
const allowRearrangeColumns = true;
|
||||
|
||||
// Calculate time comparison settings early since they're used in multiple places
|
||||
const isUsingTimeComparison =
|
||||
!isEmpty(time_compare) &&
|
||||
@@ -682,7 +744,7 @@ const transformProps = (
|
||||
hasServerPageLengthChanged = true;
|
||||
}
|
||||
|
||||
const [, percentMetrics, columns] = processColumns(chartProps);
|
||||
const [, percentMetrics, columns] = processColumns(slice_id, chartProps);
|
||||
|
||||
const timeGrain = extractTimegrain(formData);
|
||||
|
||||
@@ -700,20 +762,34 @@ const transformProps = (
|
||||
);
|
||||
}
|
||||
|
||||
// buildQuery.ts can append an "all records" percent-metric denominator
|
||||
// query *and* a totals query, independently of each other, both landing
|
||||
// in extraQueries before the totals one. A fixed totalQuery index would
|
||||
// silently bind to the wrong query's data (or drop the totals query
|
||||
// entirely) whenever both are present, so replicate buildQuery.ts's own
|
||||
// gating condition here to know whether to skip that extra slot.
|
||||
const hasAllRecordsExtraQuery = Boolean(
|
||||
formData.percent_metrics?.length &&
|
||||
(formData.percent_metric_calculation || 'row_limit') === 'all_records',
|
||||
);
|
||||
|
||||
let baseQuery;
|
||||
let countQuery;
|
||||
let rowCount;
|
||||
let totalQuery;
|
||||
if (serverPagination) {
|
||||
[baseQuery, countQuery, totalQuery] = queriesData;
|
||||
[baseQuery, countQuery] = queriesData;
|
||||
totalQuery = hasAllRecordsExtraQuery ? queriesData[3] : queriesData[2];
|
||||
rowCount = (countQuery?.data?.[0]?.rowcount as number) ?? 0;
|
||||
} else {
|
||||
[baseQuery, totalQuery] = queriesData;
|
||||
[baseQuery] = queriesData;
|
||||
totalQuery = hasAllRecordsExtraQuery ? queriesData[2] : queriesData[1];
|
||||
rowCount = baseQuery?.rowcount ?? 0;
|
||||
}
|
||||
|
||||
const data = processDataRecords(baseQuery?.data, columns);
|
||||
const data = processDataRecords(slice_id, baseQuery?.data, columns);
|
||||
const comparisonData = processComparisonDataRecords(
|
||||
slice_id,
|
||||
baseQuery?.data,
|
||||
columns,
|
||||
comparisonSuffix,
|
||||
@@ -793,12 +869,12 @@ const transformProps = (
|
||||
|
||||
// Map saved metric/calculated column labels to their SQL expressions for filter resolution
|
||||
const metricSqlExpressions: Record<string, string> = {};
|
||||
chartProps.datasource.metrics.forEach(metric => {
|
||||
(chartProps.datasource?.metrics ?? []).forEach(metric => {
|
||||
if (metric.metric_name && metric.expression) {
|
||||
metricSqlExpressions[metric.metric_name] = metric.expression;
|
||||
}
|
||||
});
|
||||
chartProps.datasource.columns.forEach(col => {
|
||||
(chartProps.datasource?.columns ?? []).forEach(col => {
|
||||
if (col.column_name && col.expression) {
|
||||
metricSqlExpressions[col.column_name] = col.expression;
|
||||
if (col.verbose_name && col.verbose_name !== col.column_name) {
|
||||
@@ -811,7 +887,7 @@ const transformProps = (
|
||||
// backed by a dataset (physical or calculated) column can be summed
|
||||
// server-side; free-form SQL expression columns are excluded.
|
||||
const datasetColumnNames = new Set(
|
||||
chartProps.datasource.columns
|
||||
(chartProps.datasource?.columns ?? [])
|
||||
.map(col => col.column_name)
|
||||
.filter((name): name is string => Boolean(name)),
|
||||
);
|
||||
@@ -849,6 +925,7 @@ const transformProps = (
|
||||
filters: filterState.filters,
|
||||
emitCrossFilters,
|
||||
allowRearrangeColumns,
|
||||
allowRenderHtml,
|
||||
slice_id,
|
||||
serverPagination,
|
||||
rowCount,
|
||||
@@ -873,6 +950,7 @@ const transformProps = (
|
||||
chartState,
|
||||
onChartStateChange,
|
||||
showNumberedColumn,
|
||||
onContextMenu,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
JsonObject,
|
||||
Metric,
|
||||
AgGridChartState,
|
||||
ContextMenuFilters,
|
||||
} from '@superset-ui/core';
|
||||
import {
|
||||
ColDef,
|
||||
@@ -81,6 +82,7 @@ export type TableChartFormData = QueryFormData & {
|
||||
time_grain_sqla?: TimeGranularity;
|
||||
column_config?: Record<string, TableColumnConfig>;
|
||||
allow_rearrange_columns?: boolean;
|
||||
allow_render_html?: boolean;
|
||||
show_numbered_column?: boolean;
|
||||
};
|
||||
|
||||
@@ -134,6 +136,11 @@ export interface AgGridTableChartTransformedProps<
|
||||
onChartStateChange?: (chartState: JsonObject) => void;
|
||||
chartState?: AgGridChartState;
|
||||
showNumberedColumn: boolean;
|
||||
onContextMenu?: (
|
||||
clientX: number,
|
||||
clientY: number,
|
||||
filters?: ContextMenuFilters,
|
||||
) => void;
|
||||
}
|
||||
|
||||
export interface SortState {
|
||||
@@ -196,6 +203,7 @@ export interface InputColumn {
|
||||
originalLabel?: string;
|
||||
metricName?: string;
|
||||
description?: string;
|
||||
currencyCodeColumn?: string;
|
||||
}
|
||||
|
||||
export type ValueRange = [number, number] | null;
|
||||
|
||||
@@ -20,6 +20,17 @@
|
||||
import { SetDataMaskHook } from '@superset-ui/core';
|
||||
import { SortByItem } from '../types';
|
||||
|
||||
export interface ClientViewColumn {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export interface ClientViewSnapshot {
|
||||
rows: Record<string, unknown>[];
|
||||
columns: ClientViewColumn[];
|
||||
count: number;
|
||||
}
|
||||
|
||||
interface TableOwnState {
|
||||
currentPage?: number;
|
||||
pageSize?: number;
|
||||
@@ -29,6 +40,7 @@ interface TableOwnState {
|
||||
sortBy?: SortByItem[];
|
||||
rawSummaryColumns?: string[];
|
||||
totalsRequested?: boolean;
|
||||
clientView?: ClientViewSnapshot;
|
||||
}
|
||||
|
||||
export const updateTableOwnState = (
|
||||
|
||||
@@ -17,9 +17,11 @@
|
||||
* under the License.
|
||||
*/
|
||||
import {
|
||||
CurrencyFormatter,
|
||||
DataRecordValue,
|
||||
getSmallNumberFormatter,
|
||||
isDefined,
|
||||
isEmptyDateInput,
|
||||
isProbablyHTML,
|
||||
sanitizeHtml,
|
||||
DateWithFormatter,
|
||||
@@ -37,6 +39,8 @@ import { DataColumnMeta, InputColumn } from '../types';
|
||||
function formatValue(
|
||||
formatter: DataColumnMeta['formatter'],
|
||||
value: DataRecordValue,
|
||||
rowData?: Record<string, DataRecordValue>,
|
||||
currencyColumn?: string,
|
||||
): [boolean, string] {
|
||||
// render undefined as empty string
|
||||
if (value === undefined) {
|
||||
@@ -45,13 +49,17 @@ function formatValue(
|
||||
// render null as `N/A`
|
||||
if (
|
||||
value === null ||
|
||||
// null values in temporal columns are wrapped in a Date object, so make sure we
|
||||
// handle them here too
|
||||
(value instanceof DateWithFormatter && value.input === null)
|
||||
// null/empty values in temporal columns are wrapped in a Date object, so make
|
||||
// sure we handle them here too
|
||||
(value instanceof DateWithFormatter && isEmptyDateInput(value.input))
|
||||
) {
|
||||
return [false, 'N/A'];
|
||||
}
|
||||
if (formatter) {
|
||||
// If formatter is a CurrencyFormatter, pass row context for AUTO mode
|
||||
if (formatter instanceof CurrencyFormatter) {
|
||||
return [false, formatter(value as number, rowData, currencyColumn)];
|
||||
}
|
||||
return [false, formatter(value as number)];
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
@@ -63,8 +71,9 @@ function formatValue(
|
||||
export function formatColumnValue(
|
||||
column: DataColumnMeta,
|
||||
value: DataRecordValue,
|
||||
rowData?: Record<string, DataRecordValue>,
|
||||
) {
|
||||
const { dataType, formatter, config = {} } = column;
|
||||
const { dataType, formatter, config = {}, currencyCodeColumn } = column;
|
||||
const isNumber = dataType === GenericDataType.Numeric;
|
||||
const smallNumberFormatter = getSmallNumberFormatter(
|
||||
formatter,
|
||||
@@ -76,6 +85,8 @@ export function formatColumnValue(
|
||||
? smallNumberFormatter
|
||||
: formatter,
|
||||
value,
|
||||
rowData,
|
||||
currencyCodeColumn,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -83,13 +94,24 @@ export const valueFormatter = (
|
||||
params: ValueFormatterParams,
|
||||
col: InputColumn,
|
||||
): string => {
|
||||
const { value, node } = params;
|
||||
const { value, node, data } = params;
|
||||
if (
|
||||
isDefined(value) &&
|
||||
value !== '' &&
|
||||
!(value instanceof DateWithFormatter && value.input === null)
|
||||
!(value instanceof DateWithFormatter && isEmptyDateInput(value.input))
|
||||
) {
|
||||
return col.formatter?.(value) || value;
|
||||
// Fall back to String(value) rather than the raw value: value can be a
|
||||
// DateWithFormatter/Date (or other object) when col.formatter is unset or
|
||||
// returns a falsy result, and returning that raw object here - though it
|
||||
// satisfies this function's `: string` signature at compile time since
|
||||
// `value`'s param type is loosely typed - crashes React with "Objects are
|
||||
// not valid as a React child" once a cell renderer renders it directly.
|
||||
if (col.formatter instanceof CurrencyFormatter) {
|
||||
return (
|
||||
col.formatter(value, data, col.currencyCodeColumn) || String(value)
|
||||
);
|
||||
}
|
||||
return col.formatter?.(value) || String(value);
|
||||
}
|
||||
if (node?.level === -1) {
|
||||
return '';
|
||||
|
||||
@@ -55,29 +55,81 @@ const getCellStyle = (params: CellStyleParams) => {
|
||||
let backgroundColor;
|
||||
let color;
|
||||
if (hasColumnColorFormatters) {
|
||||
columnColorFormatters!
|
||||
.filter(formatter => {
|
||||
const colTitle = formatter?.column?.includes('Main')
|
||||
? formatter?.column?.replace('Main', '').trim()
|
||||
: formatter?.column;
|
||||
return colTitle === colDef.field;
|
||||
})
|
||||
.forEach(formatter => {
|
||||
const formatterResult =
|
||||
value || value === 0 ? formatter.getColorFromValue(value) : false;
|
||||
if (formatterResult) {
|
||||
if (
|
||||
formatter.objectFormatting === ObjectFormattingEnum.TEXT_COLOR ||
|
||||
formatter.toTextColor
|
||||
) {
|
||||
color = formatterResult;
|
||||
} else if (
|
||||
formatter.objectFormatting !== ObjectFormattingEnum.CELL_BAR
|
||||
) {
|
||||
backgroundColor = formatterResult;
|
||||
}
|
||||
const applyFormatter = (
|
||||
formatter: ColorFormatters[number],
|
||||
valueToFormat: typeof value,
|
||||
) => {
|
||||
const formatterResult =
|
||||
valueToFormat || valueToFormat === 0
|
||||
? formatter.getColorFromValue(valueToFormat)
|
||||
: false;
|
||||
if (formatterResult) {
|
||||
if (
|
||||
formatter.objectFormatting === ObjectFormattingEnum.TEXT_COLOR ||
|
||||
formatter.toTextColor
|
||||
) {
|
||||
color = formatterResult;
|
||||
} else if (
|
||||
formatter.objectFormatting !== ObjectFormattingEnum.CELL_BAR
|
||||
) {
|
||||
backgroundColor = formatterResult;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// formatter.column can be a legacy display label ("Main colname") for
|
||||
// time-comparison columns rather than the row's actual data key, so
|
||||
// resolve it to the real field id before using it to read row values.
|
||||
const resolveColumnKey = (columnKey: string) =>
|
||||
columnKey.startsWith('Main ')
|
||||
? columnKey.slice('Main '.length)
|
||||
: columnKey;
|
||||
|
||||
// Formatters with no formatting target color their own source column,
|
||||
// keyed off this cell's own value. Excludes legacy v1 `toAllRow` rules,
|
||||
// which are entire-row formatters handled below.
|
||||
columnColorFormatters!
|
||||
.filter(
|
||||
formatter =>
|
||||
!formatter.columnFormatting &&
|
||||
!formatter.toAllRow &&
|
||||
resolveColumnKey(formatter.column) === colDef.field,
|
||||
)
|
||||
.forEach(formatter => applyFormatter(formatter, value));
|
||||
|
||||
// Formatters with a real target column color that target column,
|
||||
// keyed off the value in the formatter's own (source) column.
|
||||
columnColorFormatters!
|
||||
.filter(
|
||||
formatter =>
|
||||
formatter.columnFormatting &&
|
||||
formatter.columnFormatting !== ObjectFormattingEnum.ENTIRE_ROW &&
|
||||
resolveColumnKey(formatter.columnFormatting) === colDef.field,
|
||||
)
|
||||
.forEach(formatter =>
|
||||
applyFormatter(
|
||||
formatter,
|
||||
node?.data?.[resolveColumnKey(formatter.column)],
|
||||
),
|
||||
);
|
||||
|
||||
// Entire-row formatters apply to every cell in the row, keyed off the
|
||||
// value in the formatter's own column rather than this cell's column.
|
||||
// `toAllRow` is the legacy v1 flag for the same behavior; migrated
|
||||
// charts carry it over unchanged rather than being rewritten to
|
||||
// `columnFormatting: ENTIRE_ROW`, so both are honored here.
|
||||
columnColorFormatters!
|
||||
.filter(
|
||||
formatter =>
|
||||
formatter.columnFormatting === ObjectFormattingEnum.ENTIRE_ROW ||
|
||||
formatter.toAllRow,
|
||||
)
|
||||
.forEach(formatter =>
|
||||
applyFormatter(
|
||||
formatter,
|
||||
node?.data?.[resolveColumnKey(formatter.column)],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
let cached: number | undefined;
|
||||
|
||||
const css = (x: TemplateStringsArray) => x.join('\n');
|
||||
|
||||
export default function getScrollBarSize(forceRefresh = false) {
|
||||
if (typeof document === 'undefined') {
|
||||
return 0;
|
||||
}
|
||||
if (cached === undefined || forceRefresh) {
|
||||
const inner = document.createElement('div');
|
||||
const outer = document.createElement('div');
|
||||
inner.style.cssText = css`
|
||||
width: auto;
|
||||
height: 100%;
|
||||
overflow: scroll;
|
||||
`;
|
||||
outer.style.cssText = css`
|
||||
position: absolute;
|
||||
visibility: hidden;
|
||||
overflow: hidden;
|
||||
width: 100px;
|
||||
height: 50px;
|
||||
`;
|
||||
outer.append(inner);
|
||||
document.body.append(outer);
|
||||
cached = outer.clientWidth - inner.clientWidth;
|
||||
outer.remove();
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* 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 { TimeGranularity } from '@superset-ui/core';
|
||||
|
||||
/**
|
||||
* Calculates the inclusive/exclusive temporal range for a bucket.
|
||||
* standard SQL range pattern: [start, end)
|
||||
*/
|
||||
export default function getTimeRangeFromGranularity(
|
||||
startTime: Date,
|
||||
granularity: TimeGranularity,
|
||||
): [Date, Date] {
|
||||
const time = startTime.getTime();
|
||||
const date = startTime.getUTCDate();
|
||||
const month = startTime.getUTCMonth();
|
||||
const year = startTime.getUTCFullYear();
|
||||
|
||||
// Constants
|
||||
const MS_IN_SECOND = 1000;
|
||||
const MS_IN_MINUTE = 60 * MS_IN_SECOND;
|
||||
const MS_IN_HOUR = 60 * MS_IN_MINUTE;
|
||||
|
||||
switch (granularity) {
|
||||
case TimeGranularity.SECOND:
|
||||
return [startTime, new Date(time + MS_IN_SECOND)];
|
||||
case TimeGranularity.MINUTE:
|
||||
return [startTime, new Date(time + MS_IN_MINUTE)];
|
||||
case TimeGranularity.FIVE_MINUTES:
|
||||
return [startTime, new Date(time + MS_IN_MINUTE * 5)];
|
||||
case TimeGranularity.TEN_MINUTES:
|
||||
return [startTime, new Date(time + MS_IN_MINUTE * 10)];
|
||||
case TimeGranularity.FIFTEEN_MINUTES:
|
||||
return [startTime, new Date(time + MS_IN_MINUTE * 15)];
|
||||
case TimeGranularity.THIRTY_MINUTES:
|
||||
return [startTime, new Date(time + MS_IN_MINUTE * 30)];
|
||||
case TimeGranularity.HOUR:
|
||||
return [startTime, new Date(time + MS_IN_HOUR)];
|
||||
case TimeGranularity.DAY:
|
||||
case TimeGranularity.DATE:
|
||||
return [startTime, new Date(Date.UTC(year, month, date + 1))];
|
||||
case TimeGranularity.WEEK:
|
||||
case TimeGranularity.WEEK_STARTING_SUNDAY:
|
||||
case TimeGranularity.WEEK_STARTING_MONDAY:
|
||||
return [startTime, new Date(Date.UTC(year, month, date + 7))];
|
||||
case TimeGranularity.WEEK_ENDING_SATURDAY:
|
||||
case TimeGranularity.WEEK_ENDING_SUNDAY:
|
||||
// Week-ending buckets are labeled by the bucket's final day.
|
||||
return [
|
||||
new Date(Date.UTC(year, month, date - 6)),
|
||||
new Date(Date.UTC(year, month, date + 1)),
|
||||
];
|
||||
case TimeGranularity.MONTH:
|
||||
return [startTime, new Date(Date.UTC(year, month + 1, 1))];
|
||||
case TimeGranularity.QUARTER:
|
||||
return [
|
||||
startTime,
|
||||
new Date(Date.UTC(year, Math.floor(month / 3) * 3 + 3, 1)),
|
||||
];
|
||||
case TimeGranularity.YEAR:
|
||||
return [startTime, new Date(Date.UTC(year + 1, 0, 1))];
|
||||
default:
|
||||
return [startTime, new Date(Date.UTC(year, month, date + 1))];
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
* under the License.
|
||||
*/
|
||||
import { isEqualArray } from '@superset-ui/core';
|
||||
import { isEqual } from 'lodash-es';
|
||||
import { TableChartProps } from '../types';
|
||||
|
||||
const getDescriptions = (props: TableChartProps) => {
|
||||
@@ -47,23 +48,55 @@ export default function isEqualColumns(
|
||||
|
||||
const descA = getDescriptions(a);
|
||||
const descB = getDescriptions(b);
|
||||
return (
|
||||
a.datasource.columnFormats === b.datasource.columnFormats &&
|
||||
a.datasource.currencyFormats === b.datasource.currencyFormats &&
|
||||
a.datasource.verboseMap === b.datasource.verboseMap &&
|
||||
a.formData.tableTimestampFormat === b.formData.tableTimestampFormat &&
|
||||
a.formData.timeGrainSqla === b.formData.timeGrainSqla &&
|
||||
JSON.stringify(a.formData.columnConfig || null) ===
|
||||
JSON.stringify(b.formData.columnConfig || null) &&
|
||||
isEqualArray(a.formData.metrics, b.formData.metrics) &&
|
||||
isEqualArray(a.queriesData?.[0]?.colnames, b.queriesData?.[0]?.colnames) &&
|
||||
isEqualArray(a.queriesData?.[0]?.coltypes, b.queriesData?.[0]?.coltypes) &&
|
||||
JSON.stringify(a.formData.extraFilters || null) ===
|
||||
JSON.stringify(b.formData.extraFilters || null) &&
|
||||
JSON.stringify(a.formData.extraFormData || null) ===
|
||||
JSON.stringify(b.formData.extraFormData || null) &&
|
||||
JSON.stringify(a.rawFormData.column_config || null) ===
|
||||
JSON.stringify(b.rawFormData.column_config || null) &&
|
||||
JSON.stringify(descA) === JSON.stringify(descB)
|
||||
);
|
||||
|
||||
// Every field below is read with optional chaining because this comparator
|
||||
// also runs against partial/mock props in tests; production TableChartProps
|
||||
// always has these populated.
|
||||
const checks = {
|
||||
// These three are plain, serializable per-column config maps. Superset's
|
||||
// core datasource pipeline can rebuild them with a new object reference
|
||||
// on renders that don't actually change any formatting, so compare by
|
||||
// value here - otherwise an incidental new reference looks like a real
|
||||
// change and forces a full AG Grid column/row rebuild downstream.
|
||||
columnFormats: isEqual(
|
||||
a.datasource?.columnFormats,
|
||||
b.datasource?.columnFormats,
|
||||
),
|
||||
currencyFormats: isEqual(
|
||||
a.datasource?.currencyFormats,
|
||||
b.datasource?.currencyFormats,
|
||||
),
|
||||
verboseMap: isEqual(a.datasource?.verboseMap, b.datasource?.verboseMap),
|
||||
currencyCodeColumn:
|
||||
a.datasource?.currencyCodeColumn === b.datasource?.currencyCodeColumn,
|
||||
detectedCurrency:
|
||||
a.queriesData?.[0]?.detected_currency ===
|
||||
b.queriesData?.[0]?.detected_currency,
|
||||
tableTimestampFormat:
|
||||
a.formData?.tableTimestampFormat === b.formData?.tableTimestampFormat,
|
||||
timeGrainSqla: a.formData?.timeGrainSqla === b.formData?.timeGrainSqla,
|
||||
columnConfig:
|
||||
JSON.stringify(a.formData?.columnConfig || null) ===
|
||||
JSON.stringify(b.formData?.columnConfig || null),
|
||||
metrics: isEqualArray(a.formData?.metrics, b.formData?.metrics),
|
||||
colnames: isEqualArray(
|
||||
a.queriesData?.[0]?.colnames,
|
||||
b.queriesData?.[0]?.colnames,
|
||||
),
|
||||
coltypes: isEqualArray(
|
||||
a.queriesData?.[0]?.coltypes,
|
||||
b.queriesData?.[0]?.coltypes,
|
||||
),
|
||||
extraFilters:
|
||||
JSON.stringify(a.formData?.extraFilters || null) ===
|
||||
JSON.stringify(b.formData?.extraFilters || null),
|
||||
extraFormData:
|
||||
JSON.stringify(a.formData?.extraFormData || null) ===
|
||||
JSON.stringify(b.formData?.extraFormData || null),
|
||||
rawColumnConfig:
|
||||
JSON.stringify(a.rawFormData?.column_config || null) ===
|
||||
JSON.stringify(b.rawFormData?.column_config || null),
|
||||
descriptions: JSON.stringify(descA) === JSON.stringify(descB),
|
||||
};
|
||||
return Object.values(checks).every(Boolean);
|
||||
}
|
||||
|
||||
@@ -28,11 +28,15 @@ import { useCallback, useMemo } from 'react';
|
||||
import {
|
||||
DataRecordValue,
|
||||
DateWithFormatter,
|
||||
isEmptyDateInput,
|
||||
JsonObject,
|
||||
} from '@superset-ui/core';
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { useTheme } from '@apache-superset/core/theme';
|
||||
import { ColorFormatters } from '@superset-ui/chart-controls';
|
||||
import {
|
||||
ColorFormatters,
|
||||
ConditionalFormattingConfig,
|
||||
} from '@superset-ui/chart-controls';
|
||||
import { extent as d3Extent, max as d3Max } from 'd3-array';
|
||||
import {
|
||||
BasicColorFormatterType,
|
||||
@@ -71,11 +75,15 @@ type UseColDefsProps = {
|
||||
colorPositiveNegative: boolean;
|
||||
columnColorFormatters: ColorFormatters;
|
||||
allowRearrangeColumns?: boolean;
|
||||
allowRenderHtml?: boolean;
|
||||
basicColorFormatters?: { [Key: string]: BasicColorFormatterType }[];
|
||||
isUsingTimeComparison?: boolean;
|
||||
emitCrossFilters?: boolean;
|
||||
alignPositiveNegative: boolean;
|
||||
slice_id: number;
|
||||
conditionalFormatting?: ConditionalFormattingConfig[];
|
||||
comparisonColorEnabled?: boolean;
|
||||
comparisonColorScheme?: string;
|
||||
};
|
||||
|
||||
function getValueRange(
|
||||
@@ -131,7 +139,7 @@ const getFilterType = (col: InputColumn) => {
|
||||
|
||||
/**
|
||||
* Filter value getter for temporal columns.
|
||||
* Returns null for DateWithFormatter objects with null input,
|
||||
* Returns null for DateWithFormatter objects with null/empty input,
|
||||
* enabling AG Grid's blank filter to correctly identify null dates.
|
||||
*/
|
||||
const dateFilterValueGetter = (params: {
|
||||
@@ -139,8 +147,8 @@ const dateFilterValueGetter = (params: {
|
||||
colDef: { field?: string };
|
||||
}) => {
|
||||
const value = params.data?.[params.colDef.field as string];
|
||||
// Return null for DateWithFormatter with null input so AG Grid blank filter works
|
||||
if (value instanceof DateWithFormatter && value.input === null) {
|
||||
// Return null for DateWithFormatter with null/empty input so AG Grid blank filter works
|
||||
if (value instanceof DateWithFormatter && isEmptyDateInput(value.input)) {
|
||||
return null;
|
||||
}
|
||||
return value;
|
||||
@@ -236,13 +244,37 @@ export const useColDefs = ({
|
||||
colorPositiveNegative,
|
||||
columnColorFormatters,
|
||||
allowRearrangeColumns,
|
||||
allowRenderHtml,
|
||||
basicColorFormatters,
|
||||
isUsingTimeComparison,
|
||||
emitCrossFilters,
|
||||
alignPositiveNegative,
|
||||
slice_id,
|
||||
conditionalFormatting,
|
||||
comparisonColorEnabled,
|
||||
comparisonColorScheme,
|
||||
}: UseColDefsProps) => {
|
||||
const theme = useTheme();
|
||||
// transformProps.ts computes these fresh on every call (no memoization),
|
||||
// so a reference-based dependency here would recreate getCommonColProps -
|
||||
// and therefore colDefs - on every render regardless of whether the
|
||||
// formatting actually changed. Compare by content instead.
|
||||
//
|
||||
// columnColorFormatters/basicColorFormatters can't be stringified directly:
|
||||
// each entry's getColorFromValue closes over the rule's operator/
|
||||
// thresholds/gradient/color, none of which are mirrored as serializable
|
||||
// fields on the entry itself, so JSON.stringify drops them and two
|
||||
// differently-configured rules for the same column serialize identically.
|
||||
// Depend on the raw, fully-serializable formData that produced those
|
||||
// formatters instead.
|
||||
const stringifiedColumnColorFormatters = JSON.stringify(
|
||||
conditionalFormatting,
|
||||
);
|
||||
const stringifiedBasicColorFormatters = JSON.stringify([
|
||||
conditionalFormatting,
|
||||
comparisonColorEnabled,
|
||||
comparisonColorScheme,
|
||||
]);
|
||||
const getCommonColProps = useCallback(
|
||||
(
|
||||
col: InputColumn,
|
||||
@@ -387,7 +419,7 @@ export const useColDefs = ({
|
||||
cellRenderer: (p: CellRendererProps) =>
|
||||
isTextColumn ? TextCellRenderer(p) : NumericCellRenderer(p),
|
||||
cellRendererParams: {
|
||||
allowRenderHtml: true,
|
||||
allowRenderHtml,
|
||||
columns,
|
||||
hasBasicColorFormatters,
|
||||
col,
|
||||
@@ -401,6 +433,12 @@ export const useColDefs = ({
|
||||
isMetric,
|
||||
isPercentMetric,
|
||||
isNumeric,
|
||||
// colId (`field` above) has "Main " stripped for comparison
|
||||
// columns, but row data is still keyed by the unstripped
|
||||
// originalKey -- consumers reading row values by column (e.g. the
|
||||
// "Export Current View" snapshot) need this to look values up
|
||||
// correctly.
|
||||
dataKey: originalKey,
|
||||
},
|
||||
lockPinned: !allowRearrangeColumns,
|
||||
sortable: !serverPagination || !isPercentMetric,
|
||||
@@ -427,14 +465,15 @@ export const useColDefs = ({
|
||||
columns,
|
||||
data,
|
||||
defaultAlignPN,
|
||||
columnColorFormatters,
|
||||
basicColorFormatters,
|
||||
stringifiedColumnColorFormatters,
|
||||
stringifiedBasicColorFormatters,
|
||||
showCellBars,
|
||||
colorPositiveNegative,
|
||||
isUsingTimeComparison,
|
||||
isRawRecords,
|
||||
emitCrossFilters,
|
||||
allowRearrangeColumns,
|
||||
allowRenderHtml,
|
||||
serverPagination,
|
||||
alignPositiveNegative,
|
||||
theme.colorBgBase,
|
||||
|
||||
+140
-2
@@ -17,7 +17,14 @@
|
||||
* under the License.
|
||||
*/
|
||||
import '@testing-library/jest-dom';
|
||||
import { render, screen, waitFor } from '@superset-ui/core/spec';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
waitFor,
|
||||
fireEvent,
|
||||
within,
|
||||
userEvent,
|
||||
} from '@superset-ui/core/spec';
|
||||
import { QueryMode, TimeGranularity, SMART_DATE_ID } from '@superset-ui/core';
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import {
|
||||
@@ -259,6 +266,59 @@ test('AgGridTableChart renders Search by dropdown if includeSearch is true and t
|
||||
expect(screen.getByText(/Search by/i)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('AgGridTableChart resets currentPage when the search column changes', async () => {
|
||||
const props = transformProps({
|
||||
...testData.basic,
|
||||
rawFormData: {
|
||||
...testData.basic.rawFormData,
|
||||
server_pagination: true,
|
||||
include_search: true,
|
||||
},
|
||||
});
|
||||
props.serverPagination = true;
|
||||
props.includeSearch = true;
|
||||
props.rowCount = 50;
|
||||
props.serverPaginationData = {
|
||||
currentPage: 1,
|
||||
pageSize: 20,
|
||||
};
|
||||
|
||||
render(
|
||||
ProviderWrapper({
|
||||
children: (
|
||||
<AgGridTableChart
|
||||
{...props}
|
||||
setDataMask={mockSetDataMask}
|
||||
slice_id={1}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const searchByContainer = await waitFor(() => {
|
||||
const container = document.querySelector('.search-select');
|
||||
expect(container).toBeInTheDocument();
|
||||
return container as HTMLElement;
|
||||
});
|
||||
const searchByDropdown = within(searchByContainer).getByRole('combobox');
|
||||
await userEvent.click(searchByDropdown);
|
||||
const otherOption = await waitFor(() =>
|
||||
within(screen.getByRole('listbox')).getByText('abc.com'),
|
||||
);
|
||||
await userEvent.click(otherOption);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockSetDataMask).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ownState: expect.objectContaining({
|
||||
searchColumn: 'abc.com',
|
||||
currentPage: 0,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('AgGridTableChart does not render Search by dropdown if includeSearch is true but searchOptions is empty', async () => {
|
||||
const noStringColumnsData = {
|
||||
...testData.basic,
|
||||
@@ -873,9 +933,24 @@ test('AgGridTableChart emits column state with aggFunc through the debounced sav
|
||||
expect(document.querySelector('.ag-container')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// The very first onStateUpdated after mount just reflects the chartState
|
||||
// the grid was initialized with, so it must not trigger a save on its own
|
||||
// (persisting it unconditionally caused a mount -> save -> remount ->
|
||||
// mount loop). Let that initial debounced capture settle before
|
||||
// simulating a real user action - clicking a sortable header - so it
|
||||
// isn't coalesced into the same debounce window and mistaken for the
|
||||
// initial, ignorable capture.
|
||||
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||
|
||||
const sortableHeaderLabel = document.querySelector(
|
||||
'.ag-header-cell-sortable .ag-header-cell-label',
|
||||
);
|
||||
expect(sortableHeaderLabel).toBeTruthy();
|
||||
fireEvent.click(sortableHeaderLabel!);
|
||||
|
||||
// The save path is debounced (SLOW_DEBOUNCE = 500ms); wait for a capture.
|
||||
await waitFor(() => expect(onChartStateChange).toHaveBeenCalled(), {
|
||||
timeout: 3000,
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
const savedState =
|
||||
@@ -889,3 +964,66 @@ test('AgGridTableChart emits column state with aggFunc through the debounced sav
|
||||
// (SharedAggregation) module; the community modules always report null.
|
||||
expect(savedColumn).toMatchObject({ aggFunc: null });
|
||||
});
|
||||
|
||||
test('AgGridTableChart renders a temporal column with a blank row without crashing', async () => {
|
||||
// Regression test: a raw-mode temporal column backed by numeric epoch
|
||||
// values, where one row's raw value is '' rather than null/undefined/a
|
||||
// number, used to flip isNumeric() false for the whole column (see
|
||||
// transformProps.ts), degrading its formatter to plain `String`. That made
|
||||
// DateWithFormatter.toString() return String('') for the blank row, which
|
||||
// is falsy - and valueFormatter's old `|| value` fallback then rendered the
|
||||
// raw Date object directly, crashing React with "Objects are not valid as
|
||||
// a React child (found: [object Date])".
|
||||
const props = transformProps({
|
||||
...testData.basic,
|
||||
rawFormData: {
|
||||
...testData.basic.rawFormData,
|
||||
query_mode: QueryMode.Raw,
|
||||
table_timestamp_format: SMART_DATE_ID,
|
||||
server_pagination: false,
|
||||
},
|
||||
queriesData: [
|
||||
{
|
||||
...testData.basic.queriesData[0],
|
||||
colnames: ['__timestamp', 'name'],
|
||||
coltypes: [GenericDataType.Temporal, GenericDataType.String],
|
||||
data: [
|
||||
{ __timestamp: 1069113600000, name: 'foo' },
|
||||
{ __timestamp: 1057016400000, name: 'bar' },
|
||||
{ __timestamp: '', name: 'baz' },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
render(
|
||||
ProviderWrapper({
|
||||
children: (
|
||||
<AgGridTableChart
|
||||
{...props}
|
||||
setDataMask={mockSetDataMask}
|
||||
slice_id={1}
|
||||
/>
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(document.querySelector('.ag-container')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
const reactChildError = errorSpy.mock.calls
|
||||
.map(call => call.join(' '))
|
||||
.find(message =>
|
||||
message.includes('Objects are not valid as a React child'),
|
||||
);
|
||||
errorSpy.mockRestore();
|
||||
expect(reactChildError).toBeUndefined();
|
||||
|
||||
const cells = document.querySelectorAll('[col-id="__timestamp"]');
|
||||
const cellText = Array.from(cells).map(cell => cell.textContent);
|
||||
expect(cellText).toContain('N/A');
|
||||
expect(cellText).not.toContain('');
|
||||
});
|
||||
|
||||
@@ -834,6 +834,51 @@ describe('plugin-chart-ag-grid-table', () => {
|
||||
expect(totalsQuery.extras).toBeDefined();
|
||||
});
|
||||
|
||||
test('should exclude AG Grid HAVING filters from totals query', () => {
|
||||
const { queries } = buildQuery(
|
||||
{
|
||||
...basicFormData,
|
||||
server_pagination: true,
|
||||
show_totals: true,
|
||||
query_mode: QueryMode.Aggregate,
|
||||
},
|
||||
{
|
||||
ownState: {
|
||||
agGridHavingClause: 'count > 10',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const mainQuery = queries[0];
|
||||
const totalsQuery = queries[2]; // queries[1] is rowcount, queries[2] is totals
|
||||
|
||||
expect(mainQuery.extras?.having).toBe('count > 10');
|
||||
expect(totalsQuery.extras?.having).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should exclude download HAVING filters (sqlClauses) from totals query', () => {
|
||||
const { queries } = buildQuery(
|
||||
{
|
||||
...basicFormData,
|
||||
show_totals: true,
|
||||
query_mode: QueryMode.Aggregate,
|
||||
result_format: 'csv',
|
||||
},
|
||||
{
|
||||
ownState: {
|
||||
sqlClauses: { count: 'count > 10' },
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const mainQuery = queries[0];
|
||||
// Downloads never get a rowcount query, so totals is queries[1].
|
||||
const totalsQuery = queries[1];
|
||||
|
||||
expect(mainQuery.extras?.having).toBe('count > 10');
|
||||
expect(totalsQuery.extras?.having).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should not modify totals query when no AG Grid filters applied', () => {
|
||||
const { queries } = buildQuery(
|
||||
{
|
||||
@@ -853,6 +898,43 @@ describe('plugin-chart-ag-grid-table', () => {
|
||||
expect(totalsQuery.row_limit).toBe(0);
|
||||
});
|
||||
|
||||
test('all_records percent-metric denominator reflects AG Grid filters but totals do not', () => {
|
||||
// Regression test: the all_records denominator query is built from
|
||||
// the post-filter queryObject (so it matches the main query's result
|
||||
// set), while the totals query intentionally strips AG Grid
|
||||
// WHERE/HAVING so it summarizes the unfiltered chart-level data.
|
||||
const { queries } = buildQuery(
|
||||
{
|
||||
...basicFormData,
|
||||
metrics: ['count'],
|
||||
percent_metrics: ['count'],
|
||||
percent_metric_calculation: 'all_records',
|
||||
show_totals: true,
|
||||
server_pagination: true,
|
||||
query_mode: QueryMode.Aggregate,
|
||||
},
|
||||
{
|
||||
ownState: {
|
||||
agGridComplexWhere: 'age > 18',
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// [main, rowcount, all_records denominator, totals]
|
||||
const allRecordsQuery = queries[2];
|
||||
const totalsQuery = queries[3];
|
||||
|
||||
expect(allRecordsQuery.extras?.where).toBe('age > 18');
|
||||
expect(allRecordsQuery.columns).toEqual([]);
|
||||
expect(allRecordsQuery.metrics).toEqual(['count']);
|
||||
expect(allRecordsQuery.row_limit).toBe(0);
|
||||
expect(allRecordsQuery.row_offset).toBe(0);
|
||||
expect(allRecordsQuery.orderby).toEqual([]);
|
||||
expect(allRecordsQuery.is_timeseries).toBe(false);
|
||||
|
||||
expect(totalsQuery.extras?.where).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should reapply percent-metric contribution op to totals query', () => {
|
||||
// Regression test for #37627: when a percent metric is configured and
|
||||
// Show Summary (show_totals) is enabled, the totals query must rename
|
||||
|
||||
@@ -184,3 +184,45 @@ test('every Visual formatting control is a renderTrigger', () => {
|
||||
expect(control.config.renderTrigger).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
function findControl(
|
||||
panel: ControlPanelConfig,
|
||||
controlName: string,
|
||||
): CustomControlItem {
|
||||
const item = (panel.controlPanelSections || [])
|
||||
.flatMap(section => section?.controlSetRows || [])
|
||||
.flat()
|
||||
.find(c => isCustomControlItem(c) && c.name === controlName);
|
||||
|
||||
if (!item || !isCustomControlItem(item)) {
|
||||
throw new Error(`Control "${controlName}" not found`);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
test('allow_rearrange_columns defaults to false, matching v1, and hides while time_compare is set', () => {
|
||||
const control = findControl(config, 'allow_rearrange_columns');
|
||||
expect(control.config.type).toBe('CheckboxControl');
|
||||
expect(control.config.default).toBe(false);
|
||||
expect(control.config.renderTrigger).toBe(true);
|
||||
|
||||
const vis = control.config.visibility as VisibilityFn;
|
||||
expect(
|
||||
vis({
|
||||
controls: { time_compare: { value: [] } },
|
||||
} as unknown as ControlPanelsContainerProps),
|
||||
).toBe(true);
|
||||
expect(
|
||||
vis({
|
||||
controls: { time_compare: { value: ['1 year ago'] } },
|
||||
} as unknown as ControlPanelsContainerProps),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test('allow_render_html defaults to true, matching v1, and has no visibility gate', () => {
|
||||
const control = findControl(config, 'allow_render_html');
|
||||
expect(control.config.type).toBe('CheckboxControl');
|
||||
expect(control.config.default).toBe(true);
|
||||
expect(control.config.renderTrigger).toBe(true);
|
||||
expect(control.config.visibility).toBeUndefined();
|
||||
});
|
||||
|
||||
@@ -178,6 +178,38 @@ test('extraColorChoices not included when time_compare is empty array', () => {
|
||||
expect(result.extraColorChoices).toEqual([]);
|
||||
});
|
||||
|
||||
test('numericColumns resolves dataType by position, not a stale name lookup', () => {
|
||||
const controlConfig = findConditionalFormattingControl();
|
||||
expect(controlConfig).toBeTruthy();
|
||||
|
||||
const explore = createMockExplore(undefined);
|
||||
// Two columns share the name "metric" (e.g. a dimension and a metric
|
||||
// both aliased the same way); only the second occurrence is Numeric.
|
||||
const chart = {
|
||||
chartStatus: 'success' as const,
|
||||
queriesResponse: [
|
||||
{
|
||||
colnames: ['metric', 'metric'],
|
||||
coltypes: [GenericDataType.String, GenericDataType.Numeric],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = controlConfig!.mapStateToProps!(
|
||||
explore,
|
||||
createMockControlStateForConditionalFormatting(),
|
||||
chart,
|
||||
);
|
||||
|
||||
// Resolving dataType via `colnames.indexOf(colname)` would always find
|
||||
// the first "metric" (String) and misclassify this numeric column.
|
||||
expect(result.columnOptions).toEqual([
|
||||
expect.objectContaining({
|
||||
value: 'metric',
|
||||
dataType: GenericDataType.Numeric,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
test('consistency between extraColorChoices and columnOptions', () => {
|
||||
const controlConfig = findConditionalFormattingControl();
|
||||
expect(controlConfig).toBeTruthy();
|
||||
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* 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 { render, waitFor } from '@superset-ui/core/spec';
|
||||
import { DateWithFormatter, TimeGranularity } from '@superset-ui/core';
|
||||
import { ProviderWrapper } from '../../plugin-chart-table/test/testHelpers';
|
||||
import testData from '../../plugin-chart-table/test/testData';
|
||||
|
||||
// Only the context-menu handler is exercised below; the mock below fakes
|
||||
// its event argument rather than a real ag-grid CellContextMenuEvent, so
|
||||
// it's typed loosely (unknown) rather than pinned to that library type.
|
||||
interface CapturedGridProps {
|
||||
onCellContextMenu?: (event: Record<string, unknown>) => void;
|
||||
}
|
||||
|
||||
// Capture the props the grid is rendered with, so we can invoke the
|
||||
// onCellContextMenu handler directly without depending on AG Grid's DOM
|
||||
// rendering or the (unregistered) Enterprise context-menu module.
|
||||
const captured: { props?: CapturedGridProps } = {};
|
||||
|
||||
jest.mock('@superset-ui/core/components/ThemedAgGridReact', () => ({
|
||||
__esModule: true,
|
||||
ThemedAgGridReact: (props: CapturedGridProps) => {
|
||||
captured.props = props;
|
||||
return null;
|
||||
},
|
||||
AgGridReact: function AgGridReact() {
|
||||
return null;
|
||||
},
|
||||
AllCommunityModule: {},
|
||||
ClientSideRowModelModule: {},
|
||||
ModuleRegistry: { registerModules: () => undefined },
|
||||
setupAGGridModules: () => undefined,
|
||||
defaultModules: [],
|
||||
themeQuartz: {},
|
||||
colorSchemeDark: {},
|
||||
colorSchemeLight: {},
|
||||
}));
|
||||
|
||||
// Imported after the mock is declared (jest.mock is hoisted above imports).
|
||||
// eslint-disable-next-line import/first
|
||||
import AgGridTableChart from '../src/AgGridTableChart';
|
||||
// eslint-disable-next-line import/first
|
||||
import transformProps from '../src/transformProps';
|
||||
|
||||
function renderChart(
|
||||
onContextMenu: jest.Mock,
|
||||
propsOverrides: Record<string, unknown> = {},
|
||||
) {
|
||||
captured.props = undefined;
|
||||
const props = {
|
||||
...transformProps({
|
||||
...testData.basic,
|
||||
hooks: { ...testData.basic.hooks, onContextMenu },
|
||||
emitCrossFilters: true,
|
||||
}),
|
||||
...propsOverrides,
|
||||
};
|
||||
render(
|
||||
ProviderWrapper({
|
||||
children: (
|
||||
<AgGridTableChart {...props} setDataMask={jest.fn()} slice_id={1} />
|
||||
),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function makeColumn(colId: string, context: Record<string, unknown> = {}) {
|
||||
return {
|
||||
getColId: () => colId,
|
||||
getColDef: () => ({ context }),
|
||||
};
|
||||
}
|
||||
|
||||
test('wires an onCellContextMenu handler when onContextMenu is provided', async () => {
|
||||
renderChart(jest.fn());
|
||||
await waitFor(() => expect(captured.props).toBeDefined());
|
||||
|
||||
expect(typeof captured.props?.onCellContextMenu).toBe('function');
|
||||
});
|
||||
|
||||
test('right-clicking a dimension cell emits drillToDetail, crossFilter and drillBy', async () => {
|
||||
const onContextMenu = jest.fn();
|
||||
renderChart(onContextMenu);
|
||||
await waitFor(() => expect(captured.props?.onCellContextMenu).toBeDefined());
|
||||
|
||||
const preventDefault = jest.fn();
|
||||
const stopPropagation = jest.fn();
|
||||
const rowData = {
|
||||
__timestamp: null,
|
||||
name: 'Michael',
|
||||
sum__num: 2467063,
|
||||
'abc.com': 'foo',
|
||||
};
|
||||
|
||||
captured.props?.onCellContextMenu?.({
|
||||
column: makeColumn('name'),
|
||||
data: rowData,
|
||||
value: 'Michael',
|
||||
event: {
|
||||
preventDefault,
|
||||
stopPropagation,
|
||||
clientX: 10,
|
||||
clientY: 20,
|
||||
},
|
||||
});
|
||||
|
||||
expect(preventDefault).toHaveBeenCalled();
|
||||
expect(stopPropagation).toHaveBeenCalled();
|
||||
expect(onContextMenu).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [clientX, clientY, filters] = onContextMenu.mock.calls[0];
|
||||
expect(clientX).toBe(10);
|
||||
expect(clientY).toBe(20);
|
||||
|
||||
// Non-temporal, non-null column → exact-match filter.
|
||||
expect(filters.drillToDetail).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ col: 'name', op: '==', val: 'Michael' }),
|
||||
expect.objectContaining({ col: 'abc.com', op: '==', val: 'foo' }),
|
||||
]),
|
||||
);
|
||||
// Null column → IS NULL filter, not an exact match on null.
|
||||
expect(filters.drillToDetail).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ col: '__timestamp', op: 'IS NULL' }),
|
||||
]),
|
||||
);
|
||||
|
||||
expect(filters.crossFilter).toBeDefined();
|
||||
expect(filters.drillBy).toEqual({
|
||||
filters: [{ col: 'name', op: '==', val: 'Michael' }],
|
||||
groupbyFieldName: 'groupby',
|
||||
});
|
||||
});
|
||||
|
||||
test('right-clicking a null cell emits an IS NULL drillBy filter with a null val', async () => {
|
||||
const onContextMenu = jest.fn();
|
||||
renderChart(onContextMenu);
|
||||
await waitFor(() => expect(captured.props?.onCellContextMenu).toBeDefined());
|
||||
|
||||
captured.props?.onCellContextMenu?.({
|
||||
column: makeColumn('__timestamp'),
|
||||
data: { __timestamp: null, name: 'Michael', sum__num: 2467063 },
|
||||
value: null,
|
||||
event: {
|
||||
preventDefault: jest.fn(),
|
||||
stopPropagation: jest.fn(),
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const [, , filters] = onContextMenu.mock.calls[0];
|
||||
// op and val must agree: IS NULL must carry a null val, not the clicked
|
||||
// cell's (possibly wrapped) value.
|
||||
expect(filters.drillBy).toEqual({
|
||||
filters: [{ col: '__timestamp', op: 'IS NULL', val: null }],
|
||||
groupbyFieldName: 'groupby',
|
||||
});
|
||||
});
|
||||
|
||||
test('right-clicking a blank (empty-string) date cell emits IS NULL, not an equality filter on an invalid date', async () => {
|
||||
// A blank temporal value arrives wrapped as DateWithFormatter(input: ''),
|
||||
// not null/undefined -- the null checks below must treat that the same
|
||||
// as null rather than falling through to the temporal/equality branches,
|
||||
// which would build an invalid Date or serialize the filter value as null
|
||||
// under an '==' op instead of an 'IS NULL' op.
|
||||
const onContextMenu = jest.fn();
|
||||
const blankDate = new DateWithFormatter('');
|
||||
renderChart(onContextMenu);
|
||||
await waitFor(() => expect(captured.props?.onCellContextMenu).toBeDefined());
|
||||
|
||||
captured.props?.onCellContextMenu?.({
|
||||
column: makeColumn('__timestamp'),
|
||||
data: { __timestamp: blankDate, name: 'Michael', sum__num: 2467063 },
|
||||
value: blankDate,
|
||||
event: {
|
||||
preventDefault: jest.fn(),
|
||||
stopPropagation: jest.fn(),
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const [, , filters] = onContextMenu.mock.calls[0];
|
||||
expect(filters.drillToDetail).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ col: '__timestamp', op: 'IS NULL' }),
|
||||
]),
|
||||
);
|
||||
expect(filters.drillBy).toEqual({
|
||||
filters: [{ col: '__timestamp', op: 'IS NULL', val: null }],
|
||||
groupbyFieldName: 'groupby',
|
||||
});
|
||||
});
|
||||
|
||||
test('right-clicking a metric cell omits crossFilter and drillBy', async () => {
|
||||
const onContextMenu = jest.fn();
|
||||
renderChart(onContextMenu);
|
||||
await waitFor(() => expect(captured.props?.onCellContextMenu).toBeDefined());
|
||||
|
||||
captured.props?.onCellContextMenu?.({
|
||||
column: makeColumn('sum__num', { isMetric: true }),
|
||||
data: { name: 'Michael', sum__num: 2467063 },
|
||||
value: 2467063,
|
||||
event: {
|
||||
preventDefault: jest.fn(),
|
||||
stopPropagation: jest.fn(),
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const [, , filters] = onContextMenu.mock.calls[0];
|
||||
expect(filters.crossFilter).toBeUndefined();
|
||||
expect(filters.drillBy).toBeUndefined();
|
||||
// drillToDetail is still populated from the row's dimension columns.
|
||||
expect(filters.drillToDetail.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('right-clicking a temporal cell with a time grain emits a TEMPORAL_RANGE filter', async () => {
|
||||
const onContextMenu = jest.fn();
|
||||
renderChart(onContextMenu, { timeGrain: TimeGranularity.DAY });
|
||||
await waitFor(() => expect(captured.props?.onCellContextMenu).toBeDefined());
|
||||
|
||||
captured.props?.onCellContextMenu?.({
|
||||
column: makeColumn('name'),
|
||||
data: {
|
||||
__timestamp: '2020-01-01T12:34:56.000Z',
|
||||
name: 'Michael',
|
||||
sum__num: 2467063,
|
||||
},
|
||||
value: 'Michael',
|
||||
event: {
|
||||
preventDefault: jest.fn(),
|
||||
stopPropagation: jest.fn(),
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
},
|
||||
});
|
||||
|
||||
const [, , filters] = onContextMenu.mock.calls[0];
|
||||
const timestampFilter = filters.drillToDetail.find(
|
||||
(f: { col: string }) => f.col === '__timestamp',
|
||||
);
|
||||
expect(timestampFilter.op).toBe('TEMPORAL_RANGE');
|
||||
// DAY granularity's range starts at the row's own timestamp (not
|
||||
// truncated to midnight) and ends at the start of the next UTC day.
|
||||
expect(timestampFilter.val).toBe(
|
||||
'2020-01-01T12:34:56.000Z : 2020-01-02T00:00:00.000Z',
|
||||
);
|
||||
});
|
||||
|
||||
test('does not call onContextMenu in raw records mode', async () => {
|
||||
const onContextMenu = jest.fn();
|
||||
// isRawRecords is derived from query_mode inside transformProps; force it
|
||||
// here to isolate the handler's own guard from that derivation.
|
||||
renderChart(onContextMenu, { isRawRecords: true });
|
||||
await waitFor(() => expect(captured.props?.onCellContextMenu).toBeDefined());
|
||||
|
||||
captured.props?.onCellContextMenu?.({
|
||||
column: makeColumn('name'),
|
||||
data: { name: 'Michael' },
|
||||
value: 'Michael',
|
||||
event: {
|
||||
preventDefault: jest.fn(),
|
||||
stopPropagation: jest.fn(),
|
||||
clientX: 0,
|
||||
clientY: 0,
|
||||
},
|
||||
});
|
||||
|
||||
expect(onContextMenu).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* 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 { CurrencyFormatter, DateWithFormatter } from '@superset-ui/core';
|
||||
import { GenericDataType } from '@apache-superset/core/common';
|
||||
import { ValueFormatterParams } from '@superset-ui/core/components/ThemedAgGridReact';
|
||||
import {
|
||||
formatColumnValue,
|
||||
valueFormatter,
|
||||
valueGetter,
|
||||
} from '../src/utils/formatValue';
|
||||
import { DataColumnMeta, InputColumn } from '../src/types';
|
||||
|
||||
const baseCol: InputColumn = {
|
||||
key: 'order_date',
|
||||
label: 'order_date',
|
||||
dataType: GenericDataType.Temporal,
|
||||
isNumeric: false,
|
||||
isMetric: false,
|
||||
isPercentMetric: false,
|
||||
config: {},
|
||||
};
|
||||
|
||||
function makeParams(value: unknown, node?: { level?: number }) {
|
||||
return {
|
||||
value,
|
||||
node,
|
||||
data: {},
|
||||
} as unknown as ValueFormatterParams;
|
||||
}
|
||||
|
||||
test('valueFormatter never returns a raw Date/object when col.formatter is unset', () => {
|
||||
// Regression test: order_date (or any temporal column) is wrapped into a
|
||||
// DateWithFormatter instance before reaching this function. If col.formatter
|
||||
// is undefined - or returns a falsy result - the old `|| value` fallback
|
||||
// returned that raw object, which crashes React with "Objects are not valid
|
||||
// as a React child" once a cell renderer renders it directly.
|
||||
const date = new DateWithFormatter(1069113600000);
|
||||
const result = valueFormatter(makeParams(date), {
|
||||
...baseCol,
|
||||
formatter: undefined,
|
||||
});
|
||||
|
||||
expect(typeof result).toBe('string');
|
||||
expect(result).not.toBe(date);
|
||||
});
|
||||
|
||||
test('valueFormatter falls back to a string when the formatter returns a falsy result', () => {
|
||||
const date = new DateWithFormatter(1069113600000);
|
||||
const formatter = jest.fn().mockReturnValue('');
|
||||
const result = valueFormatter(makeParams(date), {
|
||||
...baseCol,
|
||||
formatter: formatter as unknown as InputColumn['formatter'],
|
||||
});
|
||||
|
||||
expect(typeof result).toBe('string');
|
||||
expect(result).not.toBe(date);
|
||||
});
|
||||
|
||||
test('valueFormatter falls back to a string when the CurrencyFormatter returns a falsy result', () => {
|
||||
const currencyFormatter = new CurrencyFormatter({
|
||||
currency: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
});
|
||||
jest.spyOn(currencyFormatter, 'format').mockReturnValue('');
|
||||
|
||||
const result = valueFormatter(makeParams(42), {
|
||||
...baseCol,
|
||||
dataType: GenericDataType.Numeric,
|
||||
formatter: currencyFormatter,
|
||||
});
|
||||
|
||||
expect(typeof result).toBe('string');
|
||||
expect(result).toBe('42');
|
||||
});
|
||||
|
||||
test('valueFormatter uses the formatter result when it is truthy', () => {
|
||||
const formatter = jest.fn().mockReturnValue('2003-11-18');
|
||||
const result = valueFormatter(
|
||||
makeParams(new DateWithFormatter(1069113600000)),
|
||||
{
|
||||
...baseCol,
|
||||
formatter: formatter as unknown as InputColumn['formatter'],
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toBe('2003-11-18');
|
||||
});
|
||||
|
||||
test('valueFormatter returns N/A for a DateWithFormatter wrapping a null input', () => {
|
||||
const nullDate = new DateWithFormatter(null);
|
||||
const result = valueFormatter(makeParams(nullDate), baseCol);
|
||||
|
||||
expect(result).toBe('N/A');
|
||||
});
|
||||
|
||||
test('valueFormatter returns empty string for the root aggregation row', () => {
|
||||
const result = valueFormatter(makeParams(undefined, { level: -1 }), baseCol);
|
||||
|
||||
expect(result).toBe('');
|
||||
});
|
||||
|
||||
test('valueGetter returns the main column value when colDef.isMain is set', () => {
|
||||
const params = {
|
||||
colDef: { isMain: true },
|
||||
column: { getColId: () => 'sum__num' },
|
||||
data: { 'Main sum__num': 42 },
|
||||
} as unknown as Parameters<typeof valueGetter>[0];
|
||||
|
||||
expect(valueGetter(params, baseCol)).toBe(42);
|
||||
});
|
||||
|
||||
test('valueGetter returns undefined for missing numeric column values', () => {
|
||||
const params = {
|
||||
column: { getColId: () => 'sum__num' },
|
||||
data: {},
|
||||
} as unknown as Parameters<typeof valueGetter>[0];
|
||||
|
||||
expect(valueGetter(params, { ...baseCol, isNumeric: true })).toBeUndefined();
|
||||
});
|
||||
|
||||
test('valueGetter returns empty string for missing non-numeric column values', () => {
|
||||
const params = {
|
||||
column: { getColId: () => 'name' },
|
||||
data: {},
|
||||
} as unknown as Parameters<typeof valueGetter>[0];
|
||||
|
||||
expect(valueGetter(params, baseCol)).toBe('');
|
||||
});
|
||||
|
||||
test('formatColumnValue applies the small-number formatter for values under 1 in AUTO currency mode', () => {
|
||||
const column: DataColumnMeta = {
|
||||
key: 'pct',
|
||||
label: 'pct',
|
||||
dataType: GenericDataType.Numeric,
|
||||
isNumeric: true,
|
||||
isMetric: true,
|
||||
isPercentMetric: false,
|
||||
formatter: new CurrencyFormatter({
|
||||
currency: { symbol: 'AUTO', symbolPosition: 'prefix' },
|
||||
}),
|
||||
config: {},
|
||||
};
|
||||
|
||||
const [isHtml, formatted] = formatColumnValue(column, 0.005);
|
||||
|
||||
expect(isHtml).toBe(false);
|
||||
expect(formatted).not.toBe('');
|
||||
});
|
||||
|
||||
test('formatColumnValue renders null as N/A', () => {
|
||||
const column: DataColumnMeta = {
|
||||
...baseCol,
|
||||
formatter: undefined,
|
||||
};
|
||||
|
||||
expect(formatColumnValue(column, null)).toEqual([false, 'N/A']);
|
||||
});
|
||||
@@ -54,11 +54,12 @@ test('transformProps busts its memoization caches when sub-field inputs change (
|
||||
const first = transformProps(testData.basic);
|
||||
|
||||
// `processColumns` is wrapped with a custom equality (`isEqualColumns`) that
|
||||
// compares specific chartProps sub-fields by identity — mutating only the
|
||||
// top-level props reference is NOT enough to bust it. Here we supply a fresh
|
||||
// `datasource.columnFormats` reference, which `isEqualColumns` compares with
|
||||
// `===`, forcing `processColumns` to recompute and return a new `columns`
|
||||
// array.
|
||||
// compares specific chartProps sub-fields by value — mutating only the
|
||||
// top-level props reference is NOT enough to bust it, and neither is
|
||||
// handing it a new-but-value-equal `columnFormats` reference (e.g. another
|
||||
// `{}`). Here we supply a `datasource.columnFormats` with genuinely
|
||||
// different content, forcing `processColumns` to recompute and return a
|
||||
// new `columns` array.
|
||||
//
|
||||
// `processDataRecords` uses memoize-one's default referential equality on
|
||||
// `(data, columns)`. We also hand it a fresh `queriesData[0].data` array, so
|
||||
@@ -67,7 +68,7 @@ test('transformProps busts its memoization caches when sub-field inputs change (
|
||||
...testData.basic,
|
||||
datasource: {
|
||||
...testData.basic.datasource,
|
||||
columnFormats: {},
|
||||
columnFormats: { name: '.2f' },
|
||||
},
|
||||
queriesData: [
|
||||
{
|
||||
|
||||
@@ -16,7 +16,16 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { convertFilterModel } from '../src/stateConversion';
|
||||
import {
|
||||
convertFilterModel,
|
||||
convertAgGridStateToOwnState,
|
||||
} from '../src/stateConversion';
|
||||
|
||||
const baseAgGridState = {
|
||||
columnState: [],
|
||||
sortModel: [{ colId: 'name', sort: 'asc' as const, sortIndex: 0 }],
|
||||
filterModel: {},
|
||||
};
|
||||
|
||||
describe('convertFilterModel', () => {
|
||||
test('emits a clause for a valid numeric comparison filter', () => {
|
||||
@@ -71,3 +80,38 @@ describe('convertFilterModel', () => {
|
||||
expect(result?.sqlClauses?.constructor).toBe('constructor = 5');
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertAgGridStateToOwnState', () => {
|
||||
test('suppresses client-mode state for the live query (serverPagination: false)', () => {
|
||||
const result = convertAgGridStateToOwnState({
|
||||
...baseAgGridState,
|
||||
serverPagination: false,
|
||||
});
|
||||
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
test('converts client-mode state anyway when forExport is set, so a download reproduces the displayed sort/filter', () => {
|
||||
const result = convertAgGridStateToOwnState(
|
||||
{ ...baseAgGridState, serverPagination: false },
|
||||
{ forExport: true },
|
||||
);
|
||||
|
||||
expect(result.sortBy).toEqual([{ id: 'name', key: 'name', desc: false }]);
|
||||
});
|
||||
|
||||
test('converts state when serverPagination is undefined, preserving legacy persisted table_state/permalinks saved before this field existed', () => {
|
||||
const result = convertAgGridStateToOwnState(baseAgGridState);
|
||||
|
||||
expect(result.sortBy).toEqual([{ id: 'name', key: 'name', desc: false }]);
|
||||
});
|
||||
|
||||
test('converts state for the live query when serverPagination is true', () => {
|
||||
const result = convertAgGridStateToOwnState({
|
||||
...baseAgGridState,
|
||||
serverPagination: true,
|
||||
});
|
||||
|
||||
expect(result.sortBy).toEqual([{ id: 'name', key: 'name', desc: false }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -266,6 +266,69 @@ test('uses description from column even when verboseMap renames the column', ()
|
||||
expect(columnMeta!.description).toBe('Original column description');
|
||||
});
|
||||
|
||||
test('does not crash when datasource omits metrics/columns (drill-to-detail datasource)', () => {
|
||||
const props = createMockChartProps({
|
||||
queriesData: [
|
||||
{
|
||||
data: [{ col_x: 10 }],
|
||||
colnames: ['col_x'],
|
||||
coltypes: [GenericDataType.Numeric],
|
||||
rowcount: 1,
|
||||
applied_filters: [],
|
||||
rejected_filters: [],
|
||||
},
|
||||
] as unknown as TableChartProps['queriesData'],
|
||||
datasource: {} as unknown as TableChartProps['datasource'],
|
||||
});
|
||||
|
||||
expect(() => transformProps(props)).not.toThrow();
|
||||
});
|
||||
|
||||
test('does not mistake the all_records percent-metric query for the totals query', () => {
|
||||
// buildQuery.ts appends both an "all records" percent-metric denominator
|
||||
// query and a totals query as independent extraQueries when percent
|
||||
// metrics with percent_metric_calculation "all_records" and show_totals
|
||||
// are both enabled — queriesData has 3 entries, not 2.
|
||||
const props = createMockChartProps({
|
||||
rawFormData: {
|
||||
viz_type: 'table',
|
||||
datasource: '1__table',
|
||||
query_mode: QueryMode.Aggregate,
|
||||
metrics: ['sum__num'],
|
||||
percent_metrics: ['sum__num'],
|
||||
percent_metric_calculation: 'all_records',
|
||||
show_totals: true,
|
||||
column_config: {},
|
||||
table_timestamp_format: '',
|
||||
},
|
||||
queriesData: [
|
||||
{
|
||||
data: [{ name: 'a', sum__num: 1 }],
|
||||
colnames: ['name', 'sum__num'],
|
||||
coltypes: [GenericDataType.String, GenericDataType.Numeric],
|
||||
rowcount: 1,
|
||||
applied_filters: [],
|
||||
rejected_filters: [],
|
||||
},
|
||||
// all_records extra query: raw percent-metric denominator, not totals.
|
||||
{
|
||||
data: [{ sum__num: 100 }],
|
||||
colnames: ['sum__num'],
|
||||
coltypes: [GenericDataType.Numeric],
|
||||
},
|
||||
// totals extra query: the real one.
|
||||
{
|
||||
data: [{ sum__num: 42 }],
|
||||
colnames: ['sum__num'],
|
||||
coltypes: [GenericDataType.Numeric],
|
||||
},
|
||||
] as unknown as TableChartProps['queriesData'],
|
||||
});
|
||||
|
||||
const result = transformProps(props);
|
||||
expect(result.totals).toEqual({ sum__num: 42 });
|
||||
});
|
||||
|
||||
test('excludes Green/Red color-scheme rules from columnColorFormatters', () => {
|
||||
// Green/Red rules are rendered via the increase/decrease path, so they must
|
||||
// not reach getColorFormatters, which would treat the scheme name as a hex
|
||||
@@ -316,6 +379,59 @@ test('excludes Green/Red color-scheme rules from columnColorFormatters', () => {
|
||||
expect(formattedColumns).not.toContain('metric_a');
|
||||
});
|
||||
|
||||
test('allowRearrangeColumns defaults to true when allow_rearrange_columns is unset', () => {
|
||||
// Pre-existing v2 charts saved before this control existed have no
|
||||
// allow_rearrange_columns key at all -- they must keep the always-on
|
||||
// behavior v2 originally shipped with, not v1's false default.
|
||||
const props = createMockChartProps();
|
||||
const result = transformProps(props);
|
||||
expect(result.allowRearrangeColumns).toBe(true);
|
||||
});
|
||||
|
||||
test('allowRearrangeColumns is false when allow_rearrange_columns is explicitly false', () => {
|
||||
const props = createMockChartProps({
|
||||
rawFormData: {
|
||||
viz_type: 'table',
|
||||
datasource: '1__table',
|
||||
query_mode: QueryMode.Aggregate,
|
||||
metrics: [],
|
||||
percent_metrics: [],
|
||||
column_config: {},
|
||||
table_timestamp_format: '',
|
||||
granularity_sqla: 'day',
|
||||
time_range: 'No filter',
|
||||
allow_rearrange_columns: false,
|
||||
} as unknown as TableChartProps['rawFormData'],
|
||||
});
|
||||
const result = transformProps(props);
|
||||
expect(result.allowRearrangeColumns).toBe(false);
|
||||
});
|
||||
|
||||
test('allowRenderHtml defaults to true when allow_render_html is unset', () => {
|
||||
const props = createMockChartProps();
|
||||
const result = transformProps(props);
|
||||
expect(result.allowRenderHtml).toBe(true);
|
||||
});
|
||||
|
||||
test('allowRenderHtml is false when allow_render_html is explicitly false', () => {
|
||||
const props = createMockChartProps({
|
||||
rawFormData: {
|
||||
viz_type: 'table',
|
||||
datasource: '1__table',
|
||||
query_mode: QueryMode.Aggregate,
|
||||
metrics: [],
|
||||
percent_metrics: [],
|
||||
column_config: {},
|
||||
table_timestamp_format: '',
|
||||
granularity_sqla: 'day',
|
||||
time_range: 'No filter',
|
||||
allow_render_html: false,
|
||||
} as unknown as TableChartProps['rawFormData'],
|
||||
});
|
||||
const result = transformProps(props);
|
||||
expect(result.allowRenderHtml).toBe(false);
|
||||
});
|
||||
|
||||
test('retains saved percentage rules with automatic bounds when server pagination is enabled', () => {
|
||||
const props = createMockChartProps({
|
||||
rawFormData: {
|
||||
|
||||
@@ -94,6 +94,39 @@ test('applies the increase/decrease background when the column has one', () => {
|
||||
expect(style.backgroundColor).toBe('#00ff00');
|
||||
});
|
||||
|
||||
test('applies a cross-column formatter to its target column, keyed off the source column value', () => {
|
||||
// Rule reads metric_a (source) and paints metric_b (target, via columnFormatting).
|
||||
const crossColumnFormatter = {
|
||||
column: 'metric_a',
|
||||
columnFormatting: 'metric_b',
|
||||
getColorFromValue: (v: number) => (v === 100 ? '#ff0000' : undefined),
|
||||
objectFormatting: undefined,
|
||||
toTextColor: false,
|
||||
};
|
||||
|
||||
const targetStyle = getCellStyle(
|
||||
buildParams({
|
||||
colDef: { field: 'metric_b' },
|
||||
value: 999,
|
||||
hasColumnColorFormatters: true,
|
||||
columnColorFormatters: [crossColumnFormatter],
|
||||
node: { rowPinned: undefined, data: { metric_a: 100, metric_b: 999 } },
|
||||
}),
|
||||
);
|
||||
expect(targetStyle.backgroundColor).toBe('#ff0000');
|
||||
|
||||
const sourceStyle = getCellStyle(
|
||||
buildParams({
|
||||
colDef: { field: 'metric_a' },
|
||||
value: 100,
|
||||
hasColumnColorFormatters: true,
|
||||
columnColorFormatters: [crossColumnFormatter],
|
||||
node: { rowPinned: undefined, data: { metric_a: 100, metric_b: 999 } },
|
||||
}),
|
||||
);
|
||||
expect(sourceStyle.backgroundColor).toBe('');
|
||||
});
|
||||
|
||||
test('does not apply basic formatting to the pinned summary row', () => {
|
||||
const style = getCellStyle(
|
||||
buildParams({
|
||||
@@ -106,3 +139,37 @@ test('does not apply basic formatting to the pinned summary row', () => {
|
||||
);
|
||||
expect(style.backgroundColor).toBe('');
|
||||
});
|
||||
|
||||
test('applies a legacy v1 toAllRow formatter to every cell in the row', () => {
|
||||
// Migrated v1 charts carry `toAllRow: true` unchanged rather than being
|
||||
// rewritten to `columnFormatting: ENTIRE_ROW`; both must color every cell.
|
||||
const legacyEntireRowFormatter = {
|
||||
column: 'metric_a',
|
||||
toAllRow: true,
|
||||
getColorFromValue: (v: number) => (v === 100 ? '#ff0000' : undefined),
|
||||
objectFormatting: undefined,
|
||||
toTextColor: false,
|
||||
};
|
||||
|
||||
const otherColumnStyle = getCellStyle(
|
||||
buildParams({
|
||||
colDef: { field: 'metric_b' },
|
||||
value: 999,
|
||||
hasColumnColorFormatters: true,
|
||||
columnColorFormatters: [legacyEntireRowFormatter],
|
||||
node: { rowPinned: undefined, data: { metric_a: 100, metric_b: 999 } },
|
||||
}),
|
||||
);
|
||||
expect(otherColumnStyle.backgroundColor).toBe('#ff0000');
|
||||
|
||||
const sourceColumnStyle = getCellStyle(
|
||||
buildParams({
|
||||
colDef: { field: 'metric_a' },
|
||||
value: 100,
|
||||
hasColumnColorFormatters: true,
|
||||
columnColorFormatters: [legacyEntireRowFormatter],
|
||||
node: { rowPinned: undefined, data: { metric_a: 100, metric_b: 999 } },
|
||||
}),
|
||||
);
|
||||
expect(sourceColumnStyle.backgroundColor).toBe('#ff0000');
|
||||
});
|
||||
|
||||
@@ -811,6 +811,79 @@ test('cellStyle defaults non-numeric columns to left alignment', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('cellStyle reflects an edited conditional-formatting rule (color/threshold change, same column)', () => {
|
||||
// columnColorFormatters entries only carry a computed getColorFromValue
|
||||
// closure -- the rule's operator/threshold/color aren't mirrored onto the
|
||||
// entry itself. Memoizing on JSON.stringify(columnColorFormatters) alone
|
||||
// would see the same "shape" on both renders and keep closing over the
|
||||
// first render's (red) formatter. The memo must instead depend on the raw
|
||||
// conditionalFormatting config, which does capture the color/threshold.
|
||||
const numericCol = makeColumn({
|
||||
key: 'count',
|
||||
label: 'Count',
|
||||
dataType: GenericDataType.Numeric,
|
||||
isNumeric: true,
|
||||
isMetric: true,
|
||||
});
|
||||
// getCommonColProps also depends on `columns`/`data` by reference (as it
|
||||
// must, since transformProps.ts doesn't memoize them either), so those
|
||||
// need to stay referentially stable across rerenders here -- otherwise a
|
||||
// new array on every render would mask a broken formatter dependency by
|
||||
// invalidating the memo for an unrelated reason.
|
||||
const stableColumns = [numericCol];
|
||||
const stableData = [{ count: 42 }];
|
||||
|
||||
const cellStyleParams = {
|
||||
value: 42,
|
||||
colDef: { field: 'count' },
|
||||
rowIndex: 0,
|
||||
node: {},
|
||||
} as never;
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
(props: { color: string; targetValue: number }) =>
|
||||
useColDefs({
|
||||
...defaultProps,
|
||||
columns: stableColumns,
|
||||
data: stableData,
|
||||
columnColorFormatters: [
|
||||
{
|
||||
column: 'count',
|
||||
objectFormatting: ObjectFormattingEnum.BACKGROUND_COLOR,
|
||||
getColorFromValue: (value: unknown) =>
|
||||
value === 42 ? props.color : undefined,
|
||||
},
|
||||
],
|
||||
conditionalFormatting: [
|
||||
{
|
||||
column: 'count',
|
||||
operator: '>',
|
||||
targetValue: props.targetValue,
|
||||
colorScheme: props.color,
|
||||
} as never,
|
||||
],
|
||||
}),
|
||||
{
|
||||
wrapper: defaultThemeWrapper,
|
||||
initialProps: { color: '#ff0000', targetValue: 0 },
|
||||
},
|
||||
);
|
||||
|
||||
const firstCellStyle = getCellStyleFunction(result.current[0].cellStyle);
|
||||
expect(firstCellStyle(cellStyleParams)).toMatchObject({
|
||||
backgroundColor: '#ff0000',
|
||||
});
|
||||
|
||||
// Same column, edited threshold/color -- must produce a fresh colDef
|
||||
// whose cellStyle uses the new formatter, not the stale red one.
|
||||
rerender({ color: '#0000ff', targetValue: 10 });
|
||||
|
||||
const secondCellStyle = getCellStyleFunction(result.current[0].cellStyle);
|
||||
expect(secondCellStyle(cellStyleParams)).toMatchObject({
|
||||
backgroundColor: '#0000ff',
|
||||
});
|
||||
});
|
||||
|
||||
test('cellStyle respects explicit horizontal alignment overrides', () => {
|
||||
const numericCol = makeColumn({
|
||||
key: 'count',
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
AxisType,
|
||||
buildCustomFormatters,
|
||||
CategoricalColorNamespace,
|
||||
ComparisonType,
|
||||
CurrencyFormatter,
|
||||
DataRecordValue,
|
||||
DTTM_ALIAS,
|
||||
@@ -419,6 +420,11 @@ export default function transformProps(
|
||||
|
||||
const refs: Refs = {};
|
||||
const groupBy = ensureIsArray(groupby);
|
||||
// Series whose `label_map` entry led with a time offset, recorded before the shift
|
||||
// below drops it. That leading column is the only structural marker distinguishing a
|
||||
// derived comparison row from a base row whose dimension value happens to read like
|
||||
// the offset, and it is gone from `labelMap` by the time the formatters run.
|
||||
const derivedComparisonSeries = new Set<string>();
|
||||
const labelMap: { [key: string]: string[] } = Object.entries(
|
||||
label_map,
|
||||
).reduce((acc, entry) => {
|
||||
@@ -427,6 +433,7 @@ export default function transformProps(
|
||||
Array.isArray(timeCompare) &&
|
||||
timeCompare.includes(entry[1][0])
|
||||
) {
|
||||
derivedComparisonSeries.add(entry[0]);
|
||||
entry[1].shift();
|
||||
}
|
||||
return { ...acc, [entry[0]]: entry[1] };
|
||||
@@ -681,6 +688,51 @@ export default function transformProps(
|
||||
const array = ensureIsArray(chartProps.rawFormData?.time_compare);
|
||||
const inverted = invert(verboseMap);
|
||||
|
||||
// A Percentage or Ratio time comparison replaces the derived series' values with a
|
||||
// dimensionless number, so that row is no longer in the source metric's units and
|
||||
// must not inherit its currency/D3 format.
|
||||
//
|
||||
// `label_map` carries the structured identity behind a rendered series name, and
|
||||
// `renameOperator` puts the offset at the front of a derived row's entry:
|
||||
//
|
||||
// derived '1 week ago, East' -> ['1 week ago', 'East']
|
||||
// derived 'count, 1 year ago' -> ['1 year ago', 'count']
|
||||
// base 'sum__num, East' -> ['sum__num', 'East']
|
||||
//
|
||||
// so the leading column says which it is. Matching the rendered name instead would
|
||||
// misread a base series whose dimension value happens to equal the offset — a region
|
||||
// literally named "1 week ago" gives 'sum__num, 1 week ago', which reads as derived.
|
||||
const isDerivedComparisonSeries = (seriesKey: string) => {
|
||||
// Recorded above, before the offset was shifted off the `label_map` entry.
|
||||
if (derivedComparisonSeries.has(seriesKey)) {
|
||||
return true;
|
||||
}
|
||||
const columns = labelMap?.[seriesKey];
|
||||
// The shift only runs when `timeCompare` is populated; otherwise the entry still
|
||||
// leads with the offset and can be read directly.
|
||||
return columns?.length
|
||||
? array.includes(columns[0])
|
||||
: array.includes(seriesKey);
|
||||
};
|
||||
|
||||
// Percentage yields `(s - c) / c`, which reads as a percentage. Ratio yields `s / c`,
|
||||
// a plain multiplier, so it takes a unitless number format rather than a percent one.
|
||||
const ratioFormatter = getNumberFormatter(NumberFormats.SMART_NUMBER);
|
||||
|
||||
const getComparisonFormatter = (seriesKey: string) => {
|
||||
if (!isDerivedComparisonSeries(seriesKey)) {
|
||||
return undefined;
|
||||
}
|
||||
switch (chartProps.rawFormData?.comparison_type) {
|
||||
case ComparisonType.Percentage:
|
||||
return percentFormatter;
|
||||
case ComparisonType.Ratio:
|
||||
return ratioFormatter;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
// With the "full range" time-shift option, offset series are outer-joined onto
|
||||
// the main series, which inserts null rows into the main series wherever the
|
||||
// comparison period has data the current period lacks. Connect nulls so the
|
||||
@@ -1522,6 +1574,31 @@ export default function transformProps(
|
||||
value.forecastTrend || value.forecastLower || value.forecastUpper,
|
||||
);
|
||||
|
||||
// Resolve the value formatter per series so each metric keeps its own
|
||||
// D3/currency format, matching how the series labels are formatted.
|
||||
// Without the series key, `getCustomFormatter` returns undefined for
|
||||
// multi-metric charts and every row falls back to `defaultFormatter`,
|
||||
// rendering the y-axis/currency format for all metrics.
|
||||
//
|
||||
// The tooltip key is the rendered series name, so resolve it through
|
||||
// `labelMap`, whose values lead with the raw metric label. Series
|
||||
// renamed by a verbose_name are absent from that map, so fall back to
|
||||
// the verbose-name inversion, as MixedTimeseries does. A Percentage or
|
||||
// Ratio comparison row is dimensionless rather than a value in the
|
||||
// metric's units, so it takes its own formatter instead of the metric's.
|
||||
const getSeriesFormatter = (seriesKey: string) =>
|
||||
forcePercentFormatter
|
||||
? percentFormatter
|
||||
: (getComparisonFormatter(seriesKey) ??
|
||||
getCustomFormatter(
|
||||
customFormatters,
|
||||
metrics,
|
||||
labelMap?.[seriesKey]?.[0] ?? inverted[seriesKey],
|
||||
) ??
|
||||
defaultFormatter);
|
||||
|
||||
// The total row aggregates every series, so it keeps the chart-level
|
||||
// formatter rather than any single metric's format.
|
||||
const formatter = forcePercentFormatter
|
||||
? percentFormatter
|
||||
: (getCustomFormatter(customFormatters, metrics) ?? defaultFormatter);
|
||||
@@ -1552,7 +1629,7 @@ export default function transformProps(
|
||||
const row = formatForecastTooltipSeries({
|
||||
...value,
|
||||
seriesName: key,
|
||||
formatter,
|
||||
formatter: getSeriesFormatter(key),
|
||||
marker,
|
||||
truncation: tooltipTruncation,
|
||||
});
|
||||
|
||||
+579
@@ -3576,3 +3576,582 @@ test('boundary label alignment is dropped when the orientation moves the time ax
|
||||
expect(horizontal.axisLabel.showMinLabel).toBe(true);
|
||||
expect(horizontal.axisLabel.showMaxLabel).toBe(true);
|
||||
});
|
||||
|
||||
test('tooltip formats each series with its own metric format instead of the default formatter', () => {
|
||||
// Two saved metrics with different formats: `pct_change` carries a percentage
|
||||
// D3 format, `count` carries a currency format. The series labels already
|
||||
// honor each metric's format; the tooltip must do the same.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metrics: ['count', 'pct_change'],
|
||||
richTooltip: true,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[{ count: 1000, pct_change: 0.1234, __timestamp: BASE_TIMESTAMP }],
|
||||
{ label_map: { count: ['count'], pct_change: ['pct_change'] } },
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: { pct_change: '.2%' },
|
||||
currencyFormats: { count: { symbol: 'USD', symbolPosition: 'prefix' } },
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{ seriesId: 'count', seriesName: 'count', value: [BASE_TIMESTAMP, 1000] },
|
||||
{
|
||||
seriesId: 'pct_change',
|
||||
seriesName: 'pct_change',
|
||||
value: [BASE_TIMESTAMP, 0.1234],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('12.34%');
|
||||
expect(result).toContain('$');
|
||||
});
|
||||
|
||||
test('tooltip resolves per-metric formats for series renamed by verbose_name', () => {
|
||||
// With a verbose_name configured, the rendered series name (and so the
|
||||
// tooltip key) is the verbose label, while `label_map` stays keyed by the
|
||||
// raw metric label. The formatter lookup has to bridge that gap.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metrics: ['count', 'pct_change'],
|
||||
richTooltip: true,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[{ count: 1000, pct_change: 0.1234, __timestamp: BASE_TIMESTAMP }],
|
||||
{ label_map: { count: ['count'], pct_change: ['pct_change'] } },
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: { count: 'Total Count', pct_change: 'Percent Change' },
|
||||
columnFormats: { pct_change: '.2%' },
|
||||
currencyFormats: { count: { symbol: 'USD', symbolPosition: 'prefix' } },
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'Total Count',
|
||||
seriesName: 'Total Count',
|
||||
value: [BASE_TIMESTAMP, 1000],
|
||||
},
|
||||
{
|
||||
seriesId: 'Percent Change',
|
||||
seriesName: 'Percent Change',
|
||||
value: [BASE_TIMESTAMP, 0.1234],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('12.34%');
|
||||
expect(result).toContain('$');
|
||||
});
|
||||
|
||||
test('tooltip keeps per-metric formats on time-comparison (time-shifted) series', () => {
|
||||
// A time-shifted series renders under a name carrying the offset, and its
|
||||
// `label_map` entry leads with that offset rather than the metric. The
|
||||
// formatter lookup has to land on the underlying metric so the shifted row is
|
||||
// formatted like the series it is compared against.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metrics: ['count', 'pct_change'],
|
||||
richTooltip: true,
|
||||
timeCompare: ['1 year ago'],
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[
|
||||
{
|
||||
count: 1000,
|
||||
pct_change: 0.1234,
|
||||
'count, 1 year ago': 900,
|
||||
__timestamp: BASE_TIMESTAMP,
|
||||
},
|
||||
],
|
||||
{
|
||||
label_map: {
|
||||
count: ['count'],
|
||||
pct_change: ['pct_change'],
|
||||
'count, 1 year ago': ['1 year ago', 'count'],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: { pct_change: '.2%' },
|
||||
currencyFormats: { count: { symbol: 'USD', symbolPosition: 'prefix' } },
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{ seriesId: 'count', seriesName: 'count', value: [BASE_TIMESTAMP, 1000] },
|
||||
{
|
||||
seriesId: 'count, 1 year ago',
|
||||
seriesName: 'count, 1 year ago',
|
||||
value: [BASE_TIMESTAMP, 900],
|
||||
},
|
||||
]);
|
||||
|
||||
// The base series and its time-shifted counterpart keep the currency format.
|
||||
expect(result).toContain('$ 1k');
|
||||
expect(result).toContain('$ 900');
|
||||
});
|
||||
|
||||
test('tooltip does not apply a metric currency format to a Percentage time comparison', () => {
|
||||
// Reported on #33757: a Time Comparison set to Percentage change on a
|
||||
// currency metric kept rendering the derived row in dollars. That row holds a
|
||||
// ratio rather than a value in the metric's units, so it must not inherit the
|
||||
// metric's saved CurrencyFormatter.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
richTooltip: true,
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Percentage,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[{ sum__num: 100, '1 week ago': 0.25, __timestamp: BASE_TIMESTAMP }],
|
||||
{ label_map: { sum__num: ['sum__num'], '1 week ago': ['1 week ago'] } },
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num',
|
||||
seriesName: 'sum__num',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago',
|
||||
seriesName: '1 week ago',
|
||||
value: [BASE_TIMESTAMP, 0.25],
|
||||
},
|
||||
]);
|
||||
|
||||
// The source metric keeps its currency; the percentage-change row does not.
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('25.00%');
|
||||
expect(result).not.toContain('$ 0.25');
|
||||
});
|
||||
|
||||
test('tooltip does not apply a metric currency format to a grouped Percentage time comparison', () => {
|
||||
// A groupby appends the dimension values to the derived series name
|
||||
// ("1 week ago, East"), so matching the dimensionless names alone left the
|
||||
// grouped rows resolving back to the source metric's CurrencyFormatter.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
groupby: ['region'],
|
||||
richTooltip: true,
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Percentage,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[
|
||||
{
|
||||
'sum__num, East': 100,
|
||||
'1 week ago, East': 0.25,
|
||||
__timestamp: BASE_TIMESTAMP,
|
||||
},
|
||||
],
|
||||
{
|
||||
label_map: {
|
||||
'sum__num, East': ['sum__num', 'East'],
|
||||
'1 week ago, East': ['1 week ago', 'East'],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num, East',
|
||||
seriesName: 'sum__num, East',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago, East',
|
||||
seriesName: '1 week ago, East',
|
||||
value: [BASE_TIMESTAMP, 0.25],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('25.00%');
|
||||
expect(result).not.toContain('$ 0.25');
|
||||
});
|
||||
|
||||
test('tooltip does not apply a metric currency format to a Ratio time comparison', () => {
|
||||
// A Ratio comparison is `source / compare`, a plain multiplier, so the derived row is
|
||||
// no more in the metric's currency than a Percentage one is — but it is not a
|
||||
// percentage either, so it takes a unitless number format rather than the percent one.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
richTooltip: true,
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Ratio,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[{ sum__num: 100, '1 week ago': 1.25, __timestamp: BASE_TIMESTAMP }],
|
||||
{ label_map: { sum__num: ['sum__num'], '1 week ago': ['1 week ago'] } },
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num',
|
||||
seriesName: 'sum__num',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago',
|
||||
seriesName: '1 week ago',
|
||||
value: [BASE_TIMESTAMP, 1.25],
|
||||
},
|
||||
]);
|
||||
|
||||
// The source metric keeps its currency; the ratio row renders as a plain number.
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('1.25');
|
||||
expect(result).not.toContain('$ 1.25');
|
||||
});
|
||||
|
||||
test('tooltip does not apply a metric currency format to a grouped Ratio time comparison', () => {
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
groupby: ['region'],
|
||||
richTooltip: true,
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Ratio,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[
|
||||
{
|
||||
'sum__num, East': 100,
|
||||
'1 week ago, East': 1.25,
|
||||
__timestamp: BASE_TIMESTAMP,
|
||||
},
|
||||
],
|
||||
{
|
||||
label_map: {
|
||||
'sum__num, East': ['sum__num', 'East'],
|
||||
'1 week ago, East': ['1 week ago', 'East'],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num, East',
|
||||
seriesName: 'sum__num, East',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago, East',
|
||||
seriesName: '1 week ago, East',
|
||||
value: [BASE_TIMESTAMP, 1.25],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('1.25');
|
||||
expect(result).not.toContain('$ 1.25');
|
||||
});
|
||||
|
||||
test('tooltip formats derived rows when timeCompare normalization strips the offset', () => {
|
||||
// With `timeCompare` populated, `labelMap` has its leading offset shifted off before
|
||||
// the formatters run, so the derived identity has to be captured during that pass —
|
||||
// reading `labelMap[key][0]` afterwards sees the dimension value instead.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
groupby: ['region'],
|
||||
richTooltip: true,
|
||||
timeCompare: ['1 week ago'],
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Percentage,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[
|
||||
{
|
||||
'sum__num, East': 100,
|
||||
'1 week ago, East': 0.25,
|
||||
__timestamp: BASE_TIMESTAMP,
|
||||
},
|
||||
],
|
||||
{
|
||||
label_map: {
|
||||
'sum__num, East': ['sum__num', 'East'],
|
||||
'1 week ago, East': ['1 week ago', 'East'],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num, East',
|
||||
seriesName: 'sum__num, East',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago, East',
|
||||
seriesName: '1 week ago, East',
|
||||
value: [BASE_TIMESTAMP, 0.25],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('25.00%');
|
||||
expect(result).not.toContain('$ 0.25');
|
||||
});
|
||||
|
||||
test('tooltip gives a Ratio row a unitless format when timeCompare is set', () => {
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
groupby: ['region'],
|
||||
richTooltip: true,
|
||||
timeCompare: ['1 week ago'],
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Ratio,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[
|
||||
{
|
||||
'sum__num, East': 100,
|
||||
'1 week ago, East': 1.25,
|
||||
__timestamp: BASE_TIMESTAMP,
|
||||
},
|
||||
],
|
||||
{
|
||||
label_map: {
|
||||
'sum__num, East': ['sum__num', 'East'],
|
||||
'1 week ago, East': ['1 week ago', 'East'],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num, East',
|
||||
seriesName: 'sum__num, East',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago, East',
|
||||
seriesName: '1 week ago, East',
|
||||
value: [BASE_TIMESTAMP, 1.25],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('1.25');
|
||||
expect(result).not.toContain('$ 1.25');
|
||||
});
|
||||
|
||||
test('tooltip keeps the metric format when a dimension value equals the offset', () => {
|
||||
// A groupby value can legitimately read like the configured offset, giving a *base*
|
||||
// series called `sum__num, 1 week ago`. Matching the rendered name would classify it
|
||||
// as derived and strip its currency; `label_map` leads with the metric, not the
|
||||
// offset, so it stays a base row.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
groupby: ['region'],
|
||||
richTooltip: true,
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Percentage,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[
|
||||
{
|
||||
'sum__num, 1 week ago': 100,
|
||||
'1 week ago, 1 week ago': 0.25,
|
||||
__timestamp: BASE_TIMESTAMP,
|
||||
},
|
||||
],
|
||||
{
|
||||
label_map: {
|
||||
// The region is named "1 week ago"; the metric still leads the base entry.
|
||||
'sum__num, 1 week ago': ['sum__num', '1 week ago'],
|
||||
// Its derived counterpart leads with the offset.
|
||||
'1 week ago, 1 week ago': ['1 week ago', '1 week ago'],
|
||||
},
|
||||
},
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num, 1 week ago',
|
||||
seriesName: 'sum__num, 1 week ago',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago, 1 week ago',
|
||||
seriesName: '1 week ago, 1 week ago',
|
||||
value: [BASE_TIMESTAMP, 0.25],
|
||||
},
|
||||
]);
|
||||
|
||||
// The base row keeps its currency even though its name ends in the offset, and the
|
||||
// genuinely derived row is still formatted as a percentage.
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('25.00%');
|
||||
});
|
||||
|
||||
test('tooltip keeps the metric format on a Difference time comparison', () => {
|
||||
// Difference is `source - compare`, which stays in the metric's units, so unlike
|
||||
// Percentage and Ratio it must keep the currency format.
|
||||
const chartProps = createTestChartProps({
|
||||
formData: {
|
||||
metric: 'sum__num',
|
||||
metrics: ['sum__num'],
|
||||
richTooltip: true,
|
||||
time_compare: ['1 week ago'],
|
||||
comparison_type: ComparisonType.Difference,
|
||||
},
|
||||
queriesData: [
|
||||
createTestQueryData(
|
||||
[{ sum__num: 100, '1 week ago': 25, __timestamp: BASE_TIMESTAMP }],
|
||||
{ label_map: { sum__num: ['sum__num'], '1 week ago': ['1 week ago'] } },
|
||||
),
|
||||
],
|
||||
datasource: {
|
||||
verboseMap: {},
|
||||
columnFormats: {},
|
||||
currencyFormats: {
|
||||
sum__num: { symbol: 'USD', symbolPosition: 'prefix' },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const { echartOptions } = transformProps(chartProps);
|
||||
const { tooltip } = echartOptions as unknown as TooltipFormatterOptions;
|
||||
|
||||
const result = tooltip.formatter([
|
||||
{
|
||||
seriesId: 'sum__num',
|
||||
seriesName: 'sum__num',
|
||||
value: [BASE_TIMESTAMP, 100],
|
||||
},
|
||||
{
|
||||
seriesId: '1 week ago',
|
||||
seriesName: '1 week ago',
|
||||
value: [BASE_TIMESTAMP, 25],
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toContain('$ 100');
|
||||
expect(result).toContain('$ 25');
|
||||
});
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
/** @jsxImportSource @emotion/react */
|
||||
import {
|
||||
Children,
|
||||
cloneElement,
|
||||
@@ -286,9 +288,28 @@ function StickyWrap({
|
||||
</colgroup>
|
||||
);
|
||||
|
||||
const headerContainerWidth = hasVerticalScroll
|
||||
? maxWidth - scrollBarSize
|
||||
: maxWidth;
|
||||
// Below, `width: maxWidth` is applied unconditionally (never reduced by
|
||||
// subtracting a separately-measured scrollbar width, unlike this file's
|
||||
// previous `maxWidth - scrollBarSize`). That's the load-bearing part of
|
||||
// this fix: the shared colgroup (computed from the sizer below, whose
|
||||
// own clientWidth can only ever be <= maxWidth) can never need more
|
||||
// width than that, so a header/footer wrapper that's never narrowed
|
||||
// below maxWidth can never clip it, regardless of whether any
|
||||
// JS-measured scrollbar size agrees with what the sizer/body actually
|
||||
// reserve in a given browser.
|
||||
//
|
||||
// `scrollbarGutter`/`scrollBarStyles` below are a separate, secondary
|
||||
// measure -- matching an actual clip boundary is not what they're for
|
||||
// (an `overflow: hidden` box's clip boundary sits at its real
|
||||
// border-box edge regardless of `scrollbar-gutter`, which only affects
|
||||
// what `clientWidth` reports). They keep header/footer's reported
|
||||
// `clientWidth` consistent with body's so that, when both a vertical
|
||||
// and a horizontal scrollbar are present, the horizontal `scrollLeft`
|
||||
// synced from body (see `onScroll` below) reveals the same slice of the
|
||||
// row in header/footer as is actually visible in body.
|
||||
const headerFooterGutter: CSSProperties = {
|
||||
scrollbarGutter: hasVerticalScroll ? 'stable' : undefined,
|
||||
};
|
||||
|
||||
headerTable = (
|
||||
<div
|
||||
@@ -296,9 +317,11 @@ function StickyWrap({
|
||||
ref={scrollHeaderRef}
|
||||
style={{
|
||||
overflow: 'hidden',
|
||||
width: headerContainerWidth,
|
||||
width: maxWidth,
|
||||
boxSizing: 'border-box',
|
||||
...headerFooterGutter,
|
||||
}}
|
||||
css={scrollBarStyles}
|
||||
role="presentation"
|
||||
>
|
||||
{cloneElement(
|
||||
@@ -317,9 +340,11 @@ function StickyWrap({
|
||||
ref={scrollFooterRef}
|
||||
style={{
|
||||
overflow: 'hidden',
|
||||
width: headerContainerWidth,
|
||||
width: maxWidth,
|
||||
boxSizing: 'border-box',
|
||||
...headerFooterGutter,
|
||||
}}
|
||||
css={scrollBarStyles}
|
||||
role="presentation"
|
||||
>
|
||||
{cloneElement(
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* 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 { useCallback } from 'react';
|
||||
import { useTable, Column } from 'react-table';
|
||||
import { render } from '@superset-ui/core/spec';
|
||||
import useSticky from '../../../src/DataTable/hooks/useSticky';
|
||||
|
||||
// A value distinguishable from any real scrollbar width, so the width
|
||||
// assertions below can detect whether header/footer's wrapper width was
|
||||
// computed by subtracting this JS-measured probe from `maxWidth` (the old,
|
||||
// removed `maxWidth - scrollBarSize` behavior) rather than always being the
|
||||
// unconditional `maxWidth` the fix uses. If that subtraction is ever
|
||||
// reintroduced, header/footer's `style.width` would read
|
||||
// `${MAX_WIDTH - MOCKED_SCROLLBAR_PROBE_SIZE}px`, an unmistakably wrong
|
||||
// value given how large this mock is.
|
||||
const MOCKED_SCROLLBAR_PROBE_SIZE = 42;
|
||||
|
||||
jest.mock('../../../src/DataTable/utils/getScrollBarSize', () => ({
|
||||
__esModule: true,
|
||||
CUSTOM_SCROLLBAR_SIZE: 8,
|
||||
default: () => 0,
|
||||
getCustomScrollBarSize: () => MOCKED_SCROLLBAR_PROBE_SIZE,
|
||||
}));
|
||||
|
||||
const MAX_WIDTH = 300;
|
||||
const MAX_HEIGHT = 120; // small enough that the mocked content forces a vertical scroll
|
||||
|
||||
const TOTAL_HEADER_HEIGHT = 30;
|
||||
const TOTAL_FOOTER_HEIGHT = 30;
|
||||
// Larger than `MAX_HEIGHT - TOTAL_HEADER_HEIGHT - TOTAL_FOOTER_HEIGHT`, so the
|
||||
// sticky layout effect computes `hasVerticalScroll: true`.
|
||||
const FULL_TABLE_HEIGHT = 400;
|
||||
|
||||
function mockMeasurements() {
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'clientHeight', 'get')
|
||||
.mockImplementation(function mockClientHeight(this: HTMLElement) {
|
||||
if (this.tagName === 'THEAD') return TOTAL_HEADER_HEIGHT;
|
||||
if (this.tagName === 'TFOOT') return TOTAL_FOOTER_HEIGHT;
|
||||
if (this.tagName === 'TABLE') return FULL_TABLE_HEIGHT;
|
||||
return 0;
|
||||
});
|
||||
jest
|
||||
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
|
||||
.mockImplementation(function mockRect(this: HTMLElement) {
|
||||
const width = this.tagName === 'TH' ? 60 : 0;
|
||||
return {
|
||||
width,
|
||||
height: 0,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: width,
|
||||
bottom: 0,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => {},
|
||||
} as DOMRect;
|
||||
});
|
||||
}
|
||||
|
||||
type Row = { category: string; amount: string };
|
||||
|
||||
const columns: Column<Row>[] = [
|
||||
{ Header: 'Category', accessor: 'category' },
|
||||
{ Header: 'SUM(amount)', accessor: 'amount' },
|
||||
];
|
||||
|
||||
const data: Row[] = Array.from({ length: 8 }, (_, i) => ({
|
||||
category: `Category ${i}`,
|
||||
amount: `${1234567.891234 + i}`,
|
||||
}));
|
||||
|
||||
function StickyTableHarness() {
|
||||
const getTableSize = useCallback(
|
||||
() => ({ width: MAX_WIDTH, height: MAX_HEIGHT }),
|
||||
[],
|
||||
);
|
||||
const { getTableProps, headerGroups, rows, prepareRow, wrapStickyTable } =
|
||||
useTable<Row>(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
getTableSize,
|
||||
},
|
||||
useSticky,
|
||||
);
|
||||
|
||||
const renderTable = () => (
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(hg => (
|
||||
<tr {...hg.getHeaderGroupProps()} key={hg.id}>
|
||||
{hg.headers.map(col => (
|
||||
<th {...col.getHeaderProps()} key={col.id}>
|
||||
{col.render('Header')}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(row => {
|
||||
prepareRow(row);
|
||||
return (
|
||||
<tr {...row.getRowProps()} key={row.id}>
|
||||
{row.cells.map(cell => (
|
||||
<td {...cell.getCellProps()} key={cell.column.id}>
|
||||
{cell.render('Cell')}
|
||||
</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr key="footer">
|
||||
<th>Summary</th>
|
||||
<td>
|
||||
<strong>14814904.694808</strong>
|
||||
</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
);
|
||||
|
||||
return <div data-test="sticky-root">{wrapStickyTable(renderTable)}</div>;
|
||||
}
|
||||
|
||||
test('sticky header/footer width matches the body, independent of the scrollbar-size probe', () => {
|
||||
mockMeasurements();
|
||||
|
||||
const { container } = render(<StickyTableHarness />);
|
||||
|
||||
const root = container.querySelector('[data-test="sticky-root"] > div');
|
||||
expect(root).not.toBeNull();
|
||||
const [headerDiv, bodyDiv, footerDiv] = Array.from(
|
||||
root!.children,
|
||||
) as HTMLDivElement[];
|
||||
|
||||
expect(bodyDiv.style.width).toBe(`${MAX_WIDTH}px`);
|
||||
|
||||
// This is the load-bearing assertion for the reported bug. Before the fix
|
||||
// these read `${MAX_WIDTH - MOCKED_SCROLLBAR_PROBE_SIZE}px` (258px) --
|
||||
// genuinely narrower than the body, from a real CSS `width` subtraction
|
||||
// (`maxWidth - scrollBarSize`), not just a smaller reported `clientWidth`.
|
||||
// A wrapper that's actually narrower than the shared, fixed-layout
|
||||
// colgroup it has to display gets genuinely clipped by its own
|
||||
// `overflow: hidden` (verified with real hit-testing in a real browser --
|
||||
// this is not true of the `scrollbarGutter` assertions below). The fix
|
||||
// makes header/footer always exactly `maxWidth`, which the colgroup
|
||||
// (bounded by the sizer's `clientWidth`, itself bounded by `maxWidth`)
|
||||
// can never exceed.
|
||||
expect(headerDiv.style.width).toBe(`${MAX_WIDTH}px`);
|
||||
expect(footerDiv.style.width).toBe(`${MAX_WIDTH}px`);
|
||||
|
||||
// Secondary, not itself load-bearing for preventing clipping: real
|
||||
// hit-testing shows `scrollbar-gutter` on an `overflow: hidden` box
|
||||
// changes what `clientWidth` reports without moving where it actually
|
||||
// clips, so this doesn't guard against the reported bug by itself. It's
|
||||
// asserted because header/footer's reported `clientWidth` still needs to
|
||||
// match body's `clientWidth` for their programmatically
|
||||
// synced `scrollLeft` (see `onScroll` in `useSticky.tsx`) to reveal the
|
||||
// same slice of the row body actually shows, when a horizontal scrollbar
|
||||
// is present alongside a vertical one.
|
||||
expect(headerDiv.style.scrollbarGutter).toBe(bodyDiv.style.scrollbarGutter);
|
||||
expect(footerDiv.style.scrollbarGutter).toBe(bodyDiv.style.scrollbarGutter);
|
||||
expect(bodyDiv.style.scrollbarGutter).toBe('stable');
|
||||
|
||||
// Pin the `css={scrollBarStyles}` addition to header/footer directly (part
|
||||
// of the same secondary consistency measure as the `scrollbarGutter`
|
||||
// assertions above, not the clipping fix). This component carries
|
||||
// `/** @jsxImportSource @emotion/react */`, which makes
|
||||
// Babel route its `css` prop through Emotion's jsx runtime instead of
|
||||
// passing `css` straight through as an inert DOM attribute (the default in
|
||||
// this repo's Jest/Babel setup, which -- unlike the webpack/SWC build --
|
||||
// doesn't set `importSource: '@emotion/react'` globally). With the pragma
|
||||
// in place, an applied `css` prop is observable as a real, non-empty
|
||||
// className, so this assertion actually fails without the fix instead of
|
||||
// passing regardless of whether `scrollBarStyles` is wired up.
|
||||
//
|
||||
// Before `css={scrollBarStyles}` was added to header/footer, they had no
|
||||
// emotion-generated class at all (`className === ''`) while the body kept
|
||||
// its own -- so this fails pre-fix and passes post-fix.
|
||||
expect(headerDiv.className).not.toBe('');
|
||||
expect(headerDiv.className).toBe(bodyDiv.className);
|
||||
expect(footerDiv.className).toBe(bodyDiv.className);
|
||||
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
+3
-3
@@ -45,8 +45,8 @@ test('getCustomScrollBarSize measures the probe using the shared custom scrollba
|
||||
});
|
||||
|
||||
test('CUSTOM_SCROLLBAR_SIZE matches the custom scrollbar width rendered in the sticky table', () => {
|
||||
// useSticky.tsx's scrollBarStyles must stay in sync with this constant so
|
||||
// the sticky header's shrink amount always matches the body's real
|
||||
// scrollbar width.
|
||||
// useSticky.tsx's scrollBarStyles sets `::-webkit-scrollbar { width: ... }`
|
||||
// from this constant, so it must stay in sync with it or the real
|
||||
// scrollbar body/sizer render won't match what this constant claims.
|
||||
expect(CUSTOM_SCROLLBAR_SIZE).toBe(8);
|
||||
});
|
||||
|
||||
@@ -35,12 +35,14 @@ jest.mock('src/utils/cachedSupersetGet');
|
||||
// only need a stand-in that lets us trigger onDrillBy with a distinguishable
|
||||
// config, so we can assert ChartContextMenu wires it into the modal.
|
||||
jest.mock('../DrillBy/DrillBySubmenu', () => ({
|
||||
DrillBySubmenu: ({ onDrillBy, dataset }: any) => (
|
||||
DrillBySubmenu: ({ onDrillBy, onCloseMenu, dataset }: any) => (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-test="fake-drill-by-submenu"
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
// Mirrors DrillBySubmenu's real handleSelection, which calls
|
||||
// onDrillBy and onCloseMenu together once a column is picked.
|
||||
onDrillBy(
|
||||
{ column_name: 'city', groupby: true },
|
||||
{ id: 1, columns: [], metrics: [] },
|
||||
@@ -48,8 +50,9 @@ jest.mock('../DrillBy/DrillBySubmenu', () => ({
|
||||
filters: [{ col: 'selected_scope' }],
|
||||
groupbyFieldName: 'groupby',
|
||||
},
|
||||
)
|
||||
}
|
||||
);
|
||||
onCloseMenu?.();
|
||||
}}
|
||||
>
|
||||
Fake Drill By
|
||||
</button>
|
||||
@@ -221,6 +224,39 @@ test('drill by modal uses the scope selected in the submenu over the raw context
|
||||
expect(modalConfig.filters).toEqual([{ col: 'selected_scope' }]);
|
||||
});
|
||||
|
||||
test('context menu can be reopened after Drill By closes it via onCloseMenu', async () => {
|
||||
// Ant Design's Dropdown keeps its overlay mounted and toggles an
|
||||
// `ant-dropdown-hidden` class rather than unmounting, so open/closed is
|
||||
// asserted on that class instead of the overlay's presence in the DOM.
|
||||
const isMenuOpen = () =>
|
||||
!screen
|
||||
.getByTestId('chart-context-menu')
|
||||
.closest('.ant-dropdown')
|
||||
?.classList.contains('ant-dropdown-hidden');
|
||||
|
||||
setup();
|
||||
|
||||
const openButton = screen.getByTestId('open-context-menu');
|
||||
userEvent.click(openButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(isMenuOpen()).toBe(true);
|
||||
});
|
||||
|
||||
const submenuButton = await screen.findByTestId('fake-drill-by-submenu');
|
||||
userEvent.click(submenuButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(isMenuOpen()).toBe(false);
|
||||
});
|
||||
|
||||
userEvent.click(openButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(isMenuOpen()).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('drill by only offers dimension columns', async () => {
|
||||
// drill_info returns every column so the results grid can label non-dimension
|
||||
// ones; narrowing to dimensions is this component's job, not the API's.
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
useCallback,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
@@ -110,6 +111,11 @@ const ChartContextMenu = (
|
||||
);
|
||||
|
||||
const [visible, setVisible] = useState(false);
|
||||
// `visible` state updates aren't synchronous, so a second open() call that
|
||||
// runs before React re-renders would still see the stale `false` closure.
|
||||
// This ref is updated synchronously (both here and in onOpenChange) so the
|
||||
// guard below always reflects the latest known open state.
|
||||
const visibleRef = useRef(false);
|
||||
|
||||
const isDisplayed = (item: ContextMenuItem) =>
|
||||
displayedItems === ContextMenuItem.All ||
|
||||
@@ -162,6 +168,7 @@ const ChartContextMenu = (
|
||||
const [showDrillByModal, setShowDrillByModal] = useState(false);
|
||||
|
||||
const closeContextMenu = useCallback(() => {
|
||||
visibleRef.current = false;
|
||||
setVisible(false);
|
||||
onClose();
|
||||
}, [onClose]);
|
||||
@@ -400,11 +407,26 @@ const ChartContextMenu = (
|
||||
filters,
|
||||
});
|
||||
|
||||
// Since Ant Design's Dropdown does not offer an imperative API
|
||||
// and we can't attach event triggers to charts SVG elements, we
|
||||
// use a hidden span that gets clicked on when receiving click events
|
||||
// from the charts.
|
||||
document.getElementById(`hidden-span-${id}`)?.click();
|
||||
// Some chart libraries (e.g. AG Grid) can dispatch a single logical
|
||||
// right-click as two contextmenu events in quick succession, calling
|
||||
// `open()` twice. Since Ant Design's Dropdown treats a click on an
|
||||
// already-open trigger as a toggle-to-close, re-clicking the hidden
|
||||
// span here on the second call would immediately close the menu we
|
||||
// just opened. Only click it when the menu isn't already visible; the
|
||||
// position/filters update above still applies on every call.
|
||||
//
|
||||
// visibleRef (not the `visible` state) drives this guard: the state
|
||||
// update from the first call's click hasn't been committed by the time
|
||||
// the second call runs, so a state-based check would still read the
|
||||
// stale `false` from this render's closure and click twice anyway.
|
||||
if (!visibleRef.current) {
|
||||
visibleRef.current = true;
|
||||
// Ant Design's Dropdown does not offer an imperative API and we
|
||||
// can't attach event triggers to charts' SVG elements, so we use a
|
||||
// hidden span that gets clicked on when receiving click events from
|
||||
// the charts.
|
||||
document.getElementById(`hidden-span-${id}`)?.click();
|
||||
}
|
||||
},
|
||||
[id, itemsCount],
|
||||
);
|
||||
@@ -426,6 +448,7 @@ const ChartContextMenu = (
|
||||
? menuItems
|
||||
: [{ key: 'no-actions', label: t('No actions'), disabled: true }],
|
||||
onClick: () => {
|
||||
visibleRef.current = false;
|
||||
setVisible(false);
|
||||
onClose();
|
||||
},
|
||||
@@ -435,6 +458,7 @@ const ChartContextMenu = (
|
||||
)}
|
||||
trigger={['click']}
|
||||
onOpenChange={value => {
|
||||
visibleRef.current = value;
|
||||
setVisible(value);
|
||||
if (!value) {
|
||||
onClose();
|
||||
|
||||
@@ -44,16 +44,18 @@ const setup = ({
|
||||
displayedItems = ContextMenuItem.All,
|
||||
additionalConfig = {},
|
||||
roles = undefined,
|
||||
formData = { datasource: '1__table', viz_type: VizType.Pie },
|
||||
}: {
|
||||
onSelection?: () => void;
|
||||
displayedItems?: ContextMenuItem | ContextMenuItem[];
|
||||
additionalConfig?: Record<string, any>;
|
||||
roles?: Record<string, string[][]>;
|
||||
formData?: Record<string, any>;
|
||||
} = {}) => {
|
||||
const { result } = renderHook(() =>
|
||||
useContextMenu(
|
||||
sliceId,
|
||||
{ datasource: '1__table', viz_type: VizType.Pie },
|
||||
formData as { datasource: string; viz_type: string },
|
||||
onSelection,
|
||||
displayedItems,
|
||||
additionalConfig,
|
||||
@@ -365,3 +367,24 @@ test('Dataset drill info API call is not made when user lacks drill permissions'
|
||||
expect(screen.queryByText('Drill by')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Drill to detail')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
test('Dataset drill info API call is not made when formData.datasource is not yet hydrated', async () => {
|
||||
// Regression test: right after a client-side navigation back to a
|
||||
// dashboard from Explore, the chart's formData can transiently be missing
|
||||
// `datasource` before the dashboard rehydrates. Firing a request for
|
||||
// dataset "NaN" (Number(undefined)) must not happen - see
|
||||
// useDatasetDrillInfo's Number.isNaN guard.
|
||||
const result = setup({ formData: { viz_type: VizType.Pie } });
|
||||
|
||||
act(() => {
|
||||
result.current.onContextMenu(0, 0, {});
|
||||
});
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
|
||||
expect(mockCachedSupersetGet).not.toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
endpoint: expect.stringContaining('/api/v1/dataset/NaN/drill_info/'),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
+97
-1
@@ -115,8 +115,21 @@ jest.mock('src/dashboard/components/nativeFilters/FilterBar', () => {
|
||||
MockFilterBar.displayName = 'MockFilterBar';
|
||||
return MockFilterBar;
|
||||
});
|
||||
// Exposes the sticky offset the builder hands to tab bars in the grid.
|
||||
jest.mock('src/dashboard/containers/DashboardGrid', () => {
|
||||
const MockDashboardGrid = () => <div data-test="mock-dashboard-grid" />;
|
||||
const { useContext } = jest.requireActual('react');
|
||||
const { StickyTabsOffsetContext } = jest.requireActual(
|
||||
'src/dashboard/components/gridComponents/TabsRenderer/StickyTabsOffsetContext',
|
||||
);
|
||||
const MockDashboardGrid = () => {
|
||||
const stickyTabsOffset = useContext(StickyTabsOffsetContext);
|
||||
return (
|
||||
<div
|
||||
data-test="mock-dashboard-grid"
|
||||
data-sticky-tabs-offset={stickyTabsOffset ?? 'none'}
|
||||
/>
|
||||
);
|
||||
};
|
||||
MockDashboardGrid.displayName = 'MockDashboardGrid';
|
||||
return MockDashboardGrid;
|
||||
});
|
||||
@@ -179,6 +192,89 @@ describe('DashboardBuilder', () => {
|
||||
expect(stickyContainer).toHaveClass('dashboard');
|
||||
});
|
||||
|
||||
// jsdom lays nothing out; report a height for the sticky header so the
|
||||
// offset handed to the grid is distinguishable from "no offset".
|
||||
function mockHeaderHeight(height: number) {
|
||||
return jest
|
||||
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
|
||||
.mockImplementation(function measure(this: HTMLElement) {
|
||||
const size =
|
||||
this.dataset.test === 'dashboard-header-wrapper' ? height : 0;
|
||||
return {
|
||||
x: 0,
|
||||
y: 0,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: size,
|
||||
width: 0,
|
||||
height: size,
|
||||
toJSON: () => ({}),
|
||||
} as DOMRect;
|
||||
});
|
||||
}
|
||||
|
||||
test('hands the sticky header height to tab bars in the grid while viewing', async () => {
|
||||
const rectSpy = mockHeaderHeight(120);
|
||||
try {
|
||||
const { findByTestId } = setup();
|
||||
expect(await findByTestId('mock-dashboard-grid')).toHaveAttribute(
|
||||
'data-sticky-tabs-offset',
|
||||
'120',
|
||||
);
|
||||
} finally {
|
||||
rectSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('leaves tab bars in the grid unpinned in report mode (?standalone=3)', async () => {
|
||||
// Report screenshots of large dashboards are captured tile by tile while
|
||||
// scrolling the page; a pinned bar would repeat in every tile.
|
||||
const originalHref = window.location.href;
|
||||
window.history.replaceState({}, '', '/?standalone=3');
|
||||
const rectSpy = mockHeaderHeight(120);
|
||||
try {
|
||||
const { findByTestId } = setup();
|
||||
expect(await findByTestId('mock-dashboard-grid')).toHaveAttribute(
|
||||
'data-sticky-tabs-offset',
|
||||
'none',
|
||||
);
|
||||
} finally {
|
||||
rectSpy.mockRestore();
|
||||
window.history.replaceState({}, '', originalHref);
|
||||
}
|
||||
});
|
||||
|
||||
test('leaves tab bars in the grid unpinned while a chart is maximized', async () => {
|
||||
const rectSpy = mockHeaderHeight(120);
|
||||
try {
|
||||
const { findByTestId } = setup({
|
||||
dashboardState: { ...mockState.dashboardState, fullSizeChartId: 123 },
|
||||
});
|
||||
expect(await findByTestId('mock-dashboard-grid')).toHaveAttribute(
|
||||
'data-sticky-tabs-offset',
|
||||
'none',
|
||||
);
|
||||
} finally {
|
||||
rectSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('leaves tab bars in the grid unpinned in the mobile viewport', async () => {
|
||||
(useIsMobile as jest.Mock).mockReturnValue(true);
|
||||
const rectSpy = mockHeaderHeight(120);
|
||||
try {
|
||||
const { findByTestId } = setup();
|
||||
expect(await findByTestId('mock-dashboard-grid')).toHaveAttribute(
|
||||
'data-sticky-tabs-offset',
|
||||
'none',
|
||||
);
|
||||
} finally {
|
||||
rectSpy.mockRestore();
|
||||
(useIsMobile as jest.Mock).mockReturnValue(false);
|
||||
}
|
||||
});
|
||||
|
||||
test('should add the "dashboard--editing" class if editMode=true', () => {
|
||||
const { getByTestId } = setup({
|
||||
dashboardState: { ...mockState.dashboardState, editMode: true },
|
||||
|
||||
@@ -87,6 +87,7 @@ import {
|
||||
} from 'src/dashboard/constants';
|
||||
import { selectCanRestoreDashboard } from 'src/features/versionHistory/canRestoreDashboard';
|
||||
import { selectIsDashboardVersionPreviewActive } from 'src/features/versionHistory/reducer';
|
||||
import { StickyTabsOffsetContext } from 'src/dashboard/components/gridComponents/TabsRenderer';
|
||||
import { getRootLevelTabsComponent, shouldFocusTabs } from './utils';
|
||||
import DashboardContainer from './DashboardContainer';
|
||||
import { useNativeFilters } from './state';
|
||||
@@ -490,8 +491,9 @@ const DashboardBuilder = () => {
|
||||
// always get the desktop layout -- matching the pre-existing behavior the
|
||||
// docs already promise for embedded dashboards.
|
||||
const standaloneMode = getUrlParam(URL_PARAMS.standalone);
|
||||
const isMobileViewport = useIsMobile();
|
||||
const isNotMobile =
|
||||
!useIsMobile() || standaloneMode !== DashboardStandaloneMode.None;
|
||||
!isMobileViewport || standaloneMode !== DashboardStandaloneMode.None;
|
||||
const [mobileFiltersOpen, setMobileFiltersOpen] = useState(false);
|
||||
|
||||
// Reset the drawer's open state when leaving mobile mode so it doesn't
|
||||
@@ -774,6 +776,17 @@ const DashboardBuilder = () => {
|
||||
? theme.sizeUnit * 4
|
||||
: theme.sizeUnit * 8;
|
||||
|
||||
// Tab bars nested in the grid pin just below the sticky header while the
|
||||
// page scrolls. Not in the mobile viewport, where the header scrolls away
|
||||
// and the mobile styling pins tab bars on its own; not in report mode,
|
||||
// whose tiled screenshots scroll the page and would capture a pinned bar
|
||||
// in every tile; and not while a chart is maximized, which sits inside its
|
||||
// own stacking context and must not be covered by a pinned bar.
|
||||
// (TabsRenderer itself opts out while editing, since drop targets rely on
|
||||
// document flow.)
|
||||
const stickyTabsOffset =
|
||||
isMobileViewport || isReport || fullSizeChartId ? undefined : barTopOffset;
|
||||
|
||||
const renderChild = useCallback(
|
||||
(adjustedWidth: number) => {
|
||||
const filterBarWidth = dashboardFiltersOpen
|
||||
@@ -976,7 +989,9 @@ const DashboardBuilder = () => {
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<DashboardContainer topLevelTabs={topLevelTabs} />
|
||||
<StickyTabsOffsetContext.Provider value={stickyTabsOffset}>
|
||||
<DashboardContainer topLevelTabs={topLevelTabs} />
|
||||
</StickyTabsOffsetContext.Provider>
|
||||
)
|
||||
) : (
|
||||
<Loading />
|
||||
|
||||
@@ -603,7 +603,9 @@ const Chart = (props: ChartProps) => {
|
||||
const exportOwnState = state
|
||||
? {
|
||||
...baseOwnState,
|
||||
...convertChartStateToOwnState(sliceVizType, state),
|
||||
...convertChartStateToOwnState(sliceVizType, state, {
|
||||
forExport: true,
|
||||
}),
|
||||
}
|
||||
: baseOwnState;
|
||||
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* 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 { createContext } from 'react';
|
||||
|
||||
/**
|
||||
* Distance, in pixels, from the top of the viewport at which a tab bar
|
||||
* rendered inside the dashboard grid should stick while the page scrolls.
|
||||
*
|
||||
* The dashboard header (title plus top-level tabs) is itself sticky, so the
|
||||
* first level of nested tabs pins just below it. Each level of nested tabs
|
||||
* then adds its own tab bar height for the tabs it contains, so deeper tab
|
||||
* bars stack beneath the ones above them instead of overlapping.
|
||||
*
|
||||
* `undefined` disables sticky tab bars, which is the case while editing
|
||||
* (drag-and-drop targets are laid out in document flow) and in the mobile
|
||||
* consumption experience, which pins tab bars through its own styling.
|
||||
*/
|
||||
export const StickyTabsOffsetContext = createContext<number | undefined>(
|
||||
undefined,
|
||||
);
|
||||
+169
-2
@@ -16,8 +16,15 @@
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
import { fireEvent, render, screen } from 'spec/helpers/testing-library';
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
sleep,
|
||||
} from 'spec/helpers/testing-library';
|
||||
import TabsRenderer, { TabItem, TabsRendererProps } from './TabsRenderer';
|
||||
import { StickyTabsOffsetContext } from './StickyTabsOffsetContext';
|
||||
|
||||
const mockTabItems: TabItem[] = [
|
||||
{
|
||||
@@ -240,7 +247,7 @@ describe('TabsRenderer', () => {
|
||||
expect(screen.queryByText('Tab 2 Content')).not.toBeInTheDocument(); // Not active
|
||||
});
|
||||
|
||||
test('drags from the tab title and shows the drag indicator only then', () => {
|
||||
test('drags from the tab title and shows the drag indicator only then', async () => {
|
||||
render(<TabsRenderer {...draggableTabProps} />);
|
||||
const container = screen.getByTestId('dashboard-component-tabs');
|
||||
const title = container.querySelector('textarea') as HTMLTextAreaElement;
|
||||
@@ -263,5 +270,165 @@ describe('TabsRenderer', () => {
|
||||
expect(container).toHaveStyleRule('cursor', 'move', {
|
||||
target: '.dragdroppable-tab *',
|
||||
});
|
||||
|
||||
// Release the pointer so the drag does not outlive this test. dnd-kit
|
||||
// keeps swallowing clicks on the shared document for 50ms after a drag
|
||||
// ends, which would eat the tab click of whichever test runs next.
|
||||
fireEvent.pointerUp(document, { button: 0, isPrimary: true, clientX: 50 });
|
||||
await sleep(60);
|
||||
});
|
||||
|
||||
// jsdom's cascade ignores specificity, so assert on the emotion rule rather
|
||||
// than the computed style, which antd's own `position: relative` would win
|
||||
const TAB_BAR = { target: /> ?\.ant-tabs ?> ?\.ant-tabs-nav$/ };
|
||||
|
||||
test('pins the tab bar below the offset supplied by the dashboard', () => {
|
||||
render(
|
||||
<StickyTabsOffsetContext.Provider value={64}>
|
||||
<TabsRenderer {...mockProps} />
|
||||
</StickyTabsOffsetContext.Provider>,
|
||||
);
|
||||
const container = screen.getByTestId('dashboard-component-tabs');
|
||||
|
||||
expect(container).toHaveStyleRule('position', 'sticky', TAB_BAR);
|
||||
expect(container).toHaveStyleRule('top', '64px', TAB_BAR);
|
||||
});
|
||||
|
||||
test('leaves the tab bar in document flow without a dashboard offset', () => {
|
||||
render(<TabsRenderer {...mockProps} />);
|
||||
const container = screen.getByTestId('dashboard-component-tabs');
|
||||
|
||||
expect(container).not.toHaveStyleRule('position', 'sticky', TAB_BAR);
|
||||
});
|
||||
|
||||
test('leaves the tab bar in document flow in edit mode', () => {
|
||||
render(
|
||||
<StickyTabsOffsetContext.Provider value={64}>
|
||||
<TabsRenderer {...mockProps} editMode />
|
||||
</StickyTabsOffsetContext.Provider>,
|
||||
);
|
||||
const container = screen.getByTestId('dashboard-component-tabs');
|
||||
|
||||
expect(container).not.toHaveStyleRule('position', 'sticky', TAB_BAR);
|
||||
});
|
||||
|
||||
// Reports the offset this tab set hands to tab sets nested inside it.
|
||||
const nestedTabItems: TabItem[] = [
|
||||
{
|
||||
...mockTabItems[0],
|
||||
children: (
|
||||
<StickyTabsOffsetContext.Consumer>
|
||||
{offset => <div data-test="nested-offset">{offset}</div>}
|
||||
</StickyTabsOffsetContext.Consumer>
|
||||
),
|
||||
},
|
||||
mockTabItems[1],
|
||||
];
|
||||
|
||||
test('stacks nested tab bars beneath its own tab bar', () => {
|
||||
// jsdom lays nothing out, so give the tab bar a height to add up
|
||||
const heightSpy = jest
|
||||
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
|
||||
.mockReturnValue(40);
|
||||
|
||||
try {
|
||||
render(
|
||||
<StickyTabsOffsetContext.Provider value={64}>
|
||||
<TabsRenderer {...mockProps} tabItems={nestedTabItems} />
|
||||
</StickyTabsOffsetContext.Provider>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('nested-offset')).toHaveTextContent('104');
|
||||
} finally {
|
||||
heightSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('restacks nested tab bars when its own tab bar reflows', () => {
|
||||
// The shared jsdom shim never fires its callback, so stand in an observer
|
||||
// that hands the callback back to the test. The component re-measures the
|
||||
// element rather than reading the entries, so the height comes from the
|
||||
// spy below; the callback only needs to run.
|
||||
const observerCallbacks: ResizeObserverCallback[] = [];
|
||||
const RealResizeObserver = window.ResizeObserver;
|
||||
window.ResizeObserver = class {
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
observerCallbacks.push(callback);
|
||||
}
|
||||
|
||||
observe() {}
|
||||
|
||||
unobserve() {}
|
||||
|
||||
disconnect() {}
|
||||
} as unknown as typeof ResizeObserver;
|
||||
const heightSpy = jest
|
||||
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
|
||||
.mockReturnValue(40);
|
||||
|
||||
try {
|
||||
render(
|
||||
<StickyTabsOffsetContext.Provider value={64}>
|
||||
<TabsRenderer {...mockProps} tabItems={nestedTabItems} />
|
||||
</StickyTabsOffsetContext.Provider>,
|
||||
);
|
||||
expect(screen.getByTestId('nested-offset')).toHaveTextContent('104');
|
||||
|
||||
// The bar grows -- labels wrap on a narrow viewport, a webfont lands --
|
||||
// and the tab set below it has to move down by the same amount.
|
||||
heightSpy.mockReturnValue(80);
|
||||
act(() => {
|
||||
observerCallbacks.forEach(callback =>
|
||||
callback([], {} as ResizeObserver),
|
||||
);
|
||||
});
|
||||
|
||||
expect(screen.getByTestId('nested-offset')).toHaveTextContent('144');
|
||||
} finally {
|
||||
heightSpy.mockRestore();
|
||||
window.ResizeObserver = RealResizeObserver;
|
||||
}
|
||||
});
|
||||
|
||||
// Switching tabs while the bar is pinned: the page scrolls so the tab set
|
||||
// starts where its bar is pinned, mirroring the top-level tabs' jump to top
|
||||
function renderPinnedTabSet(containerTop: number, offset?: number) {
|
||||
const scrollTo = jest.spyOn(window, 'scrollTo').mockImplementation();
|
||||
const rectSpy = jest
|
||||
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
|
||||
.mockReturnValue({ top: containerTop } as DOMRect);
|
||||
const scrollYStub = jest.replaceProperty(window, 'scrollY', 500);
|
||||
render(
|
||||
<StickyTabsOffsetContext.Provider value={offset}>
|
||||
<TabsRenderer {...mockProps} />
|
||||
</StickyTabsOffsetContext.Provider>,
|
||||
);
|
||||
fireEvent.click(screen.getByText('Tab 2').closest('[role="tab"]')!);
|
||||
rectSpy.mockRestore();
|
||||
scrollYStub.restore();
|
||||
return scrollTo;
|
||||
}
|
||||
|
||||
test('scrolls a pinned tab set back to its top when switching tabs', () => {
|
||||
// the tab set's top is 200px above the viewport, so the bar is pinned
|
||||
const scrollTo = renderPinnedTabSet(-200, 64);
|
||||
|
||||
expect(scrollTo).toHaveBeenCalledWith(window.scrollX, 500 - 200 - 64);
|
||||
scrollTo.mockRestore();
|
||||
});
|
||||
|
||||
test('leaves the page alone when the tab bar is not pinned', () => {
|
||||
// the tab set starts below where its bar would pin, so it is in flow
|
||||
const scrollTo = renderPinnedTabSet(300, 64);
|
||||
|
||||
expect(scrollTo).not.toHaveBeenCalled();
|
||||
scrollTo.mockRestore();
|
||||
});
|
||||
|
||||
test('leaves the page alone without a dashboard offset', () => {
|
||||
const scrollTo = renderPinnedTabSet(-200);
|
||||
|
||||
expect(scrollTo).not.toHaveBeenCalled();
|
||||
scrollTo.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
+132
-47
@@ -22,6 +22,8 @@ import {
|
||||
ReactElement,
|
||||
RefObject,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
@@ -46,11 +48,33 @@ import {
|
||||
import HoverMenu from '../../menu/HoverMenu';
|
||||
import DragHandle from '../../dnd/DragHandle';
|
||||
import DeleteComponentButton from '../../DeleteComponentButton';
|
||||
import { StickyTabsOffsetContext } from './StickyTabsOffsetContext';
|
||||
|
||||
const StyledTabsContainer = styled.div<{ isDragging?: boolean }>`
|
||||
// @z-index-above-dashboard-charts: above chart content, below the sticky
|
||||
// dashboard header (99) and the filter bar (11)
|
||||
const STICKY_TAB_BAR_Z_INDEX = 10;
|
||||
|
||||
const StyledTabsContainer = styled.div<{
|
||||
isDragging?: boolean;
|
||||
stickyTop?: number;
|
||||
}>`
|
||||
width: 100%;
|
||||
background-color: ${({ theme }) => theme.colorBgContainer};
|
||||
|
||||
/* Pin this component's own tab bar (direct child only, so nested tab
|
||||
sets keep their own offsets) below the sticky dashboard header while
|
||||
its content scrolls. */
|
||||
${({ theme, stickyTop }) =>
|
||||
stickyTop !== undefined &&
|
||||
css`
|
||||
& > .ant-tabs > .ant-tabs-nav {
|
||||
position: sticky;
|
||||
top: ${stickyTop}px;
|
||||
z-index: ${STICKY_TAB_BAR_Z_INDEX};
|
||||
background-color: ${theme.colorBgContainer};
|
||||
}
|
||||
`}
|
||||
|
||||
& .dashboard-component-tabs-content {
|
||||
height: 100%;
|
||||
}
|
||||
@@ -231,6 +255,59 @@ const TabsRenderer = memo<TabsRendererProps>(
|
||||
}) => {
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
|
||||
// Sticky tab bars only apply in view mode: while editing, drag-and-drop
|
||||
// targets and hover menus are positioned against the tab bar's place in
|
||||
// document flow.
|
||||
const parentStickyOffset = useContext(StickyTabsOffsetContext);
|
||||
const stickyTop = editMode ? undefined : parentStickyOffset;
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const [tabBarHeight, setTabBarHeight] = useState(0);
|
||||
|
||||
// Keyed on whether the bar is pinned rather than on the offset itself:
|
||||
// the header re-measuring on every resize would otherwise tear down and
|
||||
// recreate the observer in every tab set on the page.
|
||||
const isPinned = stickyTop !== undefined;
|
||||
useEffect(() => {
|
||||
// Direct-child selector, so nested tab sets' bars are never matched.
|
||||
const tabBar = isPinned
|
||||
? containerRef.current?.querySelector<HTMLElement>(
|
||||
':scope > .ant-tabs > .ant-tabs-nav',
|
||||
)
|
||||
: null;
|
||||
if (!tabBar) {
|
||||
return undefined;
|
||||
}
|
||||
const measure = () => setTabBarHeight(tabBar.offsetHeight);
|
||||
measure();
|
||||
// Matches the sticky header's own guard in DashboardBuilder, for
|
||||
// environments without ResizeObserver: the bar still pins, it just
|
||||
// keeps the height measured at mount.
|
||||
if (!global.hasOwnProperty('ResizeObserver')) {
|
||||
return undefined;
|
||||
}
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(tabBar);
|
||||
return () => observer.disconnect();
|
||||
}, [isPinned]);
|
||||
|
||||
// Tabs nested inside this one stack their bar beneath ours.
|
||||
const childStickyOffset =
|
||||
stickyTop === undefined ? undefined : stickyTop + tabBarHeight;
|
||||
|
||||
// Counterpart of the top-level tabs, which scroll the page to the top on
|
||||
// every switch (DashboardBuilder.handleChangeTab). With this bar pinned,
|
||||
// a switch would otherwise land the reader partway down the new tab's
|
||||
// content; bring the tab set back to where its bar is pinned instead.
|
||||
const scrollPinnedTabSetToTop = () => {
|
||||
if (stickyTop === undefined || !containerRef.current) {
|
||||
return;
|
||||
}
|
||||
const { top } = containerRef.current.getBoundingClientRect();
|
||||
if (top < stickyTop) {
|
||||
window.scrollTo(window.scrollX, window.scrollY + top - stickyTop);
|
||||
}
|
||||
};
|
||||
|
||||
// Use ref to always have access to the current tabIds in callbacks
|
||||
const tabIdsRef = useRef(tabIds);
|
||||
tabIdsRef.current = tabIds;
|
||||
@@ -267,9 +344,11 @@ const TabsRenderer = memo<TabsRendererProps>(
|
||||
|
||||
return (
|
||||
<StyledTabsContainer
|
||||
ref={containerRef}
|
||||
className="dashboard-component dashboard-component-tabs"
|
||||
data-test="dashboard-component-tabs"
|
||||
isDragging={isDragging}
|
||||
stickyTop={stickyTop}
|
||||
>
|
||||
{editMode && renderHoverMenu && tabsDragSourceRef && (
|
||||
<HoverMenu innerRef={tabsDragSourceRef} position="left">
|
||||
@@ -278,53 +357,59 @@ const TabsRenderer = memo<TabsRendererProps>(
|
||||
</HoverMenu>
|
||||
)}
|
||||
|
||||
<LineEditableTabs
|
||||
id={tabsComponent.id}
|
||||
activeKey={activeKey}
|
||||
onChange={key => {
|
||||
if (typeof key === 'string') {
|
||||
const tabIndex = tabIds.indexOf(key);
|
||||
if (tabIndex !== -1) handleClickTab(tabIndex);
|
||||
}
|
||||
}}
|
||||
onEdit={handleEdit}
|
||||
data-test="nav-list"
|
||||
type={editMode ? 'editable-card' : 'card'}
|
||||
items={tabItems}
|
||||
tabBarStyle={{ paddingLeft: tabBarPaddingLeft }}
|
||||
fullHeight
|
||||
{...(editMode && {
|
||||
renderTabBar: (tabBarProps, DefaultTabBar) => (
|
||||
<DndContext
|
||||
key={tabIds.join('-')}
|
||||
sensors={[sensor]}
|
||||
onDragStart={onDragStart}
|
||||
onDragEnd={onDragEnd}
|
||||
onDragCancel={onDragCancel}
|
||||
collisionDetection={closestCenter}
|
||||
>
|
||||
<SortableContext
|
||||
items={tabIds}
|
||||
strategy={horizontalListSortingStrategy}
|
||||
<StickyTabsOffsetContext.Provider value={childStickyOffset}>
|
||||
<LineEditableTabs
|
||||
id={tabsComponent.id}
|
||||
activeKey={activeKey}
|
||||
onChange={key => {
|
||||
if (typeof key === 'string') {
|
||||
const tabIndex = tabIds.indexOf(key);
|
||||
if (tabIndex !== -1) {
|
||||
handleClickTab(tabIndex);
|
||||
scrollPinnedTabSetToTop();
|
||||
}
|
||||
}
|
||||
}}
|
||||
onEdit={handleEdit}
|
||||
data-test="nav-list"
|
||||
type={editMode ? 'editable-card' : 'card'}
|
||||
items={tabItems}
|
||||
tabBarStyle={{ paddingLeft: tabBarPaddingLeft }}
|
||||
fullHeight
|
||||
{...(editMode && {
|
||||
renderTabBar: (tabBarProps, DefaultTabBar) => (
|
||||
<DndContext
|
||||
key={tabIds.join('-')}
|
||||
sensors={[sensor]}
|
||||
onDragStart={onDragStart}
|
||||
onDragEnd={onDragEnd}
|
||||
onDragCancel={onDragCancel}
|
||||
collisionDetection={closestCenter}
|
||||
>
|
||||
<DefaultTabBar {...tabBarProps}>
|
||||
{(node: React.ReactElement) => (
|
||||
<DraggableTabNode
|
||||
{...(node as React.ReactElement<DraggableTabNodeProps>)
|
||||
.props}
|
||||
key={node.key}
|
||||
data-node-key={node.key as string}
|
||||
disabled={isEditingTabTitle}
|
||||
>
|
||||
{node}
|
||||
</DraggableTabNode>
|
||||
)}
|
||||
</DefaultTabBar>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
),
|
||||
})}
|
||||
/>
|
||||
<SortableContext
|
||||
items={tabIds}
|
||||
strategy={horizontalListSortingStrategy}
|
||||
>
|
||||
<DefaultTabBar {...tabBarProps}>
|
||||
{(node: React.ReactElement) => (
|
||||
<DraggableTabNode
|
||||
{...(
|
||||
node as React.ReactElement<DraggableTabNodeProps>
|
||||
).props}
|
||||
key={node.key}
|
||||
data-node-key={node.key as string}
|
||||
disabled={isEditingTabTitle}
|
||||
>
|
||||
{node}
|
||||
</DraggableTabNode>
|
||||
)}
|
||||
</DefaultTabBar>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
),
|
||||
})}
|
||||
/>
|
||||
</StickyTabsOffsetContext.Provider>
|
||||
</StyledTabsContainer>
|
||||
);
|
||||
},
|
||||
|
||||
@@ -18,3 +18,4 @@
|
||||
*/
|
||||
export { default } from './TabsRenderer';
|
||||
export type { TabsRendererProps, TabItem, TabsComponent } from './TabsRenderer';
|
||||
export { StickyTabsOffsetContext } from './StickyTabsOffsetContext';
|
||||
|
||||
+177
-2
@@ -41,6 +41,38 @@ const callbackRef: {
|
||||
| null;
|
||||
} = { current: null };
|
||||
|
||||
// Real DropdownContainer partitions `items` into a visible main row and an
|
||||
// overflow slice by array index (`items.slice(0, overflowingIndex)` /
|
||||
// `items.slice(overflowingIndex)`), computed fresh every render in a
|
||||
// `useLayoutEffect` from live DOM measurements (DropdownContainer.tsx
|
||||
// lines ~166-234). It then reports that same partition to its parent
|
||||
// *separately*, one render later, via a plain `useEffect`
|
||||
// (onOverflowingStateChange, lines ~236-243) — a different effect phase
|
||||
// than the one that produced the partition it's reporting.
|
||||
//
|
||||
// This mock models both halves of that architecture instead of collapsing
|
||||
// them into one: `mockOverflowingIndex` stands in for DropdownContainer's
|
||||
// own always-fresh partition boundary — every render reads it and slices
|
||||
// `props.items` accordingly, exactly like production. `callbackRef` /
|
||||
// `fireOverflow` stand in for the separate, asynchronously delivered
|
||||
// onOverflowingStateChange report that FilterControls actually listens to
|
||||
// and mirrors into its own `overflowedIds` state. Nothing here auto-syncs
|
||||
// the two: a test can move `mockOverflowingIndex` (DropdownContainer having
|
||||
// *already* recomputed a new partition) without calling `fireOverflow`
|
||||
// again (its useEffect not having reported that new partition to the
|
||||
// parent yet) — reproducing the one-render lag that exists in production
|
||||
// between DropdownContainer's synchronous useLayoutEffect and its
|
||||
// asynchronous useEffect, rather than asserting the duplicate by
|
||||
// construction.
|
||||
//
|
||||
// Mirrors production's own sentinel exactly: -1 means "nothing overflows"
|
||||
// (DropdownContainer.tsx's `overflowingIndex` default), any other value is
|
||||
// the boundary index passed to `items.slice(0, n)` / `items.slice(n)`. A
|
||||
// bare `0` here means "everything overflows" (empty main row), so tests
|
||||
// that need that state set it explicitly rather than relying on the
|
||||
// default reading as "no overflow" by analogy with the real sentinel.
|
||||
let mockOverflowingIndex = -1;
|
||||
|
||||
// Mock the DropdownContainer subpath rather than the barrel
|
||||
// `@superset-ui/core/components` — mocking the barrel triggers a
|
||||
// circular re-export chain at requireActual time
|
||||
@@ -57,10 +89,18 @@ jest.mock('@superset-ui/core/components/DropdownContainer', () => {
|
||||
open: jest.fn(),
|
||||
close: jest.fn(),
|
||||
}));
|
||||
const notOverflowed =
|
||||
mockOverflowingIndex !== -1
|
||||
? props.items.slice(0, mockOverflowingIndex)
|
||||
: props.items;
|
||||
const overflowed =
|
||||
mockOverflowingIndex !== -1
|
||||
? props.items.slice(mockOverflowingIndex)
|
||||
: [];
|
||||
return (
|
||||
<div data-test="dropdown-container-mock">
|
||||
<div data-test="dropdown-items">
|
||||
{props.items.map((item: DropdownItem) => (
|
||||
{notOverflowed.map((item: DropdownItem) => (
|
||||
<div key={item.id} data-test="dropdown-item">
|
||||
{item.element}
|
||||
</div>
|
||||
@@ -74,7 +114,7 @@ jest.mock('@superset-ui/core/components/DropdownContainer', () => {
|
||||
</div>
|
||||
{props.dropdownContent && (
|
||||
<div data-test="dropdown-content-mock">
|
||||
{props.dropdownContent([])}
|
||||
{props.dropdownContent(overflowed)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -182,6 +222,7 @@ const fireOverflow = (overflowed: string[], notOverflowed: string[]) => {
|
||||
beforeEach(() => {
|
||||
dropdownContainerProps.length = 0;
|
||||
callbackRef.current = null;
|
||||
mockOverflowingIndex = -1;
|
||||
});
|
||||
|
||||
test('horizontal FilterControls hands every filter to DropdownContainer as an item', async () => {
|
||||
@@ -274,6 +315,137 @@ test('firing overflow with no active values keeps trigger count at 0 but supplie
|
||||
expect(latestProps().dropdownTriggerCount).toBe(0);
|
||||
});
|
||||
|
||||
// Cross-filter chips are keyed by `${name}${emitterId}` (see FilterControls.tsx's
|
||||
// `items` memo) and sourced from `crossFiltersSelector`, which reads
|
||||
// `dashboardState.sliceIds` + `dashboardLayout.present` (for the chart's name) +
|
||||
// `dataMask` (for the emitted filter's column/value) — independent of the native
|
||||
// filter config used by `buildHorizontalState` above.
|
||||
const CROSS_FILTER_CHART_ID = 85;
|
||||
const CROSS_FILTER_CHART_NAME = 'Products Sold By Product Line';
|
||||
const CROSS_FILTER_ITEM_ID = `${CROSS_FILTER_CHART_NAME}${CROSS_FILTER_CHART_ID}`;
|
||||
|
||||
const buildStateWithOneCrossFilter = () => ({
|
||||
...buildHorizontalState([]),
|
||||
dashboardState: {
|
||||
sliceIds: [CROSS_FILTER_CHART_ID],
|
||||
activeTabs: ['ROOT_ID'],
|
||||
},
|
||||
dashboardLayout: {
|
||||
present: {
|
||||
ROOT_ID: {
|
||||
type: 'ROOT',
|
||||
id: 'ROOT_ID',
|
||||
children: [`CHART-${CROSS_FILTER_CHART_ID}`],
|
||||
},
|
||||
[`CHART-${CROSS_FILTER_CHART_ID}`]: {
|
||||
type: 'CHART',
|
||||
id: `CHART-${CROSS_FILTER_CHART_ID}`,
|
||||
parents: ['ROOT_ID'],
|
||||
meta: {
|
||||
chartId: CROSS_FILTER_CHART_ID,
|
||||
sliceName: CROSS_FILTER_CHART_NAME,
|
||||
},
|
||||
},
|
||||
},
|
||||
past: [],
|
||||
future: [],
|
||||
},
|
||||
dataMask: {
|
||||
[CROSS_FILTER_CHART_ID]: {
|
||||
id: CROSS_FILTER_CHART_ID,
|
||||
filterState: {
|
||||
value: 'Classic Cars',
|
||||
filters: { product_line: 'Classic Cars' },
|
||||
},
|
||||
extraFormData: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const crossFilterControlsElement = (
|
||||
<FilterControls
|
||||
dataMaskSelected={{}}
|
||||
onFilterSelectionChange={jest.fn()}
|
||||
onPendingCustomizationDataMaskChange={jest.fn()}
|
||||
chartCustomizationValues={[]}
|
||||
/>
|
||||
);
|
||||
|
||||
const countChipCopies = async () => {
|
||||
const mainRow = within(
|
||||
await within(document.body).findByTestId('dropdown-items'),
|
||||
).queryAllByText(CROSS_FILTER_CHART_NAME);
|
||||
const popover = within(
|
||||
await within(document.body).findByTestId('dropdown-content-mock'),
|
||||
).queryAllByText(CROSS_FILTER_CHART_NAME);
|
||||
return mainRow.length + popover.length;
|
||||
};
|
||||
|
||||
test('a cross-filter chip DropdownContainer has already stopped overflowing does not also render in the popover', async () => {
|
||||
// Regression guard for the FilterBar duplicate-chip bug. This drives the
|
||||
// exact two-channel desync described in RCA.md: DropdownContainer's own
|
||||
// main-row partition (modeled here by `mockOverflowingIndex`, standing in
|
||||
// for its real useLayoutEffect-computed overflowingIndex) updates
|
||||
// synchronously and independently of the separate, asynchronous
|
||||
// onOverflowingStateChange report FilterControls mirrors into its
|
||||
// `overflowedIds` state (driven here by the real onOverflowingStateChange
|
||||
// callback via `fireOverflow`). Moving one without the other reproduces
|
||||
// the one-render lag that exists in production between DropdownContainer's
|
||||
// useLayoutEffect (immediate) and its useEffect (runs one commit later).
|
||||
const { rerender } = render(crossFilterControlsElement, {
|
||||
useRedux: true,
|
||||
useRouter: true,
|
||||
initialState: buildStateWithOneCrossFilter(),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(callbackRef.current).toBeTruthy());
|
||||
await waitFor(() =>
|
||||
expect(latestProps().items.map((i: DropdownItem) => i.id)).toContain(
|
||||
CROSS_FILTER_ITEM_ID,
|
||||
),
|
||||
);
|
||||
|
||||
// Step 1 — settled baseline: DropdownContainer's own partition
|
||||
// (mockOverflowingIndex = 0 — the sole item overflows) already excludes
|
||||
// the cross filter from the main row, and its onOverflowingStateChange
|
||||
// report agrees (fired via fireOverflow). Prove the two channels are
|
||||
// consistent and there is exactly one copy of the chip before touching
|
||||
// anything.
|
||||
mockOverflowingIndex = 0;
|
||||
fireOverflow([CROSS_FILTER_ITEM_ID], []);
|
||||
await waitFor(async () => expect(await countChipCopies()).toBe(1));
|
||||
|
||||
// Step 2 — DropdownContainer, on its own, recomputes a new partition
|
||||
// putting the cross filter back in the main row (e.g. more horizontal
|
||||
// space became available) — a plain rerender is enough to make the mock
|
||||
// re-read the moved `mockOverflowingIndex`, exactly like DropdownContainer
|
||||
// re-running its useLayoutEffect on a real resize. Deliberately do NOT
|
||||
// call fireOverflow again: production's matching useEffect runs strictly
|
||||
// after the layout effect that produced this new partition, so at this
|
||||
// point FilterControls has not been told about it yet.
|
||||
mockOverflowingIndex = 1;
|
||||
rerender(crossFilterControlsElement);
|
||||
|
||||
// DropdownContainer's fresh partition already shows the chip in the main
|
||||
// row this render — confirms the mock's synchronous half actually moved,
|
||||
// not just that nothing changed.
|
||||
await waitFor(async () => {
|
||||
const mainRow = within(
|
||||
await within(document.body).findByTestId('dropdown-items'),
|
||||
).queryAllByText(CROSS_FILTER_CHART_NAME);
|
||||
expect(mainRow.length).toBe(1);
|
||||
});
|
||||
|
||||
// FilterControls' overflowedIds state is still stale here (no fireOverflow
|
||||
// call happened for this new partition) — but the popover's content no
|
||||
// longer reads from that state. It's built from the same-render
|
||||
// `overflowedItems` argument DropdownContainer passes into dropdownContent,
|
||||
// which already excludes this chip (it just moved to the main row this
|
||||
// same render), so the popover correctly omits it despite the parent's
|
||||
// stale mirrored state disagreeing. Total count stays at one copy.
|
||||
expect(await countChipCopies()).toBe(1);
|
||||
});
|
||||
|
||||
test('all 12 overflowed filters are reachable through dropdownContent', async () => {
|
||||
// Substitutes for the disabled Cypress "scroll within overflow" assertion:
|
||||
// jsdom has no real layout/scrolling, so we instead prove every overflowed
|
||||
@@ -282,6 +454,9 @@ test('all 12 overflowed filters are reachable through dropdownContent', async ()
|
||||
createSelectNativeFilter(`NATIVE_FILTER-${i + 1}`, `filter_${i + 1}`),
|
||||
);
|
||||
|
||||
// All 12 filters overflow — DropdownContainer's own partition puts
|
||||
// nothing in the main row (mirrors real production 0-boundary).
|
||||
mockOverflowingIndex = 0;
|
||||
renderHorizontal(filters, buildDataMaskSelected(filters));
|
||||
|
||||
await waitFor(() => expect(callbackRef.current).toBeTruthy());
|
||||
|
||||
+60
-19
@@ -58,6 +58,7 @@ import {
|
||||
import { FilterBarOrientation, RootState } from 'src/dashboard/types';
|
||||
import {
|
||||
DropdownContainer,
|
||||
type DropdownItem,
|
||||
type DropdownRef as DropdownContainerRef,
|
||||
Typography,
|
||||
} from '@superset-ui/core/components';
|
||||
@@ -447,6 +448,14 @@ const FilterControls: FC<FilterControlsProps> = ({
|
||||
return [...activeOverflowedFilters, ...overflowedCrossFilters];
|
||||
}, [overflowedCrossFilters, overflowedFiltersInScope]);
|
||||
|
||||
const overflowedCustomizationsInScope = useMemo(
|
||||
() =>
|
||||
customizationsInScope.filter(({ id }) =>
|
||||
overflowedIds?.includes(`chart-customization-${id}`),
|
||||
),
|
||||
[customizationsInScope, overflowedIds],
|
||||
);
|
||||
|
||||
const rendererCrossFilter = useCallback(
|
||||
(
|
||||
crossFilter: CrossFilterIndicator,
|
||||
@@ -610,28 +619,56 @@ const FilterControls: FC<FilterControlsProps> = ({
|
||||
dropdownContent={
|
||||
overflowedFiltersInScope.length ||
|
||||
overflowedCrossFilters.length ||
|
||||
overflowedCustomizationsInScope.length ||
|
||||
(filtersOutOfScope.length && showCollapsePanel) ||
|
||||
(customizationsOutOfScope.length && showCustomizationCollapsePanel)
|
||||
? () => (
|
||||
<>
|
||||
<FiltersDropdownContent
|
||||
overflowedCrossFilters={overflowedCrossFilters}
|
||||
filtersInScope={overflowedFiltersInScope}
|
||||
filtersOutOfScope={filtersOutOfScope}
|
||||
renderer={renderer}
|
||||
rendererCrossFilter={rendererCrossFilter}
|
||||
showCollapsePanel={showCollapsePanel}
|
||||
forceRenderOutOfScope={hasRequiredFirst}
|
||||
/>
|
||||
{showCustomizationCollapsePanel && (
|
||||
<CustomizationsOutOfScopeCollapsible
|
||||
customizationsOutOfScope={customizationsOutOfScope}
|
||||
renderer={customizationRenderer}
|
||||
forceRender={false}
|
||||
? (overflowedItems: DropdownItem[]) => {
|
||||
// Which ids are overflowed comes from DropdownContainer's own
|
||||
// fresh, synchronous partition of `items` (the argument it
|
||||
// passes here), not from `overflowedIds` state — that state
|
||||
// only updates one render later via onOverflowingStateChange,
|
||||
// so using it here could show a filter here that
|
||||
// DropdownContainer's *own* main row, computed this same
|
||||
// render, has already stopped excluding (duplicate chip).
|
||||
const overflowedItemIds = new Set(
|
||||
overflowedItems.map(item => item.id),
|
||||
);
|
||||
const freshOverflowedFiltersInScope = filtersInScope.filter(
|
||||
({ id }) => overflowedItemIds.has(id),
|
||||
);
|
||||
const freshOverflowedCrossFilters =
|
||||
selectedCrossFilters.filter(({ emitterId, name }) =>
|
||||
overflowedItemIds.has(`${name}${emitterId}`),
|
||||
);
|
||||
const freshOverflowedCustomizationsInScope =
|
||||
customizationsInScope.filter(({ id }) =>
|
||||
overflowedItemIds.has(`chart-customization-${id}`),
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<FiltersDropdownContent
|
||||
overflowedCrossFilters={freshOverflowedCrossFilters}
|
||||
filtersInScope={freshOverflowedFiltersInScope}
|
||||
filtersOutOfScope={filtersOutOfScope}
|
||||
overflowedCustomizationsInScope={
|
||||
freshOverflowedCustomizationsInScope
|
||||
}
|
||||
renderer={renderer}
|
||||
rendererCrossFilter={rendererCrossFilter}
|
||||
customizationRenderer={customizationRenderer}
|
||||
showCollapsePanel={showCollapsePanel}
|
||||
forceRenderOutOfScope={hasRequiredFirst}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
{showCustomizationCollapsePanel && (
|
||||
<CustomizationsOutOfScopeCollapsible
|
||||
customizationsOutOfScope={customizationsOutOfScope}
|
||||
renderer={customizationRenderer}
|
||||
forceRender={false}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
forceRender={hasRequiredFirst}
|
||||
@@ -655,6 +692,10 @@ const FilterControls: FC<FilterControlsProps> = ({
|
||||
activeOverflowedFiltersInScope,
|
||||
overflowedFiltersInScope,
|
||||
overflowedCrossFilters,
|
||||
overflowedCustomizationsInScope,
|
||||
filtersInScope,
|
||||
selectedCrossFilters,
|
||||
customizationsInScope,
|
||||
filtersOutOfScope,
|
||||
showCollapsePanel,
|
||||
customizationsOutOfScope,
|
||||
|
||||
+20
-1
@@ -18,7 +18,12 @@
|
||||
*/
|
||||
|
||||
import { ReactNode } from 'react';
|
||||
import { Divider, Filter } from '@superset-ui/core';
|
||||
import {
|
||||
ChartCustomization,
|
||||
ChartCustomizationDivider,
|
||||
Divider,
|
||||
Filter,
|
||||
} from '@superset-ui/core';
|
||||
import { css, SupersetTheme } from '@apache-superset/core/theme';
|
||||
import { FilterBarOrientation } from 'src/dashboard/types';
|
||||
import { FiltersOutOfScopeCollapsible } from '../FiltersOutOfScopeCollapsible';
|
||||
@@ -28,12 +33,20 @@ export interface FiltersDropdownContentProps {
|
||||
overflowedCrossFilters: CrossFilterIndicator[];
|
||||
filtersInScope: (Filter | Divider)[];
|
||||
filtersOutOfScope: (Filter | Divider)[];
|
||||
overflowedCustomizationsInScope?: (
|
||||
| ChartCustomization
|
||||
| ChartCustomizationDivider
|
||||
)[];
|
||||
renderer: (filter: Filter | Divider, index: number) => ReactNode;
|
||||
rendererCrossFilter: (
|
||||
crossFilter: CrossFilterIndicator,
|
||||
orientation: FilterBarOrientation.Vertical,
|
||||
last: CrossFilterIndicator,
|
||||
) => ReactNode;
|
||||
customizationRenderer?: (
|
||||
item: ChartCustomization | ChartCustomizationDivider,
|
||||
index: number,
|
||||
) => ReactNode;
|
||||
showCollapsePanel?: boolean;
|
||||
forceRenderOutOfScope?: boolean;
|
||||
}
|
||||
@@ -42,8 +55,10 @@ export const FiltersDropdownContent = ({
|
||||
overflowedCrossFilters,
|
||||
filtersInScope,
|
||||
filtersOutOfScope,
|
||||
overflowedCustomizationsInScope = [],
|
||||
renderer,
|
||||
rendererCrossFilter,
|
||||
customizationRenderer,
|
||||
showCollapsePanel,
|
||||
forceRenderOutOfScope,
|
||||
}: FiltersDropdownContentProps) => (
|
||||
@@ -61,6 +76,10 @@ export const FiltersDropdownContent = ({
|
||||
),
|
||||
)}
|
||||
{filtersInScope.map(renderer)}
|
||||
{customizationRenderer &&
|
||||
overflowedCustomizationsInScope.map((item, index) =>
|
||||
customizationRenderer(item, index),
|
||||
)}
|
||||
{showCollapsePanel && filtersOutOfScope.length > 0 && (
|
||||
<FiltersOutOfScopeCollapsible
|
||||
filtersOutOfScope={filtersOutOfScope}
|
||||
|
||||
@@ -261,6 +261,66 @@ test('should return equal results when only clientView changes', () => {
|
||||
});
|
||||
});
|
||||
|
||||
test('should strip chartState from ownState to prevent spurious re-queries', () => {
|
||||
// Chart.tsx (dashboard) folds the AG Grid chartState (persisted separately
|
||||
// in dashboardState.chartStates) into ownState so the chart plugin can read
|
||||
// it on mount. That fold-in is not a query-affecting change and must not
|
||||
// trigger a re-query when it churns, e.g. right after a user interaction.
|
||||
const mockDataMaskWithChartState: DataMaskStateWithId = {
|
||||
chart1: {
|
||||
id: 'chart1',
|
||||
ownState: {
|
||||
pageSize: 10,
|
||||
currentPage: 0,
|
||||
chartState: {
|
||||
columnState: [{ colId: 'name', width: 200 }],
|
||||
filterModel: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const result = getRelevantDataMask(mockDataMaskWithChartState, 'ownState');
|
||||
|
||||
expect(result).toEqual({
|
||||
chart1: {
|
||||
pageSize: 10,
|
||||
currentPage: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('should return equal results when only chartState changes', () => {
|
||||
// chartState is refreshed on every AG Grid column/sort/filter change; if it
|
||||
// isn't stripped, its churn is read as a chart-state change by
|
||||
// getAffectedOwnDataCharts and re-triggers the chart's query.
|
||||
const dataMaskBefore: DataMaskStateWithId = {
|
||||
chart1: {
|
||||
id: 'chart1',
|
||||
ownState: {
|
||||
pageSize: 10,
|
||||
chartState: { columnState: [{ colId: 'name', width: 200 }] },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const dataMaskAfter: DataMaskStateWithId = {
|
||||
chart1: {
|
||||
id: 'chart1',
|
||||
ownState: {
|
||||
pageSize: 10,
|
||||
chartState: { columnState: [{ colId: 'name', width: 350 }] },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const resultBefore = getRelevantDataMask(dataMaskBefore, 'ownState');
|
||||
const resultAfter = getRelevantDataMask(dataMaskAfter, 'ownState');
|
||||
|
||||
expect(resultBefore).toEqual(resultAfter);
|
||||
expect(resultBefore).toEqual({ chart1: { pageSize: 10 } });
|
||||
});
|
||||
|
||||
test('should return extraFormData unchanged (clientView stripping only applies to ownState)', () => {
|
||||
// Verify extraFormData is passed through without modification
|
||||
const mockDataMask: DataMaskStateWithId = {
|
||||
|
||||
@@ -34,16 +34,19 @@ export const getRelevantDataMask = (
|
||||
.filter(item => item[prop])
|
||||
.map(item => {
|
||||
const value = item[prop];
|
||||
// TableChart writes clientView to ownState on every filtered-row change for export
|
||||
// but clientView changes should NOT trigger chart re-queries
|
||||
// Only clone when clientView exists to avoid unnecessary allocations
|
||||
// TableChart writes clientView to ownState on every filtered-row change for export,
|
||||
// and Chart.tsx (dashboard) folds the AG Grid chartState (column/sort/filter state,
|
||||
// persisted separately in dashboardState.chartStates) into the same ownState object
|
||||
// for the chart plugin to read on mount. Neither is query-affecting, so both must be
|
||||
// stripped here or their churn is read as a chart-state change and triggers re-queries.
|
||||
// Only clone when one of them exists to avoid unnecessary allocations.
|
||||
if (
|
||||
prop === 'ownState' &&
|
||||
value &&
|
||||
typeof value === 'object' &&
|
||||
'clientView' in value
|
||||
('clientView' in value || 'chartState' in value)
|
||||
) {
|
||||
return [item.id, omit(value, ['clientView'])];
|
||||
return [item.id, omit(value, ['clientView', 'chartState'])];
|
||||
}
|
||||
return [item.id, value];
|
||||
}),
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
import type {
|
||||
ChartStateConverter,
|
||||
ChartStateConverterOptions,
|
||||
BackendOwnState,
|
||||
JsonObject,
|
||||
} from '@superset-ui/core';
|
||||
@@ -44,14 +45,18 @@ class ChartStateConverterRegistry {
|
||||
* Convert chart-specific state to backend-compatible ownState format.
|
||||
* Returns an empty object if no converter is registered for the viz type.
|
||||
*/
|
||||
convert(vizType: string, chartState: JsonObject): Partial<BackendOwnState> {
|
||||
convert(
|
||||
vizType: string,
|
||||
chartState: JsonObject,
|
||||
options?: ChartStateConverterOptions,
|
||||
): Partial<BackendOwnState> {
|
||||
const converter = this.converters.get(vizType);
|
||||
if (!converter) {
|
||||
return {};
|
||||
}
|
||||
|
||||
try {
|
||||
return converter(chartState);
|
||||
return converter(chartState, options);
|
||||
} catch (error) {
|
||||
// Log error but don't throw - graceful degradation
|
||||
console.warn(
|
||||
@@ -115,8 +120,9 @@ export function registerChartStateConverter(
|
||||
export function convertChartStateToOwnState(
|
||||
vizType: string,
|
||||
chartState: JsonObject,
|
||||
options?: ChartStateConverterOptions,
|
||||
): Partial<BackendOwnState> {
|
||||
return registry.convert(vizType, chartState);
|
||||
return registry.convert(vizType, chartState, options);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -874,8 +874,12 @@ function ExploreViewContainer(props: ExploreViewContainerProps) {
|
||||
|
||||
const previousOwnState = usePrevious(props.ownState);
|
||||
useEffect(() => {
|
||||
// clientView (export snapshot) and chartState (AG Grid column/sort/filter
|
||||
// state read on mount) are folded into ownState but aren't query-affecting;
|
||||
// excluding them here is what the dashboard-side getRelevantDataMask does
|
||||
// for the same reason - see src/dashboard/util/activeAllDashboardFilters.ts.
|
||||
const strip = (s: JsonObject | undefined) =>
|
||||
s && typeof s === 'object' ? omit(s, ['clientView']) : s;
|
||||
omit(s && typeof s === 'object' ? s : {}, ['clientView', 'chartState']);
|
||||
if (!isEqual(strip(previousOwnState), strip(props.ownState))) {
|
||||
onQuery();
|
||||
reRenderChart();
|
||||
|
||||
+31
-17
@@ -512,13 +512,15 @@ export const useExploreAdditionalActionsMenu = (
|
||||
permalinkChartState,
|
||||
]);
|
||||
|
||||
// Minimal client-side CSV builder used for "Current View" when pagination is disabled
|
||||
// Minimal client-side CSV builder used for "Current View" when pagination is disabled.
|
||||
// `rows` may legitimately be empty (a filter that matches nothing) -- only
|
||||
// `columns` is required to produce a valid header-only export.
|
||||
const downloadClientCSV = (
|
||||
rows: ClientViewRow[],
|
||||
columns: ClientViewColumn[],
|
||||
filename: string,
|
||||
) => {
|
||||
if (!rows?.length || !columns?.length) return;
|
||||
if (!columns?.length) return;
|
||||
const header = columns
|
||||
.map(c => escapeCsvValue(c.label ?? c.key ?? ''))
|
||||
.join(',');
|
||||
@@ -536,13 +538,15 @@ export const useExploreAdditionalActionsMenu = (
|
||||
URL.revokeObjectURL(link.href);
|
||||
};
|
||||
|
||||
// Robust client-side JSON for "Current View"
|
||||
// Robust client-side JSON for "Current View". `rows` may legitimately be
|
||||
// empty (a filter that matches nothing) -- only `columns` is required to
|
||||
// produce a valid header-only export.
|
||||
const downloadClientJSON = (
|
||||
rows: ClientViewRow[],
|
||||
columns: ClientViewColumn[],
|
||||
filename: string,
|
||||
) => {
|
||||
if (!rows?.length || !columns?.length) return;
|
||||
if (!columns?.length) return;
|
||||
|
||||
const norm = (v: unknown): unknown => {
|
||||
if (v instanceof Date) return v.toISOString();
|
||||
@@ -587,13 +591,15 @@ export const useExploreAdditionalActionsMenu = (
|
||||
URL.revokeObjectURL(link.href);
|
||||
};
|
||||
|
||||
// Client-side XLSX for "Current View" (uses 'xlsx' already in deps)
|
||||
// Client-side XLSX for "Current View" (uses 'xlsx' already in deps).
|
||||
// `rows` may legitimately be empty (a filter that matches nothing) -- only
|
||||
// `columns` is required to produce a valid header-only export.
|
||||
const downloadClientXLSX = async (
|
||||
rows: ClientViewRow[],
|
||||
columns: ClientViewColumn[],
|
||||
filename: string,
|
||||
) => {
|
||||
if (!rows?.length || !columns?.length) return;
|
||||
if (!columns?.length) return;
|
||||
try {
|
||||
const XLSX = (await import(/* webpackChunkName: "xlsx" */ 'xlsx'))
|
||||
.default;
|
||||
@@ -618,12 +624,20 @@ export const useExploreAdditionalActionsMenu = (
|
||||
return o;
|
||||
});
|
||||
|
||||
const ws = XLSX.utils.json_to_sheet(data, { skipHeader: false });
|
||||
// json_to_sheet infers headers from the first data object's keys, so
|
||||
// with zero rows it would emit a completely blank sheet -- pass the
|
||||
// column labels explicitly so an empty filtered view still exports a
|
||||
// header-only sheet instead of nothing.
|
||||
const headers = columns.map(c => c.label ?? c.key);
|
||||
const ws = XLSX.utils.json_to_sheet(data, {
|
||||
header: headers,
|
||||
skipHeader: false,
|
||||
});
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, 'Current View');
|
||||
|
||||
// Autosize columns (roughly) by header length
|
||||
const colWidths = Object.keys(data[0] || {}).map(h => ({
|
||||
const colWidths = headers.map(h => ({
|
||||
wch: Math.max(10, String(h).length + 2),
|
||||
}));
|
||||
ws['!cols'] = colWidths;
|
||||
@@ -856,10 +870,10 @@ export const useExploreAdditionalActionsMenu = (
|
||||
// Pass ownState so client/UI state (e.g., filters) can be respected when supported.
|
||||
if (
|
||||
!latestQueryFormData?.server_pagination &&
|
||||
ownState?.clientView?.rows?.length &&
|
||||
ownState?.clientView?.columns?.length
|
||||
ownState?.clientView &&
|
||||
ownState.clientView.columns?.length
|
||||
) {
|
||||
const { rows, columns } = ownState.clientView;
|
||||
const { rows = [], columns = [] } = ownState.clientView;
|
||||
downloadClientCSV(
|
||||
rows,
|
||||
columns,
|
||||
@@ -894,10 +908,10 @@ export const useExploreAdditionalActionsMenu = (
|
||||
onClick: () => {
|
||||
if (
|
||||
!latestQueryFormData?.server_pagination &&
|
||||
ownState?.clientView?.rows?.length &&
|
||||
ownState?.clientView?.columns?.length
|
||||
ownState?.clientView &&
|
||||
ownState.clientView.columns?.length
|
||||
) {
|
||||
const { rows, columns } = ownState.clientView;
|
||||
const { rows = [], columns = [] } = ownState.clientView;
|
||||
downloadClientJSON(
|
||||
rows,
|
||||
columns,
|
||||
@@ -956,11 +970,11 @@ export const useExploreAdditionalActionsMenu = (
|
||||
onClick: async () => {
|
||||
if (
|
||||
!latestQueryFormData?.server_pagination &&
|
||||
ownState?.clientView?.rows?.length &&
|
||||
ownState?.clientView?.columns?.length
|
||||
ownState?.clientView &&
|
||||
ownState.clientView.columns?.length
|
||||
) {
|
||||
// Client-side filtered view → XLSX
|
||||
const { rows, columns } = ownState.clientView;
|
||||
const { rows = [], columns = [] } = ownState.clientView;
|
||||
await downloadClientXLSX(
|
||||
rows,
|
||||
columns,
|
||||
|
||||
+33
@@ -278,6 +278,39 @@ test('shows 413 error toast when Export Current View CSV server path fails with
|
||||
});
|
||||
});
|
||||
|
||||
test('Export Current View CSV takes the client path for a filter that matches zero rows, rather than falling back to an unfiltered backend export', async () => {
|
||||
global.URL.revokeObjectURL = jest.fn();
|
||||
|
||||
render(
|
||||
<TestComponent
|
||||
{...defaultProps}
|
||||
latestQueryFormData={{
|
||||
datasource: '1__table',
|
||||
viz_type: 'table',
|
||||
}}
|
||||
ownState={{
|
||||
clientView: {
|
||||
rows: [],
|
||||
columns: [{ key: 'name', label: 'Name' }],
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
{ useRedux: true },
|
||||
);
|
||||
|
||||
userEvent.hover(await screen.findByText('Data Export Options'));
|
||||
userEvent.hover(await screen.findByText('Export Current View'));
|
||||
userEvent.click(await screen.findByText('Export to .CSV'));
|
||||
|
||||
// The client path builds and clicks a download link directly rather than
|
||||
// calling exportChart; asserting exportChart was never called is what
|
||||
// distinguishes it from the backend fallback path (which doesn't know
|
||||
// about the empty client-side filter and would export every row).
|
||||
await waitFor(() => {
|
||||
expect(mockExportChart).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
const CHART_SELECTOR = '.panel-body .chart-container';
|
||||
const SLICE_NAME = 'My chart';
|
||||
const CHART_ID = 42;
|
||||
|
||||
@@ -195,6 +195,10 @@ function ReportModal({
|
||||
active: true,
|
||||
force_screenshot: false,
|
||||
custom_width: currentReport.custom_width,
|
||||
// A report belongs to either a chart or a dashboard, never both. Explore can
|
||||
// carry dashboard context even for a chart-scoped report, so send only the
|
||||
// entity that matches the creation method; a payload with both `chart` and
|
||||
// `dashboard` is rejected by the backend with a 422 error.
|
||||
...(creationMethod === CreationMethod.Charts
|
||||
? { chart: chart?.id }
|
||||
: { dashboard: dashboardId }),
|
||||
|
||||
@@ -303,24 +303,61 @@ test('useDatasetDrillInfo creates new verbose_map from columns and metrics', asy
|
||||
expect(result.current.result?.verbose_map).not.toHaveProperty('old_key');
|
||||
});
|
||||
|
||||
test('useDatasetDrillInfo handles NaN datasource ID from malformed string', async () => {
|
||||
test('useDatasetDrillInfo does not fetch when datasource ID resolves to NaN', async () => {
|
||||
// Regression test: a chart's slice entity can still be unhydrated right
|
||||
// after a client-side navigation back to a dashboard from Explore, so
|
||||
// datasetId may transiently resolve to NaN. The hook must not fire a
|
||||
// request for dataset "NaN" and should stay in loading, retrying once a
|
||||
// real datasetId arrives (see the SliceHeaderControls -> Chart.tsx
|
||||
// `state.sliceEntities.slices[id] || EMPTY_OBJECT` fallback).
|
||||
const { result, rerender } = renderHook(
|
||||
({ id }: { id: string | number }) => useDatasetDrillInfo(id, 456),
|
||||
{ initialProps: { id: 'abc' } },
|
||||
);
|
||||
|
||||
expect(result.current.status).toBe('loading');
|
||||
expect(mockedCachedSupersetGet).not.toHaveBeenCalled();
|
||||
|
||||
const mockDataset = { id: 123, columns: [], metrics: [] };
|
||||
mockedCachedSupersetGet.mockResolvedValue({
|
||||
json: {
|
||||
result: { id: NaN, columns: [], metrics: [] },
|
||||
},
|
||||
json: { result: mockDataset },
|
||||
} as any);
|
||||
|
||||
const { result } = renderHook(() => useDatasetDrillInfo('abc', 456));
|
||||
rerender({ id: '123__table' });
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.status).toBe('complete');
|
||||
});
|
||||
|
||||
// Verify hook calls endpoint with NaN (API will handle validation)
|
||||
expect(mockedCachedSupersetGet).toHaveBeenCalledWith({
|
||||
endpoint: '/api/v1/dataset/NaN/drill_info/?q=(dashboard_id:456)',
|
||||
endpoint: '/api/v1/dataset/123/drill_info/?q=(dashboard_id:456)',
|
||||
});
|
||||
expect(result.current.status).toBe('complete');
|
||||
});
|
||||
|
||||
test('useDatasetDrillInfo resets to loading when datasetId regresses to NaN after resolving another dataset', async () => {
|
||||
// Regression test: if the hook already completed for one dataset and then
|
||||
// receives a transient malformed id (e.g. a fresh navigation clears the
|
||||
// resolved datasetId before the new one hydrates), it must not keep
|
||||
// exposing the previous dataset's Complete result -- the context menu
|
||||
// would otherwise offer drill metadata for the wrong dataset.
|
||||
const mockDataset = { id: 123, columns: [], metrics: [] };
|
||||
mockedCachedSupersetGet.mockResolvedValue({
|
||||
json: { result: mockDataset },
|
||||
} as any);
|
||||
|
||||
const { result, rerender } = renderHook(
|
||||
({ id }: { id: string | number }) => useDatasetDrillInfo(id, 456),
|
||||
{ initialProps: { id: 123 } },
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.status).toBe('complete');
|
||||
});
|
||||
expect(result.current.result).toMatchObject({ id: 123 });
|
||||
|
||||
rerender({ id: 'abc' });
|
||||
|
||||
expect(result.current.status).toBe('loading');
|
||||
expect(result.current.result).toBeNull();
|
||||
});
|
||||
|
||||
test('useDatasetDrillInfo fetches dataset via extension when extension and formData provided', async () => {
|
||||
|
||||
@@ -86,11 +86,28 @@ export const useDatasetDrillInfo = (
|
||||
});
|
||||
return;
|
||||
}
|
||||
const numericDatasetId = getDatasetId(datasetId);
|
||||
if (Number.isNaN(numericDatasetId)) {
|
||||
// datasetId isn't resolved yet (e.g. the dashboard's slice entity hasn't
|
||||
// hydrated after a client-side navigation back from Explore). Reset to
|
||||
// Loading rather than firing a request for dataset "NaN" -- and rather
|
||||
// than leaving a previous id's Complete/Error result in place, which
|
||||
// would let the context menu expose drill metadata for the wrong
|
||||
// dataset until this one resolves. The effect reruns once datasetId
|
||||
// settles to a real value.
|
||||
setResource({
|
||||
status: ResourceStatus.Loading,
|
||||
result: null,
|
||||
error: null,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// `bestEffort` callers recover from a failure themselves, so it is not worth
|
||||
// logging: a deployment that registers the drill-by extension because this
|
||||
// endpoint is unreachable would otherwise log on every dashboard load.
|
||||
const fetchDrillInfo = async ({ bestEffort = false } = {}) => {
|
||||
const endpoint = `/api/v1/dataset/${getDatasetId(datasetId)}/drill_info/?q=(dashboard_id:${dashboardId})`;
|
||||
const endpoint = `/api/v1/dataset/${numericDatasetId}/drill_info/?q=(dashboard_id:${dashboardId})`;
|
||||
try {
|
||||
const { json } = await cachedSupersetGet({ endpoint });
|
||||
return json.result;
|
||||
@@ -105,7 +122,6 @@ export const useDatasetDrillInfo = (
|
||||
|
||||
const fetchDataset = async () => {
|
||||
try {
|
||||
const numericDatasetId = getDatasetId(datasetId);
|
||||
const loadDrillByOptionsExtension = getExtensionsRegistry().get(
|
||||
'load.drillby.options',
|
||||
);
|
||||
|
||||
Generated
+81
-81
@@ -24,7 +24,7 @@
|
||||
"@types/ws": "^8.18.1",
|
||||
"esbuild": "^0.28.2",
|
||||
"globals": "^17.11.0",
|
||||
"oxfmt": "^0.65.0",
|
||||
"oxfmt": "^0.66.0",
|
||||
"oxlint": "^1.81.0",
|
||||
"oxlint-tsgolint": "^7.0.2001",
|
||||
"tscw-config": "^1.1.2",
|
||||
@@ -522,9 +522,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-android-arm-eabi": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.65.0.tgz",
|
||||
"integrity": "sha512-M10Gs1SSpTNI6ahGx3M/OlIdUF4hkaP6OgUb+MS79t/Pgflk3r1nW5gPFqsZGUAXg0H1AfANT9AvLdBSTIhZKg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm-eabi/-/binding-android-arm-eabi-0.66.0.tgz",
|
||||
"integrity": "sha512-2Me9eoptv6ERdEuI2P8AOlYdHHraXebJaM6SC0kc2Dfb+mLrep2db+fedBPKaYn673h/vBgvP4tkOdAbaudX6w==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -539,9 +539,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-android-arm64": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.65.0.tgz",
|
||||
"integrity": "sha512-6DXH5sftNlaHpWJG50hFMF+Qxtq5D2TmahvcDPxWNcGIf8qrC9Y0YgHYcYZ2hlWzaccKXh/f3GcssH8vtkl4JA==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-android-arm64/-/binding-android-arm64-0.66.0.tgz",
|
||||
"integrity": "sha512-u7O+bSSF0HGsDKkQQxBqvLGVepu93RA+JKu+ONqvfh4sCnCEbj31wZj4iG5gk3XfRwrmYj0/8catkO2LcblQKQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -556,9 +556,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-darwin-arm64": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.65.0.tgz",
|
||||
"integrity": "sha512-K9m7lr53pcOLETNsC88sWes/GWHUGjZyHx95UhYcSXy0r30haLdeXlSufSenEAtoLaW753WN8/l4M7GYcRt6cg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-arm64/-/binding-darwin-arm64-0.66.0.tgz",
|
||||
"integrity": "sha512-/ikyMIVjX/sdo7KtjxoEsSUosfPzveVhT9RWMx9yGqFDKFJ89JAEKuEeLBmurDjrkb4w8tOnAdSO3SBaplY3bw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -573,9 +573,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-darwin-x64": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.65.0.tgz",
|
||||
"integrity": "sha512-sTNwIx1gre3MyiHOPLu7IGW4UyMScYL4DTmJT01p4vzB0En+OJUQz6KuH8t0PpsClRSaMuY3b0QmtoPItfO8Lg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-darwin-x64/-/binding-darwin-x64-0.66.0.tgz",
|
||||
"integrity": "sha512-q5xUsKeFqawa9NXa6ZGXWimFV19m8MogKPdTaSVDAAk2EQKBmBZRDeluwcl1p8ty/OFc9s9888OKEh3xfPVH0g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -590,9 +590,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-freebsd-x64": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.65.0.tgz",
|
||||
"integrity": "sha512-lYZMVIiIpnjGu5hJb2jxA8NYQ/e0OTGuaiAf4dqlGPNnPmUTu23FZRMltmjro/KkQm1uE4NT4n5yJ2zWmKcpfA==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-freebsd-x64/-/binding-freebsd-x64-0.66.0.tgz",
|
||||
"integrity": "sha512-CR+x4VzMY0pRXLK/xFQ/RzsSFkP5t2Z2mef0QY6OP/rTRcMUoMLCOM62/3Fp/t0K+UDoBKxvMyeb6D0zPMjleA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -607,9 +607,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-arm-gnueabihf": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.65.0.tgz",
|
||||
"integrity": "sha512-gIdXFAt/bURnjxuoedDEWdZ0PEWEmdDcm8qdpoFYYvW3QMk/5D4vUaH4mlMeRpeTdST4izUgHVO6RawQ4QulJw==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-0.66.0.tgz",
|
||||
"integrity": "sha512-ZEYmO/LbH9tTQCADILHGZE4GeOXOAj2VzedHkASNwjmwlwtutJCLpCJbIs37wRGTFgWRoEcD72jpMX+IBJUGjQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -624,9 +624,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-arm-musleabihf": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.65.0.tgz",
|
||||
"integrity": "sha512-jJVyADto7gA2AaX5qAjAexrxx9PJQaKWOe8PICE7yKMbjBRyOHcmj9TtVJ+MZYDUQ3hodU0AcoTj0jFQ1W4C6Q==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm-musleabihf/-/binding-linux-arm-musleabihf-0.66.0.tgz",
|
||||
"integrity": "sha512-hNtR9/oU0CeTkq7JnRkmBQwqe17v2ZaAMLC4VcN7IIOWeRyWDk0knSPWS9iiLmtbZ2RRBBtsG01jQgkZmKCJeQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
@@ -641,9 +641,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-arm64-gnu": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.65.0.tgz",
|
||||
"integrity": "sha512-p3RFkB+u7u+8up99b/NEcI1hdpLDiGgJYNwDorB60n7eH+eKposAKuMBxx+NqB3b+sJP4CZmYDh9G7X62tUsKg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-0.66.0.tgz",
|
||||
"integrity": "sha512-uwOVQ8i6I1LT/+eDzfsgrrcZp8Fn6NPVUPn8fF5gdFGekFf0PddF+LEuwsD0/pbNUcKZhDj2rQ5UpITh9gF4iQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -661,9 +661,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-arm64-musl": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.65.0.tgz",
|
||||
"integrity": "sha512-5Prb0uFzJHr+OUD/qS/TmU526wD+PaHDsm3KoRiUXbMIDpTSErjeQYkK3OQeshAvD/PuLa9WGEi9WPajjdOZJg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-arm64-musl/-/binding-linux-arm64-musl-0.66.0.tgz",
|
||||
"integrity": "sha512-tTkF2Dmx4nGAjmBlZb+UtTGqR/EK4ZrW9qBfzte07a9XWqzoGGKzpFFlyNDhQe+Uwql94+ReCTeNbhOXscw1Dg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -681,9 +681,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-ppc64-gnu": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.65.0.tgz",
|
||||
"integrity": "sha512-S8svxTp81obnF3admN9yd+u2rOYXtyzThLGBTg1PY6TPtGcC09BaaXLQD+TBSMa7yvqhCDZ8DFri+S/yG60qCg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-0.66.0.tgz",
|
||||
"integrity": "sha512-F3cKHUav4yXOHn6GFnwpBhSYsJOYKKf9eqO/9jlEuqPxNw9zb98E9ZFct79gcg8pibUGkbveEu9WDlmXJpDzKw==",
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
@@ -701,9 +701,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-riscv64-gnu": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.65.0.tgz",
|
||||
"integrity": "sha512-WtXBr75G/h2qOHy8SiGtC1R6aS3jt4mE52v1D8AtwMXIgoOmSNP9lKvbSaTRoL0e5wsMPoi6T72QWDYPu+S+nA==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-gnu/-/binding-linux-riscv64-gnu-0.66.0.tgz",
|
||||
"integrity": "sha512-K5fDaNZfDyQMYA/3qL21bqyN0X9T15LLwwbFPt2aHc94+ZG7bh0vZEsy2y7NlRnjjHFSwN+Hzg6ldJtbOriH4Q==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
@@ -721,9 +721,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-riscv64-musl": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.65.0.tgz",
|
||||
"integrity": "sha512-YwSLVvpaz4o/nv/miiPEBJz+eJ+VmbgNIrao6RccK9ce+L5EA8wP+ZD0uFeq6wKOza6zoWv/dR0sj6lip6R3EA==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-riscv64-musl/-/binding-linux-riscv64-musl-0.66.0.tgz",
|
||||
"integrity": "sha512-44Yc+I+qOmTElRcEhm5hUKIUJEQIOugymz4ua4tB0Wox7tGAfIbjzmXz/HDAtw1Ij6gmBwZlzh4hc9679RhWeA==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
@@ -741,9 +741,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-s390x-gnu": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.65.0.tgz",
|
||||
"integrity": "sha512-XQTPqgvyrgkKcFq+Tp2eK6JS7sqqJ+nRmy2Fav4j3I+i4dJoPJm7YwEdoeSDX9xkqj9jZ/lWfF3bXUWztIrn6A==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-0.66.0.tgz",
|
||||
"integrity": "sha512-1e29Eg9hEj2kRBB19M0seIehPbbXHCk35GvImjDvb79rjjYjXCRmtbUNHJcgoktZAMIzXrTbxDBKmTc1V4bg3A==",
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
@@ -761,9 +761,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-x64-gnu": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.65.0.tgz",
|
||||
"integrity": "sha512-cjZlx6S/VkeCNWCbwZriTnLnZeTcV3DEyeRGSw/2wwLP9viq+C0bJ4bC1k/ZLkFxDcB1lUgSasPkYGP1bdraOg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-gnu/-/binding-linux-x64-gnu-0.66.0.tgz",
|
||||
"integrity": "sha512-vODY1UQo10gngn0+D4xHKU84F1Twm1LqrzV4SqPXvmQKSd87paehvZ6jqA5wKs6XQrlWul9clYMDVHcoW9CPMA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -781,9 +781,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-linux-x64-musl": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.65.0.tgz",
|
||||
"integrity": "sha512-2azCjxdLtK4zCcIOU1dlXlU0xxfbPi6EjwWx7Ac7teWPidIIDOcIhudup83xNCKYhtqeVd/gaVDOxbUq4syXWA==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-linux-x64-musl/-/binding-linux-x64-musl-0.66.0.tgz",
|
||||
"integrity": "sha512-YDzXx2JsT4+HL4MdkVrYjO55NS5lUKNm8rLC4ZPou8+seu0v0jhecSh+ufoO6+xEa8gccEezMlI2WHJi4ApUgw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -801,9 +801,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-openharmony-arm64": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.65.0.tgz",
|
||||
"integrity": "sha512-KXQ7xi1e/voP0IQaw6fG6XY4Z5+Llf1XmRSZS1t7pVFCecFJ0iXaboKmVwjFtp5MLlT5iWQrJ2U1C3GJdZ2u+Q==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-openharmony-arm64/-/binding-openharmony-arm64-0.66.0.tgz",
|
||||
"integrity": "sha512-mJjUYd8lj0+j4JkYyEM+5qKBf1Rnrpgjn/SVYKJhicVDqLz566ooa7Fs8zflPqt+dnZDV7X054rVIQX6ZcQNlQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -818,9 +818,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-win32-arm64-msvc": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.65.0.tgz",
|
||||
"integrity": "sha512-2FbbjG5jEqLSLKVJwBap84uJfpn5Y5A53KEO0aUNr+zeiRB9nyPUIFMcSbZVMFLitfBytFWRNngozXYjb6Rsbw==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-0.66.0.tgz",
|
||||
"integrity": "sha512-soV+0vESv7e5ntCHWC61x4gg8OSak6IHHnWsZmHrJFlvMj2AK+kmldErCNkVkrvc1Ts2/++rJXn+IuAb2WMXhw==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -835,9 +835,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-win32-ia32-msvc": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.65.0.tgz",
|
||||
"integrity": "sha512-LJ+ZacAPSjegDOnSLyA1TMWAhdDrsK4el3REdr1oL2UtVBCMhO2II/Sb3cEW6mF2MfLhl8hDNCSvc7KSbgk3LQ==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-ia32-msvc/-/binding-win32-ia32-msvc-0.66.0.tgz",
|
||||
"integrity": "sha512-YCPi23uRIEYuIKTZohAkKbPFpujQ5QBuUM5iDv+UqbCmTPAkaFsxjsSuB8xlBpRT0G7eP/4HMF+cPDSqHtOD9A==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
@@ -852,9 +852,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@oxfmt/binding-win32-x64-msvc": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.65.0.tgz",
|
||||
"integrity": "sha512-higu9cWEO6XXFzATD1jf0mCK34rNfN2H9JrJie7QB1IhleVpTh0QlLH9Ip2C1H/Nd5n0v5pvRtC+5R0uE4HpVg==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/@oxfmt/binding-win32-x64-msvc/-/binding-win32-x64-msvc-0.66.0.tgz",
|
||||
"integrity": "sha512-bwTQcv/JVRPkOqQtMF0X7vpvpncDQiBcXHxZ9S2hR12Hlo8bvBdUR5x5XnxzDZ3kM0qoZw1rv7KaD66Ly+pFWA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -2923,9 +2923,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/oxfmt": {
|
||||
"version": "0.65.0",
|
||||
"resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.65.0.tgz",
|
||||
"integrity": "sha512-SgS5VgnP42T0zl3zWD+xoH8FCqg1SAFnSRoOT/qeoa6gxcYIqrDMOmcXIg/EWSN92Du4ogB4riuKhKd6Y4CGhw==",
|
||||
"version": "0.66.0",
|
||||
"resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.66.0.tgz",
|
||||
"integrity": "sha512-FfvqR8RFtV6JJpRrpkfqyVCQ7HDvZ/VriWFx7veftCgL1B5ZO9qNr+1rvPieycMQnNfVG0PWyJQiy7p0hq1I5w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -2938,28 +2938,28 @@
|
||||
"node": "^20.19.0 || >=22.12.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/Boshen"
|
||||
"url": "https://github.com/sponsors/oxc-project"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@oxfmt/binding-android-arm-eabi": "0.65.0",
|
||||
"@oxfmt/binding-android-arm64": "0.65.0",
|
||||
"@oxfmt/binding-darwin-arm64": "0.65.0",
|
||||
"@oxfmt/binding-darwin-x64": "0.65.0",
|
||||
"@oxfmt/binding-freebsd-x64": "0.65.0",
|
||||
"@oxfmt/binding-linux-arm-gnueabihf": "0.65.0",
|
||||
"@oxfmt/binding-linux-arm-musleabihf": "0.65.0",
|
||||
"@oxfmt/binding-linux-arm64-gnu": "0.65.0",
|
||||
"@oxfmt/binding-linux-arm64-musl": "0.65.0",
|
||||
"@oxfmt/binding-linux-ppc64-gnu": "0.65.0",
|
||||
"@oxfmt/binding-linux-riscv64-gnu": "0.65.0",
|
||||
"@oxfmt/binding-linux-riscv64-musl": "0.65.0",
|
||||
"@oxfmt/binding-linux-s390x-gnu": "0.65.0",
|
||||
"@oxfmt/binding-linux-x64-gnu": "0.65.0",
|
||||
"@oxfmt/binding-linux-x64-musl": "0.65.0",
|
||||
"@oxfmt/binding-openharmony-arm64": "0.65.0",
|
||||
"@oxfmt/binding-win32-arm64-msvc": "0.65.0",
|
||||
"@oxfmt/binding-win32-ia32-msvc": "0.65.0",
|
||||
"@oxfmt/binding-win32-x64-msvc": "0.65.0"
|
||||
"@oxfmt/binding-android-arm-eabi": "0.66.0",
|
||||
"@oxfmt/binding-android-arm64": "0.66.0",
|
||||
"@oxfmt/binding-darwin-arm64": "0.66.0",
|
||||
"@oxfmt/binding-darwin-x64": "0.66.0",
|
||||
"@oxfmt/binding-freebsd-x64": "0.66.0",
|
||||
"@oxfmt/binding-linux-arm-gnueabihf": "0.66.0",
|
||||
"@oxfmt/binding-linux-arm-musleabihf": "0.66.0",
|
||||
"@oxfmt/binding-linux-arm64-gnu": "0.66.0",
|
||||
"@oxfmt/binding-linux-arm64-musl": "0.66.0",
|
||||
"@oxfmt/binding-linux-ppc64-gnu": "0.66.0",
|
||||
"@oxfmt/binding-linux-riscv64-gnu": "0.66.0",
|
||||
"@oxfmt/binding-linux-riscv64-musl": "0.66.0",
|
||||
"@oxfmt/binding-linux-s390x-gnu": "0.66.0",
|
||||
"@oxfmt/binding-linux-x64-gnu": "0.66.0",
|
||||
"@oxfmt/binding-linux-x64-musl": "0.66.0",
|
||||
"@oxfmt/binding-openharmony-arm64": "0.66.0",
|
||||
"@oxfmt/binding-win32-arm64-msvc": "0.66.0",
|
||||
"@oxfmt/binding-win32-ia32-msvc": "0.66.0",
|
||||
"@oxfmt/binding-win32-x64-msvc": "0.66.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"svelte": "^5.0.0",
|
||||
|
||||
@@ -32,7 +32,7 @@
|
||||
"@types/ws": "^8.18.1",
|
||||
"esbuild": "^0.28.2",
|
||||
"globals": "^17.11.0",
|
||||
"oxfmt": "^0.65.0",
|
||||
"oxfmt": "^0.66.0",
|
||||
"oxlint": "^1.81.0",
|
||||
"oxlint-tsgolint": "^7.0.2001",
|
||||
"tscw-config": "^1.1.2",
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
# specific language governing permissions and limitations
|
||||
# under the License.
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Callable
|
||||
|
||||
import click
|
||||
@@ -58,10 +59,18 @@ def _load_dataset(
|
||||
if "force" in sig.parameters:
|
||||
params["force"] = force
|
||||
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
loader(**params)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load %s: %s", dataset_name, e)
|
||||
logger.warning(
|
||||
"Failed to load %s after %.2fs: %s",
|
||||
dataset_name,
|
||||
time.perf_counter() - start,
|
||||
e,
|
||||
)
|
||||
else:
|
||||
logger.info("Finished [%s] in %.2fs", dataset_name, time.perf_counter() - start)
|
||||
|
||||
|
||||
def load_examples_run(
|
||||
@@ -70,6 +79,7 @@ def load_examples_run(
|
||||
only_metadata: bool = False,
|
||||
force: bool = False,
|
||||
) -> None:
|
||||
run_start = time.perf_counter()
|
||||
if only_metadata:
|
||||
logger.info("Loading examples metadata")
|
||||
else:
|
||||
@@ -94,7 +104,14 @@ def load_examples_run(
|
||||
_load_dataset(loader, loader_name, only_metadata, force)
|
||||
|
||||
# Load examples that are stored as YAML config files
|
||||
configs_start = time.perf_counter()
|
||||
examples.load_examples_from_configs(force, load_test_data)
|
||||
logger.info(
|
||||
"Finished [Examples From Configs] in %.2fs",
|
||||
time.perf_counter() - configs_start,
|
||||
)
|
||||
|
||||
logger.info("load_examples finished in %.2fs", time.perf_counter() - run_start)
|
||||
|
||||
|
||||
@click.command()
|
||||
|
||||
@@ -43,6 +43,7 @@ from superset.migrations.shared.migrate_viz.processors import (
|
||||
MigratePivotTable,
|
||||
MigrateSankey,
|
||||
MigrateSunburst,
|
||||
MigrateTableChart,
|
||||
MigrateTreeMap,
|
||||
)
|
||||
from superset.migrations.shared.utils import paginated_update, try_load_json
|
||||
@@ -61,6 +62,7 @@ class VizType(str, Enum):
|
||||
PIVOT_TABLE = "pivot_table"
|
||||
SANKEY = "sankey"
|
||||
SUNBURST = "sunburst"
|
||||
TABLE = "table"
|
||||
TREEMAP = "treemap"
|
||||
|
||||
|
||||
@@ -77,6 +79,7 @@ MIGRATIONS: dict[VizType, Type[MigrateViz]] = {
|
||||
VizType.PIVOT_TABLE: MigratePivotTable,
|
||||
VizType.SANKEY: MigrateSankey,
|
||||
VizType.SUNBURST: MigrateSunburst,
|
||||
VizType.TABLE: MigrateTableChart,
|
||||
VizType.TREEMAP: MigrateTreeMap,
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ from superset.commands.exceptions import ImportFailedError
|
||||
from superset.constants import PASSWORD_MASK
|
||||
from superset.databases.ssh_tunnel.models import SSHTunnel
|
||||
from superset.databases.utils import make_url_safe
|
||||
from superset.db_engine_specs.exceptions import SupersetDBAPIConnectionError
|
||||
from superset.db_engine_specs.exceptions import SupersetDBAPIError
|
||||
from superset.exceptions import (
|
||||
OAuth2RedirectError,
|
||||
SupersetSecurityException,
|
||||
@@ -96,6 +96,21 @@ def _refuse_stored_secret_reuse(existing: Database, config: dict[str, Any]) -> N
|
||||
)
|
||||
|
||||
|
||||
def _sync_permissions_best_effort(database: Database) -> None:
|
||||
"""
|
||||
Sync catalog/schema permissions for ``database``, tolerating a transient
|
||||
or OAuth2 failure rather than letting it fail the import.
|
||||
"""
|
||||
try:
|
||||
add_permissions(database)
|
||||
except (SupersetDBAPIError, OAuth2RedirectError) as ex:
|
||||
# ``add_permissions()`` calls ``get_all_catalog_names()`` outside of
|
||||
# its own per-catalog error handling, so any DBAPI error mapped from
|
||||
# that initial catalog discovery -- not just a connection failure --
|
||||
# must be tolerated here too, or it fails the whole import.
|
||||
logger.warning(ex.message)
|
||||
|
||||
|
||||
def import_database( # noqa: C901
|
||||
config: dict[str, Any],
|
||||
overwrite: bool = False,
|
||||
@@ -108,6 +123,15 @@ def import_database( # noqa: C901
|
||||
existing = db.session.query(Database).filter_by(uuid=config["uuid"]).first()
|
||||
if existing:
|
||||
if not overwrite or not can_write:
|
||||
if can_write:
|
||||
# Chart/dataset/saved-query/dashboard bundles that reference
|
||||
# an already-imported database reach this branch; without
|
||||
# this, a schema added to the live connection since the
|
||||
# database was first imported would never get a first-time
|
||||
# grant through this path either. ``add_permissions()`` does
|
||||
# a live, uncached metadata scan, so this can be slow for
|
||||
# cross-catalog-enabled engines -- see its own comment.
|
||||
_sync_permissions_best_effort(existing)
|
||||
return existing
|
||||
config["id"] = existing.id
|
||||
# Stored secrets must not be rebound to a different endpoint: without
|
||||
@@ -184,9 +208,6 @@ def import_database( # noqa: C901
|
||||
recursive=False,
|
||||
)
|
||||
|
||||
try:
|
||||
add_permissions(database)
|
||||
except (SupersetDBAPIConnectionError, OAuth2RedirectError) as ex:
|
||||
logger.warning(ex.message)
|
||||
_sync_permissions_best_effort(database)
|
||||
|
||||
return database
|
||||
|
||||
@@ -22,6 +22,7 @@ from typing import Any, Optional, TypedDict
|
||||
import pandas as pd
|
||||
from flask import current_app
|
||||
from flask_babel import lazy_gettext as _
|
||||
from sqlalchemy import or_
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from superset import db
|
||||
@@ -168,12 +169,20 @@ class UploadCommand(BaseCommand):
|
||||
)
|
||||
)
|
||||
|
||||
catalog = self._model.get_default_catalog()
|
||||
|
||||
catalog_filter = (
|
||||
or_(SqlaTable.catalog == catalog, SqlaTable.catalog.is_(None))
|
||||
if catalog is not None
|
||||
else SqlaTable.catalog.is_(None)
|
||||
)
|
||||
sqla_table = (
|
||||
db.session.query(SqlaTable)
|
||||
.filter_by(
|
||||
table_name=self._table_name,
|
||||
schema=self._schema,
|
||||
database_id=self._model_id,
|
||||
.filter(
|
||||
SqlaTable.table_name == self._table_name,
|
||||
SqlaTable.schema == self._schema,
|
||||
SqlaTable.database_id == self._model_id,
|
||||
catalog_filter,
|
||||
)
|
||||
.one_or_none()
|
||||
)
|
||||
@@ -206,7 +215,7 @@ class UploadCommand(BaseCommand):
|
||||
)
|
||||
|
||||
if soft_twin := DatasetDAO.find_soft_deleted_logical_duplicate(
|
||||
self._model, Table(self._table_name, self._schema)
|
||||
self._model, Table(self._table_name, self._schema, catalog)
|
||||
):
|
||||
raise DatabaseUploadSoftDeletedDatasetExistsError(str(soft_twin.uuid))
|
||||
|
||||
@@ -217,12 +226,13 @@ class UploadCommand(BaseCommand):
|
||||
table_name=self._table_name,
|
||||
database=self._model,
|
||||
database_id=self._model_id,
|
||||
catalog=catalog,
|
||||
editors=editors,
|
||||
schema=self._schema,
|
||||
# Ensure catalog is set
|
||||
catalog=self._model.get_default_catalog(),
|
||||
)
|
||||
db.session.add(sqla_table)
|
||||
elif sqla_table.catalog is None and catalog is not None:
|
||||
sqla_table.catalog = catalog
|
||||
|
||||
sqla_table.fetch_metadata()
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ from superset.constants import PASSWORD_MASK
|
||||
from superset.databases.ssh_tunnel.models import SSHTunnel
|
||||
from superset.databases.utils import make_url_safe
|
||||
from superset.db_engine_specs.base import GenericDBException
|
||||
from superset.exceptions import OAuth2RedirectError
|
||||
from superset.models.core import Database
|
||||
from superset.security.manager import SupersetSecurityManager
|
||||
from superset.utils import json
|
||||
@@ -147,6 +148,29 @@ def ping(engine: Engine) -> bool:
|
||||
return engine.dialect.do_ping(conn)
|
||||
|
||||
|
||||
def _get_all_schema_names_with_retry(
|
||||
database: Database, catalog: str | None
|
||||
) -> set[str]:
|
||||
"""
|
||||
Retry the live schema-listing call once before giving up on a catalog.
|
||||
|
||||
Some catalogs are visible but not listable (eg the ``rdsadmin`` catalog on
|
||||
AWS RDS), but the exception caught by the caller doesn't distinguish that
|
||||
from a one-off transient hiccup (eg schema metadata not yet visible right
|
||||
after it was created). A single retry lets a schema that needs a
|
||||
first-time grant survive a fluke without tolerating a persistently
|
||||
unlistable catalog for any longer than before.
|
||||
"""
|
||||
try:
|
||||
return database.get_all_schema_names(catalog=catalog, cache=False)
|
||||
except OAuth2RedirectError:
|
||||
# Not transient: retrying would just kick off a second, redundant
|
||||
# OAuth2 authorization redirect for the same request.
|
||||
raise
|
||||
except GenericDBException: # pylint: disable=broad-except
|
||||
return database.get_all_schema_names(catalog=catalog, cache=False)
|
||||
|
||||
|
||||
def add_permissions(database: Database) -> None:
|
||||
"""
|
||||
Add DAR for catalogs and schemas.
|
||||
@@ -179,7 +203,8 @@ def add_permissions(database: Database) -> None:
|
||||
|
||||
for catalog in catalogs:
|
||||
try:
|
||||
for schema in database.get_all_schema_names(catalog=catalog, cache=False):
|
||||
schemas = _get_all_schema_names_with_retry(database, catalog)
|
||||
for schema in schemas:
|
||||
security_manager.add_permission_view_menu(
|
||||
"schema_access",
|
||||
security_manager.get_schema_perm(
|
||||
|
||||
@@ -163,6 +163,14 @@ class ImportExamplesCommand(ImportModelsCommand):
|
||||
dataset_info: dict[str, dict[str, Any]] = {}
|
||||
for file_name, config in configs.items():
|
||||
if file_name.startswith("datasets/"):
|
||||
# Some examples ship a dataset config for a table that another
|
||||
# example already defines (same uuid, re-exported under a
|
||||
# different folder). Import each uuid once per run --
|
||||
# reimporting it just repeats the same column/metric sync
|
||||
# against an identical config.
|
||||
if config["uuid"] in dataset_info:
|
||||
continue
|
||||
|
||||
# find the ID of the corresponding database
|
||||
if config["database_uuid"] not in database_ids:
|
||||
raise Exception( # pylint: disable=broad-exception-raised
|
||||
|
||||
@@ -42,6 +42,12 @@ NO_TIME_RANGE = "No filter"
|
||||
|
||||
QUERY_CANCEL_KEY = "cancel_query"
|
||||
QUERY_EARLY_CANCEL_KEY = "early_cancel_query"
|
||||
# Set once execute_sql_statements() has opened a DB connection and asked the
|
||||
# engine spec for a cancel handle, regardless of whether one came back. Lets
|
||||
# cancel_query() tell "hasn't been dispatched to the engine yet" (safe to
|
||||
# fabricate a stop) apart from "this engine just has no cancel support"
|
||||
# (must fail honestly) when no cancel ID is on record.
|
||||
QUERY_DISPATCHED_KEY = "query_dispatched"
|
||||
|
||||
LRU_CACHE_MAX_SIZE = 256
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ from superset.queries.filters import QueryFilter
|
||||
from superset.queries.saved_queries.filters import SavedQueryFilter
|
||||
from superset.utils.core import get_user_id
|
||||
from superset.utils.dates import now_as_float
|
||||
from superset.utils.decorators import transaction
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -59,6 +60,7 @@ class QueryDAO(BaseDAO[Query]):
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@transaction()
|
||||
def stop_query(client_id: str) -> None:
|
||||
query = (
|
||||
db.session.query(Query)
|
||||
@@ -81,6 +83,11 @@ class QueryDAO(BaseDAO[Query]):
|
||||
if not sql_lab.cancel_query(query):
|
||||
raise SupersetCancelQueryException("Could not cancel query")
|
||||
|
||||
# cancel_query() may have staged an early-cancel flag on query.extra
|
||||
# without committing it (see its docstring/comments); the
|
||||
# @transaction decorator commits it together with status=STOPPED
|
||||
# below in one transaction, closing the window where another
|
||||
# request could observe the flag set but the status still RUNNING.
|
||||
query.status = QueryStatus.STOPPED
|
||||
query.end_time = now_as_float()
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user