The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
fix(studio): key query chart series by position, not column name (#50270)
Sean Oliver32f17f994d1d
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.test.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.test.tsxnew file mode 100644index 00000000000..277d7691173--- /dev/null+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.test.tsx@@ -0,0 +1,123 @@+import { describe, expect, it } from 'vitest'++import { QueryResultChart, xKeyFor } from './QueryResultChart'+import { customRender } from '@/tests/lib/custom-render'++const CUSTOMER_COLUMN = 'customer_email_address'++const chart = {+ type: 'bar' as const,+ x_column: 'day',+ y_series: [CUSTOMER_COLUMN],+ cumulative: false,+ show_labels: true,+ scale: 'linear' as const,+}++const result = {+ rows: [+ { day: '2026-01-01', [CUSTOMER_COLUMN]: 4 },+ { day: '2026-01-02', [CUSTOMER_COLUMN]: 7 },+ ],+}++const styleTextOf = (container: HTMLElement) =>+ Array.from(container.querySelectorAll('style'))+ .map((style) => style.textContent ?? '')+ .join('\n')++/**+ * `ChartContainer` writes every config key into a `<style>` element as `--color-<key>`,+ * and rrweb records `<style>` text without masking it, so a config keyed by column name+ * would put customer column names into a recording.+ */+describe('QueryResultChart column names in CSS', () => {+ it.each([+ ['bar', false],+ ['line', false],+ ['bar', true],+ ['line', true],+ ])('keys the style by position for type=%s cumulative=%s', (type, cumulative) => {+ const { container } = customRender(+ <QueryResultChart+ chart={{ ...chart, type: type as 'bar' | 'line', cumulative }}+ result={result as never}+ />+ )++ const css = styleTextOf(container)+ expect(css).toContain('--color-series_0')+ expect(css).not.toContain(CUSTOMER_COLUMN)+ })++ it('emits one distinct series key per selected column', () => {+ const twoSeries = { ...chart, y_series: [CUSTOMER_COLUMN, 'customer_plan'] }+ const rows = result.rows.map((row) => ({ ...row, customer_plan: 1 }))+ const { container } = customRender(+ <QueryResultChart chart={twoSeries} result={{ rows } as never} />+ )++ // ChartStyle emits one block per theme, so count distinct keys rather than matches.+ const seriesKeys = new Set(styleTextOf(container).match(/--color-series_\d+/g))+ expect(seriesKeys.size).toBe(twoSeries.y_series.length)+ expect(styleTextOf(container)).not.toContain('customer_plan')+ })++ it('leaves the X column name alone, which ChartBar and ChartLine check for "timestamp"', () => {+ const timestampChart = { ...chart, x_column: 'timestamp' }+ const rows = [+ { timestamp: '2026-01-01T00:00:00Z', [CUSTOMER_COLUMN]: 4 },+ { timestamp: '2026-01-02T00:00:00Z', [CUSTOMER_COLUMN]: 7 },+ ]+ const { container } = customRender(+ <QueryResultChart chart={timestampChart} result={{ rows } as never} />+ )++ // The date-range footer only renders when xKey is literally 'timestamp'.+ expect(container.textContent).toContain('2026')+ expect(styleTextOf(container)).not.toContain(CUSTOMER_COLUMN)+ })++ it('renders with an X column named like a series key', () => {+ const colliding = { ...chart, x_column: 'series_0' }+ const rows = [+ { series_0: 'a', [CUSTOMER_COLUMN]: 4 },+ { series_0: 'b', [CUSTOMER_COLUMN]: 7 },+ ]+ const { container } = customRender(+ <QueryResultChart chart={colliding} result={{ rows } as never} />+ )++ expect(styleTextOf(container)).not.toContain(CUSTOMER_COLUMN)+ })+})++/**+ * Asserted directly rather than through a render. jsdom draws no bars or ticks at the+ * 0x0 size it gives the chart container, so a rendered collision is not observable and+ * the same assertions pass with the guard removed.+ */+describe('xKeyFor', () => {+ it('moves the X key off a colliding series key', () => {+ expect(xKeyFor('series_0', ['series_0'])).toBe('series_0_')+ })++ it('keeps appending until the X key is distinct', () => {+ expect(xKeyFor('series_0', ['series_0', 'series_0_'])).toBe('series_0__')+ })++ it('leaves a non-colliding X column alone', () => {+ expect(xKeyFor('timestamp', ['series_0', 'series_1'])).toBe('timestamp')+ expect(xKeyFor('day', [])).toBe('day')+ })++ it('cannot produce a key that collides again, since series keys carry no trailing underscore', () => {+ const seriesKeys = ['series_0', 'series_1', 'series_2']+ const result = xKeyFor('series_1', seriesKeys)+ expect(seriesKeys).not.toContain(result)+ })+})++// The column name still reaches the chart as `config[key].label`, which `chart.tsx`+// renders into the tooltip and legend as text. That path is not asserted here because+// recharts does not render either one at the 0x0 size jsdom gives the container.diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsxindex 760b3a994bd..32e018133a6 100644--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx@@ -29,6 +29,33 @@ const toChartValue = (value: unknown): string | number => {return String(value)}+/**+ * Y series are keyed by position rather than by the column name they came from.+ *+ * `ChartContainer` writes every config key into a `<style>` element as+ * `--color-<key>`, and rrweb records `<style>` text verbatim: its text-node serializer+ * skips masking whenever the parent is a `STYLE` element, so neither `maskTextFn` nor+ * `maskAttributeFn` sees it. Keying by column name would therefore put the customer's own+ * column names into a recording. The name still reaches the chart as `label`, which+ * renders as text and is masked.+ *+ * The X column keeps its own name. Only config keys reach the `<style>`, and the X column+ * is never a config key, so renaming it buys nothing. It also costs something: ChartBar+ * and ChartLine branch on `xKey === 'timestamp'` to format tooltip dates and render the+ * date-range footer.+ */+const seriesKeyFor = (index: number) => `series_${index}`++/**+ * Guards the one collision the positional keys introduce: an X column literally named+ * `series_0`. Appends underscores until the X key is distinct from every series key.+ */+export function xKeyFor(xColumn: string, seriesKeys: string[]): string {+ let key = xColumn+ while (seriesKeys.includes(key)) key = `${key}_`+ return key+}+export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {const { type, x_column, y_series = [], cumulative, show_labels, scale } = chart ?? {}@@ -37,35 +64,39 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {// resets `scale` to linear once a second Y column is addedconst effectiveScale = y_series.length > 1 ? 'linear' : scale+ const seriesKeys = useMemo(() => y_series.map((_, index) => seriesKeyFor(index)), [y_series])+const chartConfig: ChartSeriesConfig = useMemo(() =>- y_series.reduce((acc, key, index) => {- acc[key] = { label: key, color: Y_SERIES_COLORS[index] }+ y_series.reduce((acc, column, index) => {+ acc[seriesKeyFor(index)] = { label: column, color: Y_SERIES_COLORS[index] }return acc}, {} as ChartSeriesConfig),[y_series])+ const xKey = useMemo(() => xKeyFor(x_column ?? '', seriesKeys), [x_column, seriesKeys])+const chartRows = useMemo(() => {- const xKey = x_column ?? ''+ const sourceColumn = x_column ?? ''return (result?.rows ?? []).map((row) => {- const chartRow: Record<string, string | number> = { [xKey]: toChartValue(row[xKey]) }- y_series.forEach((yKey) => {- chartRow[yKey] = toChartValue(row[yKey])+ const chartRow: Record<string, string | number> = { [xKey]: toChartValue(row[sourceColumn]) }+ y_series.forEach((column, index) => {+ chartRow[seriesKeyFor(index)] = toChartValue(row[column])})return chartRow})- }, [result, x_column, y_series])+ }, [result, x_column, xKey, y_series])const cumulativeResults = useMemo(- () => getCumulativeResults({ rows: chartRows }, { yKey: y_series }),- [chartRows, y_series]+ () => getCumulativeResults({ rows: chartRows }, { yKey: seriesKeys }),+ [chartRows, seriesKeys])const resultToRender = cumulative ? cumulativeResults : chartRowsconst yAxisWidth = Math.max(36,- ...y_series.map((key) =>+ ...seriesKeys.map((key) =>computeYAxisWidth(resultToRender, key, { isLogScale: effectiveScale === 'log' })))@@ -106,9 +137,9 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {{type === 'bar' && (<ChartBarisFullHeight- xKey={x_column}- dataKey={y_series[0]}- dataKeys={y_series}+ xKey={xKey}+ dataKey={seriesKeys[0]}+ dataKeys={seriesKeys}config={chartConfig}showXAxis={show_labels}showYAxis={show_labels}@@ -119,9 +150,9 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {{type === 'line' && (<ChartLineisFullHeight- xKey={x_column}- dataKey={y_series[0]}- dataKeys={y_series}+ xKey={xKey}+ dataKey={seriesKeys[0]}+ dataKeys={seriesKeys}config={chartConfig}showXAxis={show_labels}showYAxis={show_labels}