Skip to content

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

feat: SQL Editor Charts (#21638)

Jordi Enric6fcb3c12540e
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index 0c1a6e9cdf3..25a7f8c00cf 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -20,6 +20,7 @@ import {
IconSettings,
IconX,
Input_Shadcn_,
+ Loading,
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
@@ -868,7 +869,11 @@ const SQLEditor = () => {
)}
{isLoading ? (
- <div className="flex h-full w-full items-center justify-center">Loading...</div>
+ <div className="flex h-full w-full items-center justify-center">
+ <Loading active={true}>
+ <></>
+ </Loading>
+ </div>
) : (
<>
{isDiffOpen && (
@@ -980,7 +985,11 @@ const SQLEditor = () => {
<ResizableHandle withHandle />
<ResizablePanel collapsible collapsedSize={10} minSize={20}>
{isLoading ? (
- <div className="flex h-full w-full items-center justify-center">Loading...</div>
+ <div className="flex h-full w-full items-center justify-center">
+ <Loading active={true}>
+ <></>
+ </Loading>
+ </div>
) : (
<UtilityPanel
id={id}
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx
new file mode 100644
index 00000000000..431a42ca8dc
--- /dev/null
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ChartConfig.tsx
@@ -0,0 +1,181 @@
+import BarChart from 'components/ui/Charts/BarChart'
+import NoDataPlaceholder from 'components/ui/Charts/NoDataPlaceholder'
+import dayjs from 'dayjs'
+import { ArrowUpDown } from 'lucide-react'
+import { useMemo } from 'react'
+import {
+ Button,
+ Checkbox_Shadcn_,
+ Label_Shadcn_,
+ ResizableHandle,
+ ResizablePanel,
+ ResizablePanelGroup,
+ SelectContent_Shadcn_,
+ SelectGroup_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ Select_Shadcn_,
+} from 'ui'
+
+type Results = { rows: readonly any[] }
+
+export type ChartConfig = {
+ type: 'bar' | 'line'
+ cumulative: boolean
+ xKey: string
+ yKey: string
+}
+
+const getCumulativeResults = (results: Results, config: ChartConfig) => {
+ if (!results?.rows?.length) {
+ return []
+ }
+
+ const cumulativeResults = results.rows.reduce((acc, row) => {
+ const prev = acc[acc.length - 1] || {}
+ const next = {
+ ...row,
+ [config.yKey]: (prev[config.yKey] || 0) + row[config.yKey],
+ }
+ return [...acc, next]
+ }, [])
+ return cumulativeResults
+}
+const VALID_RESULT_KEY_TYPES = ['number', 'string', 'date']
+
+type ChartConfigProps = {
+ results: Results
+ config: ChartConfig
+ onConfigChange: (config: ChartConfig) => void
+}
+export function ChartConfig({ results = { rows: [] }, config, onConfigChange }: ChartConfigProps) {
+ // If a result key is not valid, it will be filtered out
+ const resultKeys = useMemo(() => {
+ return Object.keys(results.rows[0] || {}).filter((key) => {
+ const type = typeof results.rows[0][key]
+ return VALID_RESULT_KEY_TYPES.includes(type)
+ })
+ }, [results])
+
+ // Compute cumulative results only if necessary
+ const cumulativeResults = useMemo(() => getCumulativeResults(results, config), [results, config])
+
+ const resultToRender = config.cumulative ? cumulativeResults : results.rows
+
+ if (!resultKeys.length) {
+ return (
+ <div className="p-2">
+ <NoDataPlaceholder
+ size="normal"
+ message="
+ Execute a query and configure the chart options.
+ "
+ />
+ </div>
+ )
+ }
+
+ const getDateFormat = (key: any) => {
+ const value = resultToRender[0][key]
+ if (typeof value === 'number') return 'number'
+ if (dayjs(value).isValid()) return 'date'
+ return 'string'
+ }
+
+ const xKeyDateFormat = getDateFormat(config.xKey)
+
+ return (
+ <ResizablePanelGroup direction="horizontal" className="flex-grow h-full">
+ <>
+ <ResizablePanel className="p-4 h-full" defaultSize={85}>
+ {config.type === 'bar' && (
+ <BarChart
+ showLegend
+ size="normal"
+ xAxisIsDate={xKeyDateFormat === 'date'}
+ data={resultToRender as any}
+ xAxisKey={config.xKey}
+ yAxisKey={config.yKey}
+ emptyStateMessage="Execute a query and configure the chart options"
+ />
+ )}
+ </ResizablePanel>
+ <ResizableHandle withHandle />
+ <ResizablePanel defaultSize={15} minSize={15} className="px-3 py-3 space-y-4">
+ <>
+ <div className="flex justify-between items-center h-5">
+ <h2 className="text-sm text-foreground-lighter">Chart options</h2>
+ {config.xKey && config.yKey && (
+ <Button
+ type="text"
+ onClick={() => {
+ const currentX = config.xKey
+ const currentY = config.yKey
+ onConfigChange({ ...config, xKey: currentY, yKey: currentX })
+ }}
+ title="Swap X and Y axis"
+ icon={<ArrowUpDown size="15" className="text-foreground-lighter" />}
+ >
+ Flip
+ </Button>
+ )}
+ </div>
+
+ <Select_Shadcn_
+ value={config.xKey}
+ onValueChange={(value) => {
+ onConfigChange({ ...config, xKey: value })
+ }}
+ >
+ <SelectTrigger_Shadcn_>
+ X Axis {config.xKey && `- ${config.xKey}`}
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectGroup_Shadcn_>
+ {resultKeys.map((key) => (
+ <SelectItem_Shadcn_ value={key} key={key}>
+ {key}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectGroup_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ <Select_Shadcn_
+ value={config.yKey}
+ onValueChange={(value) => {
+ onConfigChange({ ...config, yKey: value })
+ }}
+ >
+ <SelectTrigger_Shadcn_>
+ Y Axis {config.yKey && `- ${config.yKey}`}
+ </SelectTrigger_Shadcn_>
+ <SelectContent_Shadcn_>
+ <SelectGroup_Shadcn_>
+ {resultKeys.map((key) => (
+ <SelectItem_Shadcn_ value={key} key={key}>
+ {key}
+ </SelectItem_Shadcn_>
+ ))}
+ </SelectGroup_Shadcn_>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ <div className="flex items-center">
+ <Checkbox_Shadcn_
+ id="cumulative"
+ name="cumulative"
+ checked={config.cumulative}
+ onClick={(e) => {
+ console.log(e)
+ onConfigChange({ ...config, cumulative: !config.cumulative })
+ }}
+ />
+ <Label_Shadcn_ className="text-foreground-light p-1.5" htmlFor="cumulative">
+ Cumulative
+ </Label_Shadcn_>
+ </div>
+ </>
+ </ResizablePanel>
+ </>
+ </ResizablePanelGroup>
+ )
+}
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx
index 5b637ff2932..e3ed51c9bf6 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/Results.tsx
@@ -52,8 +52,9 @@ const Results = ({ id, rows }: { id: string; rows: readonly any[] }) => {
)
}
const columnRender = (name: string) => {
- return <div className="flex h-full items-center justify-center font-mono">{name}</div>
+ return <div className="flex h-full items-center justify-center font-mono text-xs">{name}</div>
}
+
const columns: CalculatedColumn<any>[] = Object.keys(rows?.[0] ?? []).map((key, idx) => ({
idx,
key,
@@ -90,7 +91,7 @@ const Results = ({ id, rows }: { id: string; rows: readonly any[] }) => {
columns={columns}
rows={rows}
// style={{ height: '100%' }}
- className="flex-grow"
+ className="flex-grow border-t-0"
rowClass={() => '[&>.rdg-cell]:items-center'}
onSelectedCellChange={onSelectedCellChange}
/>
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx
index 541e588aac3..6e7e25010df 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/ResultsDropdown.tsx
@@ -104,17 +104,28 @@ const ResultsDropdown = ({ id, isExecuting }: ResultsDropdownProps) => {
}
}
+ function onCopyAsJSON() {
+ if (navigator) {
+ if (!result || !result.rows) return 'results is empty'
+ if (result.rows.constructor !== Array && !!result.error) return result.error
+ if (result.rows.length == 0) return 'results is empty'
+
+ copyToClipboard(JSON.stringify(result.rows, null, 2), () => {
+ ui.setNotification({ category: 'success', message: 'Copied results to clipboard' })
+ Telemetry.sendEvent(
+ { category: 'sql_editor', action: 'sql_copy_as_json', label: '' },
+ telemetryProps,
+ router
+ )
+ })
+ }
+ }
+
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="text" iconRight={<IconChevronDown />}>
- <span>
- Results
- {!isExecuting &&
- result &&
- result.rows.length > 0 &&
- ` (${result.rows.length.toLocaleString()})`}
- </span>
+ Export
</Button>
</DropdownMenuTrigger>
@@ -136,6 +147,10 @@ const ResultsDropdown = ({ id, isExecuting }: ResultsDropdownProps) => {
<IconClipboard size="tiny" />
<p>Copy as markdown</p>
</DropdownMenuItem>
+ <DropdownMenuItem onClick={onCopyAsJSON} className="space-x-2">
+ <IconClipboard size="tiny" />
+ <p>Copy as JSON</p>
+ </DropdownMenuItem>
</>
</DropdownMenuContent>
</DropdownMenu>
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index 6ffc291b1b8..6e65ed72fc5 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -12,6 +12,7 @@ import {
IconCheck,
IconCommand,
IconCornerDownLeft,
+ IconLoader,
IconSettings,
Toggle_Shadcn,
TooltipContent_Shadcn_,
@@ -55,8 +56,6 @@ const UtilityActions = ({
return (
<div className="inline-flex items-center justify-end gap-x-2">
- <SavingIndicator id={id} />
-
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
@@ -105,18 +104,21 @@ const UtilityActions = ({
<Button
onClick={() => executeQuery()}
disabled={isDisabled || isExecuting}
- loading={isExecuting}
type="primary"
size="tiny"
iconRight={
- <div className="flex items-center space-x-1">
- {os === 'macos' ? (
- <IconCommand size={10} strokeWidth={1.5} />
- ) : (
- <p className="text-xs text-foreground-light">CTRL</p>
- )}
- <IconCornerDownLeft size={10} strokeWidth={1.5} />
- </div>
+ isExecuting ? (
+ <IconLoader className="animate-spin" size={10} strokeWidth={1.5} />
+ ) : (
+ <div className="flex items-center space-x-1">
+ {os === 'macos' ? (
+ <IconCommand size={10} strokeWidth={1.5} />
+ ) : (
+ <p className="text-xs text-foreground-light">CTRL</p>
+ )}
+ <IconCornerDownLeft size={10} strokeWidth={1.5} />
+ </div>
+ )
}
className="rounded-l-none"
>
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
index e6c9821552d..9d798eb2c86 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
@@ -1,6 +1,12 @@
+import { useState } from 'react'
import ResultsDropdown from './ResultsDropdown'
import UtilityActions from './UtilityActions'
import UtilityTabResults from './UtilityTabResults'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
+
+import { TabsContent_Shadcn_, TabsList_Shadcn_, TabsTrigger_Shadcn_, Tabs_Shadcn_ } from 'ui'
+import { ChartConfig } from './ChartConfig'
+import { useFlag } from 'hooks'
export type UtilityPanelProps = {
id: string
@@ -19,24 +25,59 @@ const UtilityPanel = ({
prettifyQuery,
executeQuery,
}: UtilityPanelProps) => {
+ const snap = useSqlEditorStateSnapshot()
+ const result = snap.results[id]?.[0]
+
+ const showCharts = useFlag('showSQLEditorCharts')
+
+ const [config, setConfig] = useState<ChartConfig>({
+ type: 'bar',
+ cumulative: false,
+ xKey: '',
+ yKey: '',
+ })
+
+ if (result?.error) {
+ return <div>{result.error}</div>
+ }
+
return (
- <>
- <div className="flex justify-between overflow-visible px-6 py-2 border-b">
- <ResultsDropdown id={id} isExecuting={isExecuting} />
- <UtilityActions
- id={id}
- isExecuting={isExecuting}
- isDisabled={isDisabled}
- hasSelection={hasSelection}
- prettifyQuery={prettifyQuery}
- executeQuery={executeQuery}
- />
- </div>
-
- <div className="flex-1 p-0 pt-0 pb-0">
+ <Tabs_Shadcn_ defaultValue="results" className="w-full h-full">
+ <TabsList_Shadcn_ className="flex justify-between px-2">
+ <div>
+ <TabsTrigger_Shadcn_ className="py-3 text-xs" value="results">
+ Results{' '}
+ {!isExecuting &&
+ (result?.rows ?? []).length > 0 &&
+ `(${result.rows.length.toLocaleString()})`}
+ </TabsTrigger_Shadcn_>
+ {showCharts && (
+ <TabsTrigger_Shadcn_ className="py-3 text-xs" value="chart">
+ Chart
+ </TabsTrigger_Shadcn_>
+ )}
+ </div>
+ <div className="flex gap-1 h-full">
+ {result && result.rows && <ResultsDropdown id={id} isExecuting={isExecuting} />}
+ <UtilityActions
+ id={id}
+ isExecuting={isExecuting}
+ isDisabled={isDisabled}
+ hasSelection={hasSelection}
+ prettifyQuery={prettifyQuery}
+ executeQuery={executeQuery}
+ />
+ </div>
+ </TabsList_Shadcn_>
+ <TabsContent_Shadcn_ className="mt-0 h-full" value="results">
<UtilityTabResults id={id} isExecuting={isExecuting} />
- </div>
- </>
+ </TabsContent_Shadcn_>
+ {showCharts && (
+ <TabsContent_Shadcn_ className="mt-0 h-full" value="chart">
+ <ChartConfig results={result} config={config} onConfigChange={setConfig} />
+ </TabsContent_Shadcn_>
+ )}
+ </Tabs_Shadcn_>
)
}
diff --git a/apps/studio/components/ui/Charts/BarChart.tsx b/apps/studio/components/ui/Charts/BarChart.tsx
index 77f08befb9a..9f843aa9426 100644
--- a/apps/studio/components/ui/Charts/BarChart.tsx
+++ b/apps/studio/components/ui/Charts/BarChart.tsx
@@ -2,7 +2,7 @@ import { CHART_COLORS, DateTimeFormats } from 'components/ui/Charts/Charts.const
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import { useState } from 'react'
-import { Bar, BarChart as RechartBarChart, Cell, Tooltip, XAxis } from 'recharts'
+import { Bar, BarChart as RechartBarChart, Cell, Tooltip, XAxis, Legend } from 'recharts'
import { CategoricalChartState } from 'recharts/types/chart/generateCategoricalChart'
import ChartHeader from './ChartHeader'
import { CommonChartProps, Datum } from './Charts.types'
@@ -16,6 +16,9 @@ export interface BarChartProps<D = Datum> extends CommonChartProps<D> {
customDateFormat?: string
displayDateInUtc?: boolean
onBarClick?: (datum: Datum, tooltipData?: CategoricalChartState) => void
+ emptyStateMessage?: string
+ showLegend?: boolean
+ xAxisIsDate?: boolean
}
const BarChart = ({
@@ -32,12 +35,16 @@ const BarChart = ({
valuePrecision,
className = '',
size = 'normal',
+ emptyStateMessage,
onBarClick,
+ showLegend = false,
+ xAxisIsDate = true,
}: BarChartProps) => {
const { Container } = useChartSize(size)
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
- if (data.length === 0) return <ChartNoData size={size} className={className} />
+ if (data.length === 0)
+ return <ChartNoData message={emptyStateMessage} size={size} className={className} />
const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))
const resolvedHighlightedLabel =
@@ -87,6 +94,7 @@ const BarChart = ({
if (onBarClick) onBarClick(datum, tooltipData)
}}
>
+ {showLegend && <Legend />}
<XAxis
dataKey={xAxisKey}
interval={data.length - 2}
@@ -122,8 +130,14 @@ const BarChart = ({
</Container>
{data && (
<div className="text-foreground-lighter -mt-9 flex items-center justify-between text-xs">
- <span>{day(data[0][xAxisKey]).format(customDateFormat)}</span>
- <span>{day(data[data?.length - 1]?.[xAxisKey]).format(customDateFormat)}</span>
+ <span>
+ {xAxisIsDate ? day(data[0][xAxisKey]).format(customDateFormat) : data[0][xAxisKey]}
+ </span>
+ <span>
+ {xAxisIsDate
+ ? day(data[data?.length - 1]?.[xAxisKey]).format(customDateFormat)
+ : data[data?.length - 1]?.[xAxisKey]}
+ </span>
</div>
)}
</div>