Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Support multi series bar charts in explorer and chart-bar (#49241)

Joshen Lim6fd48944a8a8
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx
index b8eb3785b0e..e093b3c2ddc 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/DisplaySettingsButton.tsx
@@ -18,11 +18,18 @@ import {
TooltipTrigger,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import {
+ MultiSelector,
+ MultiSelectorContent,
+ MultiSelectorItem,
+ MultiSelectorList,
+ MultiSelectorTrigger,
+} from 'ui-patterns/multi-select'
import { ExplorerToolbarAction } from '../ExplorerToolbar'
import { type QueryDisplay, type QueryResult } from '../types'
import { checkHasNonPositiveValues } from '@/components/ui/QueryBlock/QueryBlock.utils'
-import { type ChartConfig } from '@/data/content/notebooks/notebook-schema'
+import { MAX_CHART_Y_COLUMNS, type ChartConfig } from '@/data/content/notebooks/notebook-schema'
interface DisplaySettingsButtonProps {
display: QueryDisplay
@@ -32,9 +39,11 @@ interface DisplaySettingsButtonProps {
onChange: (display: QueryDisplay) => void
}
-// [Joshen] TODO support multiple y axis charts
-// [Joshen] TODO onUpdateChartConfig can likely be shifted into the notebook-state
-// so this component doesn't need to know about other cells
+const getLogScaleDisabledReason = (y_columns: string[]) => {
+ if (y_columns.length === 0) return 'Select a column for the Y axis first'
+ if (y_columns.length > 1) return 'Only available with a single Y axis column'
+ return 'Data contains zero or negative values'
+}
export const DisplaySettingsButton = ({
display,
@@ -58,8 +67,9 @@ export const DisplaySettingsButton = ({
[result, y_columns]
)
+ // Logarithmic scale only applies to a single series.
const canToggleLogScale = useMemo(() => {
- if (y_columns.length === 0 || !result || (result.rows ?? []).length === 0) return false
+ if (y_columns.length !== 1 || !result || (result.rows ?? []).length === 0) return false
return !hasNonPositiveValues
}, [hasNonPositiveValues, result, y_columns.length])
@@ -87,17 +97,17 @@ export const DisplaySettingsButton = ({
})
useEffect(() => {
- if (hasNonPositiveValues && scale === 'log') {
+ if (scale === 'log' && (hasNonPositiveValues || y_columns.length > 1)) {
resetToLinearScale()
}
- }, [hasNonPositiveValues, scale])
+ }, [hasNonPositiveValues, scale, y_columns.length])
return (
<Popover>
<PopoverTrigger asChild>
<ExplorerToolbarAction disabled={disabled} icon={<Settings2 />} tooltip="Result settings" />
</PopoverTrigger>
- <PopoverContent side="bottom" className="flex flex-col gap-y-3 p-0 py-3 mr-8">
+ <PopoverContent side="bottom" className="flex flex-col gap-y-3 p-0 py-3 mr-8 w-80">
<div className="flex flex-col gap-y-3 px-3">
<p className="text-xs tracking-tighter uppercase font-mono text-foreground-lighter">
Result display settings
@@ -147,12 +157,17 @@ export const DisplaySettingsButton = ({
</FormItemLayout>
<div className="px-3 flex flex-col gap-y-2">
- <FormItemLayout isReactForm={false} layout="flex-row-reverse" label="X axis">
+ <FormItemLayout
+ isReactForm={false}
+ layout="flex-row-reverse"
+ label="X axis"
+ className="[&>div:first-child]:xl:w-3/5"
+ >
<Select
value={x_column}
onValueChange={(x_column) => onUpdateChartConfig({ x_column })}
>
- <SelectTrigger className="w-32">
+ <SelectTrigger className="w-full">
<SelectValue placeholder="Select a column" />
</SelectTrigger>
<SelectContent>
@@ -165,32 +180,59 @@ export const DisplaySettingsButton = ({
</Select>
</FormItemLayout>
- <FormItemLayout isReactForm={false} layout="flex-row-reverse" label="Y Axis">
- <Select
- value={y_columns?.[0]}
- onValueChange={(y_column) => onUpdateChartConfig({ y_columns: [y_column] })}
+ <FormItemLayout
+ isReactForm={false}
+ layout="flex-row-reverse"
+ label="Y Axis"
+ className="[&>div:first-child]:xl:w-3/5"
+ >
+ <MultiSelector
+ values={y_columns}
+ onValuesChange={(values) => {
+ if (values.length > MAX_CHART_Y_COLUMNS) return
+ onUpdateChartConfig({ y_columns: values })
+ }}
+ className="w-full"
>
- <SelectTrigger className="w-32">
- <SelectValue placeholder="Select a column" />
- </SelectTrigger>
- <SelectContent>
- {columns.map((x) => (
- <SelectItem key={x} value={x}>
- {x}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
+ <MultiSelectorTrigger
+ mode="inline-combobox"
+ label={`Select up to ${MAX_CHART_Y_COLUMNS} columns`}
+ deletableBadge
+ badgeLimit="wrap"
+ showIcon={false}
+ className="min-w-32!"
+ />
+ <MultiSelectorContent>
+ <MultiSelectorList>
+ {columns.map((x) => (
+ <MultiSelectorItem
+ key={x}
+ value={x}
+ disabled={
+ y_columns.length >= MAX_CHART_Y_COLUMNS && !y_columns.includes(x)
+ }
+ >
+ {x}
+ </MultiSelectorItem>
+ ))}
+ </MultiSelectorList>
+ </MultiSelectorContent>
+ </MultiSelector>
</FormItemLayout>
- <FormItemLayout isReactForm={false} layout="flex-row-reverse" label="Scale">
+ <FormItemLayout
+ isReactForm={false}
+ layout="flex-row-reverse"
+ label="Scale"
+ className="[&>div:first-child]:xl:w-3/5"
+ >
<Select
value={scale}
onValueChange={(scale) =>
onUpdateChartConfig({ scale: scale as 'log' | 'linear' })
}
>
- <SelectTrigger className="w-32">
+ <SelectTrigger className="w-full">
<SelectValue placeholder="Select a column" />
</SelectTrigger>
<SelectContent>
@@ -207,9 +249,7 @@ export const DisplaySettingsButton = ({
</TooltipTrigger>
{!canToggleLogScale && (
<TooltipContent side="left">
- {y_columns.length === 0
- ? 'Select a column for the Y axis first'
- : 'Data contains zero or negative values'}
+ {getLogScaleDisabledReason(y_columns)}
</TooltipContent>
)}
</Tooltip>
diff --git a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx
index 7028ca31168..55c13a34c31 100644
--- a/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx
+++ b/apps/studio/components/interfaces/Explorer/QueryEditor/QueryResultChart.tsx
@@ -1,4 +1,5 @@
import { useMemo } from 'react'
+import { type ChartConfig as ChartSeriesConfig } from 'ui'
import { Chart, ChartBar, ChartCard, ChartContent, ChartLine } from 'ui-patterns/Chart'
import { type QueryResult } from '../types'
@@ -11,8 +12,11 @@ interface QueryResultChartProps {
result?: QueryResult
}
-// [Joshen] Will need to implement log scale - refer to QueryBlock.tsx `effectiveLogScale`
-// [Joshen] Will also need to implement error handling where appropriate (e.g if query errors)
+const Y_COLUMN_COLORS = [
+ 'hsl(var(--brand-default))',
+ 'hsl(var(--chart-blue))',
+ 'hsl(var(--chart-3))',
+]
const toChartValue = (value: unknown): string | number => {
if (typeof value === 'number' || typeof value === 'string') return value
@@ -24,17 +28,32 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {
const { type, x_column, y_columns = [], cumulative, show_labels, scale } = chart ?? {}
const hasConfig = !!x_column && y_columns.length > 0
+ // Logarithmic scale only makes sense for a single series — DisplaySettingsButton
+ // resets `scale` to linear once a second Y column is added
+ const effectiveScale = y_columns.length > 1 ? 'linear' : scale
+
+ const chartConfig: ChartSeriesConfig = useMemo(
+ () =>
+ y_columns.reduce((acc, key, index) => {
+ acc[key] = { label: key, color: Y_COLUMN_COLORS[index] }
+ return acc
+ }, {} as ChartSeriesConfig),
+ [y_columns]
+ )
+
const chartRows = useMemo(() => {
const xKey = x_column ?? ''
- const yKey = y_columns[0] ?? ''
- return (result?.rows ?? []).map((row) => ({
- [xKey]: toChartValue(row[xKey]),
- [yKey]: toChartValue(row[yKey]),
- }))
+ return (result?.rows ?? []).map((row) => {
+ const chartRow: Record<string, string | number> = { [xKey]: toChartValue(row[xKey]) }
+ y_columns.forEach((yKey) => {
+ chartRow[yKey] = toChartValue(row[yKey])
+ })
+ return chartRow
+ })
}, [result, x_column, y_columns])
const cumulativeResults = useMemo(
- () => getCumulativeResults({ rows: chartRows }, { yKey: y_columns[0] ?? '' }),
+ () => getCumulativeResults({ rows: chartRows }, { yKey: y_columns }),
[chartRows, y_columns]
)
const resultToRender = cumulative ? cumulativeResults : chartRows
@@ -71,13 +90,15 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {
isFullHeight
xKey={x_column}
dataKey={y_columns[0]}
+ dataKeys={y_columns}
+ config={chartConfig}
showXAxis={show_labels}
showYAxis={show_labels}
data={resultToRender}
YAxisProps={{
- scale: scale === 'log' ? 'log' : 'auto',
- domain: scale === 'log' ? [1, 'auto'] : undefined,
- tickFormatter: scale === 'log' ? formatLogTick : undefined,
+ scale: effectiveScale === 'log' ? 'log' : 'auto',
+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,
+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,
}}
/>
)}
@@ -86,13 +107,15 @@ export const QueryResultChart = ({ chart, result }: QueryResultChartProps) => {
isFullHeight
xKey={x_column}
dataKey={y_columns[0]}
+ dataKeys={y_columns}
+ config={chartConfig}
showXAxis={show_labels}
showYAxis={show_labels}
data={resultToRender}
YAxisProps={{
- scale: scale === 'log' ? 'log' : 'auto',
- domain: scale === 'log' ? [1, 'auto'] : undefined,
- tickFormatter: scale === 'log' ? formatLogTick : undefined,
+ scale: effectiveScale === 'log' ? 'log' : 'auto',
+ domain: effectiveScale === 'log' ? [1, 'auto'] : undefined,
+ tickFormatter: effectiveScale === 'log' ? formatLogTick : undefined,
}}
/>
)}
diff --git a/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts b/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts
index 19fec3bbd95..25a25f2212c 100644
--- a/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts
+++ b/apps/studio/components/ui/QueryBlock/QueryBlock.utils.ts
@@ -49,21 +49,23 @@ export const formatLogTick = (value: number): string => {
export const getCumulativeResults = (
results: { rows: readonly any[] },
- config: { yKey: string }
+ config: { yKey: string | string[] }
) => {
if (!results?.rows?.length) {
return []
}
+ const yKeys = Array.isArray(config.yKey) ? config.yKey : [config.yKey]
+
const cumulativeResults = results.rows.reduce((acc, row) => {
const prev = acc[acc.length - 1] || {}
- // Coerce to Number before adding: Postgres returns `bigint`, `numeric`,
- // `money` and `count(*)` columns as strings, so a bare `+` would
- // concatenate (e.g. "10" + "20" -> "1020") instead of summing.
- const next = {
- ...row,
- [config.yKey]: (Number(prev[config.yKey]) || 0) + (Number(row[config.yKey]) || 0),
- }
+ const next = { ...row }
+ yKeys.forEach((yKey) => {
+ // Coerce to Number before adding: Postgres returns `bigint`, `numeric`,
+ // `money` and `count(*)` columns as strings, so a bare `+` would
+ // concatenate (e.g. "10" + "20" -> "1020") instead of summing.
+ next[yKey] = (Number(prev[yKey]) || 0) + (Number(row[yKey]) || 0)
+ })
return [...acc, next]
}, [])
diff --git a/apps/studio/data/content/notebooks/notebook-schema.ts b/apps/studio/data/content/notebooks/notebook-schema.ts
index 8a1e1332ed6..65c2539cfc5 100644
--- a/apps/studio/data/content/notebooks/notebook-schema.ts
+++ b/apps/studio/data/content/notebooks/notebook-schema.ts
@@ -14,10 +14,12 @@ const isoDateTimeSchema = z.string().transform((raw, ctx) => {
return parsed
})
+export const MAX_CHART_Y_COLUMNS = 3
+
const chartConfigSchema = z.object({
type: z.enum(['bar', 'line']),
x_column: z.string(),
- y_columns: z.array(z.string()),
+ y_columns: z.array(z.string()).max(MAX_CHART_Y_COLUMNS),
cumulative: z.boolean(),
scale: z.enum(['linear', 'log']).default('linear'),
show_labels: z.boolean(),
diff --git a/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts b/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts
index a5af0a97f54..a2d5ceb372d 100644
--- a/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts
+++ b/apps/studio/tests/components/ui/QueryBlock/QueryBlock.utils.test.ts
@@ -109,6 +109,22 @@ describe('getCumulativeResults', () => {
])
})
+ it('accumulates each key independently when yKey is an array', () => {
+ const results = {
+ rows: [
+ { x: 'a', y1: 10, y2: 1 },
+ { x: 'b', y1: 20, y2: 2 },
+ { x: 'c', y1: 5, y2: 3 },
+ ],
+ }
+ const output = getCumulativeResults(results, { yKey: ['y1', 'y2'] })
+ expect(output).toEqual([
+ { x: 'a', y1: 10, y2: 1 },
+ { x: 'b', y1: 30, y2: 3 },
+ { x: 'c', y1: 35, y2: 6 },
+ ])
+ })
+
it('preserves other keys on each row', () => {
const results = {
rows: [
diff --git a/packages/ui-patterns/src/Chart/charts/chart-bar.tsx b/packages/ui-patterns/src/Chart/charts/chart-bar.tsx
index e81034adabb..7367ca8efb8 100644
--- a/packages/ui-patterns/src/Chart/charts/chart-bar.tsx
+++ b/packages/ui-patterns/src/Chart/charts/chart-bar.tsx
@@ -51,6 +51,7 @@ export interface ChartBarProps {
data: ChartBarTick[]
xKey?: string
dataKey: string
+ dataKeys?: string[]
config?: ChartConfig
onBarClick?: (datum: ChartBarTick, tooltipData?: CategoricalChartState) => void
DateTimeFormat?: string
@@ -80,6 +81,7 @@ export const ChartBar = ({
data,
xKey = 'timestamp',
dataKey,
+ dataKeys,
config,
onBarClick,
DateTimeFormat = 'MMM D, YYYY, hh:mma',
@@ -104,11 +106,15 @@ export const ChartBar = ({
return null
}
- const chartConfig: ChartConfig = config || {
- [dataKey]: {
- label: dataKey,
- },
- }
+ const keysToRender = dataKeys || [dataKey]
+ const isMultiSeries = keysToRender.length > 1
+
+ const chartConfig: ChartConfig =
+ config ||
+ keysToRender.reduce((acc, key) => {
+ acc[key] = { label: key }
+ return acc
+ }, {} as ChartConfig)
const showHighlightActions =
showHighlightArea &&
@@ -225,15 +231,29 @@ export const ChartBar = ({
fillOpacity={0.2}
/>
)}
- <Bar dataKey={dataKey} fill={color} maxBarSize={24}>
- {data?.map((_entry: ChartBarTick, index: number) => (
- <Cell
- className="cursor-pointer transition-colors"
- key={`bar-${index}`}
- fill={focusDataIndex === index || focusDataIndex === null ? color : hoverColor}
- />
- ))}
- </Bar>
+ {isMultiSeries ? (
+ keysToRender.map((key) => {
+ const keyConfig = chartConfig[key]
+ const barColor =
+ keyConfig?.color ||
+ (keyConfig?.theme
+ ? isDarkMode
+ ? keyConfig.theme.dark
+ : keyConfig.theme.light
+ : color)
+ return <Bar key={key} dataKey={key} fill={barColor} maxBarSize={24} />
+ })
+ ) : (
+ <Bar dataKey={dataKey} fill={color} maxBarSize={24}>
+ {data?.map((_entry: ChartBarTick, index: number) => (
+ <Cell
+ className="cursor-pointer transition-colors"
+ key={`bar-${index}`}
+ fill={focusDataIndex === index || focusDataIndex === null ? color : hoverColor}
+ />
+ ))}
+ </Bar>
+ )}
</RechartBarChart>
</ChartContainer>