superset icon indicating copy to clipboard operation
superset copied to clipboard

feat: Dynamic currency

Open richardfogaca opened this issue 11 months ago • 29 comments

SUMMARY

Adds dynamic currency detection for chart formatting. When a metric's currency is set to "Auto-detect", Superset queries the dataset's designated currency code column to determine the appropriate currency symbol.

How it works:

  • Dataset owners configure a currency_code_column (e.g., a column containing "USD", "EUR", "GBP")
  • When building a chart, users select "Auto-detect" in the currency format dropdown
  • Backend detects the currency from filtered data:
    • Single currency → formats with that currency symbol
    • Mixed currencies → falls back to neutral numeric formatting

Key changes:

Backend:

  • Added currency_code_column field to SqlaTable model with DB migration
  • Added detect_currency() utility that queries distinct currencies from filtered data
  • Integrated currency detection into both QueryContext API and legacy viz API
  • Returns detected_currency in API response for frontend consumption

Frontend:

  • Added "Auto-detect" option to CurrencyControl (only shown when dataset has currency_code_column)
  • Updated chart plugins to handle AUTO currency resolution: Timeseries, MixedTimeseries, BigNumber variants, Table, PivotTable, Heatmap, Sunburst, Treemap, Pie, Funnel, Gauge
  • Refactored DatasourceEditor: moved main_dttm_col from inline radio buttons to a new "Default Column Settings" section alongside currency_code_column

Example data:

  • Added international_sales example dataset demonstrating multi-currency transactions across regions

BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF

N/A - Requires screenshot of:

  • Currency code column Screenshot 2025-12-01 at 20 29 36

  • Currency control dropdown with "Auto-detect" option + Chart displaying auto-detected currency formatting Screenshot 2025-12-01 at 20 19 54 (1)

    TESTING INSTRUCTIONS

    1. Open the international_sales dataset and set "Currency code column" to currency_code
    2. Create a new chart (e.g., Big Number Total) using this dataset
    3. Select a numeric metric (e.g., revenue)
    4. In the "Number Format" section, set currency to "Auto-detect"
    5. Apply filters to show single-currency data (e.g., filter by country = USA)
    6. Verify the chart displays USD formatting
    7. Change filter to show mixed currencies (e.g., all countries)
    8. Verify the chart falls back to neutral number formatting

    ADDITIONAL INFORMATION

    • [ ] Has associated issue:
    • [ ] Required feature flags:
    • [x] Changes UI
    • [x] Includes DB Migration (follow approval process in SIP-193)
      • [x] Migration is atomic, supports rollback & is backwards-compatible
      • [x] Confirm DB migration upgrade and downgrade tested
      • [ ] Runtime estimates and downtime expectations provided
    • [x] Introduces new feature or API
    • [ ] Removes existing feature or API

CodeAnt-AI Description

Auto-detect currency from dataset and per-row for chart formatting

What Changed

  • Charts can use "Auto-detect" currency: when a dataset defines a currency code column, selecting Auto-detect formats values with the dataset’s currency (or a per-row currency for tables/pivot tables) instead of a fixed symbol.
  • Table and PivotTable now perform per-cell currency detection when Auto-detect is selected and the currency column is included in query results; mixed-currency rows fall back to neutral numeric formatting.
  • The backend returns a detected_currency value for chart queries; other chart types (timeseries, big number, pie, heatmap, treemap, gauge, etc.) use this dataset-level detection as a fallback when per-row data is not available.
  • Currency selector in controls shows an "Auto-detect" option only when the current dataset has a configured currency code column and moves that option to the top of the list.
  • Dataset editor exposes a "Default Column Settings" area to pick the currency code column (string columns only) and stores it on datasets; a DB migration and example dataset demonstrating multi-currency data were added.
  • Currency formatting behavior: AUTO mode now uses row context when available, then backend-detected currency, and finally neutral formatting for mixed or missing currencies; numerous tests added to cover these cases.

Impact

✅ Clearer currency symbols in charts when dataset provides a currency column ✅ Fewer mixed-currency formatting errors (mixed rows now show neutral numbers) ✅ Auto-detect option only appears when it will work for the selected dataset

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

richardfogaca avatar Dec 04 '25 01:12 richardfogaca

CodeAnt AI is reviewing your PR.

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • [ ] Intl.RangeError risk
    Calls to getCurrencySymbol(this.currency) use the currency.symbol value directly as the Intl currency code. If that value is invalid (not a valid ISO 4217 code) Intl.NumberFormat may throw a RangeError. The non-AUTO path has no try/catch or validation and can crash at runtime.

  • [ ] Null/undefined value handling
    The formatter interface allows value to be null/undefined but the implementation (format) expects a number and immediately passes it to a number formatter. If callers pass null/undefined the formatter may throw or produce invalid output. The implementation should guard/coerce value before formatting.

  • [ ] Detected currency validation
    detectedCurrency is used if truthy, but backend could return unexpected values (arrays, 'MIXED', null, lowercase, etc.). The frontend should validate the detected value (e.g., ensure it's a single ISO currency code) and fall back to neutral formatting for mixed/invalid results to avoid incorrect currency formatting.

  • [ ] Currency object shape
    The code sets resolvedCurrency = { ...currency, symbol: detectedCurrency }. Ensure that CurrencyFormatter accepts symbol being an ISO currency code string here; if the Currency type expects other keys (e.g., code, locale, or symbol with different semantics), this can produce incorrect formatting or runtime errors. Confirm the type/shape and mapping between detected value and CurrencyFormatter expectations.

  • [ ] CurrencyFormatter type mismatch
    The new code passes resolvedCurrency into CurrencyFormatter (as currency) and into buildCustomFormatters. Verify resolvedCurrency shape matches what these APIs expect (string currency code vs. currency object with symbol/code). If shapes differ, formatting could be incorrect or runtime errors may appear. Also ensure resolveAutoCurrency returns consistent structure for primary and secondary series.

  • [ ] buildCustomFormatters signature change
    buildCustomFormatters is now called with extra params (resolvedCurrency, data1, currencyCodeColumn). Ensure the function signature and behaviour have been updated accordingly and that these are used only when available to avoid undefined propagation.

  • [ ] Memoization staleness
    processColumns is memoized with a custom equality function (isEqualColumns). New inputs (dataset currencyCodeColumn and the backend detected_currency) affect the returned column formatters but may not be considered by the current memoization comparator, causing stale formatter/column outputs when the detected currency changes. Verify the memoization comparator covers these new fields or remove/adjust it so changes to detection trigger recomputation.

  • [ ] Formatting behavior / assumption
    The AUTO currency handling depends on currencyFormat having symbol === 'AUTO' and the aggregator exposing currencies per-cell. Verify the UI/backend contract: ensure that when currencyFormat.symbol is 'AUTO' the dataset actually provides currencyCodeColumn, that aggregators are instrumented to collect currencies, and that detectedCurrency fallback logic uses the intended server-provided value. Confirm behavior for mixed/null currency values.

  • [ ] Possible Bug
    The query object uses the key "filter" but Superset's Query object typically expects "filters" (plural). If the underlying datasource.query expects "filters", the query will ignore provided filters and may return wrong results (or a full table scan). Confirm the expected query object schema and make the key consistent with consumers.

  • [ ] Assumption about currency_format shape
    _detect_currency expects self.form_data["currency_format"] to be a dict with a symbol key. If currency_format has a different shape (e.g. a string or a legacy format), the AUTO check may silently skip detection. Validate or normalize currency_format shape before checking symbol to avoid missed detection or unexpected behavior.

  • [ ] Cache inconsistency
    The detected currency is added to the payload but is not stored in the data cache (get_df_payload stores only {"df": df, "query": self.query}). When serving from cache, detected_currency is not part of cache_value and may be recomputed (causing extra queries) or differ from what the cached df represents. The detection result should be cached alongside the dataframe (or factored into the cache key) to avoid re-detection and ensure consistency between cached df and reported detected currency.

  • [ ] Performance / Duplicate Query
    The newly added _detect_currency helper likely issues an additional query to the datasource (via the shared detect_currency utility) even though get_payload() already obtains the dataframe for the same query. This can double the query cost and add latency for charts using AUTO currency. Prefer detecting currency from the already-fetched df when possible and only fall back to detect_currency() when the dataframe does not contain the configured currency column or the detection requires a separate query.

  • [ ] Currency auto-detect context missing
    The change appears to support passing the aggregator to format, likely to enable row-level currency auto-detection. However, there is no row/row-data context being passed (only agg), so formatters that need the original row object or a currency column value may still lack the necessary context. Investigate how row-level information should be provided to the formatter (e.g., supplying raw row data or keys) so AUTO currency detection can be accurate.

  • [ ] Formatter argument ordering
    getValueFormatter is now called with additional args (undefined, data, currencyCodeColumn, detectedCurrency). Ensure this matches the expected parameter order for all call sites; a mismatch can produce incorrect formatting or silent failures.

  • [ ] Possible Format Signature Mismatch
    The new calls pass the aggregator object as a second argument to agg.format(aggValue, agg). Verify all aggregator implementations (including fallback aggregator returned by getAggregator) accept a second argument. If any aggregator's format implementation ignores extra args or expects a different shape, this may cause inconsistent formatting or unexpected behavior. Also ensure any custom aggregators written elsewhere in the codebase are updated to accept the new second argument if they rely on it.

  • [ ] Memory / duplicate growth
    Each aggregator now pushes seen currency codes into plain arrays (e.g. this.currencies.push(...)) without deduplication or bounds. For large datasets or high-cardinality result sets these arrays will grow unbounded and contain many duplicates, increasing memory usage and slowing get/dedup operations later.

CodeAnt AI finished reviewing your PR.

Codecov Report

:x: Patch coverage is 27.33813% with 101 lines in your changes missing coverage. Please review. :white_check_mark: Project coverage is 67.73%. Comparing base (4f3403b) to head (2a9bafe). :warning: Report is 215 commits behind head on master.

Files with missing lines Patch % Lines
superset/examples/international_sales.py 0.00% 43 Missing :warning:
superset/utils/currency.py 26.00% 35 Missing and 2 partials :warning:
superset/common/query_actions.py 58.82% 6 Missing and 1 partial :warning:
superset/common/query_context_factory.py 53.33% 6 Missing and 1 partial :warning:
superset/cli/examples.py 0.00% 2 Missing :warning:
superset/connectors/sqla/models.py 50.00% 2 Missing :warning:
superset/views/core.py 0.00% 2 Missing :warning:
superset/examples/data_loading.py 0.00% 1 Missing :warning:
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #36416       +/-   ##
===========================================
+ Coverage        0   67.73%   +67.73%     
===========================================
  Files           0      644      +644     
  Lines           0    48214    +48214     
  Branches        0     5284     +5284     
===========================================
+ Hits            0    32660    +32660     
- Misses          0    14263    +14263     
- Partials        0     1291     +1291     
Flag Coverage Δ
hive 42.76% <14.38%> (?)
mysql 65.76% <27.33%> (?)
postgres 65.81% <27.33%> (?)
presto 46.36% <25.17%> (?)
python 67.70% <27.33%> (?)
sqlite 65.53% <27.33%> (?)
unit 100.00% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

codecov[bot] avatar Dec 04 '25 02:12 codecov[bot]

CodeAnt AI is running Incremental review

CodeAnt AI is running Incremental review

CodeAnt AI is running Incremental review

@richardfogaca let's change the label in the dropdown from "Auto-detect from dataset" to "Auto-detect" so that it fits nicely :)

kasiazjc avatar Dec 05 '25 12:12 kasiazjc

Hi @kasiazjc, sorry that screenshot is outdated, I have already updated the label to "Auto-detect" all good, thanks! :)

richardfogaca avatar Dec 05 '25 12:12 richardfogaca

Hi @kasiazjc, sorry that screenshot is outdated, I have already updated the label to "Auto-detect" all good, thanks! :)

perfect, thank you! 🫶

kasiazjc avatar Dec 05 '25 12:12 kasiazjc

Taking a look, but just wanted to mention that this is a really big PR... next time it would be better to use stacked diffs to make the review easier and faster. 😄

betodealmeida avatar Dec 05 '25 15:12 betodealmeida

CodeAnt AI is running Incremental review

Hi @betodealmeida, I didn't know about that. It does seem quite helpful for these cases, I'll make sure I use it next time. Thanks for the tip

richardfogaca avatar Dec 05 '25 20:12 richardfogaca

🎪 Showtime is building environment on GHA for f0165e5

github-actions[bot] avatar Dec 08 '25 18:12 github-actions[bot]

🎪 Showtime deployed environment on GHA for f0165e5

• Environment: http://44.255.20.214:8080 (admin/admin) • Lifetime: 48h auto-cleanup • Updates: New commits create fresh environments automatically

github-actions[bot] avatar Dec 08 '25 18:12 github-actions[bot]

CodeAnt AI is running Incremental review

🎪 Showtime is building environment on GHA for 5b992bb

github-actions[bot] avatar Dec 09 '25 01:12 github-actions[bot]

🎪 Showtime is building environment on GHA for 5b992bb

github-actions[bot] avatar Dec 09 '25 01:12 github-actions[bot]

🎪 Showtime deployed environment on GHA for 5b992bb

• Environment: http://35.162.7.251:8080 (admin/admin) • Lifetime: 48h auto-cleanup • Updates: New commits create fresh environments automatically

github-actions[bot] avatar Dec 09 '25 01:12 github-actions[bot]

🎪 Showtime is building environment on GHA for 5b992bb

github-actions[bot] avatar Dec 11 '25 22:12 github-actions[bot]